diff --git a/README.md b/README.md index e208d00..97510a2 100644 --- a/README.md +++ b/README.md @@ -1,3 +1,20 @@ # pyscript-bootstrap-templates -templates and pyscript wrappers for various bootstrap properties \ No newline at end of file +templates and pyscript wrappers for various bootstrap properties + +## installation + +```bash +pip install git+https://the-cake-is-a-lie.net/gogs/jonas/pyscript-bootstrap-templates.git +``` + +## usage + +to create a new project, run + +```bash +pyscript_bootstrap_app create +``` + +this will create a new folder containing a PWA app skeleton to start with. +The main entry point should be in main.py \ No newline at end of file diff --git a/examples/01_hello_world/config.json b/examples/01_hello_world/config.json index d8b4ac8..98fb21f 100644 --- a/examples/01_hello_world/config.json +++ b/examples/01_hello_world/config.json @@ -8,7 +8,7 @@ "pyscript_py_url": "https://pyscript.net/latest/pyscript.py", "bootstrap_css_url": "https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css", "bootstrap_js_url": "https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js", - "pyscript_bootstrap_templates_wheel_url": "../dist/pyscript_bootstrap_templates-0.1.0-py3-none-any.whl", + "pyscript_bootstrap_templates_wheel_url": "../dist/pyscript_bootstrap_templates-0.2.0-py3-none-any.whl", "pwa_bg_color": "#000000", "pwa_theme_color": "#ffffff" } \ No newline at end of file diff --git a/examples/01_hello_world/index.html b/examples/01_hello_world/index.html index 38e4767..c806a70 100644 --- a/examples/01_hello_world/index.html +++ b/examples/01_hello_world/index.html @@ -19,9 +19,11 @@ <body style="width: 100%; height: 100%"> <py-config type="json"> { - "autoclose_loader": true, + "splashscreen": { + "autoclose": true + }, "packages": [ - "./resources/pyscript_bootstrap_templates-0.1.0-py3-none-any.whl" + "./resources/pyscript_bootstrap_templates-0.2.0-py3-none-any.whl" ], "paths": [] } diff --git a/examples/01_hello_world/resources/pyscript.css b/examples/01_hello_world/resources/pyscript.css index be94299..10a1f1c 100644 --- a/examples/01_hello_world/resources/pyscript.css +++ b/examples/01_hello_world/resources/pyscript.css @@ -1,9 +1,35 @@ -:not(:defined) { - display: none +/* py-config - not a component */ +py-config { + display: none; +} +/* py-{el} - components not defined */ +py-script:not(:defined) { + display: none; } -html{ - font-family: ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, "Noto Sans", sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji"; +py-repl:not(:defined) { + display: none; +} + +py-title:not(:defined) { + display: none; +} + +py-inputbox:not(:defined) { + display: none; +} + +py-button:not(:defined) { + display: none; +} + +py-box:not(:defined) { + display: none; +} + +html { + font-family: ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', + Arial, 'Noto Sans', sans-serif, 'Apple Color Emoji', 'Segoe UI Emoji', 'Segoe UI Symbol', 'Noto Color Emoji'; line-height: 1.5; } @@ -24,6 +50,7 @@ html{ border-right: 4px solid rgba(255, 255, 255, 0); animation: spinner 0.6s linear infinite; } + @keyframes spinner { to { transform: rotate(360deg); @@ -81,27 +108,68 @@ html{ right: 5%; } -.py-box{ +/* Pop-up second layer end */ +.alert-banner { + position: relative; + padding: 0.5rem 1.5rem 0.5rem 0.5rem; + margin: 5px 0; +} + +.alert-banner p { + margin: 0; +} + +.py-error { + background-color: #ffe9e8; + border: solid; + border-color: #f0625f; + color: #9d041c; +} + +.py-warning { + background-color: rgb(255, 244, 229); + border: solid; + border-color: #ffa016; + color: #794700; +} + +.alert-banner.py-error > #alert-close-button { + color: #9d041c; +} + +.alert-banner.py-warning > #alert-close-button { + color: #794700; +} + +#alert-close-button { + position: absolute; + right: 0.5rem; + top: 0.5rem; + cursor: pointer; + background: transparent; + border: none; +} + +.py-box { display: flex; flex-direction: row; justify-content: flex-start; } -.py-box div.py-box-child * -{ +.py-box div.py-box-child * { max-width: 100%; } -.py-repl-box{ +.py-repl-box { flex-direction: column; } -.editor-box{ +.py-repl-editor { --tw-border-opacity: 1; border-color: rgba(209, 213, 219, var(--tw-border-opacity)); border-width: 1px; position: relative; - --tw-ring-inset: var(--tw-empty,/*!*/ /*!*/); + --tw-ring-inset: var(--tw-empty, /*!*/ /*!*/); --tw-ring-offset-width: 0px; --tw-ring-offset-color: #fff; --tw-ring-color: rgba(59, 130, 246, 0.5); @@ -113,14 +181,14 @@ html{ box-sizing: border-box; border-width: 1px; border-style: solid; - border-color: rgb(209, 213, 219) + border-color: rgb(209, 213, 219); } -.editor-box:hover button{ +.editor-box:hover button { opacity: 1; } -.repl-play-button{ +.py-repl-run-button { opacity: 0; bottom: 0.25rem; right: 0.25rem; @@ -154,65 +222,64 @@ html{ border: 0; } -.repl-play-button:hover{ +.py-repl-run-button:hover { opacity: 1; } -.py-title{ +.py-title { text-transform: uppercase; text-align: center; } -.py-title h1{ +.py-title h1 { font-weight: 700; font-size: 1.875rem; } -.py-input{ +.py-input { padding: 0.5rem; --tw-border-opacity: 1; border-color: rgba(209, 213, 219, var(--tw-border-opacity)); border-width: 1px; - border-radius: 0.25rem; + border-radius: 0.25rem; margin-right: 0.75rem; border-style: solid; width: auto; } -.py-box input.py-input{ +.py-box input.py-input { width: -webkit-fill-available; } -.central-content{ +.central-content { max-width: 20rem; margin-left: auto; margin-right: auto; } input { - text-rendering: auto; - color: -internal-light-dark(black, white); - letter-spacing: normal; - word-spacing: normal; - line-height: normal; - text-transform: none; - text-indent: 0px; - text-shadow: none; - display: inline-block; - text-align: start; - appearance: auto; - -webkit-rtl-ordering: logical; - cursor: text; - background-color: -internal-light-dark(rgb(255, 255, 255), rgb(59, 59, 59)); - margin: 0em; - padding: 1px 2px; - border-width: 2px; - border-style: inset; - border-color: -internal-light-dark(rgb(118, 118, 118), rgb(133, 133, 133)); - border-image: initial; + text-rendering: auto; + color: -internal-light-dark(black, white); + letter-spacing: normal; + word-spacing: normal; + line-height: normal; + text-transform: none; + text-indent: 0px; + text-shadow: none; + display: inline-block; + text-align: start; + appearance: auto; + -webkit-rtl-ordering: logical; + background-color: -internal-light-dark(rgb(255, 255, 255), rgb(59, 59, 59)); + margin: 0em; + padding: 1px 2px; + border-width: 2px; + border-style: inset; + border-color: -internal-light-dark(rgb(118, 118, 118), rgb(133, 133, 133)); + border-image: initial; } -.py-button{ +.py-button { --tw-text-opacity: 1; color: rgba(255, 255, 255, var(--tw-text-opacity)); padding: 0.5rem; @@ -222,17 +289,22 @@ input { border-color: rgba(37, 99, 235, var(--tw-border-opacity)); border-width: 1px; border-radius: 0.25rem; + cursor: pointer; } -.py-li-element p{ +.py-li-element p { margin: 5px; } -.py-li-element p{ +.py-li-element p { display: inline; } -button, input, optgroup, select, textarea { +button, +input, +optgroup, +select, +textarea { font-family: inherit; font-size: 100%; line-height: 1.15; @@ -242,3 +314,19 @@ button, input, optgroup, select, textarea { .line-through { text-decoration: line-through; } + +/* ===== py-terminal plugin ===== */ +/* XXX: it would be nice if these rules were stored in e.g. pyterminal.css and + bundled together at build time (by rollup?) */ + +.py-terminal { + min-height: 10em; + background-color: black; + color: white; + padding: 0.5rem; + overflow: auto; +} + +.py-terminal-hidden { + display: none; +} diff --git a/examples/01_hello_world/resources/pyscript.js b/examples/01_hello_world/resources/pyscript.js index e9b92a0..4bc0b89 100644 --- a/examples/01_hello_world/resources/pyscript.js +++ b/examples/01_hello_world/resources/pyscript.js @@ -1,4167 +1,28471 @@ -(function () { - 'use strict'; +var pyscript = (function (exports) { + 'use strict'; - function noop() { } - function safe_not_equal(a, b) { - return a != a ? b == b : a !== b || ((a && typeof a === 'object') || typeof a === 'function'); + var parser$2 = /* + * Generated by PEG.js 0.10.0. + * + * http://pegjs.org/ + */ + (function() { + + function peg$subclass(child, parent) { + function ctor() { this.constructor = child; } + ctor.prototype = parent.prototype; + child.prototype = new ctor(); } - Promise.resolve(); - const subscriber_queue = []; - /** - * Create a `Writable` store that allows both updating and reading by subscription. - * @param {*=}value initial value - * @param {StartStopNotifier=}start start and stop notifications for subscriptions - */ - function writable(value, start = noop) { - let stop; - const subscribers = new Set(); - function set(new_value) { - if (safe_not_equal(value, new_value)) { - value = new_value; - if (stop) { // store is ready - const run_queue = !subscriber_queue.length; - for (const subscriber of subscribers) { - subscriber[1](); - subscriber_queue.push(subscriber, value); - } - if (run_queue) { - for (let i = 0; i < subscriber_queue.length; i += 2) { - subscriber_queue[i][0](subscriber_queue[i + 1]); - } - subscriber_queue.length = 0; - } - } + function peg$SyntaxError(message, expected, found, location) { + this.message = message; + this.expected = expected; + this.found = found; + this.location = location; + this.name = "SyntaxError"; + + if (typeof Error.captureStackTrace === "function") { + Error.captureStackTrace(this, peg$SyntaxError); + } + } + + peg$subclass(peg$SyntaxError, Error); + + peg$SyntaxError.buildMessage = function(expected, found) { + var DESCRIBE_EXPECTATION_FNS = { + literal: function(expectation) { + return "\"" + literalEscape(expectation.text) + "\""; + }, + + "class": function(expectation) { + var escapedParts = "", + i; + + for (i = 0; i < expectation.parts.length; i++) { + escapedParts += expectation.parts[i] instanceof Array + ? classEscape(expectation.parts[i][0]) + "-" + classEscape(expectation.parts[i][1]) + : classEscape(expectation.parts[i]); + } + + return "[" + (expectation.inverted ? "^" : "") + escapedParts + "]"; + }, + + any: function(expectation) { + return "any character"; + }, + + end: function(expectation) { + return "end of input"; + }, + + other: function(expectation) { + return expectation.description; } + }; + + function hex(ch) { + return ch.charCodeAt(0).toString(16).toUpperCase(); + } + + function literalEscape(s) { + return s + .replace(/\\/g, '\\\\') + .replace(/"/g, '\\"') + .replace(/\0/g, '\\0') + .replace(/\t/g, '\\t') + .replace(/\n/g, '\\n') + .replace(/\r/g, '\\r') + .replace(/[\x00-\x0F]/g, function(ch) { return '\\x0' + hex(ch); }) + .replace(/[\x10-\x1F\x7F-\x9F]/g, function(ch) { return '\\x' + hex(ch); }); + } + + function classEscape(s) { + return s + .replace(/\\/g, '\\\\') + .replace(/\]/g, '\\]') + .replace(/\^/g, '\\^') + .replace(/-/g, '\\-') + .replace(/\0/g, '\\0') + .replace(/\t/g, '\\t') + .replace(/\n/g, '\\n') + .replace(/\r/g, '\\r') + .replace(/[\x00-\x0F]/g, function(ch) { return '\\x0' + hex(ch); }) + .replace(/[\x10-\x1F\x7F-\x9F]/g, function(ch) { return '\\x' + hex(ch); }); + } + + function describeExpectation(expectation) { + return DESCRIBE_EXPECTATION_FNS[expectation.type](expectation); + } + + function describeExpected(expected) { + var descriptions = new Array(expected.length), + i, j; + + for (i = 0; i < expected.length; i++) { + descriptions[i] = describeExpectation(expected[i]); } - function update(fn) { - set(fn(value)); - } - function subscribe(run, invalidate = noop) { - const subscriber = [run, invalidate]; - subscribers.add(subscriber); - if (subscribers.size === 1) { - stop = start(set) || noop; + + descriptions.sort(); + + if (descriptions.length > 0) { + for (i = 1, j = 1; i < descriptions.length; i++) { + if (descriptions[i - 1] !== descriptions[i]) { + descriptions[j] = descriptions[i]; + j++; } - run(value); - return () => { - subscribers.delete(subscriber); - if (subscribers.size === 0) { - stop(); - stop = null; - } - }; + } + descriptions.length = j; } - return { set, update, subscribe }; - } - /* Very simple logger interface. + switch (descriptions.length) { + case 1: + return descriptions[0]; - Each module is expected to create its own logger by doing e.g.: + case 2: + return descriptions[0] + " or " + descriptions[1]; - const logger = getLogger('my-prefix'); - - and then use it instead of console: - - logger.info('hello', 'world'); - logger.warn('...'); - logger.error('...'); - - The logger automatically adds the prefix "[my-prefix]" to all logs; so e.g., the - above call would print: - - [my-prefix] hello world - - logger.log is intentionally omitted. The idea is that PyScript should not - write anything to console.log, to leave it free for the user. - - Currently, the logger does not to anything more than that. In the future, - we might want to add additional features such as the ability to - enable/disable logs on a global or per-module basis. - */ - const _cache = new Map(); - function getLogger(prefix) { - let logger = _cache.get(prefix); - if (logger === undefined) { - logger = _makeLogger(prefix); - _cache.set(prefix, logger); + default: + return descriptions.slice(0, -1).join(", ") + + ", or " + + descriptions[descriptions.length - 1]; } - return logger; - } - function _makeLogger(prefix) { - prefix = "[" + prefix + "] "; - function make(level) { - const out_fn = console[level].bind(console); - function fn(fmt, ...args) { - out_fn(prefix + fmt, ...args); - } - return fn; - } - // 'log' is intentionally omitted - const debug = make('debug'); - const info = make('info'); - const warn = make('warn'); - const error = make('error'); - return { debug, info, warn, error }; - } + } - /* - A store for Runtime which can encompass any - runtime, but currently only has Pyodide as its offering. - */ - const runtimeLoaded = writable(); - const loadedEnvironments = writable({}); - const scriptsQueue = writable([]); - const initializers = writable([]); - const postInitializers = writable([]); - const globalLoader = writable(); - const appConfig = writable(); - const addToScriptsQueue = (script) => { - scriptsQueue.update(scriptsQueue => [...scriptsQueue, script]); - }; - const addInitializer = (initializer) => { - initializers.update(initializers => [...initializers, initializer]); - }; - const addPostInitializer = (initializer) => { - postInitializers.update(postInitializers => [...postInitializers, initializer]); + function describeFound(found) { + return found ? "\"" + literalEscape(found) + "\"" : "end of input"; + } + + return "Expected " + describeExpected(expected) + " but " + describeFound(found) + " found."; }; - // taken from https://github.com/Gin-Quin/fast-toml - let e = "", t$1 = 0; - function i$2(e, t = 0) { - let i; - for (; (i = e[t++]) && (" " == i || "\t" == i || "\r" == i);) - ; - return t - 1; - } - function n(e) { - switch (e[0]) { - case void 0: - return ""; - case '"': - return (function (e) { - let t, i = 0, n = ""; - for (; (t = e.indexOf("\\", i) + 1);) { - switch (((n += e.slice(i, t - 1)), e[t])) { - case "\\": - n += "\\"; - break; - case '"': - n += '"'; - break; - case "\r": - "\n" == e[t + 1] && t++; - case "\n": - break; - case "b": - n += "\b"; - break; - case "t": - n += "\t"; - break; - case "n": - n += "\n"; - break; - case "f": - n += "\f"; - break; - case "r": - n += "\r"; - break; - case "u": - (n += String.fromCharCode(parseInt(e.substr(t + 1, 4), 16))), (t += 4); - break; - case "U": - (n += String.fromCharCode(parseInt(e.substr(t + 1, 8), 16))), (t += 8); - break; - default: - throw r(e[t]); - } - i = t + 1; + function peg$parse(input, options) { + options = options !== void 0 ? options : {}; + + var peg$FAILED = {}, + + peg$startRuleFunctions = { Expressions: peg$parseExpressions }, + peg$startRuleFunction = peg$parseExpressions, + + peg$c0 = function() { + return g_root; + }, + peg$c1 = function(path) { + g_context = findContext(g_root, true, path); + }, + peg$c2 = function(path) { + g_context = findContext(g_root, false, path); + }, + peg$c3 = function(keyValue) { + checkTableKey(g_context.table, keyValue[0]); + g_context.table[keyValue[0]] = keyValue[1]; + }, + peg$c4 = peg$otherExpectation("Newline"), + peg$c5 = "\n", + peg$c6 = peg$literalExpectation("\n", false), + peg$c7 = "\r\n", + peg$c8 = peg$literalExpectation("\r\n", false), + peg$c9 = peg$otherExpectation("Whitespace"), + peg$c10 = /^[ \t]/, + peg$c11 = peg$classExpectation([" ", "\t"], false, false), + peg$c12 = peg$otherExpectation("Comment"), + peg$c13 = "#", + peg$c14 = peg$literalExpectation("#", false), + peg$c15 = peg$anyExpectation(), + peg$c16 = "=", + peg$c17 = peg$literalExpectation("=", false), + peg$c18 = function(key, value) { + return [key, value.value]; + }, + peg$c19 = function() { + return text(); + }, + peg$c20 = peg$otherExpectation("[a-z], [A-Z], [0-9], \"-\", \"_\""), + peg$c21 = /^[a-zA-Z0-9\-_]/, + peg$c22 = peg$classExpectation([["a", "z"], ["A", "Z"], ["0", "9"], "-", "_"], false, false), + peg$c23 = function(chars) { + return chars.join(''); + }, + peg$c24 = peg$otherExpectation("DoubleQuote"), + peg$c25 = "\"", + peg$c26 = peg$literalExpectation("\"", false), + peg$c27 = peg$otherExpectation("SingleQuote"), + peg$c28 = "'", + peg$c29 = peg$literalExpectation("'", false), + peg$c30 = peg$otherExpectation("ThreeDoubleQuotes"), + peg$c31 = "\"\"\"", + peg$c32 = peg$literalExpectation("\"\"\"", false), + peg$c33 = peg$otherExpectation("ThreeSingleQuotes"), + peg$c34 = "'''", + peg$c35 = peg$literalExpectation("'''", false), + peg$c36 = function(chars) { + return { + type: 'String', + value: chars.join('') + }; + }, + peg$c37 = peg$otherExpectation("NormalCharacter"), + peg$c38 = /^[^\0-\x1F"\\]/, + peg$c39 = peg$classExpectation([["\0", "\x1F"], "\"", "\\"], true, false), + peg$c40 = "u", + peg$c41 = peg$literalExpectation("u", false), + peg$c42 = "U", + peg$c43 = peg$literalExpectation("U", false), + peg$c44 = function() { + var s = text(); + if (s.length <= 2) { + return unescape(s[1]); + } + return fromCodePoint(parseInt(s.substr(2), 16)); + }, + peg$c45 = peg$otherExpectation("\"b\", \"f\", \"n\", \"r\", \"t\""), + peg$c46 = /^[bfnrt]/, + peg$c47 = peg$classExpectation(["b", "f", "n", "r", "t"], false, false), + peg$c48 = peg$otherExpectation("Backslash"), + peg$c49 = "\\", + peg$c50 = peg$literalExpectation("\\", false), + peg$c51 = peg$otherExpectation("FourHexadecimalDigits"), + peg$c52 = peg$otherExpectation("EightHexadecimalDigits"), + peg$c53 = /^[0-9A-Fa-f]/, + peg$c54 = peg$classExpectation([["0", "9"], ["A", "F"], ["a", "f"]], false, false), + peg$c55 = function() { + var s = text(); + return { + type: 'String', + value: s.substr(1, s.length - 2) + }; + }, + peg$c56 = /^[^\0-\x08\n-\x1F']/, + peg$c57 = peg$classExpectation([["\0", "\b"], ["\n", "\x1F"], "'"], true, false), + peg$c58 = function(chars) { + return { + type: 'String', + value: chars.join('').replace(/\\\r?\n(?:\r?\n|[ \t])*/g, '') + }; + }, + peg$c59 = /^[^\0-\x1F\\]/, + peg$c60 = peg$classExpectation([["\0", "\x1F"], "\\"], true, false), + peg$c61 = peg$otherExpectation("AnyCharacter"), + peg$c62 = /^[^\0-\x08\n-\x1F]/, + peg$c63 = peg$classExpectation([["\0", "\b"], ["\n", "\x1F"]], true, false), + peg$c64 = "true", + peg$c65 = peg$literalExpectation("true", false), + peg$c66 = function() { + return { + type: 'Boolean', + value: true + }; + }, + peg$c67 = "false", + peg$c68 = peg$literalExpectation("false", false), + peg$c69 = function() { + return { + type: 'Boolean', + value: false + }; + }, + peg$c70 = function() { + // A double-precision 64-bit floating-point number in IEEE 754 standard. + var s = text(); + var number = parseFloat(s.replace(/_/g, '')); + if (!isFiniteNumber(number)) { + error(s + 'is not a 64-bit floating-point number.'); + } + return { + type: 'Float', + value: number + }; + }, + peg$c71 = ".", + peg$c72 = peg$literalExpectation(".", false), + peg$c73 = "_", + peg$c74 = peg$literalExpectation("_", false), + peg$c75 = "e", + peg$c76 = peg$literalExpectation("e", false), + peg$c77 = "E", + peg$c78 = peg$literalExpectation("E", false), + peg$c79 = function() { + // Be careful of JavaScript limits: + // 1) Number.MAX_SAFE_INTEGER = 9007199254740991 + // 2) Number.MIN_SAFE_INTEGER = -9007199254740991 + var s = text(); + var number = s.replace(/_/g, ''); + // Check if it is a 64-bit signed integer. + var invalid = false; + if (number[0] === '-') { + var minInt = '-9223372036854775808'; + if (number.length > minInt.length || + (number.length === minInt.length && number > minInt)) { + invalid = true; } - return n + e.slice(i); - })(e.slice(1, -1)); - case "'": - return e.slice(1, -1); - case "0": - case "1": - case "2": - case "3": - case "4": - case "5": - case "6": - case "7": - case "8": - case "9": - case "+": - case "-": - case ".": - let t = e; - if ((-1 != t.indexOf("_") && (t = t.replace(/_/g, "")), !isNaN(t))) - return +t; - if ("-" == e[4] && "-" == e[7]) { - let t = new Date(e); - if ("Invalid Date" != t.toString()) - return t; - } - else if (":" == e[2] && ":" == e[5] && e.length >= 7) { - let t = new Date("0000-01-01T" + e + "Z"); - if ("Invalid Date" != t.toString()) - return t; - } - return e; - } - switch (e) { - case "true": - return !0; - case "false": - return !1; - case "nan": - case "NaN": - return !1; - case "null": - return null; - case "inf": - case "+inf": - case "Infinity": - case "+Infinity": - return 1 / 0; - case "-inf": - case "-Infinity": - return -1 / 0; - } - return e; - } - function r(i) { - let n = (function () { - let i = e[t$1], n = t$1; - "\n" == i && n--; - let r = 1, s = e.lastIndexOf("\n", n), a = e.indexOf("\n", n); - -1 == a && (a = 1 / 0); - ("," != i && "\n" != i) || (n = s + 1); - if (-1 == s) - return { line: r, column: n + 1, position: n, lineContent: e.slice(0, a).trim() }; - const c = n - s + 1, o = e.slice(s + 1, a).trim(); - r++; - for (; -1 != (s = e.lastIndexOf("\n", s - 1));) - r++; - return { line: r, column: c, position: n, lineContent: o }; - })(), r = String(n.line); - return (i += "\n" + r + " | " + n.lineContent + "\n"), (i += " ".repeat(r.length + n.column + 2) + "^"), SyntaxError(i); - } - function s(e, i = 0, n = !1) { - let a, c = e[i], o = c, f = c, l = !0, u = !1; - switch (c) { - case '"': - case "'": - if (((a = i + 1), n && e[i + 1] == c && e[i + 2] == c ? ((f = c + c + c), (a += 2)) : (u = !0), "'" == c)) - a = e.indexOf(f, a) + 1; - else - for (; (a = e.indexOf(f, a) + 1);) { - let t = !0, i = a - 1; - for (; "\\" == e[--i];) - t = !t; - if (t) - break; + } else { + if (number[0] === '+') { + number = number.substr(1); } - if (!a) - throw r("Missing " + f + " closer"); - if (c != f) - a += 2; - else if (u) { - let n = e.indexOf("\n", i + 1) + 1; - if (n && n < a) - throw ((t$1 = n - 2), r("Forbidden end-of-line character in single-line string")); - } - return a; - case "(": - f = ")"; - break; - case "{": - f = "}"; - break; - case "[": - f = "]"; - break; - case "<": - f = ">"; - break; - default: - l = !1; - } - let h = 0; - for (; (c = e[++i]);) - if (c == f) { - if (0 == h) - return i + 1; - h--; - } - else if ('"' == c || "'" == c) { - i = s(e, i, n) - 1; - } - else - l && c == o && h++; - throw r("Missing " + f); - } - function a(e) { - "string" != typeof e && (e = String(e)); - let t, i, n = -1, a = "", c = []; - for (; (i = e[++n]);) - switch (i) { - case ".": - if (!a) - throw r('Unexpected "."'); - c.push(a), (a = ""); - continue; - case '"': - case "'": - if (((t = s(e, n)), t == n + 2)) - throw r("Empty string key"); - (a += e.slice(n + 1, t - 1)), (n = t - 1); - continue; - default: - a += i; - } - return a && c.push(a), c; - } - function c(e, t = []) { - const i = t.pop(); - for (let i of t) { - if ("object" != typeof e) { - throw r('["' + t.slice(0, t.indexOf(i) + 1).join('"].["') + '"]' + " must be an object"); - } - void 0 === e[i] && (e[i] = {}), (e = e[i]) instanceof Array && (e = e[e.length - 1]); - } - return [e, i]; - } - class o { - root; - data; - inlineScopeList; - constructor() { - this.root = {}; - this.data = this.root; - this.inlineScopeList = []; - } - get isRoot() { - return this.data == this.root; - } - set(e, t) { - let [i, n] = c(this.data, a(e)); - if ("string" == typeof i) - throw "Wtf the scope is a string. Please report the bug"; - if (n in i) - throw r(`Re-writing the key '${e}'`); - return (i[n] = t), t; - } - push(e) { - if (!(this.data instanceof Array)) { - if (!this.isRoot) - throw r("Missing key"); - (this.data = Object.assign([], this.data)), (this.root = this.data); - } - return this.data.push(e), this; - } - use(e) { - return ((this.data = (function (e, t = []) { - for (let i of t) { - //if (void 0 === e) e = lastData[lastElt] = {}; - //else - if ("object" != typeof e) { - throw r('["' + t.slice(0, t.indexOf(i) + 1).join('"].["') + '"]' + " must be an object"); + var maxInt = '9223372036854775807'; + if (number.length > maxInt.length || + (number.length === maxInt.length && number > maxInt)) { + invalid = true; } - void 0 === e[i] && (e[i] = {}), (e = e[i]) instanceof Array && (e = e[e.length - 1]); - } - return e; - })(this.root, a(e))), - this); + } + if (invalid) { + error(s + ' is not a 64-bit signed integer.'); + } + number = parseInt(number, 10); + if (!isFiniteNumber(number)) { + error(s + ' is not a 64-bit signed integer.'); + } + return { + type: 'Integer', + value: number + }; + }, + peg$c80 = "+", + peg$c81 = peg$literalExpectation("+", false), + peg$c82 = "-", + peg$c83 = peg$literalExpectation("-", false), + peg$c84 = /^[1-9]/, + peg$c85 = peg$classExpectation([["1", "9"]], false, false), + peg$c86 = /^[0-9]/, + peg$c87 = peg$classExpectation([["0", "9"]], false, false), + peg$c88 = "T", + peg$c89 = peg$literalExpectation("T", false), + peg$c90 = function() { + var s = text(); + var date = new Date(s); + if (!isFiniteNumber(date.getTime())) { + error('Date-time ' + s + ' is invalid. It does not conform to RFC 3339 or this is a browser-specific problem.'); + } + return { + type: 'DateTime', + value: date + }; + }, + peg$c91 = peg$otherExpectation("FullDate (YYYY-mm-dd)"), + peg$c92 = ":", + peg$c93 = peg$literalExpectation(":", false), + peg$c94 = peg$otherExpectation("Hour (HH)"), + peg$c95 = peg$otherExpectation("Minute (MM)"), + peg$c96 = peg$otherExpectation("Second (SS)"), + peg$c97 = peg$otherExpectation("TimeOffset (Z or +/-HH:MM)"), + peg$c98 = "Z", + peg$c99 = peg$literalExpectation("Z", false), + peg$c100 = "[", + peg$c101 = peg$literalExpectation("[", false), + peg$c102 = ",", + peg$c103 = peg$literalExpectation(",", false), + peg$c104 = "]", + peg$c105 = peg$literalExpectation("]", false), + peg$c106 = function(values) { + var o = { + type: 'Array', + value: values ? values[0] : [] + }; + for (var i = 0, arr = o.value, l = arr.length; i < l; i++) { + arr[i] = arr[i].value; + } + return o; + }, + peg$c107 = function(value, opt) { + var array = [value]; + if (opt) { + var type = value.type; + for (var i = 0, arr = opt[3], l = arr.length; i < l; i++) { + if (type !== arr[i].type) { + error(stringify(arr[i].value) + ' should be of type "' + type + + '".'); + } + array.push(arr[i]); + } + } + return array; + }, + peg$c108 = "{", + peg$c109 = peg$literalExpectation("{", false), + peg$c110 = "}", + peg$c111 = peg$literalExpectation("}", false), + peg$c112 = function(opt) { + var table = {}; + if (opt) { + table[opt[0][0]] = opt[0][1]; + for (var i = 0, arr = opt[1], l = arr.length; i < l; i++) { + var kv = arr[i][3]; + checkTableKey(table, kv[0]); + table[kv[0]] = kv[1]; + } + } + return { + type: 'InlineTable', + value: table + }; + }, + peg$c113 = function(path) { + return path; + }, + peg$c114 = function(key, arr) { + var path = [key]; + for (var i = 0, l = arr.length; i < l; i++) { + path.push(arr[i][3]); + } + return path; + }, + + peg$currPos = 0, + peg$savedPos = 0, + peg$posDetailsCache = [{ line: 1, column: 1 }], + peg$maxFailPos = 0, + peg$maxFailExpected = [], + peg$silentFails = 0, + + peg$result; + + if ("startRule" in options) { + if (!(options.startRule in peg$startRuleFunctions)) { + throw new Error("Can't start parsing from rule \"" + options.startRule + "\"."); } - useArray(e) { - let [t, i] = c(this.root, a(e)); - return (this.data = {}), void 0 === t[i] && (t[i] = []), t[i].push(this.data), this; - } - enter(e, t) { - return this.inlineScopeList.push(this.data), this.set(e, t), (this.data = t), this; - } - enterArray(e) { - return this.inlineScopeList.push(this.data), this.push(e), (this.data = e), this; - } - exit() { - return (this.data = this.inlineScopeList.pop()), this; - } - } - function f(a) { - "string" != typeof a && (a = String(a)); - const c = new o(), f = []; - (e = a), (t$1 = 0); - let l, u, h = "", d = "", p = e[0], w = !0; - const g = () => { - if (((h = h.trimEnd()), w)) - h && c.push(n(h)); - else { - if (!h) - throw r("Expected key before ="); - if (!d) - throw r("Expected value after ="); - c.set(h, n(d.trimEnd())); + + peg$startRuleFunction = peg$startRuleFunctions[options.startRule]; + } + + function text() { + return input.substring(peg$savedPos, peg$currPos); + } + + function error(message, location) { + location = location !== void 0 ? location : peg$computeLocation(peg$savedPos, peg$currPos); + + throw peg$buildSimpleError(message, location); + } + + function peg$literalExpectation(text, ignoreCase) { + return { type: "literal", text: text, ignoreCase: ignoreCase }; + } + + function peg$classExpectation(parts, inverted, ignoreCase) { + return { type: "class", parts: parts, inverted: inverted, ignoreCase: ignoreCase }; + } + + function peg$anyExpectation() { + return { type: "any" }; + } + + function peg$endExpectation() { + return { type: "end" }; + } + + function peg$otherExpectation(description) { + return { type: "other", description: description }; + } + + function peg$computePosDetails(pos) { + var details = peg$posDetailsCache[pos], p; + + if (details) { + return details; + } else { + p = pos - 1; + while (!peg$posDetailsCache[p]) { + p--; + } + + details = peg$posDetailsCache[p]; + details = { + line: details.line, + column: details.column + }; + + while (p < pos) { + if (input.charCodeAt(p) === 10) { + details.line++; + details.column = 1; + } else { + details.column++; } - (h = ""), (d = ""), (w = !0); + + p++; + } + + peg$posDetailsCache[pos] = details; + return details; + } + } + + function peg$computeLocation(startPos, endPos) { + var startPosDetails = peg$computePosDetails(startPos), + endPosDetails = peg$computePosDetails(endPos); + + return { + start: { + offset: startPos, + line: startPosDetails.line, + column: startPosDetails.column + }, + end: { + offset: endPos, + line: endPosDetails.line, + column: endPosDetails.column + } }; - do { - switch (p) { - case " ": - w ? h && (h += p) : d && (d += p); - case "\t": - case "\r": - continue; - case "#": - (t$1 = e.indexOf("\n", t$1 + 1) - 1), -2 == t$1 && (t$1 = 1 / 0); - continue; - case '"': - case "'": - if (!w && d) { - d += p; - continue; - } - let n = e[t$1 + 1] == p && e[t$1 + 2] == p; - if (((l = s(e, t$1, !0)), w)) { - if (h) - throw r("Unexpected " + p); - (h += n ? e.slice(t$1 + 2, l - 2) : e.slice(t$1, l)), (t$1 = l); - } - else - (d = e.slice(t$1, l)), (t$1 = l), n && ((d = d.slice(2, -2)), "\n" == d[1] ? (d = d[0] + d.slice(2)) : "\r" == d[1] && "\n" == d[2] && (d = d[0] + d.slice(3))); - if (((t$1 = i$2(e, t$1)), (p = e[t$1]), p && "," != p && "\n" != p && "#" != p && "}" != p && "]" != p && "=" != p)) - throw r("Unexpected character after end of string"); - t$1--; - continue; - case "\n": - case ",": - case void 0: - g(); - continue; - case "[": - case "{": - if (((u = "[" == p ? "]" : "}"), w && !f.length)) { - if (h) - throw r("Unexpected " + p); - if (((l = s(e, t$1)), "[" == p && "[" == e[t$1 + 1])) { - if ("]" != e[l - 2]) - throw r("Missing ]]"); - c.useArray(e.slice(t$1 + 2, l - 2)); - } - else - c.use(e.slice(t$1 + 1, l - 1)); - t$1 = l; - } - else if (w) { - if (h) - throw r("Unexpected " + p); - c.enterArray("[" == p ? [] : {}), f.push(u); - } - else { - if (d) - throw r("Unexpected " + p); - c.enter(h.trimEnd(), "[" == p ? [] : {}), f.push(u), (h = ""), (w = !0); - } - continue; - case "]": - case "}": - if ((h && g(), f.pop() != p)) - throw r("Unexpected " + p); - if ((c.exit(), (t$1 = i$2(e, t$1 + 1)), (p = e[t$1]), p && "," != p && "\n" != p && "#" != p && "}" != p && "]" != p)) - throw r("Unexpected character after end of scope"); - t$1--; - continue; - case "=": - if (!w) - throw r("Unexpected " + p); - if (!h) - throw r("Missing key before " + p); - w = !1; - continue; - default: - w ? (h += p) : (d += p); - } - } while ((p = e[++t$1]) || h); - if (f.length) - throw r("Missing " + f.pop()); - return c.root; - } - function h() { - let e = ""; - for (let t of arguments) - e += "string" == typeof t ? t : t[0]; - return f(e); - } - const toml = ((h.parse = f), - h); + } - const allKeys = { - "string": ["name", "description", "version", "type", "author_name", "author_email", "license"], - "number": ["schema_version"], - "boolean": ["autoclose_loader"], - "array": ["runtimes", "packages", "paths", "plugins"] - }; - const defaultConfig$1 = { - "schema_version": 1, - "type": "app", - "autoclose_loader": true, - "runtimes": [{ - "src": "https://cdn.jsdelivr.net/pyodide/v0.21.2/full/pyodide.js", - "name": "pyodide-0.21.2", - "lang": "python" - }], - "packages": [], - "paths": [], - "plugins": [] - }; - function addClasses(element, classes) { - for (const entry of classes) { - element.classList.add(entry); + function peg$fail(expected) { + if (peg$currPos < peg$maxFailPos) { return; } + + if (peg$currPos > peg$maxFailPos) { + peg$maxFailPos = peg$currPos; + peg$maxFailExpected = []; } - } - function removeClasses(element, classes) { - for (const entry of classes) { - element.classList.remove(entry); + + peg$maxFailExpected.push(expected); + } + + function peg$buildSimpleError(message, location) { + return new peg$SyntaxError(message, null, null, location); + } + + function peg$buildStructuredError(expected, found, location) { + return new peg$SyntaxError( + peg$SyntaxError.buildMessage(expected, found), + expected, + found, + location + ); + } + + function peg$parseExpressions() { + var s0, s1, s2, s3, s4, s5, s6, s7; + + s0 = peg$currPos; + s1 = []; + s2 = peg$parseWhitespace(); + if (s2 === peg$FAILED) { + s2 = peg$parseNewline(); + if (s2 === peg$FAILED) { + s2 = peg$parseComment(); + } } - } - function getLastPath(str) { - return str.split('\\').pop().split('/').pop(); - } - function escape(str) { - return str.replace(/</g, "<").replace(/>/g, ">"); - } - function htmlDecode(input) { - const doc = new DOMParser().parseFromString(ltrim(escape(input)), 'text/html'); - return doc.documentElement.textContent; - } - function ltrim(code) { - const lines = code.split('\n'); - if (lines.length == 0) - return code; - const lengths = lines - .filter(line => line.trim().length != 0) - .map(line => { - const [prefix] = line.match(/^\s*/); - return prefix.length; - }); - const k = Math.min(...lengths); - return k != 0 ? lines.map(line => line.substring(k)).join('\n') - : code; - } - function guidGenerator() { - const S4 = function () { - return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1); + while (s2 !== peg$FAILED) { + s1.push(s2); + s2 = peg$parseWhitespace(); + if (s2 === peg$FAILED) { + s2 = peg$parseNewline(); + if (s2 === peg$FAILED) { + s2 = peg$parseComment(); + } + } + } + if (s1 !== peg$FAILED) { + s2 = peg$currPos; + s3 = peg$parseExpression(); + if (s3 !== peg$FAILED) { + s4 = []; + s5 = peg$parseWhitespace(); + if (s5 === peg$FAILED) { + s5 = peg$parseComment(); + } + while (s5 !== peg$FAILED) { + s4.push(s5); + s5 = peg$parseWhitespace(); + if (s5 === peg$FAILED) { + s5 = peg$parseComment(); + } + } + if (s4 !== peg$FAILED) { + s5 = peg$currPos; + s6 = peg$parseNewline(); + if (s6 !== peg$FAILED) { + s7 = peg$parseExpressions(); + if (s7 !== peg$FAILED) { + s6 = [s6, s7]; + s5 = s6; + } else { + peg$currPos = s5; + s5 = peg$FAILED; + } + } else { + peg$currPos = s5; + s5 = peg$FAILED; + } + if (s5 === peg$FAILED) { + s5 = null; + } + if (s5 !== peg$FAILED) { + s3 = [s3, s4, s5]; + s2 = s3; + } else { + peg$currPos = s2; + s2 = peg$FAILED; + } + } else { + peg$currPos = s2; + s2 = peg$FAILED; + } + } else { + peg$currPos = s2; + s2 = peg$FAILED; + } + if (s2 === peg$FAILED) { + s2 = null; + } + if (s2 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c0(); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + + return s0; + } + + function peg$parseExpression() { + var s0, s1; + + s0 = peg$currPos; + s1 = peg$parseTableArrayHeader(); + if (s1 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c1(s1); + } + s0 = s1; + if (s0 === peg$FAILED) { + s0 = peg$currPos; + s1 = peg$parseTableHeader(); + if (s1 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c2(s1); + } + s0 = s1; + if (s0 === peg$FAILED) { + s0 = peg$currPos; + s1 = peg$parseKeyValue(); + if (s1 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c3(s1); + } + s0 = s1; + } + } + + return s0; + } + + function peg$parseNewline() { + var s0; + + peg$silentFails++; + if (input.charCodeAt(peg$currPos) === 10) { + s0 = peg$c5; + peg$currPos++; + } else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c6); } + } + if (s0 === peg$FAILED) { + if (input.substr(peg$currPos, 2) === peg$c7) { + s0 = peg$c7; + peg$currPos += 2; + } else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c8); } + } + } + peg$silentFails--; + if (s0 === peg$FAILED) { + if (peg$silentFails === 0) { peg$fail(peg$c4); } + } + + return s0; + } + + function peg$parseWhitespace() { + var s0; + + peg$silentFails++; + if (peg$c10.test(input.charAt(peg$currPos))) { + s0 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c11); } + } + peg$silentFails--; + if (s0 === peg$FAILED) { + if (peg$silentFails === 0) { peg$fail(peg$c9); } + } + + return s0; + } + + function peg$parseComment() { + var s0, s1, s2, s3, s4, s5; + + peg$silentFails++; + s0 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 35) { + s1 = peg$c13; + peg$currPos++; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c14); } + } + if (s1 !== peg$FAILED) { + s2 = []; + s3 = peg$currPos; + s4 = peg$currPos; + peg$silentFails++; + s5 = peg$parseNewline(); + peg$silentFails--; + if (s5 === peg$FAILED) { + s4 = void 0; + } else { + peg$currPos = s4; + s4 = peg$FAILED; + } + if (s4 !== peg$FAILED) { + if (input.length > peg$currPos) { + s5 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s5 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c15); } + } + if (s5 !== peg$FAILED) { + s4 = [s4, s5]; + s3 = s4; + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + while (s3 !== peg$FAILED) { + s2.push(s3); + s3 = peg$currPos; + s4 = peg$currPos; + peg$silentFails++; + s5 = peg$parseNewline(); + peg$silentFails--; + if (s5 === peg$FAILED) { + s4 = void 0; + } else { + peg$currPos = s4; + s4 = peg$FAILED; + } + if (s4 !== peg$FAILED) { + if (input.length > peg$currPos) { + s5 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s5 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c15); } + } + if (s5 !== peg$FAILED) { + s4 = [s4, s5]; + s3 = s4; + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } + if (s2 !== peg$FAILED) { + s1 = [s1, s2]; + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + peg$silentFails--; + if (s0 === peg$FAILED) { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c12); } + } + + return s0; + } + + function peg$parseKeyValue() { + var s0, s1, s2, s3, s4, s5; + + s0 = peg$currPos; + s1 = peg$parseKey(); + if (s1 !== peg$FAILED) { + s2 = []; + s3 = peg$parseWhitespace(); + while (s3 !== peg$FAILED) { + s2.push(s3); + s3 = peg$parseWhitespace(); + } + if (s2 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 61) { + s3 = peg$c16; + peg$currPos++; + } else { + s3 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c17); } + } + if (s3 !== peg$FAILED) { + s4 = []; + s5 = peg$parseWhitespace(); + while (s5 !== peg$FAILED) { + s4.push(s5); + s5 = peg$parseWhitespace(); + } + if (s4 !== peg$FAILED) { + s5 = peg$parseValue(); + if (s5 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c18(s1, s5); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + + return s0; + } + + function peg$parseKey() { + var s0; + + s0 = peg$parseBareKey(); + if (s0 === peg$FAILED) { + s0 = peg$parseQuotedKey(); + } + + return s0; + } + + function peg$parseBareKey() { + var s0, s1, s2; + + s0 = peg$currPos; + s1 = []; + s2 = peg$parseBareKeyCharacter(); + if (s2 !== peg$FAILED) { + while (s2 !== peg$FAILED) { + s1.push(s2); + s2 = peg$parseBareKeyCharacter(); + } + } else { + s1 = peg$FAILED; + } + if (s1 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c19(); + } + s0 = s1; + + return s0; + } + + function peg$parseBareKeyCharacter() { + var s0; + + peg$silentFails++; + if (peg$c21.test(input.charAt(peg$currPos))) { + s0 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c22); } + } + peg$silentFails--; + if (s0 === peg$FAILED) { + if (peg$silentFails === 0) { peg$fail(peg$c20); } + } + + return s0; + } + + function peg$parseQuotedKey() { + var s0, s1, s2, s3; + + s0 = peg$currPos; + s1 = peg$parseDoubleQuote(); + if (s1 !== peg$FAILED) { + s2 = []; + s3 = peg$parseBasicCharacter(); + if (s3 !== peg$FAILED) { + while (s3 !== peg$FAILED) { + s2.push(s3); + s3 = peg$parseBasicCharacter(); + } + } else { + s2 = peg$FAILED; + } + if (s2 !== peg$FAILED) { + s3 = peg$parseDoubleQuote(); + if (s3 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c23(s2); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + + return s0; + } + + function peg$parseDoubleQuote() { + var s0; + + peg$silentFails++; + if (input.charCodeAt(peg$currPos) === 34) { + s0 = peg$c25; + peg$currPos++; + } else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c26); } + } + peg$silentFails--; + if (s0 === peg$FAILED) { + if (peg$silentFails === 0) { peg$fail(peg$c24); } + } + + return s0; + } + + function peg$parseSingleQuote() { + var s0; + + peg$silentFails++; + if (input.charCodeAt(peg$currPos) === 39) { + s0 = peg$c28; + peg$currPos++; + } else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c29); } + } + peg$silentFails--; + if (s0 === peg$FAILED) { + if (peg$silentFails === 0) { peg$fail(peg$c27); } + } + + return s0; + } + + function peg$parseThreeDoubleQuotes() { + var s0; + + peg$silentFails++; + if (input.substr(peg$currPos, 3) === peg$c31) { + s0 = peg$c31; + peg$currPos += 3; + } else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c32); } + } + peg$silentFails--; + if (s0 === peg$FAILED) { + if (peg$silentFails === 0) { peg$fail(peg$c30); } + } + + return s0; + } + + function peg$parseThreeSingleQuotes() { + var s0; + + peg$silentFails++; + if (input.substr(peg$currPos, 3) === peg$c34) { + s0 = peg$c34; + peg$currPos += 3; + } else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c35); } + } + peg$silentFails--; + if (s0 === peg$FAILED) { + if (peg$silentFails === 0) { peg$fail(peg$c33); } + } + + return s0; + } + + function peg$parseValue() { + var s0; + + s0 = peg$parseString(); + if (s0 === peg$FAILED) { + s0 = peg$parseBoolean(); + if (s0 === peg$FAILED) { + s0 = peg$parseDateTime(); + if (s0 === peg$FAILED) { + s0 = peg$parseFloat(); + if (s0 === peg$FAILED) { + s0 = peg$parseInteger(); + if (s0 === peg$FAILED) { + s0 = peg$parseArray(); + if (s0 === peg$FAILED) { + s0 = peg$parseInlineTable(); + } + } + } + } + } + } + + return s0; + } + + function peg$parseString() { + var s0; + + s0 = peg$parseMultilineBasicString(); + if (s0 === peg$FAILED) { + s0 = peg$parseBasicString(); + if (s0 === peg$FAILED) { + s0 = peg$parseMultilineLiteralString(); + if (s0 === peg$FAILED) { + s0 = peg$parseLiteralString(); + } + } + } + + return s0; + } + + function peg$parseBasicString() { + var s0, s1, s2, s3; + + s0 = peg$currPos; + s1 = peg$parseDoubleQuote(); + if (s1 !== peg$FAILED) { + s2 = []; + s3 = peg$parseBasicCharacter(); + while (s3 !== peg$FAILED) { + s2.push(s3); + s3 = peg$parseBasicCharacter(); + } + if (s2 !== peg$FAILED) { + s3 = peg$parseDoubleQuote(); + if (s3 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c36(s2); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + + return s0; + } + + function peg$parseBasicCharacter() { + var s0; + + s0 = peg$parseNormalCharacter(); + if (s0 === peg$FAILED) { + s0 = peg$parseEscapedCharacter(); + } + + return s0; + } + + function peg$parseNormalCharacter() { + var s0, s1, s2; + + peg$silentFails++; + s0 = peg$currPos; + s1 = peg$currPos; + peg$silentFails++; + s2 = peg$parseNewline(); + peg$silentFails--; + if (s2 === peg$FAILED) { + s1 = void 0; + } else { + peg$currPos = s1; + s1 = peg$FAILED; + } + if (s1 !== peg$FAILED) { + if (peg$c38.test(input.charAt(peg$currPos))) { + s2 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c39); } + } + if (s2 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c19(); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + peg$silentFails--; + if (s0 === peg$FAILED) { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c37); } + } + + return s0; + } + + function peg$parseEscapedCharacter() { + var s0, s1, s2, s3, s4; + + s0 = peg$currPos; + s1 = peg$parseBackslash(); + if (s1 !== peg$FAILED) { + s2 = peg$parseControlCharacter(); + if (s2 === peg$FAILED) { + s2 = peg$parseDoubleQuote(); + if (s2 === peg$FAILED) { + s2 = peg$parseBackslash(); + if (s2 === peg$FAILED) { + s2 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 117) { + s3 = peg$c40; + peg$currPos++; + } else { + s3 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c41); } + } + if (s3 !== peg$FAILED) { + s4 = peg$parseFourHexadecimalDigits(); + if (s4 !== peg$FAILED) { + s3 = [s3, s4]; + s2 = s3; + } else { + peg$currPos = s2; + s2 = peg$FAILED; + } + } else { + peg$currPos = s2; + s2 = peg$FAILED; + } + if (s2 === peg$FAILED) { + s2 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 85) { + s3 = peg$c42; + peg$currPos++; + } else { + s3 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c43); } + } + if (s3 !== peg$FAILED) { + s4 = peg$parseEightHexadecimalDigits(); + if (s4 !== peg$FAILED) { + s3 = [s3, s4]; + s2 = s3; + } else { + peg$currPos = s2; + s2 = peg$FAILED; + } + } else { + peg$currPos = s2; + s2 = peg$FAILED; + } + } + } + } + } + if (s2 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c44(); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + + return s0; + } + + function peg$parseControlCharacter() { + var s0; + + peg$silentFails++; + if (peg$c46.test(input.charAt(peg$currPos))) { + s0 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c47); } + } + peg$silentFails--; + if (s0 === peg$FAILED) { + if (peg$silentFails === 0) { peg$fail(peg$c45); } + } + + return s0; + } + + function peg$parseBackslash() { + var s0; + + peg$silentFails++; + if (input.charCodeAt(peg$currPos) === 92) { + s0 = peg$c49; + peg$currPos++; + } else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c50); } + } + peg$silentFails--; + if (s0 === peg$FAILED) { + if (peg$silentFails === 0) { peg$fail(peg$c48); } + } + + return s0; + } + + function peg$parseFourHexadecimalDigits() { + var s0, s1, s2, s3, s4; + + peg$silentFails++; + s0 = peg$currPos; + s1 = peg$parseHexDigit(); + if (s1 !== peg$FAILED) { + s2 = peg$parseHexDigit(); + if (s2 !== peg$FAILED) { + s3 = peg$parseHexDigit(); + if (s3 !== peg$FAILED) { + s4 = peg$parseHexDigit(); + if (s4 !== peg$FAILED) { + s1 = [s1, s2, s3, s4]; + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + peg$silentFails--; + if (s0 === peg$FAILED) { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c51); } + } + + return s0; + } + + function peg$parseEightHexadecimalDigits() { + var s0, s1, s2, s3, s4, s5, s6, s7, s8; + + peg$silentFails++; + s0 = peg$currPos; + s1 = peg$parseHexDigit(); + if (s1 !== peg$FAILED) { + s2 = peg$parseHexDigit(); + if (s2 !== peg$FAILED) { + s3 = peg$parseHexDigit(); + if (s3 !== peg$FAILED) { + s4 = peg$parseHexDigit(); + if (s4 !== peg$FAILED) { + s5 = peg$parseHexDigit(); + if (s5 !== peg$FAILED) { + s6 = peg$parseHexDigit(); + if (s6 !== peg$FAILED) { + s7 = peg$parseHexDigit(); + if (s7 !== peg$FAILED) { + s8 = peg$parseHexDigit(); + if (s8 !== peg$FAILED) { + s1 = [s1, s2, s3, s4, s5, s6, s7, s8]; + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + peg$silentFails--; + if (s0 === peg$FAILED) { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c52); } + } + + return s0; + } + + function peg$parseHexDigit() { + var s0; + + if (peg$c53.test(input.charAt(peg$currPos))) { + s0 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c54); } + } + + return s0; + } + + function peg$parseLiteralString() { + var s0, s1, s2, s3; + + s0 = peg$currPos; + s1 = peg$parseSingleQuote(); + if (s1 !== peg$FAILED) { + s2 = []; + s3 = peg$parseLiteralCharacter(); + while (s3 !== peg$FAILED) { + s2.push(s3); + s3 = peg$parseLiteralCharacter(); + } + if (s2 !== peg$FAILED) { + s3 = peg$parseSingleQuote(); + if (s3 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c55(); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + + return s0; + } + + function peg$parseLiteralCharacter() { + var s0, s1, s2; + + peg$silentFails++; + s0 = peg$currPos; + s1 = peg$currPos; + peg$silentFails++; + s2 = peg$parseNewline(); + peg$silentFails--; + if (s2 === peg$FAILED) { + s1 = void 0; + } else { + peg$currPos = s1; + s1 = peg$FAILED; + } + if (s1 !== peg$FAILED) { + if (peg$c56.test(input.charAt(peg$currPos))) { + s2 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c57); } + } + if (s2 !== peg$FAILED) { + s1 = [s1, s2]; + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + peg$silentFails--; + if (s0 === peg$FAILED) { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c37); } + } + + return s0; + } + + function peg$parseMultilineBasicString() { + var s0, s1, s2, s3, s4; + + s0 = peg$currPos; + s1 = peg$parseThreeDoubleQuotes(); + if (s1 !== peg$FAILED) { + s2 = peg$parseNewline(); + if (s2 === peg$FAILED) { + s2 = null; + } + if (s2 !== peg$FAILED) { + s3 = []; + s4 = peg$parseMultilineBasicText(); + while (s4 !== peg$FAILED) { + s3.push(s4); + s4 = peg$parseMultilineBasicText(); + } + if (s3 !== peg$FAILED) { + s4 = peg$parseThreeDoubleQuotes(); + if (s4 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c58(s3); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + + return s0; + } + + function peg$parseMultilineBasicText() { + var s0, s1, s2; + + s0 = peg$parseMultilineBasicCharacter(); + if (s0 === peg$FAILED) { + s0 = peg$currPos; + s1 = peg$parseBackslash(); + if (s1 !== peg$FAILED) { + s2 = peg$parseNewline(); + if (s2 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c19(); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + if (s0 === peg$FAILED) { + s0 = peg$parseNewline(); + } + } + + return s0; + } + + function peg$parseMultilineBasicCharacter() { + var s0, s1, s2; + + s0 = peg$currPos; + s1 = peg$currPos; + peg$silentFails++; + s2 = peg$parseThreeDoubleQuotes(); + peg$silentFails--; + if (s2 === peg$FAILED) { + s1 = void 0; + } else { + peg$currPos = s1; + s1 = peg$FAILED; + } + if (s1 !== peg$FAILED) { + s2 = peg$parseMultilineNormalCharacter(); + if (s2 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c19(); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + if (s0 === peg$FAILED) { + s0 = peg$parseEscapedCharacter(); + } + + return s0; + } + + function peg$parseMultilineNormalCharacter() { + var s0, s1, s2; + + peg$silentFails++; + s0 = peg$currPos; + s1 = peg$currPos; + peg$silentFails++; + s2 = peg$parseNewline(); + peg$silentFails--; + if (s2 === peg$FAILED) { + s1 = void 0; + } else { + peg$currPos = s1; + s1 = peg$FAILED; + } + if (s1 !== peg$FAILED) { + if (peg$c59.test(input.charAt(peg$currPos))) { + s2 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c60); } + } + if (s2 !== peg$FAILED) { + s1 = [s1, s2]; + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + peg$silentFails--; + if (s0 === peg$FAILED) { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c37); } + } + + return s0; + } + + function peg$parseMultilineLiteralString() { + var s0, s1, s2, s3, s4; + + s0 = peg$currPos; + s1 = peg$parseThreeSingleQuotes(); + if (s1 !== peg$FAILED) { + s2 = peg$parseNewline(); + if (s2 === peg$FAILED) { + s2 = null; + } + if (s2 !== peg$FAILED) { + s3 = []; + s4 = peg$parseMultilineLiteralText(); + while (s4 !== peg$FAILED) { + s3.push(s4); + s4 = peg$parseMultilineLiteralText(); + } + if (s3 !== peg$FAILED) { + s4 = peg$parseThreeSingleQuotes(); + if (s4 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c36(s3); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + + return s0; + } + + function peg$parseMultilineLiteralText() { + var s0, s1, s2; + + s0 = peg$currPos; + s1 = peg$currPos; + peg$silentFails++; + if (input.substr(peg$currPos, 3) === peg$c34) { + s2 = peg$c34; + peg$currPos += 3; + } else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c35); } + } + peg$silentFails--; + if (s2 === peg$FAILED) { + s1 = void 0; + } else { + peg$currPos = s1; + s1 = peg$FAILED; + } + if (s1 !== peg$FAILED) { + s2 = peg$parseMultilineLiteralCharacter(); + if (s2 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c19(); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + if (s0 === peg$FAILED) { + s0 = peg$parseNewline(); + } + + return s0; + } + + function peg$parseMultilineLiteralCharacter() { + var s0, s1, s2; + + peg$silentFails++; + s0 = peg$currPos; + s1 = peg$currPos; + peg$silentFails++; + s2 = peg$parseNewline(); + peg$silentFails--; + if (s2 === peg$FAILED) { + s1 = void 0; + } else { + peg$currPos = s1; + s1 = peg$FAILED; + } + if (s1 !== peg$FAILED) { + if (peg$c62.test(input.charAt(peg$currPos))) { + s2 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c63); } + } + if (s2 !== peg$FAILED) { + s1 = [s1, s2]; + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + peg$silentFails--; + if (s0 === peg$FAILED) { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c61); } + } + + return s0; + } + + function peg$parseBoolean() { + var s0, s1; + + s0 = peg$currPos; + if (input.substr(peg$currPos, 4) === peg$c64) { + s1 = peg$c64; + peg$currPos += 4; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c65); } + } + if (s1 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c66(); + } + s0 = s1; + if (s0 === peg$FAILED) { + s0 = peg$currPos; + if (input.substr(peg$currPos, 5) === peg$c67) { + s1 = peg$c67; + peg$currPos += 5; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c68); } + } + if (s1 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c69(); + } + s0 = s1; + } + + return s0; + } + + function peg$parseFloat() { + var s0, s1, s2, s3, s4; + + s0 = peg$currPos; + s1 = peg$parseInteger(); + if (s1 !== peg$FAILED) { + s2 = peg$currPos; + s3 = peg$parseFraction(); + if (s3 !== peg$FAILED) { + s4 = peg$parseExponent(); + if (s4 === peg$FAILED) { + s4 = null; + } + if (s4 !== peg$FAILED) { + s3 = [s3, s4]; + s2 = s3; + } else { + peg$currPos = s2; + s2 = peg$FAILED; + } + } else { + peg$currPos = s2; + s2 = peg$FAILED; + } + if (s2 === peg$FAILED) { + s2 = peg$parseExponent(); + } + if (s2 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c70(); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + + return s0; + } + + function peg$parseFraction() { + var s0, s1, s2, s3, s4, s5, s6; + + s0 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 46) { + s1 = peg$c71; + peg$currPos++; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c72); } + } + if (s1 !== peg$FAILED) { + s2 = peg$parseDigit(); + if (s2 !== peg$FAILED) { + s3 = []; + s4 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 95) { + s5 = peg$c73; + peg$currPos++; + } else { + s5 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c74); } + } + if (s5 === peg$FAILED) { + s5 = null; + } + if (s5 !== peg$FAILED) { + s6 = peg$parseDigit(); + if (s6 !== peg$FAILED) { + s5 = [s5, s6]; + s4 = s5; + } else { + peg$currPos = s4; + s4 = peg$FAILED; + } + } else { + peg$currPos = s4; + s4 = peg$FAILED; + } + while (s4 !== peg$FAILED) { + s3.push(s4); + s4 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 95) { + s5 = peg$c73; + peg$currPos++; + } else { + s5 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c74); } + } + if (s5 === peg$FAILED) { + s5 = null; + } + if (s5 !== peg$FAILED) { + s6 = peg$parseDigit(); + if (s6 !== peg$FAILED) { + s5 = [s5, s6]; + s4 = s5; + } else { + peg$currPos = s4; + s4 = peg$FAILED; + } + } else { + peg$currPos = s4; + s4 = peg$FAILED; + } + } + if (s3 !== peg$FAILED) { + s1 = [s1, s2, s3]; + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + + return s0; + } + + function peg$parseExponent() { + var s0, s1, s2; + + s0 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 101) { + s1 = peg$c75; + peg$currPos++; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c76); } + } + if (s1 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 69) { + s1 = peg$c77; + peg$currPos++; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c78); } + } + } + if (s1 !== peg$FAILED) { + s2 = peg$parseInteger(); + if (s2 !== peg$FAILED) { + s1 = [s1, s2]; + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + + return s0; + } + + function peg$parseInteger() { + var s0, s1, s2; + + s0 = peg$currPos; + s1 = peg$parseSign(); + if (s1 === peg$FAILED) { + s1 = null; + } + if (s1 !== peg$FAILED) { + s2 = peg$parseIntDigits(); + if (s2 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c79(); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + + return s0; + } + + function peg$parseSign() { + var s0; + + if (input.charCodeAt(peg$currPos) === 43) { + s0 = peg$c80; + peg$currPos++; + } else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c81); } + } + if (s0 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 45) { + s0 = peg$c82; + peg$currPos++; + } else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c83); } + } + } + + return s0; + } + + function peg$parseIntDigits() { + var s0, s1, s2, s3, s4, s5; + + s0 = peg$currPos; + s1 = peg$parseDigit_1to9(); + if (s1 !== peg$FAILED) { + s2 = []; + s3 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 95) { + s4 = peg$c73; + peg$currPos++; + } else { + s4 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c74); } + } + if (s4 === peg$FAILED) { + s4 = null; + } + if (s4 !== peg$FAILED) { + s5 = peg$parseDigit(); + if (s5 !== peg$FAILED) { + s4 = [s4, s5]; + s3 = s4; + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + if (s3 !== peg$FAILED) { + while (s3 !== peg$FAILED) { + s2.push(s3); + s3 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 95) { + s4 = peg$c73; + peg$currPos++; + } else { + s4 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c74); } + } + if (s4 === peg$FAILED) { + s4 = null; + } + if (s4 !== peg$FAILED) { + s5 = peg$parseDigit(); + if (s5 !== peg$FAILED) { + s4 = [s4, s5]; + s3 = s4; + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } + } else { + s2 = peg$FAILED; + } + if (s2 !== peg$FAILED) { + s1 = [s1, s2]; + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + if (s0 === peg$FAILED) { + s0 = peg$parseDigit(); + } + + return s0; + } + + function peg$parseDigit_1to9() { + var s0; + + if (peg$c84.test(input.charAt(peg$currPos))) { + s0 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c85); } + } + + return s0; + } + + function peg$parseDigit() { + var s0; + + if (peg$c86.test(input.charAt(peg$currPos))) { + s0 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c87); } + } + + return s0; + } + + function peg$parseDateTime() { + var s0, s1, s2, s3; + + s0 = peg$currPos; + s1 = peg$parseFullDate(); + if (s1 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 84) { + s2 = peg$c88; + peg$currPos++; + } else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c89); } + } + if (s2 !== peg$FAILED) { + s3 = peg$parseFullTime(); + if (s3 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c90(); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + + return s0; + } + + function peg$parseFullDate() { + var s0, s1, s2, s3, s4, s5; + + peg$silentFails++; + s0 = peg$currPos; + s1 = peg$parseYear(); + if (s1 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 45) { + s2 = peg$c82; + peg$currPos++; + } else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c83); } + } + if (s2 !== peg$FAILED) { + s3 = peg$parseMonth(); + if (s3 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 45) { + s4 = peg$c82; + peg$currPos++; + } else { + s4 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c83); } + } + if (s4 !== peg$FAILED) { + s5 = peg$parseMDay(); + if (s5 !== peg$FAILED) { + s1 = [s1, s2, s3, s4, s5]; + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + peg$silentFails--; + if (s0 === peg$FAILED) { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c91); } + } + + return s0; + } + + function peg$parseYear() { + var s0, s1, s2, s3, s4; + + s0 = peg$currPos; + s1 = peg$parseDigit(); + if (s1 !== peg$FAILED) { + s2 = peg$parseDigit(); + if (s2 !== peg$FAILED) { + s3 = peg$parseDigit(); + if (s3 !== peg$FAILED) { + s4 = peg$parseDigit(); + if (s4 !== peg$FAILED) { + s1 = [s1, s2, s3, s4]; + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + + return s0; + } + + function peg$parseMonth() { + var s0, s1, s2; + + s0 = peg$currPos; + s1 = peg$parseDigit(); + if (s1 !== peg$FAILED) { + s2 = peg$parseDigit(); + if (s2 !== peg$FAILED) { + s1 = [s1, s2]; + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + + return s0; + } + + function peg$parseMDay() { + var s0, s1, s2; + + s0 = peg$currPos; + s1 = peg$parseDigit(); + if (s1 !== peg$FAILED) { + s2 = peg$parseDigit(); + if (s2 !== peg$FAILED) { + s1 = [s1, s2]; + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + + return s0; + } + + function peg$parseFullTime() { + var s0, s1, s2; + + s0 = peg$currPos; + s1 = peg$parseTime(); + if (s1 !== peg$FAILED) { + s2 = peg$parseTimeOffset(); + if (s2 !== peg$FAILED) { + s1 = [s1, s2]; + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + + return s0; + } + + function peg$parseTime() { + var s0, s1, s2, s3, s4, s5, s6; + + s0 = peg$currPos; + s1 = peg$parseHour(); + if (s1 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 58) { + s2 = peg$c92; + peg$currPos++; + } else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c93); } + } + if (s2 !== peg$FAILED) { + s3 = peg$parseMinute(); + if (s3 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 58) { + s4 = peg$c92; + peg$currPos++; + } else { + s4 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c93); } + } + if (s4 !== peg$FAILED) { + s5 = peg$parseSecond(); + if (s5 !== peg$FAILED) { + s6 = peg$parseSecondFraction(); + if (s6 === peg$FAILED) { + s6 = null; + } + if (s6 !== peg$FAILED) { + s1 = [s1, s2, s3, s4, s5, s6]; + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + + return s0; + } + + function peg$parseHour() { + var s0, s1, s2; + + peg$silentFails++; + s0 = peg$currPos; + s1 = peg$parseDigit(); + if (s1 !== peg$FAILED) { + s2 = peg$parseDigit(); + if (s2 !== peg$FAILED) { + s1 = [s1, s2]; + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + peg$silentFails--; + if (s0 === peg$FAILED) { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c94); } + } + + return s0; + } + + function peg$parseMinute() { + var s0, s1, s2; + + peg$silentFails++; + s0 = peg$currPos; + s1 = peg$parseDigit(); + if (s1 !== peg$FAILED) { + s2 = peg$parseDigit(); + if (s2 !== peg$FAILED) { + s1 = [s1, s2]; + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + peg$silentFails--; + if (s0 === peg$FAILED) { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c95); } + } + + return s0; + } + + function peg$parseSecond() { + var s0, s1, s2; + + peg$silentFails++; + s0 = peg$currPos; + s1 = peg$parseDigit(); + if (s1 !== peg$FAILED) { + s2 = peg$parseDigit(); + if (s2 !== peg$FAILED) { + s1 = [s1, s2]; + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + peg$silentFails--; + if (s0 === peg$FAILED) { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c96); } + } + + return s0; + } + + function peg$parseSecondFraction() { + var s0, s1, s2, s3; + + s0 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 46) { + s1 = peg$c71; + peg$currPos++; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c72); } + } + if (s1 !== peg$FAILED) { + s2 = []; + s3 = peg$parseDigit(); + if (s3 !== peg$FAILED) { + while (s3 !== peg$FAILED) { + s2.push(s3); + s3 = peg$parseDigit(); + } + } else { + s2 = peg$FAILED; + } + if (s2 !== peg$FAILED) { + s1 = [s1, s2]; + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + + return s0; + } + + function peg$parseTimeOffset() { + var s0, s1, s2, s3, s4; + + peg$silentFails++; + if (input.charCodeAt(peg$currPos) === 90) { + s0 = peg$c98; + peg$currPos++; + } else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c99); } + } + if (s0 === peg$FAILED) { + s0 = peg$currPos; + s1 = peg$parseSign(); + if (s1 !== peg$FAILED) { + s2 = peg$parseHour(); + if (s2 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 58) { + s3 = peg$c92; + peg$currPos++; + } else { + s3 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c93); } + } + if (s3 !== peg$FAILED) { + s4 = peg$parseMinute(); + if (s4 !== peg$FAILED) { + s1 = [s1, s2, s3, s4]; + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + peg$silentFails--; + if (s0 === peg$FAILED) { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c97); } + } + + return s0; + } + + function peg$parseArray() { + var s0, s1, s2, s3, s4, s5, s6, s7, s8, s9; + + s0 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 91) { + s1 = peg$c100; + peg$currPos++; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c101); } + } + if (s1 !== peg$FAILED) { + s2 = []; + s3 = peg$parseArraySpace(); + while (s3 !== peg$FAILED) { + s2.push(s3); + s3 = peg$parseArraySpace(); + } + if (s2 !== peg$FAILED) { + s3 = peg$currPos; + s4 = peg$parseArrayValue(); + if (s4 !== peg$FAILED) { + s5 = []; + s6 = peg$parseArraySpace(); + while (s6 !== peg$FAILED) { + s5.push(s6); + s6 = peg$parseArraySpace(); + } + if (s5 !== peg$FAILED) { + s6 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 44) { + s7 = peg$c102; + peg$currPos++; + } else { + s7 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c103); } + } + if (s7 !== peg$FAILED) { + s8 = []; + s9 = peg$parseArraySpace(); + while (s9 !== peg$FAILED) { + s8.push(s9); + s9 = peg$parseArraySpace(); + } + if (s8 !== peg$FAILED) { + s7 = [s7, s8]; + s6 = s7; + } else { + peg$currPos = s6; + s6 = peg$FAILED; + } + } else { + peg$currPos = s6; + s6 = peg$FAILED; + } + if (s6 === peg$FAILED) { + s6 = null; + } + if (s6 !== peg$FAILED) { + s4 = [s4, s5, s6]; + s3 = s4; + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + if (s3 === peg$FAILED) { + s3 = null; + } + if (s3 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 93) { + s4 = peg$c104; + peg$currPos++; + } else { + s4 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c105); } + } + if (s4 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c106(s3); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + + return s0; + } + + function peg$parseArrayValue() { + var s0, s1, s2, s3, s4, s5, s6; + + s0 = peg$currPos; + s1 = peg$parseValue(); + if (s1 !== peg$FAILED) { + s2 = peg$currPos; + s3 = []; + s4 = peg$parseArraySpace(); + while (s4 !== peg$FAILED) { + s3.push(s4); + s4 = peg$parseArraySpace(); + } + if (s3 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 44) { + s4 = peg$c102; + peg$currPos++; + } else { + s4 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c103); } + } + if (s4 !== peg$FAILED) { + s5 = []; + s6 = peg$parseArraySpace(); + while (s6 !== peg$FAILED) { + s5.push(s6); + s6 = peg$parseArraySpace(); + } + if (s5 !== peg$FAILED) { + s6 = peg$parseArrayValue(); + if (s6 !== peg$FAILED) { + s3 = [s3, s4, s5, s6]; + s2 = s3; + } else { + peg$currPos = s2; + s2 = peg$FAILED; + } + } else { + peg$currPos = s2; + s2 = peg$FAILED; + } + } else { + peg$currPos = s2; + s2 = peg$FAILED; + } + } else { + peg$currPos = s2; + s2 = peg$FAILED; + } + if (s2 === peg$FAILED) { + s2 = null; + } + if (s2 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c107(s1, s2); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + + return s0; + } + + function peg$parseArraySpace() { + var s0; + + s0 = peg$parseWhitespace(); + if (s0 === peg$FAILED) { + s0 = peg$parseNewline(); + if (s0 === peg$FAILED) { + s0 = peg$parseComment(); + } + } + + return s0; + } + + function peg$parseInlineTable() { + var s0, s1, s2, s3, s4, s5, s6, s7, s8, s9, s10; + + s0 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 123) { + s1 = peg$c108; + peg$currPos++; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c109); } + } + if (s1 !== peg$FAILED) { + s2 = []; + s3 = peg$parseWhitespace(); + while (s3 !== peg$FAILED) { + s2.push(s3); + s3 = peg$parseWhitespace(); + } + if (s2 !== peg$FAILED) { + s3 = peg$currPos; + s4 = peg$parseKeyValue(); + if (s4 !== peg$FAILED) { + s5 = []; + s6 = peg$currPos; + s7 = []; + s8 = peg$parseWhitespace(); + while (s8 !== peg$FAILED) { + s7.push(s8); + s8 = peg$parseWhitespace(); + } + if (s7 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 44) { + s8 = peg$c102; + peg$currPos++; + } else { + s8 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c103); } + } + if (s8 !== peg$FAILED) { + s9 = []; + s10 = peg$parseWhitespace(); + while (s10 !== peg$FAILED) { + s9.push(s10); + s10 = peg$parseWhitespace(); + } + if (s9 !== peg$FAILED) { + s10 = peg$parseKeyValue(); + if (s10 !== peg$FAILED) { + s7 = [s7, s8, s9, s10]; + s6 = s7; + } else { + peg$currPos = s6; + s6 = peg$FAILED; + } + } else { + peg$currPos = s6; + s6 = peg$FAILED; + } + } else { + peg$currPos = s6; + s6 = peg$FAILED; + } + } else { + peg$currPos = s6; + s6 = peg$FAILED; + } + while (s6 !== peg$FAILED) { + s5.push(s6); + s6 = peg$currPos; + s7 = []; + s8 = peg$parseWhitespace(); + while (s8 !== peg$FAILED) { + s7.push(s8); + s8 = peg$parseWhitespace(); + } + if (s7 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 44) { + s8 = peg$c102; + peg$currPos++; + } else { + s8 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c103); } + } + if (s8 !== peg$FAILED) { + s9 = []; + s10 = peg$parseWhitespace(); + while (s10 !== peg$FAILED) { + s9.push(s10); + s10 = peg$parseWhitespace(); + } + if (s9 !== peg$FAILED) { + s10 = peg$parseKeyValue(); + if (s10 !== peg$FAILED) { + s7 = [s7, s8, s9, s10]; + s6 = s7; + } else { + peg$currPos = s6; + s6 = peg$FAILED; + } + } else { + peg$currPos = s6; + s6 = peg$FAILED; + } + } else { + peg$currPos = s6; + s6 = peg$FAILED; + } + } else { + peg$currPos = s6; + s6 = peg$FAILED; + } + } + if (s5 !== peg$FAILED) { + s6 = []; + s7 = peg$parseWhitespace(); + while (s7 !== peg$FAILED) { + s6.push(s7); + s7 = peg$parseWhitespace(); + } + if (s6 !== peg$FAILED) { + s4 = [s4, s5, s6]; + s3 = s4; + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + if (s3 === peg$FAILED) { + s3 = null; + } + if (s3 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 125) { + s4 = peg$c110; + peg$currPos++; + } else { + s4 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c111); } + } + if (s4 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c112(s3); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + + return s0; + } + + function peg$parseTableArrayHeader() { + var s0, s1, s2, s3; + + s0 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 91) { + s1 = peg$c100; + peg$currPos++; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c101); } + } + if (s1 !== peg$FAILED) { + s2 = peg$parseTableHeader(); + if (s2 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 93) { + s3 = peg$c104; + peg$currPos++; + } else { + s3 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c105); } + } + if (s3 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c113(s2); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + + return s0; + } + + function peg$parseTableHeader() { + var s0, s1, s2, s3, s4, s5, s6, s7, s8, s9; + + s0 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 91) { + s1 = peg$c100; + peg$currPos++; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c101); } + } + if (s1 !== peg$FAILED) { + s2 = []; + s3 = peg$parseWhitespace(); + while (s3 !== peg$FAILED) { + s2.push(s3); + s3 = peg$parseWhitespace(); + } + if (s2 !== peg$FAILED) { + s3 = peg$parseKey(); + if (s3 !== peg$FAILED) { + s4 = []; + s5 = peg$currPos; + s6 = []; + s7 = peg$parseWhitespace(); + while (s7 !== peg$FAILED) { + s6.push(s7); + s7 = peg$parseWhitespace(); + } + if (s6 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 46) { + s7 = peg$c71; + peg$currPos++; + } else { + s7 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c72); } + } + if (s7 !== peg$FAILED) { + s8 = []; + s9 = peg$parseWhitespace(); + while (s9 !== peg$FAILED) { + s8.push(s9); + s9 = peg$parseWhitespace(); + } + if (s8 !== peg$FAILED) { + s9 = peg$parseKey(); + if (s9 !== peg$FAILED) { + s6 = [s6, s7, s8, s9]; + s5 = s6; + } else { + peg$currPos = s5; + s5 = peg$FAILED; + } + } else { + peg$currPos = s5; + s5 = peg$FAILED; + } + } else { + peg$currPos = s5; + s5 = peg$FAILED; + } + } else { + peg$currPos = s5; + s5 = peg$FAILED; + } + while (s5 !== peg$FAILED) { + s4.push(s5); + s5 = peg$currPos; + s6 = []; + s7 = peg$parseWhitespace(); + while (s7 !== peg$FAILED) { + s6.push(s7); + s7 = peg$parseWhitespace(); + } + if (s6 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 46) { + s7 = peg$c71; + peg$currPos++; + } else { + s7 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c72); } + } + if (s7 !== peg$FAILED) { + s8 = []; + s9 = peg$parseWhitespace(); + while (s9 !== peg$FAILED) { + s8.push(s9); + s9 = peg$parseWhitespace(); + } + if (s8 !== peg$FAILED) { + s9 = peg$parseKey(); + if (s9 !== peg$FAILED) { + s6 = [s6, s7, s8, s9]; + s5 = s6; + } else { + peg$currPos = s5; + s5 = peg$FAILED; + } + } else { + peg$currPos = s5; + s5 = peg$FAILED; + } + } else { + peg$currPos = s5; + s5 = peg$FAILED; + } + } else { + peg$currPos = s5; + s5 = peg$FAILED; + } + } + if (s4 !== peg$FAILED) { + s5 = []; + s6 = peg$parseWhitespace(); + while (s6 !== peg$FAILED) { + s5.push(s6); + s6 = peg$parseWhitespace(); + } + if (s5 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 93) { + s6 = peg$c104; + peg$currPos++; + } else { + s6 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c105); } + } + if (s6 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c114(s3, s4); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + + return s0; + } + + + var genMsgRedefined, isFiniteNumber, isArray, hasOwnProperty, stringify, + unescape, fromCodePoint, checkTableKey, findContext; + + genMsgRedefined = function (key) { + return ('Value for ' + key + ' should not be redefined in the same table.'); }; - return S4() + S4() + '-' + S4() + '-' + S4() + '-' + S4() + '-' + S4() + S4() + S4(); + + isFiniteNumber = Number.isFinite || function (n) { + return typeof n === 'number' && isFinite(n); + }; + + isArray = Array.isArray || function (obj) { + return Object.prototype.toString.call(obj) === '[object Array]'; + }; + + hasOwnProperty = function (obj, key) { + return Object.prototype.hasOwnProperty.call(obj, key); + }; + + stringify = typeof JSON === 'object' && JSON ? JSON.stringify : function (o) { + return '"' + String(o).replace(/[\x00-\x1F"\\]/g, function (c) { + switch (c) { + case '"': case '\\': return '\\' + c; + case '\t': return '\\t'; + case '\n': return '\\n'; + case '\r': return '\\r'; + case '\b': return '\\b'; + case '\f': return '\\f'; + default: + var hex = c.charCodeAt(0).toString(16); + return '\\u' + '0000'.substr(hex.length) + hex; + } + }) + '"'; + }; + + unescape = function (c) { + switch (c) { + case '"': case '\\': return c; + case 't': return '\t'; + case 'n': return '\n'; + case 'r': return '\r'; + case 'b': return '\b'; + case 'f': return '\f'; + default: error(stringify(c) + ' cannot be escaped.'); + } + }; + + fromCodePoint = function (codepoint) { + if (!isFiniteNumber(codepoint) || codepoint < 0 || codepoint > 0x10FFFF) { + error('U+' + codepoint.toString(16) + + ' is not a valid Unicode code point.'); + } + if (String.fromCodePoint) { + return String.fromCodePoint(codepoint); + } + // See: punnycode.ucs2.encode from https://github.com/bestiejs/punycode.js + var c = ''; + if (codepoint > 0xFFFF) { + codepoint -= 0x10000; + c += String.fromCharCode((codepoint >>> 10) & 0x3FF | 0xD800); + codepoint = 0xDC00 | codepoint & 0x3FF; + } + c += String.fromCharCode(codepoint); + return c; + }; + + checkTableKey = function (table, k) { + if (hasOwnProperty(table, k)) { + error(genMsgRedefined(stringify(k))); + } + }; + + findContext = function (table, isTableArray, path) { + var s = ''; + for (var i = 0, l = path.length; i < l; i++) { + var k = path[i]; + s += (s ? '.' : '') + stringify(k); + if (!hasOwnProperty(table, k)) { + if (isTableArray && i + 1 === l) { + var t = {}; + table[k] = [t]; + table = t; + g_table_arrays[s] = true; + } else { + table = table[k] = {}; + g_tables[s] = true; + } + } else { + if (isTableArray) { + if (isArray(table[k])) { + if (!g_table_arrays[s]) { + error(genMsgRedefined(s)); + } + if (i + 1 === l) { + var t = {}; + table[k].push(t); + table = t; + } else { + s += '.' + stringify(table[k].length - 1); + table = table[k][table[k].length-1]; + } + } else { + if (!g_tables[s]) { + error(genMsgRedefined(s)); + } + table = table[k]; + } + } else { + if (isArray(table[k])) { + if (!g_table_arrays[s] || i + 1 === l) { + error(genMsgRedefined(s)); + } + s += '.' + stringify(table[k].length - 1); + table = table[k][table[k].length-1]; + } else { + if (!g_tables[s]) { + error(genMsgRedefined(s)); + } + table = table[k]; + } + } + } + } + if (isTableArray) { + if (!g_table_arrays[s]) { + error(genMsgRedefined(s)); + } + } else { + if (g_defined_tables[s] || g_table_arrays[s]) { + error(genMsgRedefined(s)); + } + g_defined_tables[s] = true; + } + return { + table: table, + path: path + }; + }; + + var g_root = {}; // TOML table + var g_context = { // current context + table: g_root, + path: [] + }; + var g_tables = {}; // paths to tables + var g_defined_tables = {}; // paths to tables directly defined + var g_table_arrays = {}; // paths to table arrays + + + peg$result = peg$startRuleFunction(); + + if (peg$result !== peg$FAILED && peg$currPos === input.length) { + return peg$result; + } else { + if (peg$result !== peg$FAILED && peg$currPos < input.length) { + peg$fail(peg$endExpectation()); + } + + throw peg$buildStructuredError( + peg$maxFailExpected, + peg$maxFailPos < input.length ? input.charAt(peg$maxFailPos) : null, + peg$maxFailPos < input.length + ? peg$computeLocation(peg$maxFailPos, peg$maxFailPos + 1) + : peg$computeLocation(peg$maxFailPos, peg$maxFailPos) + ); + } } - /* - * Display a page-wide error message to show that something has gone wrong with - * PyScript or Pyodide during loading. Probably not be used for issues that occur within - * Python scripts, since stderr can be routed to somewhere in the DOM - */ - function showError(msg) { - const warning = document.createElement('div'); - warning.style.backgroundColor = 'LightCoral'; - warning.style.alignContent = 'center'; - warning.style.margin = '4px'; - warning.style.padding = '4px'; - warning.innerHTML = msg; - document.body.prepend(warning); + + return { + SyntaxError: peg$SyntaxError, + parse: peg$parse + }; + })(); + + function subclass(child, parent) { + function ctor() { + this.constructor = child; } - function handleFetchError(e, singleFile) { - //Should we still export full error contents to console? - console.warn(`Caught an error in loadPaths:\r\n ${e.toString()}`); - let errorContent; - if (e.message.includes('TypeError: Failed to fetch')) { - errorContent = `<p>PyScript: Access to local files - (using "Paths:" in <py-env>) + ctor.prototype = parent.prototype; + child.prototype = new ctor(); + } + + function TomlSyntaxError(message, offset, line, column) { + this.message = message; + this.offset = offset; + this.line = line; + this.column = column; + } + + subclass(TomlSyntaxError, SyntaxError); + + var parser$1 = parser$2; + var toml = { + parse: function (src) { + try { + return parser$1.parse(src); + } catch (err) { + if (err instanceof parser$1.SyntaxError) { + err.line = err.location.start.line; + err.column = err.location.start.column; + err.offset = err.location.start.offset; + throw new TomlSyntaxError( + err.message, + err.location.start.offset, + err.location.start.line, + err.location.start.column); + } else { + throw err; + } + } + }, + SyntaxError: TomlSyntaxError + }; + + var toml_1 = toml; + + /* Very simple logger interface. + + Each module is expected to create its own logger by doing e.g.: + + const logger = getLogger('my-prefix'); + + and then use it instead of console: + + logger.info('hello', 'world'); + logger.warn('...'); + logger.error('...'); + + The logger automatically adds the prefix "[my-prefix]" to all logs. + E.g., the above call would print: + + [my-prefix] hello world + + logger.log is intentionally omitted. The idea is that PyScript should not + write anything to console.log, to leave it free for the user. + + Currently, the logger does not to anything more than that. In the future, + we might want to add additional features such as the ability to + enable/disable logs on a global or per-module basis. + */ + const _cache = new Map(); + function getLogger(prefix) { + let logger = _cache.get(prefix); + if (logger === undefined) { + logger = _makeLogger(prefix); + _cache.set(prefix, logger); + } + return logger; + } + function _makeLogger(prefix) { + prefix = `[${prefix}] `; + function make(level) { + const out_fn = console[level].bind(console); + function fn(fmt, ...args) { + out_fn(prefix + fmt, ...args); + } + return fn; + } + // 'log' is intentionally omitted + const debug = make('debug'); + const info = make('info'); + const warn = make('warn'); + const error = make('error'); + return { debug, info, warn, error }; + } + + /** + * @fileoverview Version of pyscript + * The version is based on calver which contains YEAR.MONTH.DAY.MODIFIER. + * The Modifier can be an optional text tag, such as "dev", "rc", etc. + * + * We are adding this file because we can't add version in main.js due to + * circular imports. + */ + const version = '2022.12.1.dev'; + + const CLOSEBUTTON = `<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 16 16' fill="currentColor" width="12px"><path d='M.293.293a1 1 0 011.414 0L8 6.586 14.293.293a1 1 0 111.414 1.414L9.414 8l6.293 6.293a1 1 0 01-1.414 1.414L8 9.414l-6.293 6.293a1 1 0 01-1.414-1.414L6.586 8 .293 1.707a1 1 0 010-1.414z'/></svg>`; + /* + These error codes are used to identify the type of error that occurred. + The convention is: + * PY0 - errors that occur when fetching + * PY1 - errors that occur in config + * Py2 - errors that occur in plugins + * PY9 - Deprecation errors + */ + var ErrorCode; + (function (ErrorCode) { + ErrorCode["GENERIC"] = "PY0000"; + ErrorCode["FETCH_ERROR"] = "PY0001"; + ErrorCode["FETCH_NAME_ERROR"] = "PY0002"; + // Currently these are created depending on error code received from fetching + ErrorCode["FETCH_UNAUTHORIZED_ERROR"] = "PY0401"; + ErrorCode["FETCH_FORBIDDEN_ERROR"] = "PY0403"; + ErrorCode["FETCH_NOT_FOUND_ERROR"] = "PY0404"; + ErrorCode["FETCH_SERVER_ERROR"] = "PY0500"; + ErrorCode["FETCH_UNAVAILABLE_ERROR"] = "PY0503"; + ErrorCode["BAD_CONFIG"] = "PY1000"; + ErrorCode["MICROPIP_INSTALL_ERROR"] = "PY1001"; + ErrorCode["BAD_PLUGIN_FILE_EXTENSION"] = "PY2000"; + ErrorCode["NO_DEFAULT_EXPORT"] = "PY2001"; + ErrorCode["TOP_LEVEL_AWAIT"] = "PY9000"; + })(ErrorCode || (ErrorCode = {})); + class UserError extends Error { + constructor(errorCode, message, t = 'text') { + super(message); + this.errorCode = errorCode; + this.name = 'UserError'; + this.messageType = t; + this.message = `(${errorCode}): ${message}`; + } + } + class FetchError extends UserError { + constructor(errorCode, message) { + super(errorCode, message); + this.name = 'FetchError'; + } + } + class InstallError extends UserError { + constructor(errorCode, message) { + super(errorCode, message); + this.name = 'InstallError'; + } + } + function _createAlertBanner(message, level = 'error', messageType = 'text', logMessage = true) { + // eslint-disable-next-line @typescript-eslint/restrict-template-expressions + switch (`log-${level}-${logMessage}`) { + case 'log-error-true': + console.error(message); + break; + case 'log-warning-true': + console.warn(message); + break; + } + const banner = document.createElement('div'); + banner.className = `alert-banner py-${level}`; + if (messageType === 'html') { + banner.innerHTML = message; + } + else { + banner.textContent = message; + } + if (level === 'warning') { + const closeButton = document.createElement('button'); + closeButton.id = 'alert-close-button'; + closeButton.addEventListener('click', () => { + banner.remove(); + }); + closeButton.innerHTML = CLOSEBUTTON; + banner.appendChild(closeButton); + } + document.body.prepend(banner); + } + + function escape(str) { + return str.replace(/</g, '<').replace(/>/g, '>'); + } + function htmlDecode(input) { + const doc = new DOMParser().parseFromString(ltrim(escape(input)), 'text/html'); + return doc.documentElement.textContent; + } + function ltrim(code) { + const lines = code.split('\n'); + if (lines.length == 0) + return code; + const lengths = lines + .filter(line => line.trim().length != 0) + .map(line => { + return line.match(/^\s*/)?.pop()?.length; + }); + const k = Math.min(...lengths); + return k != 0 ? lines.map(line => line.substring(k)).join('\n') : code; + } + let _uniqueIdCounter = 0; + function ensureUniqueId(el) { + if (el.id === '') + el.id = `py-internal-${_uniqueIdCounter++}`; + } + function showWarning(msg, messageType = 'text') { + _createAlertBanner(msg, 'warning', messageType); + } + function readTextFromPath(path) { + const request = new XMLHttpRequest(); + request.open('GET', path, false); + request.send(); + const returnValue = request.responseText; + return returnValue; + } + function globalExport(name, obj) { + // attach the given object to the global object, so that it is globally + // visible everywhere. Should be used very sparingly! + globalThis[name] = obj; + } + function getAttribute(el, attr) { + if (el.hasAttribute(attr)) { + const value = el.getAttribute(attr); + if (value) { + return value; + } + } + return null; + } + function joinPaths(parts, separator = '/') { + const res = parts + .map(function (part) { + return part.trim().replace(/(^[/]*|[/]*$)/g, ''); + }) + .filter(p => p !== '') + .join(separator || '/'); + if (parts[0].startsWith('/')) { + return '/' + res; + } + return res; + } + function createDeprecationWarning(msg, elementName) { + createSingularWarning(msg, elementName); + } + /** Adds a warning banner with content {msg} at the top of the page if + * and only if no banner containing the {sentinelText} already exists. + * If sentinelText is null, the full text of {msg} is used instead + * + * @param msg {string} The full text content of the warning banner to be displayed + * @param sentinelText {string} [null] The text to match against existing warning banners. + * If null, the full text of 'msg' is used instead. + */ + function createSingularWarning(msg, sentinelText = null) { + const banners = document.getElementsByClassName('alert-banner py-warning'); + let bannerCount = 0; + for (const banner of banners) { + if (banner.innerHTML.includes(sentinelText ? sentinelText : msg)) { + bannerCount++; + } + } + if (bannerCount == 0) { + _createAlertBanner(msg, 'warning'); + } + } + /** + * @returns A new asynchronous lock + * @private + */ + function createLock() { + // This is a promise that is resolved when the lock is open, not resolved when lock is held. + let _lock = Promise.resolve(); + /** + * Acquire the async lock + * @returns A zero argument function that releases the lock. + * @private + */ + async function acquireLock() { + const old_lock = _lock; + let releaseLock; + _lock = new Promise(resolve => (releaseLock = resolve)); + await old_lock; + return releaseLock; + } + return acquireLock; + } + + const logger$b = getLogger('py-config'); + const allKeys = { + string: ['name', 'description', 'version', 'type', 'author_name', 'author_email', 'license'], + number: ['schema_version'], + array: ['runtimes', 'interpreters', 'packages', 'fetch', 'plugins'], + }; + const defaultConfig$1 = { + schema_version: 1, + type: 'app', + interpreters: [ + { + src: 'https://cdn.jsdelivr.net/pyodide/v0.22.1/full/pyodide.js', + name: 'pyodide-0.22.1', + lang: 'python', + }, + ], + // This is for backward compatibility, we need to remove it in the future + runtimes: [], + packages: [], + fetch: [], + plugins: [], + }; + function loadConfigFromElement(el) { + let srcConfig; + let inlineConfig; + if (el === null) { + srcConfig = {}; + inlineConfig = {}; + } + else { + const configType = getAttribute(el, 'type') || 'toml'; + srcConfig = extractFromSrc(el, configType); + inlineConfig = extractFromInline(el, configType); + } + srcConfig = mergeConfig(srcConfig, defaultConfig$1); + const result = mergeConfig(inlineConfig, srcConfig); + result.pyscript = { + version, + time: new Date().toISOString(), + }; + return result; + } + function extractFromSrc(el, configType) { + const src = getAttribute(el, 'src'); + if (src) { + logger$b.info('loading ', src); + return validateConfig(readTextFromPath(src), configType); + } + return {}; + } + function extractFromInline(el, configType) { + if (el.innerHTML !== '') { + logger$b.info('loading <py-config> content'); + return validateConfig(htmlDecode(el.innerHTML), configType); + } + return {}; + } + function fillUserData(inputConfig, resultConfig) { + for (const key in inputConfig) { + // fill in all extra keys ignored by the validator + if (!(key in defaultConfig$1)) { + resultConfig[key] = inputConfig[key]; + } + } + return resultConfig; + } + function mergeConfig(inlineConfig, externalConfig) { + if (Object.keys(inlineConfig).length === 0 && Object.keys(externalConfig).length === 0) { + return defaultConfig$1; + } + else if (Object.keys(inlineConfig).length === 0) { + return externalConfig; + } + else if (Object.keys(externalConfig).length === 0) { + return inlineConfig; + } + else { + let merged = {}; + for (const keyType in allKeys) { + const keys = allKeys[keyType]; + keys.forEach(function (item) { + if (keyType === 'boolean') { + merged[item] = + typeof inlineConfig[item] !== 'undefined' ? inlineConfig[item] : externalConfig[item]; + } + else { + merged[item] = inlineConfig[item] || externalConfig[item]; + } + }); + } + // fill extra keys from external first + // they will be overridden by inline if extra keys also clash + merged = fillUserData(externalConfig, merged); + merged = fillUserData(inlineConfig, merged); + return merged; + } + } + function parseConfig(configText, configType = 'toml') { + if (configType === 'toml') { + // TOML parser is soft and can parse even JSON strings, this additional check prevents it. + if (configText.trim()[0] === '{') { + throw new UserError(ErrorCode.BAD_CONFIG, `The config supplied: ${configText} is an invalid TOML and cannot be parsed`); + } + try { + return toml_1.parse(configText); + } + catch (err) { + const errMessage = err.toString(); + throw new UserError(ErrorCode.BAD_CONFIG, `The config supplied: ${configText} is an invalid TOML and cannot be parsed: ${errMessage}`); + } + } + else if (configType === 'json') { + try { + return JSON.parse(configText); + } + catch (err) { + const errMessage = err.toString(); + throw new UserError(ErrorCode.BAD_CONFIG, `The config supplied: ${configText} is an invalid JSON and cannot be parsed: ${errMessage}`); + } + } + else { + throw new UserError(ErrorCode.BAD_CONFIG, `The type of config supplied '${configType}' is not supported, supported values are ["toml", "json"]`); + } + } + function validateConfig(configText, configType = 'toml') { + const config = parseConfig(configText, configType); + const finalConfig = {}; + for (const keyType in allKeys) { + const keys = allKeys[keyType]; + keys.forEach(function (item) { + if (validateParamInConfig(item, keyType, config)) { + if (item === 'interpreters') { + finalConfig[item] = []; + const interpreters = config[item]; + interpreters.forEach(function (eachInterpreter) { + const interpreterConfig = {}; + for (const eachInterpreterParam in eachInterpreter) { + if (validateParamInConfig(eachInterpreterParam, 'string', eachInterpreter)) { + interpreterConfig[eachInterpreterParam] = eachInterpreter[eachInterpreterParam]; + } + } + finalConfig[item].push(interpreterConfig); + }); + } + else if (item === 'runtimes') { + // This code is a bit of a mess, but it's used for backwards + // compatibility with the old runtimes config. It should be + // removed when we remove support for the old config. + // We also need the warning here since we are pushing + // runtimes to `interpreter` and we can't show the warning + // in main.js + createDeprecationWarning('The configuration option `config.runtimes` is deprecated. ' + + 'Please use `config.interpreters` instead.', ''); + finalConfig['interpreters'] = []; + const interpreters = config[item]; + interpreters.forEach(function (eachInterpreter) { + const interpreterConfig = {}; + for (const eachInterpreterParam in eachInterpreter) { + if (validateParamInConfig(eachInterpreterParam, 'string', eachInterpreter)) { + interpreterConfig[eachInterpreterParam] = eachInterpreter[eachInterpreterParam]; + } + } + finalConfig['interpreters'].push(interpreterConfig); + }); + } + else if (item === 'fetch') { + finalConfig[item] = []; + const fetchList = config[item]; + fetchList.forEach(function (eachFetch) { + const eachFetchConfig = {}; + for (const eachFetchConfigParam in eachFetch) { + const targetType = eachFetchConfigParam === 'files' ? 'array' : 'string'; + if (validateParamInConfig(eachFetchConfigParam, targetType, eachFetch)) { + eachFetchConfig[eachFetchConfigParam] = eachFetch[eachFetchConfigParam]; + } + } + finalConfig[item].push(eachFetchConfig); + }); + } + else { + finalConfig[item] = config[item]; + } + } + }); + } + return fillUserData(config, finalConfig); + } + function validateParamInConfig(paramName, paramType, config) { + if (paramName in config) { + return paramType === 'array' ? Array.isArray(config[paramName]) : typeof config[paramName] === paramType; + } + return false; + } + + /** + * This is a fetch wrapper that handles any non 200 responses and throws a + * FetchError with the right ErrorCode. This is useful because our FetchError + * will automatically create an alert banner. + * + * @param url - URL to fetch + * @param options - options to pass to fetch + * @returns Response + */ + async function robustFetch(url, options) { + let response; + // Note: We need to wrap fetch into a try/catch block because fetch + // throws a TypeError if the URL is invalid such as http://blah.blah + try { + response = await fetch(url, options); + } + catch (err) { + const error = err; + let errMsg; + if (url.startsWith('http')) { + errMsg = + `Fetching from URL ${url} failed with error ` + + `'${error.message}'. Are your filename and path correct?`; + } + else { + errMsg = `PyScript: Access to local files + (using "Paths:" in <py-config>) is not available when directly opening a HTML file; you must use a webserver to serve the additional files. See <a style="text-decoration: underline;" href="https://github.com/pyscript/pyscript/issues/257#issuecomment-1119595062">this reference</a> - on starting a simple webserver with Python.</p>`; - } - else if (e.message.includes('404')) { - errorContent = - `<p>PyScript: Loading from file <u>` + - singleFile + - `</u> failed with error 404 (File not Found). Are your filename and path are correct?</p>`; - } - else { - errorContent = '<p>PyScript encountered an error while loading from file: ' + e.message + '</p>'; - } - showError(errorContent); - } - function readTextFromPath(path) { - const request = new XMLHttpRequest(); - request.open("GET", path, false); - request.send(); - const returnValue = request.responseText; - return returnValue; - } - function fillUserData(inputConfig, resultConfig) { - for (const key in inputConfig) { - // fill in all extra keys ignored by the validator - if (!(key in defaultConfig$1)) { - resultConfig[key] = inputConfig[key]; - } - } - return resultConfig; - } - function mergeConfig(inlineConfig, externalConfig) { - if (Object.keys(inlineConfig).length === 0 && Object.keys(externalConfig).length === 0) { - return defaultConfig$1; - } - else if (Object.keys(inlineConfig).length === 0) { - return externalConfig; - } - else if (Object.keys(externalConfig).length === 0) { - return inlineConfig; - } - else { - let merged = {}; - for (const keyType in allKeys) { - const keys = allKeys[keyType]; - keys.forEach(function (item) { - if (keyType === "boolean") { - merged[item] = (typeof inlineConfig[item] !== "undefined") ? inlineConfig[item] : externalConfig[item]; - } - else { - merged[item] = inlineConfig[item] || externalConfig[item]; - } - }); - } - // fill extra keys from external first - // they will be overridden by inline if extra keys also clash - merged = fillUserData(externalConfig, merged); - merged = fillUserData(inlineConfig, merged); - return merged; - } - } - function parseConfig(configText, configType = "toml") { - let config; - if (configType === "toml") { - try { - // TOML parser is soft and can parse even JSON strings, this additional check prevents it. - if (configText.trim()[0] === "{") { - const errMessage = `config supplied: ${configText} is an invalid TOML and cannot be parsed`; - showError(`<p>${errMessage}</p>`); - throw Error(errMessage); - } - config = toml.parse(configText); - } - catch (err) { - const errMessage = err.toString(); - showError(`<p>config supplied: ${configText} is an invalid TOML and cannot be parsed: ${errMessage}</p>`); - throw err; - } - } - else if (configType === "json") { - try { - config = JSON.parse(configText); - } - catch (err) { - const errMessage = err.toString(); - showError(`<p>config supplied: ${configText} is an invalid JSON and cannot be parsed: ${errMessage}</p>`); - throw err; - } - } - else { - showError(`<p>type of config supplied is: ${configType}, supported values are ["toml", "json"].</p>`); - } - return config; - } - function validateConfig(configText, configType = "toml") { - const config = parseConfig(configText, configType); - const finalConfig = {}; - for (const keyType in allKeys) { - const keys = allKeys[keyType]; - keys.forEach(function (item) { - if (validateParamInConfig(item, keyType, config)) { - if (item === "runtimes") { - finalConfig[item] = []; - const runtimes = config[item]; - runtimes.forEach(function (eachRuntime) { - const runtimeConfig = {}; - for (const eachRuntimeParam in eachRuntime) { - if (validateParamInConfig(eachRuntimeParam, "string", eachRuntime)) { - runtimeConfig[eachRuntimeParam] = eachRuntime[eachRuntimeParam]; - } - } - finalConfig[item].push(runtimeConfig); - }); - } - else { - finalConfig[item] = config[item]; - } - } - }); - } - return fillUserData(config, finalConfig); - } - function validateParamInConfig(paramName, paramType, config) { - if (paramName in config) { - return paramType === "array" ? Array.isArray(config[paramName]) : typeof config[paramName] === paramType; - } - return false; - } + on starting a simple webserver with Python. + `; + } + throw new FetchError(ErrorCode.FETCH_ERROR, errMsg); + } + // Note that response.ok is true for 200-299 responses + if (!response.ok) { + const errorMsg = `Fetching from URL ${url} failed with error ${response.status} (${response.statusText}). Are your filename and path correct?`; + switch (response.status) { + case 404: + throw new FetchError(ErrorCode.FETCH_NOT_FOUND_ERROR, errorMsg); + case 401: + throw new FetchError(ErrorCode.FETCH_UNAUTHORIZED_ERROR, errorMsg); + case 403: + throw new FetchError(ErrorCode.FETCH_FORBIDDEN_ERROR, errorMsg); + case 500: + throw new FetchError(ErrorCode.FETCH_SERVER_ERROR, errorMsg); + case 503: + throw new FetchError(ErrorCode.FETCH_UNAVAILABLE_ERROR, errorMsg); + default: + throw new FetchError(ErrorCode.FETCH_ERROR, errorMsg); + } + } + return response; + } - const logger$b = getLogger('pyscript/base'); - // Global `Runtime` that implements the generic runtimes API - let runtime$2; - let Element; - runtimeLoaded.subscribe(value => { - runtime$2 = value; - }); - class BaseEvalElement extends HTMLElement { - shadow; - wrapper; - code; - source; - btnConfig; - btnRun; - outputElement; - errorElement; - theme; - appendOutput; - constructor() { - super(); - // attach shadow so we can preserve the element original innerHtml content - this.shadow = this.attachShadow({ mode: 'open' }); - this.wrapper = document.createElement('slot'); - this.shadow.appendChild(this.wrapper); - this.setOutputMode("append"); - } - addToOutput(s) { - this.outputElement.innerHTML += '<div>' + s + '</div>'; - this.outputElement.hidden = false; - } - setOutputMode(defaultMode = "append") { - const mode = this.hasAttribute('output-mode') ? this.getAttribute('output-mode') : defaultMode; - switch (mode) { - case "append": - this.appendOutput = true; - break; - case "replace": - this.appendOutput = false; - break; - default: - logger$b.warn(`${this.id}: custom output-modes are currently not implemented`); - } - } - // subclasses should overwrite this method to define custom logic - // before code gets evaluated - preEvaluate() { - return null; - } - // subclasses should overwrite this method to define custom logic - // after code has been evaluated - postEvaluate() { - return null; - } - checkId() { - if (!this.id) - this.id = 'py-' + guidGenerator(); - } - getSourceFromElement() { - return ''; - } - async getSourceFromFile(s) { - const response = await fetch(s); - this.code = await response.text(); - return this.code; - } - async _register_esm(runtime) { - const imports = {}; - const nodes = document.querySelectorAll("script[type='importmap']"); - const importmaps = []; - nodes.forEach(node => { - let importmap; - try { - importmap = JSON.parse(node.textContent); - if (importmap?.imports == null) - return; - importmaps.push(importmap); - } - catch { - return; - } - }); - for (const importmap of importmaps) { - for (const [name, url] of Object.entries(importmap.imports)) { - if (typeof name != 'string' || typeof url != 'string') - continue; - try { - // XXX: pyodide doesn't like Module(), failing with - // "can't read 'name' of undefined" at import time - imports[name] = { ...(await import(url)) }; - } - catch { - logger$b.error(`failed to fetch '${url}' for '${name}'`); - } - } - } - runtime.registerJsModule('esm', imports); - } - async evaluate() { - this.preEvaluate(); - let source; - let output; - try { - source = this.source ? await this.getSourceFromFile(this.source) - : this.getSourceFromElement(); - this._register_esm(runtime$2); - await runtime$2.run(`output_manager.change(out="${this.outputElement.id}", err="${this.errorElement.id}", append=${this.appendOutput ? 'True' : 'False'})`); - output = await runtime$2.run(source); - if (output !== undefined) { - if (Element === undefined) { - Element = runtime$2.globals.get('Element'); - } - const out = Element(this.outputElement.id); - out.write.callKwargs(output, { append: this.appendOutput }); - this.outputElement.hidden = false; - this.outputElement.style.display = 'block'; - } - await runtime$2.run(`output_manager.revert()`); - // check if this REPL contains errors, delete them and remove error classes - const errorElements = document.querySelectorAll(`div[id^='${this.errorElement.id}'][error]`); - if (errorElements.length > 0) { - errorElements.forEach(errorElement => { - errorElement.classList.add('hidden'); - if (this.hasAttribute('std-err')) { - this.errorElement.hidden = true; - this.errorElement.style.removeProperty('display'); - } - }); - } - removeClasses(this.errorElement, ['bg-red-200', 'p-2']); - this.postEvaluate(); - } - catch (err) { - logger$b.error(err); - try { - if (Element === undefined) { - Element = runtime$2.globals.get('Element'); - } - const out = Element(this.errorElement.id); - addClasses(this.errorElement, ['bg-red-200', 'p-2']); - out.write.callKwargs(err.toString(), { append: this.appendOutput }); - if (this.errorElement.children.length === 0) { - this.errorElement.setAttribute('error', ''); - } - else { - this.errorElement.children[this.errorElement.children.length - 1].setAttribute('error', ''); - } - this.errorElement.hidden = false; - this.errorElement.style.display = 'block'; - this.errorElement.style.visibility = 'visible'; - } - catch (internalErr) { - logger$b.error("Unnable to write error to error element in page."); - } - } - } // end evaluate - async eval(source) { - try { - const output = await runtime$2.run(source); - if (output !== undefined) { - logger$b.info(output); - } - } - catch (err) { - logger$b.error(err); - } - } // end eval - runAfterRuntimeInitialized(callback) { - runtimeLoaded.subscribe(value => { - if ('run' in value) { - setTimeout(() => { - void callback(); - }, 100); - } - }); - } - } - function createWidget(name, code, klass) { - class CustomWidget extends HTMLElement { - shadow; - wrapper; - name = name; - klass = klass; - code = code; - proxy; - proxyClass; - constructor() { - super(); - // attach shadow so we can preserve the element original innerHtml content - this.shadow = this.attachShadow({ mode: 'open' }); - this.wrapper = document.createElement('slot'); - this.shadow.appendChild(this.wrapper); - } - connectedCallback() { - // TODO: we are calling with a 2secs delay to allow pyodide to load - // ideally we can just wait for it to load and then run. To do - // so we need to replace using the promise and actually using - // the interpreter after it loads completely - // setTimeout(() => { - // void (async () => { - // await this.eval(this.code); - // this.proxy = this.proxyClass(this); - // console.log('proxy', this.proxy); - // this.proxy.connect(); - // this.registerWidget(); - // })(); - // }, 2000); - runtimeLoaded.subscribe(value => { - if ('run' in value) { - runtime$2 = value; - setTimeout(() => { - void (async () => { - await this.eval(this.code); - this.proxy = this.proxyClass(this); - this.proxy.connect(); - this.registerWidget(); - })(); - }, 1000); - } - }); - } - registerWidget() { - logger$b.info('new widget registered:', this.name); - runtime$2.globals.set(this.id, this.proxy); - } - async eval(source) { - try { - const output = await runtime$2.run(source); - this.proxyClass = runtime$2.globals.get(this.klass); - if (output !== undefined) { - logger$b.info('CustomWidget.eval: ', output); - } - } - catch (err) { - logger$b.error('CustomWidget.eval: ', err); - } - } - } - customElements.define(name, CustomWidget); - } - class PyWidget extends HTMLElement { - shadow; - name; - klass; - outputElement; - errorElement; - wrapper; - theme; - source; - code; - constructor() { - super(); - // attach shadow so we can preserve the element original innerHtml content - this.shadow = this.attachShadow({ mode: 'open' }); - this.wrapper = document.createElement('slot'); - this.shadow.appendChild(this.wrapper); - this.addAttributes('src', 'name', 'klass'); - } - addAttributes(...attrs) { - for (const each of attrs) { - const property = each === "src" ? "source" : each; - if (this.hasAttribute(each)) { - this[property] = this.getAttribute(each); - } - } - } - async connectedCallback() { - if (this.id === undefined) { - throw new ReferenceError(`No id specified for component. Components must have an explicit id. Please use id="" to specify your component id.`); - } - const mainDiv = document.createElement('div'); - mainDiv.id = this.id + '-main'; - this.appendChild(mainDiv); - logger$b.debug('PyWidget: reading source', this.source); - this.code = await this.getSourceFromFile(this.source); - createWidget(this.name, this.code, this.klass); - } - initOutErr() { - if (this.hasAttribute('output')) { - this.errorElement = this.outputElement = document.getElementById(this.getAttribute('output')); - // in this case, the default output-mode is append, if hasn't been specified - if (!this.hasAttribute('output-mode')) { - this.setAttribute('output-mode', 'append'); - } - } - else { - if (this.hasAttribute('std-out')) { - this.outputElement = document.getElementById(this.getAttribute('std-out')); - } - else { - // In this case neither output or std-out have been provided so we need - // to create a new output div to output to - this.outputElement = document.createElement('div'); - this.outputElement.classList.add('output'); - this.outputElement.hidden = true; - this.outputElement.id = this.id + '-' + this.getAttribute('exec-id'); - } - if (this.hasAttribute('std-err')) { - this.errorElement = document.getElementById(this.getAttribute('std-err')); - } - else { - this.errorElement = this.outputElement; - } - } - } - async getSourceFromFile(s) { - const response = await fetch(s); - return await response.text(); - } - async eval(source) { - try { - const output = await runtime$2.run(source); - if (output !== undefined) { - logger$b.info('PyWidget.eval: ', output); - } - } - catch (err) { - logger$b.error('PyWidget.eval: ', err); - } - } - } + const logger$a = getLogger('pyscript/pyodide'); + /* + RemoteInterpreter class is responsible to process requests from the + `InterpreterClient` class -- these can be requests for installation of + a package, executing code, etc. - const logger$a = getLogger('py-script'); - // Premise used to connect to the first available runtime (can be pyodide or others) - let runtime$1; - runtimeLoaded.subscribe(value => { - runtime$1 = value; - }); - loadedEnvironments.subscribe(value => { - }); - class PyScript extends BaseEvalElement { - constructor() { - super(); - // add an extra div where we can attach the codemirror editor - this.shadow.appendChild(this.wrapper); - } - connectedCallback() { - this.checkId(); - this.code = htmlDecode(this.innerHTML); - this.innerHTML = ''; - const mainDiv = document.createElement('div'); - addClasses(mainDiv, ['output']); - // add Editor to main PyScript div - if (this.hasAttribute('output')) { - this.errorElement = this.outputElement = document.getElementById(this.getAttribute('output')); - // in this case, the default output-mode is append, if hasn't been specified - if (!this.hasAttribute('output-mode')) { - this.setAttribute('output-mode', 'append'); - } - } - else { - if (this.hasAttribute('std-out')) { - this.outputElement = document.getElementById(this.getAttribute('std-out')); - } - else { - // In this case neither output or std-out have been provided so we need - // to create a new output div to output to - // Let's check if we have an id first and create one if not - this.outputElement = document.createElement('div'); - const exec_id = this.getAttribute('exec-id'); - this.outputElement.id = this.id + (exec_id ? '-' + exec_id : ''); - // add the output div id if there's not output pre-defined - mainDiv.appendChild(this.outputElement); - } - if (this.hasAttribute('std-err')) { - this.errorElement = document.getElementById(this.getAttribute('std-err')); - } - else { - this.errorElement = this.outputElement; - } - } - this.appendChild(mainDiv); - addToScriptsQueue(this); - if (this.hasAttribute('src')) { - this.source = this.getAttribute('src'); - } - } - async _register_esm(runtime) { - for (const node of document.querySelectorAll("script[type='importmap']")) { - const importmap = (() => { - try { - return JSON.parse(node.textContent); - } - catch { - return null; - } - })(); - if (importmap?.imports == null) - continue; - for (const [name, url] of Object.entries(importmap.imports)) { - if (typeof name != 'string' || typeof url != 'string') - continue; - let exports; - try { - // XXX: pyodide doesn't like Module(), failing with - // "can't read 'name' of undefined" at import time - exports = { ...(await import(url)) }; - } - catch { - logger$a.warn(`failed to fetch '${url}' for '${name}'`); - continue; - } - runtime.registerJsModule(name, exports); - } - } - } - getSourceFromElement() { - return htmlDecode(this.code); - } - } - /** Defines all possible py-on* and their corresponding event types */ - const pyAttributeToEvent = new Map([ - // Leaving pys-onClick and pys-onKeyDown for backward compatibility - ["pys-onClick", "click"], - ["pys-onKeyDown", "keydown"], - ["py-onClick", "click"], - ["py-onKeyDown", "keydown"], - // Window Events - ["py-afterprint", "afterprint"], - ["py-beforeprint", "beforeprint"], - ["py-beforeunload", "beforeunload"], - ["py-error", "error"], - ["py-hashchange", "hashchange"], - ["py-load", "load"], - ["py-message", "message"], - ["py-offline", "offline"], - ["py-online", "online"], - ["py-pagehide", "pagehide"], - ["py-pageshow", "pageshow"], - ["py-popstate", "popstate"], - ["py-resize", "resize"], - ["py-storage", "storage"], - ["py-unload", "unload"], - // Form Events - ["py-blur", "blur"], - ["py-change", "change"], - ["py-contextmenu", "contextmenu"], - ["py-focus", "focus"], - ["py-input", "input"], - ["py-invalid", "invalid"], - ["py-reset", "reset"], - ["py-search", "search"], - ["py-select", "select"], - ["py-submit", "submit"], - // Keyboard Events - ["py-keydown", "keydown"], - ["py-keypress", "keypress"], - ["py-keyup", "keyup"], - // Mouse Events - ["py-click", "click"], - ["py-dblclick", "dblclick"], - ["py-mousedown", "mousedown"], - ["py-mousemove", "mousemove"], - ["py-mouseout", "mouseout"], - ["py-mouseover", "mouseover"], - ["py-mouseup", "mouseup"], - ["py-mousewheel", "mousewheel"], - ["py-wheel", "wheel"], - // Drag Events - ["py-drag", "drag"], - ["py-dragend", "dragend"], - ["py-dragenter", "dragenter"], - ["py-dragleave", "dragleave"], - ["py-dragover", "dragover"], - ["py-dragstart", "dragstart"], - ["py-drop", "drop"], - ["py-scroll", "scroll"], - // Clipboard Events - ["py-copy", "copy"], - ["py-cut", "cut"], - ["py-paste", "paste"], - // Media Events - ["py-abort", "abort"], - ["py-canplay", "canplay"], - ["py-canplaythrough", "canplaythrough"], - ["py-cuechange", "cuechange"], - ["py-durationchange", "durationchange"], - ["py-emptied", "emptied"], - ["py-ended", "ended"], - ["py-loadeddata", "loadeddata"], - ["py-loadedmetadata", "loadedmetadata"], - ["py-loadstart", "loadstart"], - ["py-pause", "pause"], - ["py-play", "play"], - ["py-playing", "playing"], - ["py-progress", "progress"], - ["py-ratechange", "ratechange"], - ["py-seeked", "seeked"], - ["py-seeking", "seeking"], - ["py-stalled", "stalled"], - ["py-suspend", "suspend"], - ["py-timeupdate", "timeupdate"], - ["py-volumechange", "volumechange"], - ["py-waiting", "waiting"], - // Misc Events - ["py-toggle", "toggle"], - ]); - /** Initialize all elements with py-* handlers attributes */ - async function initHandlers() { - logger$a.debug('Initializing py-* event handlers...'); - for (const pyAttribute of pyAttributeToEvent.keys()) { - await createElementsWithEventListeners(runtime$1, pyAttribute); - } - } - /** Initializes an element with the given py-on* attribute and its handler */ - async function createElementsWithEventListeners(runtime, pyAttribute) { - const matches = document.querySelectorAll(`[${pyAttribute}]`); - for (const el of matches) { - if (el.id.length === 0) { - throw new TypeError(`<${el.tagName.toLowerCase()}> must have an id attribute, when using the ${pyAttribute} attribute`); - } - const handlerCode = el.getAttribute(pyAttribute); - const event = pyAttributeToEvent.get(pyAttribute); - if (pyAttribute === 'pys-onClick' || pyAttribute === 'pys-onKeyDown') { - console.warn("Use of pys-onClick and pys-onKeyDown attributes is deprecated in favor of py-onClick() and py-onKeyDown(). pys-on* attributes will be deprecated in a future version of PyScript."); - const source = ` + Currently, the only interpreter available is Pyodide as indicated by the + `InterpreterInterface` type above. This serves as a Union of types of + different interpreters which will be added in near future. + + Methods available handle loading of the interpreter, initialization, + running code, loading and installation of packages, loading from files etc. + + The class will be turned `abstract` in future, to support more runtimes + such as MicroPython. + */ + class RemoteInterpreter extends Object { + constructor(src = 'https://cdn.jsdelivr.net/pyodide/v0.22.1/full/pyodide.js') { + super(); + this.src = src; + } + /** + * loads the interface for the interpreter and saves an instance of it + * in the `this.interface` property along with calling of other + * additional convenience functions. + * */ + /** + * Although `loadPyodide` is used below, + * notice that it is not imported i.e. + * import { loadPyodide } from 'pyodide'; + * is not used at the top of this file. + * + * This is because, if it's used, loadPyodide + * behaves mischievously i.e. it tries to load + * `pyodide.asm.js` and `pyodide_py.tar` but + * with paths that are wrong such as: + * + * http://127.0.0.1:8080/build/pyodide_py.tar + * which results in a 404 since `build` doesn't + * contain these files and is clearly the wrong + * path. + */ + async loadInterpreter(config, stdio) { + this.interface = await loadPyodide({ + stdout: (msg) => { + stdio.stdout_writeline(msg); + }, + stderr: (msg) => { + stdio.stderr_writeline(msg); + }, + fullStdLib: false, + }); + // TODO: Remove this once `runtimes` is removed! + this.interpreter = this.interface; + this.globals = this.interface.globals; + if (config.packages) { + logger$a.info('Found packages in configuration to install. Loading micropip...'); + await this.loadPackage('micropip'); + } + logger$a.info('pyodide loaded and initialized'); + await this.run('print("Python initialization complete")'); + } + /* eslint-disable */ + async run(code) { + /** + * eslint wants `await` keyword to be used i.e. + * { result: await this.interface.runPython(code) } + * However, `await` is not a no-op (no-operation) i.e. + * `await 42` is NOT the same as `42` i.e. if the awaited + * thing is not a promise, it is wrapped inside a promise and + * that promise is awaited. Thus, it changes the execution order. + * See https://stackoverflow.com/questions/55262996/does-awaiting-a-non-promise-have-any-detectable-effect + * Thus, `eslint` is disabled for this block / snippet. + */ + /** + * The output of `runPython` is wrapped inside an object + * since an object is not thennable and avoids return of + * a coroutine directly. This is so we do not `await` the results + * of the underlying python execution, even if it's an + * awaitable object (Future, Task, etc.) + */ + return { result: this.interface.runPython(code) }; + } + /* eslint-enable */ + /** + * delegates the registration of JS modules to + * the underlying interface. + * */ + registerJsModule(name, module) { + this.interface.registerJsModule(name, module); + } + /** + * delegates the loading of packages to + * the underlying interface. + * */ + async loadPackage(names) { + logger$a.info(`pyodide.loadPackage: ${names.toString()}`); + // the new way in v0.22.1 is to pass it as a dict of options i.e. + // { messageCallback: logger.info.bind(logger), errorCallback: logger.info.bind(logger) } + // but one of our tests tries to use a locally downloaded older version of pyodide + // for which the signature of `loadPackage` accepts the above params as args i.e. + // the call uses `logger.info.bind(logger), logger.info.bind(logger)`. + const pyodide_version = (await this.run("import sys; sys.modules['pyodide'].__version__")).result.toString(); + if (pyodide_version.startsWith('0.22')) { + await this.interface.loadPackage(names, { + messageCallback: logger$a.info.bind(logger$a), + errorCallback: logger$a.info.bind(logger$a), + }); + } + else { + await this.interface.loadPackage(names, logger$a.info.bind(logger$a), logger$a.info.bind(logger$a)); + } + } + /** + * delegates the installation of packages + * (using a package manager, which can be specific to + * the interface) to the underlying interface. + * + * For Pyodide, we use `micropip` + * */ + async installPackage(package_name) { + if (package_name.length > 0) { + logger$a.info(`micropip install ${package_name.toString()}`); + const micropip = this.interface.pyimport('micropip'); + try { + await micropip.install(package_name); + micropip.destroy(); + } + catch (e) { + let exceptionMessage = `Unable to install package(s) '` + package_name + `'.`; + // If we can't fetch `package_name` micropip.install throws a huge + // Python traceback in `e.message` this logic is to handle the + // error and throw a more sensible error message instead of the + // huge traceback. + if (e.message.includes("Can't find a pure Python 3 wheel")) { + exceptionMessage += + ` Reason: Can't find a pure Python 3 Wheel for package(s) '` + + package_name + + `'. See: https://pyodide.org/en/stable/usage/faq.html#micropip-can-t-find-a-pure-python-wheel ` + + `for more information.`; + } + else if (e.message.includes("Can't fetch metadata")) { + exceptionMessage += + ' Unable to find package in PyPI. ' + + 'Please make sure you have entered a correct package name.'; + } + else { + exceptionMessage += + ` Reason: ${e.message}. Please open an issue at ` + + `https://github.com/pyscript/pyscript/issues/new if you require help or ` + + `you think it's a bug.`; + } + logger$a.error(e); + throw new InstallError(ErrorCode.MICROPIP_INSTALL_ERROR, exceptionMessage); + } + } + } + /** + * + * @param path : the path in the filesystem + * @param fetch_path : the path to be fetched + * + * Given a file available at `fetch_path` URL (eg: + * `http://dummy.com/hi.py`), the function downloads the file and saves it + * to the `path` (eg: `a/b/c/foo.py`) on the FS. + * + * Example usage: await loadFromFile(`a/b/c/foo.py`, + * `http://dummy.com/hi.py`) + * + * Write content of `http://dummy.com/hi.py` to `a/b/c/foo.py` + * + * NOTE: The `path` parameter expects to have the `filename` in it i.e. + * `a/b/c/foo.py` is valid while `a/b/c` (i.e. only the folders) are + * incorrect. + * + * The path will be resolved relative to the current working directory, + * which is initially `/home/pyodide`. So by default `a/b.py` will be placed + * in `/home/pyodide/a/b.py`, `../a/b.py` will be placed into `/home/a/b.py` + * and `/a/b.py` will be placed into `/a/b.py`. + */ + async loadFromFile(path, fetch_path) { + // eslint-disable-next-line @typescript-eslint/ban-ts-comment + // @ts-ignore + path = this.interface._module.PATH_FS.resolve(path); + // eslint-disable-next-line @typescript-eslint/ban-ts-comment + // @ts-ignore + const dir = this.interface._module.PATH.dirname(path); + this.interface.FS.mkdirTree(dir); + // `robustFetch` checks for failures in getting a response + const response = await robustFetch(fetch_path); + const buffer = await response.arrayBuffer(); + const data = new Uint8Array(buffer); + this.interface.FS.writeFile(path, data, { canOwn: true }); + } + /** + * delegates clearing importlib's module path + * caches to the underlying interface + */ + invalidate_module_path_cache() { + const importlib = this.interface.pyimport('importlib'); + importlib.invalidate_caches(); + } + } + + const logger$9 = getLogger('pyscript/interpreter'); + /* + InterpreterClient class is responsible to request code execution + (among other things) from a `RemoteInterpreter` + */ + class InterpreterClient extends Object { + constructor(config, stdio) { + super(); + this.config = config; + this._remote = new RemoteInterpreter(this.config.interpreters[0].src); + this.stdio = stdio; + } + /** + * initializes the remote interpreter, which further loads the underlying + * interface. + * */ + async initializeRemote() { + await this._remote.loadInterpreter(this.config, this.stdio); + this.globals = this._remote.globals; + } + /** + * delegates the code to be run to the underlying interface of + * the remote interpreter. + * Python exceptions are turned into JS exceptions. + * */ + async run(code) { + return await this._remote.run(code); + } + /** + * Same as run, but Python exceptions are not propagated: instead, they + * are logged to the console. + * + * This is a bad API and should be killed/refactored/changed eventually, + * but for now we have code which relies on it. + * */ + async runButDontRaise(code) { + let result; + try { + result = (await this.run(code)).result; + } + catch (error) { + logger$9.error('Error:', error); + } + return result; + } + } + + const logger$8 = getLogger('plugin'); + class Plugin { + /** Validate the configuration of the plugin and handle default values. + * + * Individual plugins are expected to check that the config keys/sections + * which are relevant to them contains valid values, and to raise an error + * if they contains unknown keys. + * + * This is also a good place where set default values for those keys which + * are not specified by the user. + * + * This hook should **NOT** contain expensive operations, else it delays + * the download of the python interpreter which is initiated later. + */ + configure(config) { } + /** The preliminary initialization phase is complete and we are about to + * download and launch the Python interpreter. + * + * We can assume that the page is already shown to the user and that the + * DOM content has been loaded. This is a good place where to add tags to + * the DOM, if needed. + * + * This hook should **NOT** contain expensive operations, else it delays + * the download of the python interpreter which is initiated later. + */ + beforeLaunch(config) { } + /** The Python interpreter has been launched, the virtualenv has been + * installed and we are ready to execute user code. + * + * The <py-script> tags will be executed after this hook. + */ + afterSetup(interpreter) { } + /** The source of a <py-script>> tag has been fetched, and we're about + * to evaluate that source using the provided interpreter. + * + * @param options.interpreter The Interpreter object that will be used to evaluated the Python source code + * @param options.src {string} The Python source code to be evaluated + * @param options.pyScriptTag The <py-script> HTML tag that originated the evaluation + */ + beforePyScriptExec(options) { } + /** The Python in a <py-script> has just been evaluated, but control + * has not been ceded back to the JavaScript event loop yet + * + * @param options.interpreter The Interpreter object that will be used to evaluated the Python source code + * @param options.src {string} The Python source code to be evaluated + * @param options.pyScriptTag The <py-script> HTML tag that originated the evaluation + * @param options.result The returned result of evaluating the Python (if any) + */ + afterPyScriptExec(options) { } + /** Startup complete. The interpreter is initialized and ready, user + * scripts have been executed: the main initialization logic ends here and + * the page is ready to accept user interactions. + */ + afterStartup(interpreter) { } + /** Called when an UserError is raised + */ + onUserError(error) { } + } + class PluginManager { + constructor() { + this._plugins = []; + this._pythonPlugins = []; + } + add(...plugins) { + for (const p of plugins) + this._plugins.push(p); + } + addPythonPlugin(plugin) { + this._pythonPlugins.push(plugin); + } + configure(config) { + for (const p of this._plugins) + p.configure?.(config); + for (const p of this._pythonPlugins) + p.configure?.(config); + } + beforeLaunch(config) { + for (const p of this._plugins) { + try { + p?.beforeLaunch?.(config); + } + catch (e) { + logger$8.error(`Error while calling beforeLaunch hook of plugin ${p.constructor.name}`, e); + } + } + } + afterSetup(interpreter) { + for (const p of this._plugins) { + try { + p.afterSetup?.(interpreter); + } + catch (e) { + logger$8.error(`Error while calling afterSetup hook of plugin ${p.constructor.name}`, e); + } + } + for (const p of this._pythonPlugins) + p.afterSetup?.(interpreter); + } + afterStartup(interpreter) { + for (const p of this._plugins) + p.afterStartup?.(interpreter); + for (const p of this._pythonPlugins) + p.afterStartup?.(interpreter); + } + beforePyScriptExec(options) { + for (const p of this._plugins) + p.beforePyScriptExec?.(options); + for (const p of this._pythonPlugins) + p.beforePyScriptExec?.callKwargs(options); + } + afterPyScriptExec(options) { + for (const p of this._plugins) + p.afterPyScriptExec?.(options); + for (const p of this._pythonPlugins) + p.afterPyScriptExec?.callKwargs(options); + } + onUserError(error) { + for (const p of this._plugins) + p.onUserError?.(error); + for (const p of this._pythonPlugins) + p.onUserError?.(error); + } + } + /** + * Defines a new CustomElement (via customElement.defines) with `tag`, + * where the new CustomElement is a proxy that delegates the logic to + * pyPluginClass. + * + * @param tag - tag that will be used to define the new CustomElement (i.e: "py-script") + * @param pyPluginClass - class that will be used to create instance to be + * used as CustomElement logic handler. Any DOM event + * received by the newly created CustomElement will be + * delegated to that instance. + */ + function define_custom_element(tag, pyPluginClass) { + logger$8.info(`creating plugin: ${tag}`); + class ProxyCustomElement extends HTMLElement { + constructor() { + logger$8.debug(`creating ${tag} plugin instance`); + super(); + this.shadow = this.attachShadow({ mode: 'open' }); + this.wrapper = document.createElement('slot'); + this.shadow.appendChild(this.wrapper); + this.originalInnerHTML = this.innerHTML; + this.pyPluginInstance = pyPluginClass(this); + } + connectedCallback() { + const innerHTML = this.pyPluginInstance.connect(); + if (typeof innerHTML === 'string') + this.innerHTML = innerHTML; + } + } + customElements.define(tag, ProxyCustomElement); + } + + const logger$7 = getLogger('pyexec'); + async function pyExec(interpreter, pysrc, outElem) { + //This is pyscript.py + const pyscript_py = interpreter._remote.interface.pyimport('pyscript'); + ensureUniqueId(outElem); + pyscript_py.set_current_display_target(outElem.id); + try { + try { + if (pyscript_py.uses_top_level_await(pysrc)) { + throw new UserError(ErrorCode.TOP_LEVEL_AWAIT, 'The use of top-level "await", "async for", and ' + + '"async with" has been removed.' + + '\nPlease write a coroutine containing ' + + 'your code and schedule it using asyncio.ensure_future() or similar.' + + '\nSee https://docs.pyscript.net/latest/guides/asyncio.html for more information.'); + } + return await interpreter.run(pysrc); + } + catch (err) { + // XXX: currently we display exceptions in the same position as + // the output. But we probably need a better way to do that, + // e.g. allowing plugins to intercept exceptions and display them + // in a configurable way. + displayPyException(err, outElem); + return { result: undefined }; + } + } + finally { + pyscript_py.set_current_display_target(undefined); + pyscript_py.destroy(); + } + } + /** + * Javascript API to call the python display() function + * + * Expected usage: + * pyDisplay(interpreter, obj); + * pyDisplay(interpreter, obj, { target: targetID }); + */ + function pyDisplay(interpreter, obj, kwargs) { + const display = interpreter.globals.get('display'); + if (kwargs === undefined) + display(obj); + else { + display.callKwargs(obj, kwargs); + } + } + function displayPyException(err, errElem) { + //addClasses(errElem, ['py-error']) + const pre = document.createElement('pre'); + pre.className = 'py-error'; + if (err.name === 'PythonError') { + // err.message contains the python-level traceback (i.e. a string + // starting with: "Traceback (most recent call last) ..." + logger$7.error('Python exception:\n' + err.message); + pre.innerText = err.message; + } + else { + // this is very likely a normal JS exception. The best we can do is to + // display it as is. + logger$7.error('Non-python exception:\n' + err); + pre.innerText = err; + } + errElem.appendChild(pre); + } + + const logger$6 = getLogger('py-script'); + function make_PyScript(interpreter, app) { + class PyScript extends HTMLElement { + async connectedCallback() { + /** + * Since connectedCallback is async, multiple py-script tags can be executed in + * an order which is not particularly sequential. The locking mechanism here ensures + * a sequential execution of multiple py-script tags present in one page. + * + * Concurrent access to the multiple py-script tags is thus avoided. + */ + let releaseLock; + try { + releaseLock = await app.tagExecutionLock(); + ensureUniqueId(this); + // Save innerHTML information in srcCode so we can access it later + // once we clean innerHTML (which is required since we don't want + // source code to be rendered on the screen) + this.srcCode = this.innerHTML; + const pySrc = await this.getPySrc(); + this.innerHTML = ''; + app.plugins.beforePyScriptExec({ interpreter: interpreter, src: pySrc, pyScriptTag: this }); + const result = (await pyExec(interpreter, pySrc, this)).result; + app.plugins.afterPyScriptExec({ + interpreter: interpreter, + src: pySrc, + pyScriptTag: this, + result: result, + }); + } + finally { + releaseLock(); + } + } + async getPySrc() { + if (this.hasAttribute('src')) { + const url = this.getAttribute('src'); + try { + const response = await robustFetch(url); + return await response.text(); + } + catch (e) { + _createAlertBanner(e.message); + this.innerHTML = ''; + throw e; + } + } + else { + return htmlDecode(this.srcCode); + } + } + } + return PyScript; + } + /** Defines all possible py-on* and their corresponding event types */ + const pyAttributeToEvent = new Map([ + // Leaving pys-onClick and pys-onKeyDown for backward compatibility + ['pys-onClick', 'click'], + ['pys-onKeyDown', 'keydown'], + ['py-onClick', 'click'], + ['py-onKeyDown', 'keydown'], + // Window Events + ['py-afterprint', 'afterprint'], + ['py-beforeprint', 'beforeprint'], + ['py-beforeunload', 'beforeunload'], + ['py-error', 'error'], + ['py-hashchange', 'hashchange'], + ['py-load', 'load'], + ['py-message', 'message'], + ['py-offline', 'offline'], + ['py-online', 'online'], + ['py-pagehide', 'pagehide'], + ['py-pageshow', 'pageshow'], + ['py-popstate', 'popstate'], + ['py-resize', 'resize'], + ['py-storage', 'storage'], + ['py-unload', 'unload'], + // Form Events + ['py-blur', 'blur'], + ['py-change', 'change'], + ['py-contextmenu', 'contextmenu'], + ['py-focus', 'focus'], + ['py-input', 'input'], + ['py-invalid', 'invalid'], + ['py-reset', 'reset'], + ['py-search', 'search'], + ['py-select', 'select'], + ['py-submit', 'submit'], + // Keyboard Events + ['py-keydown', 'keydown'], + ['py-keypress', 'keypress'], + ['py-keyup', 'keyup'], + // Mouse Events + ['py-click', 'click'], + ['py-dblclick', 'dblclick'], + ['py-mousedown', 'mousedown'], + ['py-mousemove', 'mousemove'], + ['py-mouseout', 'mouseout'], + ['py-mouseover', 'mouseover'], + ['py-mouseup', 'mouseup'], + ['py-mousewheel', 'mousewheel'], + ['py-wheel', 'wheel'], + // Drag Events + ['py-drag', 'drag'], + ['py-dragend', 'dragend'], + ['py-dragenter', 'dragenter'], + ['py-dragleave', 'dragleave'], + ['py-dragover', 'dragover'], + ['py-dragstart', 'dragstart'], + ['py-drop', 'drop'], + ['py-scroll', 'scroll'], + // Clipboard Events + ['py-copy', 'copy'], + ['py-cut', 'cut'], + ['py-paste', 'paste'], + // Media Events + ['py-abort', 'abort'], + ['py-canplay', 'canplay'], + ['py-canplaythrough', 'canplaythrough'], + ['py-cuechange', 'cuechange'], + ['py-durationchange', 'durationchange'], + ['py-emptied', 'emptied'], + ['py-ended', 'ended'], + ['py-loadeddata', 'loadeddata'], + ['py-loadedmetadata', 'loadedmetadata'], + ['py-loadstart', 'loadstart'], + ['py-pause', 'pause'], + ['py-play', 'play'], + ['py-playing', 'playing'], + ['py-progress', 'progress'], + ['py-ratechange', 'ratechange'], + ['py-seeked', 'seeked'], + ['py-seeking', 'seeking'], + ['py-stalled', 'stalled'], + ['py-suspend', 'suspend'], + ['py-timeupdate', 'timeupdate'], + ['py-volumechange', 'volumechange'], + ['py-waiting', 'waiting'], + // Misc Events + ['py-toggle', 'toggle'], + ]); + /** Initialize all elements with py-* handlers attributes */ + function initHandlers(interpreter) { + logger$6.debug('Initializing py-* event handlers...'); + for (const pyAttribute of pyAttributeToEvent.keys()) { + createElementsWithEventListeners(interpreter, pyAttribute); + } + } + /** Initializes an element with the given py-on* attribute and its handler */ + function createElementsWithEventListeners(interpreter, pyAttribute) { + const matches = document.querySelectorAll(`[${pyAttribute}]`); + for (const el of matches) { + // If the element doesn't have an id, let's add one automatically! + if (el.id.length === 0) { + ensureUniqueId(el); + } + const handlerCode = el.getAttribute(pyAttribute); + const event = pyAttributeToEvent.get(pyAttribute); + if (pyAttribute === 'pys-onClick' || pyAttribute === 'pys-onKeyDown') { + const msg = `The attribute 'pys-onClick' and 'pys-onKeyDown' are deprecated. Please 'py-click="myFunction()"' ` + + ` or 'py-keydown="myFunction()"' instead.`; + createDeprecationWarning(msg, msg); + const source = ` from pyodide.ffi import create_proxy Element("${el.id}").element.addEventListener("${event}", create_proxy(${handlerCode})) `; - await runtime.run(source); - } - else { - el.addEventListener(event, () => { - (async () => { await runtime.run(handlerCode); })(); - }); - } - // TODO: Should we actually map handlers in JS instead of Python? - // el.onclick = (evt: any) => { - // console.log("click"); - // new Promise((resolve, reject) => { - // setTimeout(() => { - // console.log('Inside') - // }, 300); - // }).then(() => { - // console.log("resolved") - // }); - // // let handlerCode = el.getAttribute('py-onClick'); - // // pyodide.runPython(handlerCode); - // } - } - } - /** Mount all elements with attribute py-mount into the Python namespace */ - async function mountElements() { - const matches = document.querySelectorAll('[py-mount]'); - logger$a.info(`py-mount: found ${matches.length} elements`); - let source = ''; - for (const el of matches) { - const mountName = el.getAttribute('py-mount') || el.id.split('-').join('_'); - source += `\n${mountName} = Element("${el.id}")`; - } - await runtime$1.run(source); - } - addInitializer(mountElements); - addPostInitializer(initHandlers); - - /*! js-yaml 4.1.0 https://github.com/nodeca/js-yaml @license MIT */ - function isNothing(subject) { - return (typeof subject === 'undefined') || (subject === null); - } - - - function isObject(subject) { - return (typeof subject === 'object') && (subject !== null); - } - - - function toArray(sequence) { - if (Array.isArray(sequence)) return sequence; - else if (isNothing(sequence)) return []; - - return [ sequence ]; - } - - - function extend$1(target, source) { - var index, length, key, sourceKeys; - - if (source) { - sourceKeys = Object.keys(source); - - for (index = 0, length = sourceKeys.length; index < length; index += 1) { - key = sourceKeys[index]; - target[key] = source[key]; - } + // We meed to run the source code in a try/catch block, because + // the source code may contain a syntax error, which will cause + // the splashscreen to not be removed. + try { + interpreter.run(source); + } + catch (e) { + logger$6.error(e.message); + } + } + else { + el.addEventListener(event, () => { + void (async () => { + try { + await interpreter.run(handlerCode); + } + catch (err) { + displayPyException(err, el.parentElement); + } + })(); + }); + } + // TODO: Should we actually map handlers in JS instead of Python? + // el.onclick = (evt: any) => { + // console.log("click"); + // new Promise((resolve, reject) => { + // setTimeout(() => { + // console.log('Inside') + // }, 300); + // }).then(() => { + // console.log("resolved") + // }); + // // let handlerCode = el.getAttribute('py-onClick'); + // // pyodide.runPython(handlerCode); + // } } + } + /** Mount all elements with attribute py-mount into the Python namespace */ + async function mountElements(interpreter) { + const matches = document.querySelectorAll('[py-mount]'); + logger$6.info(`py-mount: found ${matches.length} elements`); + let source = ''; + for (const el of matches) { + const mountName = el.getAttribute('py-mount') || el.id.split('-').join('_'); + source += `\n${mountName} = Element("${el.id}")`; + } + await interpreter.run(source); + } + function calculatePaths(fetch_cfg) { + const fetchPaths = []; + const paths = []; + fetch_cfg.forEach(function (each_fetch_cfg) { + const from = each_fetch_cfg.from || ''; + const to_folder = each_fetch_cfg.to_folder || '.'; + const to_file = each_fetch_cfg.to_file; + const files = each_fetch_cfg.files; + if (files !== undefined) { + if (to_file !== undefined) { + throw new UserError(ErrorCode.BAD_CONFIG, `Cannot use 'to_file' and 'files' parameters together!`); + } + for (const each_f of files) { + const each_fetch_path = joinPaths([from, each_f]); + fetchPaths.push(each_fetch_path); + const each_path = joinPaths([to_folder, each_f]); + paths.push(each_path); + } + } + else { + fetchPaths.push(from); + const filename = to_file || from.split('/').pop(); + if (filename === '') { + throw new UserError(ErrorCode.BAD_CONFIG, `Couldn't determine the filename from the path ${from}, please supply 'to_file' parameter.`); + } + else { + paths.push(joinPaths([to_folder, filename])); + } + } + }); + return [paths, fetchPaths]; + } + + /** + The data structure for documents. @nonabstract + */ + class Text { + /** + @internal + */ + constructor() { } + /** + Get the line description around the given position. + */ + lineAt(pos) { + if (pos < 0 || pos > this.length) + throw new RangeError(`Invalid position ${pos} in document of length ${this.length}`); + return this.lineInner(pos, false, 1, 0); + } + /** + Get the description for the given (1-based) line number. + */ + line(n) { + if (n < 1 || n > this.lines) + throw new RangeError(`Invalid line number ${n} in ${this.lines}-line document`); + return this.lineInner(n, true, 1, 0); + } + /** + Replace a range of the text with the given content. + */ + replace(from, to, text) { + let parts = []; + this.decompose(0, from, parts, 2 /* Open.To */); + if (text.length) + text.decompose(0, text.length, parts, 1 /* Open.From */ | 2 /* Open.To */); + this.decompose(to, this.length, parts, 1 /* Open.From */); + return TextNode.from(parts, this.length - (to - from) + text.length); + } + /** + Append another document to this one. + */ + append(other) { + return this.replace(this.length, this.length, other); + } + /** + Retrieve the text between the given points. + */ + slice(from, to = this.length) { + let parts = []; + this.decompose(from, to, parts, 0); + return TextNode.from(parts, to - from); + } + /** + Test whether this text is equal to another instance. + */ + eq(other) { + if (other == this) + return true; + if (other.length != this.length || other.lines != this.lines) + return false; + let start = this.scanIdentical(other, 1), end = this.length - this.scanIdentical(other, -1); + let a = new RawTextCursor(this), b = new RawTextCursor(other); + for (let skip = start, pos = start;;) { + a.next(skip); + b.next(skip); + skip = 0; + if (a.lineBreak != b.lineBreak || a.done != b.done || a.value != b.value) + return false; + pos += a.value.length; + if (a.done || pos >= end) + return true; + } + } + /** + Iterate over the text. When `dir` is `-1`, iteration happens + from end to start. This will return lines and the breaks between + them as separate strings. + */ + iter(dir = 1) { return new RawTextCursor(this, dir); } + /** + Iterate over a range of the text. When `from` > `to`, the + iterator will run in reverse. + */ + iterRange(from, to = this.length) { return new PartialTextCursor(this, from, to); } + /** + Return a cursor that iterates over the given range of lines, + _without_ returning the line breaks between, and yielding empty + strings for empty lines. + + When `from` and `to` are given, they should be 1-based line numbers. + */ + iterLines(from, to) { + let inner; + if (from == null) { + inner = this.iter(); + } + else { + if (to == null) + to = this.lines + 1; + let start = this.line(from).from; + inner = this.iterRange(start, Math.max(start, to == this.lines + 1 ? this.length : to <= 1 ? 0 : this.line(to - 1).to)); + } + return new LineCursor(inner); + } + /** + @internal + */ + toString() { return this.sliceString(0); } + /** + Convert the document to an array of lines (which can be + deserialized again via [`Text.of`](https://codemirror.net/6/docs/ref/#state.Text^of)). + */ + toJSON() { + let lines = []; + this.flatten(lines); + return lines; + } + /** + Create a `Text` instance for the given array of lines. + */ + static of(text) { + if (text.length == 0) + throw new RangeError("A document must have at least one line"); + if (text.length == 1 && !text[0]) + return Text.empty; + return text.length <= 32 /* Tree.Branch */ ? new TextLeaf(text) : TextNode.from(TextLeaf.split(text, [])); + } + } + // Leaves store an array of line strings. There are always line breaks + // between these strings. Leaves are limited in size and have to be + // contained in TextNode instances for bigger documents. + class TextLeaf extends Text { + constructor(text, length = textLength(text)) { + super(); + this.text = text; + this.length = length; + } + get lines() { return this.text.length; } + get children() { return null; } + lineInner(target, isLine, line, offset) { + for (let i = 0;; i++) { + let string = this.text[i], end = offset + string.length; + if ((isLine ? line : end) >= target) + return new Line(offset, end, line, string); + offset = end + 1; + line++; + } + } + decompose(from, to, target, open) { + let text = from <= 0 && to >= this.length ? this + : new TextLeaf(sliceText(this.text, from, to), Math.min(to, this.length) - Math.max(0, from)); + if (open & 1 /* Open.From */) { + let prev = target.pop(); + let joined = appendText(text.text, prev.text.slice(), 0, text.length); + if (joined.length <= 32 /* Tree.Branch */) { + target.push(new TextLeaf(joined, prev.length + text.length)); + } + else { + let mid = joined.length >> 1; + target.push(new TextLeaf(joined.slice(0, mid)), new TextLeaf(joined.slice(mid))); + } + } + else { + target.push(text); + } + } + replace(from, to, text) { + if (!(text instanceof TextLeaf)) + return super.replace(from, to, text); + let lines = appendText(this.text, appendText(text.text, sliceText(this.text, 0, from)), to); + let newLen = this.length + text.length - (to - from); + if (lines.length <= 32 /* Tree.Branch */) + return new TextLeaf(lines, newLen); + return TextNode.from(TextLeaf.split(lines, []), newLen); + } + sliceString(from, to = this.length, lineSep = "\n") { + let result = ""; + for (let pos = 0, i = 0; pos <= to && i < this.text.length; i++) { + let line = this.text[i], end = pos + line.length; + if (pos > from && i) + result += lineSep; + if (from < end && to > pos) + result += line.slice(Math.max(0, from - pos), to - pos); + pos = end + 1; + } + return result; + } + flatten(target) { + for (let line of this.text) + target.push(line); + } + scanIdentical() { return 0; } + static split(text, target) { + let part = [], len = -1; + for (let line of text) { + part.push(line); + len += line.length + 1; + if (part.length == 32 /* Tree.Branch */) { + target.push(new TextLeaf(part, len)); + part = []; + len = -1; + } + } + if (len > -1) + target.push(new TextLeaf(part, len)); + return target; + } + } + // Nodes provide the tree structure of the `Text` type. They store a + // number of other nodes or leaves, taking care to balance themselves + // on changes. There are implied line breaks _between_ the children of + // a node (but not before the first or after the last child). + class TextNode extends Text { + constructor(children, length) { + super(); + this.children = children; + this.length = length; + this.lines = 0; + for (let child of children) + this.lines += child.lines; + } + lineInner(target, isLine, line, offset) { + for (let i = 0;; i++) { + let child = this.children[i], end = offset + child.length, endLine = line + child.lines - 1; + if ((isLine ? endLine : end) >= target) + return child.lineInner(target, isLine, line, offset); + offset = end + 1; + line = endLine + 1; + } + } + decompose(from, to, target, open) { + for (let i = 0, pos = 0; pos <= to && i < this.children.length; i++) { + let child = this.children[i], end = pos + child.length; + if (from <= end && to >= pos) { + let childOpen = open & ((pos <= from ? 1 /* Open.From */ : 0) | (end >= to ? 2 /* Open.To */ : 0)); + if (pos >= from && end <= to && !childOpen) + target.push(child); + else + child.decompose(from - pos, to - pos, target, childOpen); + } + pos = end + 1; + } + } + replace(from, to, text) { + if (text.lines < this.lines) + for (let i = 0, pos = 0; i < this.children.length; i++) { + let child = this.children[i], end = pos + child.length; + // Fast path: if the change only affects one child and the + // child's size remains in the acceptable range, only update + // that child + if (from >= pos && to <= end) { + let updated = child.replace(from - pos, to - pos, text); + let totalLines = this.lines - child.lines + updated.lines; + if (updated.lines < (totalLines >> (5 /* Tree.BranchShift */ - 1)) && + updated.lines > (totalLines >> (5 /* Tree.BranchShift */ + 1))) { + let copy = this.children.slice(); + copy[i] = updated; + return new TextNode(copy, this.length - (to - from) + text.length); + } + return super.replace(pos, end, updated); + } + pos = end + 1; + } + return super.replace(from, to, text); + } + sliceString(from, to = this.length, lineSep = "\n") { + let result = ""; + for (let i = 0, pos = 0; i < this.children.length && pos <= to; i++) { + let child = this.children[i], end = pos + child.length; + if (pos > from && i) + result += lineSep; + if (from < end && to > pos) + result += child.sliceString(from - pos, to - pos, lineSep); + pos = end + 1; + } + return result; + } + flatten(target) { + for (let child of this.children) + child.flatten(target); + } + scanIdentical(other, dir) { + if (!(other instanceof TextNode)) + return 0; + let length = 0; + let [iA, iB, eA, eB] = dir > 0 ? [0, 0, this.children.length, other.children.length] + : [this.children.length - 1, other.children.length - 1, -1, -1]; + for (;; iA += dir, iB += dir) { + if (iA == eA || iB == eB) + return length; + let chA = this.children[iA], chB = other.children[iB]; + if (chA != chB) + return length + chA.scanIdentical(chB, dir); + length += chA.length + 1; + } + } + static from(children, length = children.reduce((l, ch) => l + ch.length + 1, -1)) { + let lines = 0; + for (let ch of children) + lines += ch.lines; + if (lines < 32 /* Tree.Branch */) { + let flat = []; + for (let ch of children) + ch.flatten(flat); + return new TextLeaf(flat, length); + } + let chunk = Math.max(32 /* Tree.Branch */, lines >> 5 /* Tree.BranchShift */), maxChunk = chunk << 1, minChunk = chunk >> 1; + let chunked = [], currentLines = 0, currentLen = -1, currentChunk = []; + function add(child) { + let last; + if (child.lines > maxChunk && child instanceof TextNode) { + for (let node of child.children) + add(node); + } + else if (child.lines > minChunk && (currentLines > minChunk || !currentLines)) { + flush(); + chunked.push(child); + } + else if (child instanceof TextLeaf && currentLines && + (last = currentChunk[currentChunk.length - 1]) instanceof TextLeaf && + child.lines + last.lines <= 32 /* Tree.Branch */) { + currentLines += child.lines; + currentLen += child.length + 1; + currentChunk[currentChunk.length - 1] = new TextLeaf(last.text.concat(child.text), last.length + 1 + child.length); + } + else { + if (currentLines + child.lines > chunk) + flush(); + currentLines += child.lines; + currentLen += child.length + 1; + currentChunk.push(child); + } + } + function flush() { + if (currentLines == 0) + return; + chunked.push(currentChunk.length == 1 ? currentChunk[0] : TextNode.from(currentChunk, currentLen)); + currentLen = -1; + currentLines = currentChunk.length = 0; + } + for (let child of children) + add(child); + flush(); + return chunked.length == 1 ? chunked[0] : new TextNode(chunked, length); + } + } + Text.empty = /*@__PURE__*/new TextLeaf([""], 0); + function textLength(text) { + let length = -1; + for (let line of text) + length += line.length + 1; + return length; + } + function appendText(text, target, from = 0, to = 1e9) { + for (let pos = 0, i = 0, first = true; i < text.length && pos <= to; i++) { + let line = text[i], end = pos + line.length; + if (end >= from) { + if (end > to) + line = line.slice(0, to - pos); + if (pos < from) + line = line.slice(from - pos); + if (first) { + target[target.length - 1] += line; + first = false; + } + else + target.push(line); + } + pos = end + 1; + } return target; - } - - - function repeat(string, count) { - var result = '', cycle; - - for (cycle = 0; cycle < count; cycle += 1) { - result += string; + } + function sliceText(text, from, to) { + return appendText(text, [""], from, to); + } + class RawTextCursor { + constructor(text, dir = 1) { + this.dir = dir; + this.done = false; + this.lineBreak = false; + this.value = ""; + this.nodes = [text]; + this.offsets = [dir > 0 ? 1 : (text instanceof TextLeaf ? text.text.length : text.children.length) << 1]; } - - return result; - } - - - function isNegativeZero(number) { - return (number === 0) && (Number.NEGATIVE_INFINITY === 1 / number); - } - - - var isNothing_1 = isNothing; - var isObject_1 = isObject; - var toArray_1 = toArray; - var repeat_1 = repeat; - var isNegativeZero_1 = isNegativeZero; - var extend_1 = extend$1; - - var common = { - isNothing: isNothing_1, - isObject: isObject_1, - toArray: toArray_1, - repeat: repeat_1, - isNegativeZero: isNegativeZero_1, - extend: extend_1 - }; - - // YAML error class. http://stackoverflow.com/questions/8458984 - - - function formatError(exception, compact) { - var where = '', message = exception.reason || '(unknown reason)'; - - if (!exception.mark) return message; - - if (exception.mark.name) { - where += 'in "' + exception.mark.name + '" '; - } - - where += '(' + (exception.mark.line + 1) + ':' + (exception.mark.column + 1) + ')'; - - if (!compact && exception.mark.snippet) { - where += '\n\n' + exception.mark.snippet; - } - - return message + ' ' + where; - } - - - function YAMLException$1(reason, mark) { - // Super constructor - Error.call(this); - - this.name = 'YAMLException'; - this.reason = reason; - this.mark = mark; - this.message = formatError(this, false); - - // Include stack trace in error object - if (Error.captureStackTrace) { - // Chrome and NodeJS - Error.captureStackTrace(this, this.constructor); - } else { - // FF, IE 10+ and Safari 6+. Fallback for others - this.stack = (new Error()).stack || ''; - } - } - - - // Inherit from Error - YAMLException$1.prototype = Object.create(Error.prototype); - YAMLException$1.prototype.constructor = YAMLException$1; - - - YAMLException$1.prototype.toString = function toString(compact) { - return this.name + ': ' + formatError(this, compact); - }; - - - var exception = YAMLException$1; - - // get snippet for a single line, respecting maxLength - function getLine(buffer, lineStart, lineEnd, position, maxLineLength) { - var head = ''; - var tail = ''; - var maxHalfLength = Math.floor(maxLineLength / 2) - 1; - - if (position - lineStart > maxHalfLength) { - head = ' ... '; - lineStart = position - maxHalfLength + head.length; - } - - if (lineEnd - position > maxHalfLength) { - tail = ' ...'; - lineEnd = position + maxHalfLength - tail.length; - } - - return { - str: head + buffer.slice(lineStart, lineEnd).replace(/\t/g, '→') + tail, - pos: position - lineStart + head.length // relative position - }; - } - - - function padStart(string, max) { - return common.repeat(' ', max - string.length) + string; - } - - - function makeSnippet(mark, options) { - options = Object.create(options || null); - - if (!mark.buffer) return null; - - if (!options.maxLength) options.maxLength = 79; - if (typeof options.indent !== 'number') options.indent = 1; - if (typeof options.linesBefore !== 'number') options.linesBefore = 3; - if (typeof options.linesAfter !== 'number') options.linesAfter = 2; - - var re = /\r?\n|\r|\0/g; - var lineStarts = [ 0 ]; - var lineEnds = []; - var match; - var foundLineNo = -1; - - while ((match = re.exec(mark.buffer))) { - lineEnds.push(match.index); - lineStarts.push(match.index + match[0].length); - - if (mark.position <= match.index && foundLineNo < 0) { - foundLineNo = lineStarts.length - 2; - } - } - - if (foundLineNo < 0) foundLineNo = lineStarts.length - 1; - - var result = '', i, line; - var lineNoLength = Math.min(mark.line + options.linesAfter, lineEnds.length).toString().length; - var maxLineLength = options.maxLength - (options.indent + lineNoLength + 3); - - for (i = 1; i <= options.linesBefore; i++) { - if (foundLineNo - i < 0) break; - line = getLine( - mark.buffer, - lineStarts[foundLineNo - i], - lineEnds[foundLineNo - i], - mark.position - (lineStarts[foundLineNo] - lineStarts[foundLineNo - i]), - maxLineLength - ); - result = common.repeat(' ', options.indent) + padStart((mark.line - i + 1).toString(), lineNoLength) + - ' | ' + line.str + '\n' + result; - } - - line = getLine(mark.buffer, lineStarts[foundLineNo], lineEnds[foundLineNo], mark.position, maxLineLength); - result += common.repeat(' ', options.indent) + padStart((mark.line + 1).toString(), lineNoLength) + - ' | ' + line.str + '\n'; - result += common.repeat('-', options.indent + lineNoLength + 3 + line.pos) + '^' + '\n'; - - for (i = 1; i <= options.linesAfter; i++) { - if (foundLineNo + i >= lineEnds.length) break; - line = getLine( - mark.buffer, - lineStarts[foundLineNo + i], - lineEnds[foundLineNo + i], - mark.position - (lineStarts[foundLineNo] - lineStarts[foundLineNo + i]), - maxLineLength - ); - result += common.repeat(' ', options.indent) + padStart((mark.line + i + 1).toString(), lineNoLength) + - ' | ' + line.str + '\n'; - } - - return result.replace(/\n$/, ''); - } - - - var snippet = makeSnippet; - - var TYPE_CONSTRUCTOR_OPTIONS = [ - 'kind', - 'multi', - 'resolve', - 'construct', - 'instanceOf', - 'predicate', - 'represent', - 'representName', - 'defaultStyle', - 'styleAliases' - ]; - - var YAML_NODE_KINDS = [ - 'scalar', - 'sequence', - 'mapping' - ]; - - function compileStyleAliases(map) { - var result = {}; - - if (map !== null) { - Object.keys(map).forEach(function (style) { - map[style].forEach(function (alias) { - result[String(alias)] = style; - }); - }); - } - - return result; - } - - function Type$1(tag, options) { - options = options || {}; - - Object.keys(options).forEach(function (name) { - if (TYPE_CONSTRUCTOR_OPTIONS.indexOf(name) === -1) { - throw new exception('Unknown option "' + name + '" is met in definition of "' + tag + '" YAML type.'); - } - }); - - // TODO: Add tag format check. - this.options = options; // keep original options in case user wants to extend this type later - this.tag = tag; - this.kind = options['kind'] || null; - this.resolve = options['resolve'] || function () { return true; }; - this.construct = options['construct'] || function (data) { return data; }; - this.instanceOf = options['instanceOf'] || null; - this.predicate = options['predicate'] || null; - this.represent = options['represent'] || null; - this.representName = options['representName'] || null; - this.defaultStyle = options['defaultStyle'] || null; - this.multi = options['multi'] || false; - this.styleAliases = compileStyleAliases(options['styleAliases'] || null); - - if (YAML_NODE_KINDS.indexOf(this.kind) === -1) { - throw new exception('Unknown kind "' + this.kind + '" is specified for "' + tag + '" YAML type.'); - } - } - - var type = Type$1; - - /*eslint-disable max-len*/ - - - - - - function compileList(schema, name) { - var result = []; - - schema[name].forEach(function (currentType) { - var newIndex = result.length; - - result.forEach(function (previousType, previousIndex) { - if (previousType.tag === currentType.tag && - previousType.kind === currentType.kind && - previousType.multi === currentType.multi) { - - newIndex = previousIndex; + nextInner(skip, dir) { + this.done = this.lineBreak = false; + for (;;) { + let last = this.nodes.length - 1; + let top = this.nodes[last], offsetValue = this.offsets[last], offset = offsetValue >> 1; + let size = top instanceof TextLeaf ? top.text.length : top.children.length; + if (offset == (dir > 0 ? size : 0)) { + if (last == 0) { + this.done = true; + this.value = ""; + return this; + } + if (dir > 0) + this.offsets[last - 1]++; + this.nodes.pop(); + this.offsets.pop(); + } + else if ((offsetValue & 1) == (dir > 0 ? 0 : 1)) { + this.offsets[last] += dir; + if (skip == 0) { + this.lineBreak = true; + this.value = "\n"; + return this; + } + skip--; + } + else if (top instanceof TextLeaf) { + // Move to the next string + let next = top.text[offset + (dir < 0 ? -1 : 0)]; + this.offsets[last] += dir; + if (next.length > Math.max(0, skip)) { + this.value = skip == 0 ? next : dir > 0 ? next.slice(skip) : next.slice(0, next.length - skip); + return this; + } + skip -= next.length; + } + else { + let next = top.children[offset + (dir < 0 ? -1 : 0)]; + if (skip > next.length) { + skip -= next.length; + this.offsets[last] += dir; + } + else { + if (dir < 0) + this.offsets[last]--; + this.nodes.push(next); + this.offsets.push(dir > 0 ? 1 : (next instanceof TextLeaf ? next.text.length : next.children.length) << 1); + } + } } - }); - - result[newIndex] = currentType; - }); - - return result; - } - - - function compileMap(/* lists... */) { - var result = { - scalar: {}, - sequence: {}, - mapping: {}, - fallback: {}, - multi: { - scalar: [], - sequence: [], - mapping: [], - fallback: [] - } - }, index, length; - - function collectType(type) { - if (type.multi) { - result.multi[type.kind].push(type); - result.multi['fallback'].push(type); - } else { - result[type.kind][type.tag] = result['fallback'][type.tag] = type; - } } - - for (index = 0, length = arguments.length; index < length; index += 1) { - arguments[index].forEach(collectType); - } - return result; - } - - - function Schema$1(definition) { - return this.extend(definition); - } - - - Schema$1.prototype.extend = function extend(definition) { - var implicit = []; - var explicit = []; - - if (definition instanceof type) { - // Schema.extend(type) - explicit.push(definition); - - } else if (Array.isArray(definition)) { - // Schema.extend([ type1, type2, ... ]) - explicit = explicit.concat(definition); - - } else if (definition && (Array.isArray(definition.implicit) || Array.isArray(definition.explicit))) { - // Schema.extend({ explicit: [ type1, type2, ... ], implicit: [ type1, type2, ... ] }) - if (definition.implicit) implicit = implicit.concat(definition.implicit); - if (definition.explicit) explicit = explicit.concat(definition.explicit); - - } else { - throw new exception('Schema.extend argument should be a Type, [ Type ], ' + - 'or a schema definition ({ implicit: [...], explicit: [...] })'); - } - - implicit.forEach(function (type$1) { - if (!(type$1 instanceof type)) { - throw new exception('Specified list of YAML types (or a single Type object) contains a non-Type object.'); - } - - if (type$1.loadKind && type$1.loadKind !== 'scalar') { - throw new exception('There is a non-scalar type in the implicit list of a schema. Implicit resolving of such types is not supported.'); - } - - if (type$1.multi) { - throw new exception('There is a multi type in the implicit list of a schema. Multi tags can only be listed as explicit.'); - } - }); - - explicit.forEach(function (type$1) { - if (!(type$1 instanceof type)) { - throw new exception('Specified list of YAML types (or a single Type object) contains a non-Type object.'); - } - }); - - var result = Object.create(Schema$1.prototype); - - result.implicit = (this.implicit || []).concat(implicit); - result.explicit = (this.explicit || []).concat(explicit); - - result.compiledImplicit = compileList(result, 'implicit'); - result.compiledExplicit = compileList(result, 'explicit'); - result.compiledTypeMap = compileMap(result.compiledImplicit, result.compiledExplicit); - - return result; - }; - - - var schema = Schema$1; - - var str = new type('tag:yaml.org,2002:str', { - kind: 'scalar', - construct: function (data) { return data !== null ? data : ''; } - }); - - var seq = new type('tag:yaml.org,2002:seq', { - kind: 'sequence', - construct: function (data) { return data !== null ? data : []; } - }); - - var map = new type('tag:yaml.org,2002:map', { - kind: 'mapping', - construct: function (data) { return data !== null ? data : {}; } - }); - - var failsafe = new schema({ - explicit: [ - str, - seq, - map - ] - }); - - function resolveYamlNull(data) { - if (data === null) return true; - - var max = data.length; - - return (max === 1 && data === '~') || - (max === 4 && (data === 'null' || data === 'Null' || data === 'NULL')); - } - - function constructYamlNull() { - return null; - } - - function isNull(object) { - return object === null; - } - - var _null = new type('tag:yaml.org,2002:null', { - kind: 'scalar', - resolve: resolveYamlNull, - construct: constructYamlNull, - predicate: isNull, - represent: { - canonical: function () { return '~'; }, - lowercase: function () { return 'null'; }, - uppercase: function () { return 'NULL'; }, - camelcase: function () { return 'Null'; }, - empty: function () { return ''; } - }, - defaultStyle: 'lowercase' - }); - - function resolveYamlBoolean(data) { - if (data === null) return false; - - var max = data.length; - - return (max === 4 && (data === 'true' || data === 'True' || data === 'TRUE')) || - (max === 5 && (data === 'false' || data === 'False' || data === 'FALSE')); - } - - function constructYamlBoolean(data) { - return data === 'true' || - data === 'True' || - data === 'TRUE'; - } - - function isBoolean(object) { - return Object.prototype.toString.call(object) === '[object Boolean]'; - } - - var bool = new type('tag:yaml.org,2002:bool', { - kind: 'scalar', - resolve: resolveYamlBoolean, - construct: constructYamlBoolean, - predicate: isBoolean, - represent: { - lowercase: function (object) { return object ? 'true' : 'false'; }, - uppercase: function (object) { return object ? 'TRUE' : 'FALSE'; }, - camelcase: function (object) { return object ? 'True' : 'False'; } - }, - defaultStyle: 'lowercase' - }); - - function isHexCode(c) { - return ((0x30/* 0 */ <= c) && (c <= 0x39/* 9 */)) || - ((0x41/* A */ <= c) && (c <= 0x46/* F */)) || - ((0x61/* a */ <= c) && (c <= 0x66/* f */)); - } - - function isOctCode(c) { - return ((0x30/* 0 */ <= c) && (c <= 0x37/* 7 */)); - } - - function isDecCode(c) { - return ((0x30/* 0 */ <= c) && (c <= 0x39/* 9 */)); - } - - function resolveYamlInteger(data) { - if (data === null) return false; - - var max = data.length, - index = 0, - hasDigits = false, - ch; - - if (!max) return false; - - ch = data[index]; - - // sign - if (ch === '-' || ch === '+') { - ch = data[++index]; - } - - if (ch === '0') { - // 0 - if (index + 1 === max) return true; - ch = data[++index]; - - // base 2, base 8, base 16 - - if (ch === 'b') { - // base 2 - index++; - - for (; index < max; index++) { - ch = data[index]; - if (ch === '_') continue; - if (ch !== '0' && ch !== '1') return false; - hasDigits = true; + next(skip = 0) { + if (skip < 0) { + this.nextInner(-skip, (-this.dir)); + skip = this.value.length; } - return hasDigits && ch !== '_'; - } - - - if (ch === 'x') { - // base 16 - index++; - - for (; index < max; index++) { - ch = data[index]; - if (ch === '_') continue; - if (!isHexCode(data.charCodeAt(index))) return false; - hasDigits = true; + return this.nextInner(skip, this.dir); + } + } + class PartialTextCursor { + constructor(text, start, end) { + this.value = ""; + this.done = false; + this.cursor = new RawTextCursor(text, start > end ? -1 : 1); + this.pos = start > end ? text.length : 0; + this.from = Math.min(start, end); + this.to = Math.max(start, end); + } + nextInner(skip, dir) { + if (dir < 0 ? this.pos <= this.from : this.pos >= this.to) { + this.value = ""; + this.done = true; + return this; } - return hasDigits && ch !== '_'; - } - - - if (ch === 'o') { - // base 8 - index++; - - for (; index < max; index++) { - ch = data[index]; - if (ch === '_') continue; - if (!isOctCode(data.charCodeAt(index))) return false; - hasDigits = true; + skip += Math.max(0, dir < 0 ? this.pos - this.to : this.from - this.pos); + let limit = dir < 0 ? this.pos - this.from : this.to - this.pos; + if (skip > limit) + skip = limit; + limit -= skip; + let { value } = this.cursor.next(skip); + this.pos += (value.length + skip) * dir; + this.value = value.length <= limit ? value : dir < 0 ? value.slice(value.length - limit) : value.slice(0, limit); + this.done = !this.value; + return this; + } + next(skip = 0) { + if (skip < 0) + skip = Math.max(skip, this.from - this.pos); + else if (skip > 0) + skip = Math.min(skip, this.to - this.pos); + return this.nextInner(skip, this.cursor.dir); + } + get lineBreak() { return this.cursor.lineBreak && this.value != ""; } + } + class LineCursor { + constructor(inner) { + this.inner = inner; + this.afterBreak = true; + this.value = ""; + this.done = false; + } + next(skip = 0) { + let { done, lineBreak, value } = this.inner.next(skip); + if (done) { + this.done = true; + this.value = ""; } - return hasDigits && ch !== '_'; - } + else if (lineBreak) { + if (this.afterBreak) { + this.value = ""; + } + else { + this.afterBreak = true; + this.next(); + } + } + else { + this.value = value; + this.afterBreak = false; + } + return this; } - - // base 10 (except 0) - - // value should not start with `_`; - if (ch === '_') return false; - - for (; index < max; index++) { - ch = data[index]; - if (ch === '_') continue; - if (!isDecCode(data.charCodeAt(index))) { - return false; - } - hasDigits = true; + get lineBreak() { return false; } + } + if (typeof Symbol != "undefined") { + Text.prototype[Symbol.iterator] = function () { return this.iter(); }; + RawTextCursor.prototype[Symbol.iterator] = PartialTextCursor.prototype[Symbol.iterator] = + LineCursor.prototype[Symbol.iterator] = function () { return this; }; + } + /** + This type describes a line in the document. It is created + on-demand when lines are [queried](https://codemirror.net/6/docs/ref/#state.Text.lineAt). + */ + class Line { + /** + @internal + */ + constructor( + /** + The position of the start of the line. + */ + from, + /** + The position at the end of the line (_before_ the line break, + or at the end of document for the last line). + */ + to, + /** + This line's line number (1-based). + */ + number, + /** + The line's content. + */ + text) { + this.from = from; + this.to = to; + this.number = number; + this.text = text; } + /** + The length of the line (not including any line break after it). + */ + get length() { return this.to - this.from; } + } - // Should have digits and should not end with `_` - if (!hasDigits || ch === '_') return false; - - return true; - } - - function constructYamlInteger(data) { - var value = data, sign = 1, ch; - - if (value.indexOf('_') !== -1) { - value = value.replace(/_/g, ''); - } - - ch = value[0]; - - if (ch === '-' || ch === '+') { - if (ch === '-') sign = -1; - value = value.slice(1); - ch = value[0]; - } - - if (value === '0') return 0; - - if (ch === '0') { - if (value[1] === 'b') return sign * parseInt(value.slice(2), 2); - if (value[1] === 'x') return sign * parseInt(value.slice(2), 16); - if (value[1] === 'o') return sign * parseInt(value.slice(2), 8); - } - - return sign * parseInt(value, 10); - } - - function isInteger(object) { - return (Object.prototype.toString.call(object)) === '[object Number]' && - (object % 1 === 0 && !common.isNegativeZero(object)); - } - - var int = new type('tag:yaml.org,2002:int', { - kind: 'scalar', - resolve: resolveYamlInteger, - construct: constructYamlInteger, - predicate: isInteger, - represent: { - binary: function (obj) { return obj >= 0 ? '0b' + obj.toString(2) : '-0b' + obj.toString(2).slice(1); }, - octal: function (obj) { return obj >= 0 ? '0o' + obj.toString(8) : '-0o' + obj.toString(8).slice(1); }, - decimal: function (obj) { return obj.toString(10); }, - /* eslint-disable max-len */ - hexadecimal: function (obj) { return obj >= 0 ? '0x' + obj.toString(16).toUpperCase() : '-0x' + obj.toString(16).toUpperCase().slice(1); } - }, - defaultStyle: 'decimal', - styleAliases: { - binary: [ 2, 'bin' ], - octal: [ 8, 'oct' ], - decimal: [ 10, 'dec' ], - hexadecimal: [ 16, 'hex' ] - } - }); - - var YAML_FLOAT_PATTERN = new RegExp( - // 2.5e4, 2.5 and integers - '^(?:[-+]?(?:[0-9][0-9_]*)(?:\\.[0-9_]*)?(?:[eE][-+]?[0-9]+)?' + - // .2e4, .2 - // special case, seems not from spec - '|\\.[0-9_]+(?:[eE][-+]?[0-9]+)?' + - // .inf - '|[-+]?\\.(?:inf|Inf|INF)' + - // .nan - '|\\.(?:nan|NaN|NAN))$'); - - function resolveYamlFloat(data) { - if (data === null) return false; - - if (!YAML_FLOAT_PATTERN.test(data) || - // Quick hack to not allow integers end with `_` - // Probably should update regexp & check speed - data[data.length - 1] === '_') { - return false; - } - - return true; - } - - function constructYamlFloat(data) { - var value, sign; - - value = data.replace(/_/g, '').toLowerCase(); - sign = value[0] === '-' ? -1 : 1; - - if ('+-'.indexOf(value[0]) >= 0) { - value = value.slice(1); - } - - if (value === '.inf') { - return (sign === 1) ? Number.POSITIVE_INFINITY : Number.NEGATIVE_INFINITY; - - } else if (value === '.nan') { - return NaN; - } - return sign * parseFloat(value, 10); - } - - - var SCIENTIFIC_WITHOUT_DOT = /^[-+]?[0-9]+e/; - - function representYamlFloat(object, style) { - var res; - - if (isNaN(object)) { - switch (style) { - case 'lowercase': return '.nan'; - case 'uppercase': return '.NAN'; - case 'camelcase': return '.NaN'; - } - } else if (Number.POSITIVE_INFINITY === object) { - switch (style) { - case 'lowercase': return '.inf'; - case 'uppercase': return '.INF'; - case 'camelcase': return '.Inf'; - } - } else if (Number.NEGATIVE_INFINITY === object) { - switch (style) { - case 'lowercase': return '-.inf'; - case 'uppercase': return '-.INF'; - case 'camelcase': return '-.Inf'; - } - } else if (common.isNegativeZero(object)) { - return '-0.0'; - } - - res = object.toString(10); - - // JS stringifier can build scientific format without dots: 5e-100, - // while YAML requres dot: 5.e-100. Fix it with simple hack - - return SCIENTIFIC_WITHOUT_DOT.test(res) ? res.replace('e', '.e') : res; - } - - function isFloat(object) { - return (Object.prototype.toString.call(object) === '[object Number]') && - (object % 1 !== 0 || common.isNegativeZero(object)); - } - - var float = new type('tag:yaml.org,2002:float', { - kind: 'scalar', - resolve: resolveYamlFloat, - construct: constructYamlFloat, - predicate: isFloat, - represent: representYamlFloat, - defaultStyle: 'lowercase' - }); - - var json = failsafe.extend({ - implicit: [ - _null, - bool, - int, - float - ] - }); - - var core = json; - - var YAML_DATE_REGEXP = new RegExp( - '^([0-9][0-9][0-9][0-9])' + // [1] year - '-([0-9][0-9])' + // [2] month - '-([0-9][0-9])$'); // [3] day - - var YAML_TIMESTAMP_REGEXP = new RegExp( - '^([0-9][0-9][0-9][0-9])' + // [1] year - '-([0-9][0-9]?)' + // [2] month - '-([0-9][0-9]?)' + // [3] day - '(?:[Tt]|[ \\t]+)' + // ... - '([0-9][0-9]?)' + // [4] hour - ':([0-9][0-9])' + // [5] minute - ':([0-9][0-9])' + // [6] second - '(?:\\.([0-9]*))?' + // [7] fraction - '(?:[ \\t]*(Z|([-+])([0-9][0-9]?)' + // [8] tz [9] tz_sign [10] tz_hour - '(?::([0-9][0-9]))?))?$'); // [11] tz_minute - - function resolveYamlTimestamp(data) { - if (data === null) return false; - if (YAML_DATE_REGEXP.exec(data) !== null) return true; - if (YAML_TIMESTAMP_REGEXP.exec(data) !== null) return true; + // Compressed representation of the Grapheme_Cluster_Break=Extend + // information from + // http://www.unicode.org/Public/13.0.0/ucd/auxiliary/GraphemeBreakProperty.txt. + // Each pair of elements represents a range, as an offet from the + // previous range and a length. Numbers are in base-36, with the empty + // string being a shorthand for 1. + let extend = /*@__PURE__*/"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(s => s ? parseInt(s, 36) : 1); + // Convert offsets into absolute values + for (let i = 1; i < extend.length; i++) + extend[i] += extend[i - 1]; + function isExtendingChar(code) { + for (let i = 1; i < extend.length; i += 2) + if (extend[i] > code) + return extend[i - 1] <= code; return false; - } - - function constructYamlTimestamp(data) { - var match, year, month, day, hour, minute, second, fraction = 0, - delta = null, tz_hour, tz_minute, date; - - match = YAML_DATE_REGEXP.exec(data); - if (match === null) match = YAML_TIMESTAMP_REGEXP.exec(data); - - if (match === null) throw new Error('Date resolve error'); - - // match: [1] year [2] month [3] day - - year = +(match[1]); - month = +(match[2]) - 1; // JS month starts with 0 - day = +(match[3]); - - if (!match[4]) { // no hour - return new Date(Date.UTC(year, month, day)); - } - - // match: [4] hour [5] minute [6] second [7] fraction - - hour = +(match[4]); - minute = +(match[5]); - second = +(match[6]); - - if (match[7]) { - fraction = match[7].slice(0, 3); - while (fraction.length < 3) { // milli-seconds - fraction += '0'; - } - fraction = +fraction; - } - - // match: [8] tz [9] tz_sign [10] tz_hour [11] tz_minute - - if (match[9]) { - tz_hour = +(match[10]); - tz_minute = +(match[11] || 0); - delta = (tz_hour * 60 + tz_minute) * 60000; // delta in mili-seconds - if (match[9] === '-') delta = -delta; - } - - date = new Date(Date.UTC(year, month, day, hour, minute, second, fraction)); - - if (delta) date.setTime(date.getTime() - delta); - - return date; - } - - function representYamlTimestamp(object /*, style*/) { - return object.toISOString(); - } - - var timestamp = new type('tag:yaml.org,2002:timestamp', { - kind: 'scalar', - resolve: resolveYamlTimestamp, - construct: constructYamlTimestamp, - instanceOf: Date, - represent: representYamlTimestamp - }); - - function resolveYamlMerge(data) { - return data === '<<' || data === null; - } - - var merge = new type('tag:yaml.org,2002:merge', { - kind: 'scalar', - resolve: resolveYamlMerge - }); - - /*eslint-disable no-bitwise*/ - - - - - - // [ 64, 65, 66 ] -> [ padding, CR, LF ] - var BASE64_MAP = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=\n\r'; - - - function resolveYamlBinary(data) { - if (data === null) return false; - - var code, idx, bitlen = 0, max = data.length, map = BASE64_MAP; - - // Convert one by one. - for (idx = 0; idx < max; idx++) { - code = map.indexOf(data.charAt(idx)); - - // Skip CR/LF - if (code > 64) continue; - - // Fail on illegal characters - if (code < 0) return false; - - bitlen += 6; - } - - // If there are any bits left, source was corrupted - return (bitlen % 8) === 0; - } - - function constructYamlBinary(data) { - var idx, tailbits, - input = data.replace(/[\r\n=]/g, ''), // remove CR/LF & padding to simplify scan - max = input.length, - map = BASE64_MAP, - bits = 0, - result = []; - - // Collect by 6*4 bits (3 bytes) - - for (idx = 0; idx < max; idx++) { - if ((idx % 4 === 0) && idx) { - result.push((bits >> 16) & 0xFF); - result.push((bits >> 8) & 0xFF); - result.push(bits & 0xFF); - } - - bits = (bits << 6) | map.indexOf(input.charAt(idx)); - } - - // Dump tail - - tailbits = (max % 4) * 6; - - if (tailbits === 0) { - result.push((bits >> 16) & 0xFF); - result.push((bits >> 8) & 0xFF); - result.push(bits & 0xFF); - } else if (tailbits === 18) { - result.push((bits >> 10) & 0xFF); - result.push((bits >> 2) & 0xFF); - } else if (tailbits === 12) { - result.push((bits >> 4) & 0xFF); - } - - return new Uint8Array(result); - } - - function representYamlBinary(object /*, style*/) { - var result = '', bits = 0, idx, tail, - max = object.length, - map = BASE64_MAP; - - // Convert every three bytes to 4 ASCII characters. - - for (idx = 0; idx < max; idx++) { - if ((idx % 3 === 0) && idx) { - result += map[(bits >> 18) & 0x3F]; - result += map[(bits >> 12) & 0x3F]; - result += map[(bits >> 6) & 0x3F]; - result += map[bits & 0x3F]; - } - - bits = (bits << 8) + object[idx]; - } - - // Dump tail - - tail = max % 3; - - if (tail === 0) { - result += map[(bits >> 18) & 0x3F]; - result += map[(bits >> 12) & 0x3F]; - result += map[(bits >> 6) & 0x3F]; - result += map[bits & 0x3F]; - } else if (tail === 2) { - result += map[(bits >> 10) & 0x3F]; - result += map[(bits >> 4) & 0x3F]; - result += map[(bits << 2) & 0x3F]; - result += map[64]; - } else if (tail === 1) { - result += map[(bits >> 2) & 0x3F]; - result += map[(bits << 4) & 0x3F]; - result += map[64]; - result += map[64]; - } - - return result; - } - - function isBinary(obj) { - return Object.prototype.toString.call(obj) === '[object Uint8Array]'; - } - - var binary = new type('tag:yaml.org,2002:binary', { - kind: 'scalar', - resolve: resolveYamlBinary, - construct: constructYamlBinary, - predicate: isBinary, - represent: representYamlBinary - }); - - var _hasOwnProperty$3 = Object.prototype.hasOwnProperty; - var _toString$2 = Object.prototype.toString; - - function resolveYamlOmap(data) { - if (data === null) return true; - - var objectKeys = [], index, length, pair, pairKey, pairHasKey, - object = data; - - for (index = 0, length = object.length; index < length; index += 1) { - pair = object[index]; - pairHasKey = false; - - if (_toString$2.call(pair) !== '[object Object]') return false; - - for (pairKey in pair) { - if (_hasOwnProperty$3.call(pair, pairKey)) { - if (!pairHasKey) pairHasKey = true; - else return false; + } + function isRegionalIndicator(code) { + return code >= 0x1F1E6 && code <= 0x1F1FF; + } + const ZWJ = 0x200d; + /** + Returns a next grapheme cluster break _after_ (not equal to) + `pos`, if `forward` is true, or before otherwise. Returns `pos` + itself if no further cluster break is available in the string. + Moves across surrogate pairs, extending characters (when + `includeExtending` is true), characters joined with zero-width + joiners, and flag emoji. + */ + function findClusterBreak(str, pos, forward = true, includeExtending = true) { + return (forward ? nextClusterBreak : prevClusterBreak)(str, pos, includeExtending); + } + function nextClusterBreak(str, pos, includeExtending) { + if (pos == str.length) + return pos; + // If pos is in the middle of a surrogate pair, move to its start + if (pos && surrogateLow(str.charCodeAt(pos)) && surrogateHigh(str.charCodeAt(pos - 1))) + pos--; + let prev = codePointAt(str, pos); + pos += codePointSize(prev); + while (pos < str.length) { + let next = codePointAt(str, pos); + if (prev == ZWJ || next == ZWJ || includeExtending && isExtendingChar(next)) { + pos += codePointSize(next); + prev = next; } - } - - if (!pairHasKey) return false; - - if (objectKeys.indexOf(pairKey) === -1) objectKeys.push(pairKey); - else return false; - } - - return true; - } - - function constructYamlOmap(data) { - return data !== null ? data : []; - } - - var omap = new type('tag:yaml.org,2002:omap', { - kind: 'sequence', - resolve: resolveYamlOmap, - construct: constructYamlOmap - }); - - var _toString$1 = Object.prototype.toString; - - function resolveYamlPairs(data) { - if (data === null) return true; - - var index, length, pair, keys, result, - object = data; - - result = new Array(object.length); - - for (index = 0, length = object.length; index < length; index += 1) { - pair = object[index]; - - if (_toString$1.call(pair) !== '[object Object]') return false; - - keys = Object.keys(pair); - - if (keys.length !== 1) return false; - - result[index] = [ keys[0], pair[keys[0]] ]; - } - - return true; - } - - function constructYamlPairs(data) { - if (data === null) return []; - - var index, length, pair, keys, result, - object = data; - - result = new Array(object.length); - - for (index = 0, length = object.length; index < length; index += 1) { - pair = object[index]; - - keys = Object.keys(pair); - - result[index] = [ keys[0], pair[keys[0]] ]; - } - - return result; - } - - var pairs = new type('tag:yaml.org,2002:pairs', { - kind: 'sequence', - resolve: resolveYamlPairs, - construct: constructYamlPairs - }); - - var _hasOwnProperty$2 = Object.prototype.hasOwnProperty; - - function resolveYamlSet(data) { - if (data === null) return true; - - var key, object = data; - - for (key in object) { - if (_hasOwnProperty$2.call(object, key)) { - if (object[key] !== null) return false; - } - } - - return true; - } - - function constructYamlSet(data) { - return data !== null ? data : {}; - } - - var set = new type('tag:yaml.org,2002:set', { - kind: 'mapping', - resolve: resolveYamlSet, - construct: constructYamlSet - }); - - var _default = core.extend({ - implicit: [ - timestamp, - merge - ], - explicit: [ - binary, - omap, - pairs, - set - ] - }); - - /*eslint-disable max-len,no-use-before-define*/ - - - - - - - - var _hasOwnProperty$1 = Object.prototype.hasOwnProperty; - - - var CONTEXT_FLOW_IN = 1; - var CONTEXT_FLOW_OUT = 2; - var CONTEXT_BLOCK_IN = 3; - var CONTEXT_BLOCK_OUT = 4; - - - var CHOMPING_CLIP = 1; - var CHOMPING_STRIP = 2; - var CHOMPING_KEEP = 3; - - - var PATTERN_NON_PRINTABLE = /[\x00-\x08\x0B\x0C\x0E-\x1F\x7F-\x84\x86-\x9F\uFFFE\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]/; - var PATTERN_NON_ASCII_LINE_BREAKS = /[\x85\u2028\u2029]/; - var PATTERN_FLOW_INDICATORS = /[,\[\]\{\}]/; - var PATTERN_TAG_HANDLE = /^(?:!|!!|![a-z\-]+!)$/i; - var PATTERN_TAG_URI = /^(?:!|[^,\[\]\{\}])(?:%[0-9a-f]{2}|[0-9a-z\-#;\/\?:@&=\+\$,_\.!~\*'\(\)\[\]])*$/i; - - - function _class(obj) { return Object.prototype.toString.call(obj); } - - function is_EOL(c) { - return (c === 0x0A/* LF */) || (c === 0x0D/* CR */); - } - - function is_WHITE_SPACE(c) { - return (c === 0x09/* Tab */) || (c === 0x20/* Space */); - } - - function is_WS_OR_EOL(c) { - return (c === 0x09/* Tab */) || - (c === 0x20/* Space */) || - (c === 0x0A/* LF */) || - (c === 0x0D/* CR */); - } - - function is_FLOW_INDICATOR(c) { - return c === 0x2C/* , */ || - c === 0x5B/* [ */ || - c === 0x5D/* ] */ || - c === 0x7B/* { */ || - c === 0x7D/* } */; - } - - function fromHexCode(c) { - var lc; - - if ((0x30/* 0 */ <= c) && (c <= 0x39/* 9 */)) { - return c - 0x30; - } - - /*eslint-disable no-bitwise*/ - lc = c | 0x20; - - if ((0x61/* a */ <= lc) && (lc <= 0x66/* f */)) { - return lc - 0x61 + 10; - } - - return -1; - } - - function escapedHexLen(c) { - if (c === 0x78/* x */) { return 2; } - if (c === 0x75/* u */) { return 4; } - if (c === 0x55/* U */) { return 8; } - return 0; - } - - function fromDecimalCode(c) { - if ((0x30/* 0 */ <= c) && (c <= 0x39/* 9 */)) { - return c - 0x30; - } - - return -1; - } - - function simpleEscapeSequence(c) { - /* eslint-disable indent */ - return (c === 0x30/* 0 */) ? '\x00' : - (c === 0x61/* a */) ? '\x07' : - (c === 0x62/* b */) ? '\x08' : - (c === 0x74/* t */) ? '\x09' : - (c === 0x09/* Tab */) ? '\x09' : - (c === 0x6E/* n */) ? '\x0A' : - (c === 0x76/* v */) ? '\x0B' : - (c === 0x66/* f */) ? '\x0C' : - (c === 0x72/* r */) ? '\x0D' : - (c === 0x65/* e */) ? '\x1B' : - (c === 0x20/* Space */) ? ' ' : - (c === 0x22/* " */) ? '\x22' : - (c === 0x2F/* / */) ? '/' : - (c === 0x5C/* \ */) ? '\x5C' : - (c === 0x4E/* N */) ? '\x85' : - (c === 0x5F/* _ */) ? '\xA0' : - (c === 0x4C/* L */) ? '\u2028' : - (c === 0x50/* P */) ? '\u2029' : ''; - } - - function charFromCodepoint(c) { - if (c <= 0xFFFF) { - return String.fromCharCode(c); - } - // Encode UTF-16 surrogate pair - // https://en.wikipedia.org/wiki/UTF-16#Code_points_U.2B010000_to_U.2B10FFFF - return String.fromCharCode( - ((c - 0x010000) >> 10) + 0xD800, - ((c - 0x010000) & 0x03FF) + 0xDC00 - ); - } - - var simpleEscapeCheck = new Array(256); // integer, for fast access - var simpleEscapeMap = new Array(256); - for (var i$1 = 0; i$1 < 256; i$1++) { - simpleEscapeCheck[i$1] = simpleEscapeSequence(i$1) ? 1 : 0; - simpleEscapeMap[i$1] = simpleEscapeSequence(i$1); - } - - - function State$1(input, options) { - this.input = input; - - this.filename = options['filename'] || null; - this.schema = options['schema'] || _default; - this.onWarning = options['onWarning'] || null; - // (Hidden) Remove? makes the loader to expect YAML 1.1 documents - // if such documents have no explicit %YAML directive - this.legacy = options['legacy'] || false; - - this.json = options['json'] || false; - this.listener = options['listener'] || null; - - this.implicitTypes = this.schema.compiledImplicit; - this.typeMap = this.schema.compiledTypeMap; - - this.length = input.length; - this.position = 0; - this.line = 0; - this.lineStart = 0; - this.lineIndent = 0; - - // position of first leading tab in the current line, - // used to make sure there are no tabs in the indentation - this.firstTabInLine = -1; - - this.documents = []; - - /* - this.version; - this.checkLineBreaks; - this.tagMap; - this.anchorMap; - this.tag; - this.anchor; - this.kind; - this.result;*/ - - } - - - function generateError(state, message) { - var mark = { - name: state.filename, - buffer: state.input.slice(0, -1), // omit trailing \0 - position: state.position, - line: state.line, - column: state.position - state.lineStart - }; - - mark.snippet = snippet(mark); - - return new exception(message, mark); - } - - function throwError(state, message) { - throw generateError(state, message); - } - - function throwWarning(state, message) { - if (state.onWarning) { - state.onWarning.call(null, generateError(state, message)); - } - } - - - var directiveHandlers = { - - YAML: function handleYamlDirective(state, name, args) { - - var match, major, minor; - - if (state.version !== null) { - throwError(state, 'duplication of %YAML directive'); - } - - if (args.length !== 1) { - throwError(state, 'YAML directive accepts exactly one argument'); - } - - match = /^([0-9]+)\.([0-9]+)$/.exec(args[0]); - - if (match === null) { - throwError(state, 'ill-formed argument of the YAML directive'); - } - - major = parseInt(match[1], 10); - minor = parseInt(match[2], 10); - - if (major !== 1) { - throwError(state, 'unacceptable YAML version of the document'); - } - - state.version = args[0]; - state.checkLineBreaks = (minor < 2); - - if (minor !== 1 && minor !== 2) { - throwWarning(state, 'unsupported YAML version of the document'); - } - }, - - TAG: function handleTagDirective(state, name, args) { - - var handle, prefix; - - if (args.length !== 2) { - throwError(state, 'TAG directive accepts exactly two arguments'); - } - - handle = args[0]; - prefix = args[1]; - - if (!PATTERN_TAG_HANDLE.test(handle)) { - throwError(state, 'ill-formed tag handle (first argument) of the TAG directive'); - } - - if (_hasOwnProperty$1.call(state.tagMap, handle)) { - throwError(state, 'there is a previously declared suffix for "' + handle + '" tag handle'); - } - - if (!PATTERN_TAG_URI.test(prefix)) { - throwError(state, 'ill-formed tag prefix (second argument) of the TAG directive'); - } - - try { - prefix = decodeURIComponent(prefix); - } catch (err) { - throwError(state, 'tag prefix is malformed: ' + prefix); - } - - state.tagMap[handle] = prefix; - } - }; - - - function captureSegment(state, start, end, checkJson) { - var _position, _length, _character, _result; - - if (start < end) { - _result = state.input.slice(start, end); - - if (checkJson) { - for (_position = 0, _length = _result.length; _position < _length; _position += 1) { - _character = _result.charCodeAt(_position); - if (!(_character === 0x09 || - (0x20 <= _character && _character <= 0x10FFFF))) { - throwError(state, 'expected valid JSON character'); - } - } - } else if (PATTERN_NON_PRINTABLE.test(_result)) { - throwError(state, 'the stream contains non-printable characters'); - } - - state.result += _result; - } - } - - function mergeMappings(state, destination, source, overridableKeys) { - var sourceKeys, key, index, quantity; - - if (!common.isObject(source)) { - throwError(state, 'cannot merge mappings; the provided source object is unacceptable'); - } - - sourceKeys = Object.keys(source); - - for (index = 0, quantity = sourceKeys.length; index < quantity; index += 1) { - key = sourceKeys[index]; - - if (!_hasOwnProperty$1.call(destination, key)) { - destination[key] = source[key]; - overridableKeys[key] = true; - } - } - } - - function storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, valueNode, - startLine, startLineStart, startPos) { - - var index, quantity; - - // The output is a plain object here, so keys can only be strings. - // We need to convert keyNode to a string, but doing so can hang the process - // (deeply nested arrays that explode exponentially using aliases). - if (Array.isArray(keyNode)) { - keyNode = Array.prototype.slice.call(keyNode); - - for (index = 0, quantity = keyNode.length; index < quantity; index += 1) { - if (Array.isArray(keyNode[index])) { - throwError(state, 'nested arrays are not supported inside keys'); - } - - if (typeof keyNode === 'object' && _class(keyNode[index]) === '[object Object]') { - keyNode[index] = '[object Object]'; - } - } - } - - // Avoid code execution in load() via toString property - // (still use its own toString for arrays, timestamps, - // and whatever user schema extensions happen to have @@toStringTag) - if (typeof keyNode === 'object' && _class(keyNode) === '[object Object]') { - keyNode = '[object Object]'; - } - - - keyNode = String(keyNode); - - if (_result === null) { - _result = {}; - } - - if (keyTag === 'tag:yaml.org,2002:merge') { - if (Array.isArray(valueNode)) { - for (index = 0, quantity = valueNode.length; index < quantity; index += 1) { - mergeMappings(state, _result, valueNode[index], overridableKeys); - } - } else { - mergeMappings(state, _result, valueNode, overridableKeys); - } - } else { - if (!state.json && - !_hasOwnProperty$1.call(overridableKeys, keyNode) && - _hasOwnProperty$1.call(_result, keyNode)) { - state.line = startLine || state.line; - state.lineStart = startLineStart || state.lineStart; - state.position = startPos || state.position; - throwError(state, 'duplicated mapping key'); - } - - // used for this specific key only because Object.defineProperty is slow - if (keyNode === '__proto__') { - Object.defineProperty(_result, keyNode, { - configurable: true, - enumerable: true, - writable: true, - value: valueNode - }); - } else { - _result[keyNode] = valueNode; - } - delete overridableKeys[keyNode]; - } - - return _result; - } - - function readLineBreak(state) { - var ch; - - ch = state.input.charCodeAt(state.position); - - if (ch === 0x0A/* LF */) { - state.position++; - } else if (ch === 0x0D/* CR */) { - state.position++; - if (state.input.charCodeAt(state.position) === 0x0A/* LF */) { - state.position++; - } - } else { - throwError(state, 'a line break is expected'); - } - - state.line += 1; - state.lineStart = state.position; - state.firstTabInLine = -1; - } - - function skipSeparationSpace(state, allowComments, checkIndent) { - var lineBreaks = 0, - ch = state.input.charCodeAt(state.position); - - while (ch !== 0) { - while (is_WHITE_SPACE(ch)) { - if (ch === 0x09/* Tab */ && state.firstTabInLine === -1) { - state.firstTabInLine = state.position; - } - ch = state.input.charCodeAt(++state.position); - } - - if (allowComments && ch === 0x23/* # */) { - do { - ch = state.input.charCodeAt(++state.position); - } while (ch !== 0x0A/* LF */ && ch !== 0x0D/* CR */ && ch !== 0); - } - - if (is_EOL(ch)) { - readLineBreak(state); - - ch = state.input.charCodeAt(state.position); - lineBreaks++; - state.lineIndent = 0; - - while (ch === 0x20/* Space */) { - state.lineIndent++; - ch = state.input.charCodeAt(++state.position); - } - } else { - break; - } - } - - if (checkIndent !== -1 && lineBreaks !== 0 && state.lineIndent < checkIndent) { - throwWarning(state, 'deficient indentation'); - } - - return lineBreaks; - } - - function testDocumentSeparator(state) { - var _position = state.position, - ch; - - ch = state.input.charCodeAt(_position); - - // Condition state.position === state.lineStart is tested - // in parent on each call, for efficiency. No needs to test here again. - if ((ch === 0x2D/* - */ || ch === 0x2E/* . */) && - ch === state.input.charCodeAt(_position + 1) && - ch === state.input.charCodeAt(_position + 2)) { - - _position += 3; - - ch = state.input.charCodeAt(_position); - - if (ch === 0 || is_WS_OR_EOL(ch)) { - return true; - } - } - - return false; - } - - function writeFoldedLines(state, count) { - if (count === 1) { - state.result += ' '; - } else if (count > 1) { - state.result += common.repeat('\n', count - 1); - } - } - - - function readPlainScalar(state, nodeIndent, withinFlowCollection) { - var preceding, - following, - captureStart, - captureEnd, - hasPendingContent, - _line, - _lineStart, - _lineIndent, - _kind = state.kind, - _result = state.result, - ch; - - ch = state.input.charCodeAt(state.position); - - if (is_WS_OR_EOL(ch) || - is_FLOW_INDICATOR(ch) || - ch === 0x23/* # */ || - ch === 0x26/* & */ || - ch === 0x2A/* * */ || - ch === 0x21/* ! */ || - ch === 0x7C/* | */ || - ch === 0x3E/* > */ || - ch === 0x27/* ' */ || - ch === 0x22/* " */ || - ch === 0x25/* % */ || - ch === 0x40/* @ */ || - ch === 0x60/* ` */) { - return false; - } - - if (ch === 0x3F/* ? */ || ch === 0x2D/* - */) { - following = state.input.charCodeAt(state.position + 1); - - if (is_WS_OR_EOL(following) || - withinFlowCollection && is_FLOW_INDICATOR(following)) { - return false; - } - } - - state.kind = 'scalar'; - state.result = ''; - captureStart = captureEnd = state.position; - hasPendingContent = false; - - while (ch !== 0) { - if (ch === 0x3A/* : */) { - following = state.input.charCodeAt(state.position + 1); - - if (is_WS_OR_EOL(following) || - withinFlowCollection && is_FLOW_INDICATOR(following)) { - break; - } - - } else if (ch === 0x23/* # */) { - preceding = state.input.charCodeAt(state.position - 1); - - if (is_WS_OR_EOL(preceding)) { - break; - } - - } else if ((state.position === state.lineStart && testDocumentSeparator(state)) || - withinFlowCollection && is_FLOW_INDICATOR(ch)) { - break; - - } else if (is_EOL(ch)) { - _line = state.line; - _lineStart = state.lineStart; - _lineIndent = state.lineIndent; - skipSeparationSpace(state, false, -1); - - if (state.lineIndent >= nodeIndent) { - hasPendingContent = true; - ch = state.input.charCodeAt(state.position); - continue; - } else { - state.position = captureEnd; - state.line = _line; - state.lineStart = _lineStart; - state.lineIndent = _lineIndent; - break; - } - } - - if (hasPendingContent) { - captureSegment(state, captureStart, captureEnd, false); - writeFoldedLines(state, state.line - _line); - captureStart = captureEnd = state.position; - hasPendingContent = false; - } - - if (!is_WHITE_SPACE(ch)) { - captureEnd = state.position + 1; - } - - ch = state.input.charCodeAt(++state.position); - } - - captureSegment(state, captureStart, captureEnd, false); - - if (state.result) { - return true; - } - - state.kind = _kind; - state.result = _result; - return false; - } - - function readSingleQuotedScalar(state, nodeIndent) { - var ch, - captureStart, captureEnd; - - ch = state.input.charCodeAt(state.position); - - if (ch !== 0x27/* ' */) { - return false; - } - - state.kind = 'scalar'; - state.result = ''; - state.position++; - captureStart = captureEnd = state.position; - - while ((ch = state.input.charCodeAt(state.position)) !== 0) { - if (ch === 0x27/* ' */) { - captureSegment(state, captureStart, state.position, true); - ch = state.input.charCodeAt(++state.position); - - if (ch === 0x27/* ' */) { - captureStart = state.position; - state.position++; - captureEnd = state.position; - } else { - return true; - } - - } else if (is_EOL(ch)) { - captureSegment(state, captureStart, captureEnd, true); - writeFoldedLines(state, skipSeparationSpace(state, false, nodeIndent)); - captureStart = captureEnd = state.position; - - } else if (state.position === state.lineStart && testDocumentSeparator(state)) { - throwError(state, 'unexpected end of the document within a single quoted scalar'); - - } else { - state.position++; - captureEnd = state.position; - } - } - - throwError(state, 'unexpected end of the stream within a single quoted scalar'); - } - - function readDoubleQuotedScalar(state, nodeIndent) { - var captureStart, - captureEnd, - hexLength, - hexResult, - tmp, - ch; - - ch = state.input.charCodeAt(state.position); - - if (ch !== 0x22/* " */) { - return false; - } - - state.kind = 'scalar'; - state.result = ''; - state.position++; - captureStart = captureEnd = state.position; - - while ((ch = state.input.charCodeAt(state.position)) !== 0) { - if (ch === 0x22/* " */) { - captureSegment(state, captureStart, state.position, true); - state.position++; - return true; - - } else if (ch === 0x5C/* \ */) { - captureSegment(state, captureStart, state.position, true); - ch = state.input.charCodeAt(++state.position); - - if (is_EOL(ch)) { - skipSeparationSpace(state, false, nodeIndent); - - // TODO: rework to inline fn with no type cast? - } else if (ch < 256 && simpleEscapeCheck[ch]) { - state.result += simpleEscapeMap[ch]; - state.position++; - - } else if ((tmp = escapedHexLen(ch)) > 0) { - hexLength = tmp; - hexResult = 0; - - for (; hexLength > 0; hexLength--) { - ch = state.input.charCodeAt(++state.position); - - if ((tmp = fromHexCode(ch)) >= 0) { - hexResult = (hexResult << 4) + tmp; - - } else { - throwError(state, 'expected hexadecimal character'); + else if (isRegionalIndicator(next)) { + let countBefore = 0, i = pos - 2; + while (i >= 0 && isRegionalIndicator(codePointAt(str, i))) { + countBefore++; + i -= 2; } - } - - state.result += charFromCodepoint(hexResult); - - state.position++; - - } else { - throwError(state, 'unknown escape sequence'); + if (countBefore % 2 == 0) + break; + else + pos += 2; } - - captureStart = captureEnd = state.position; - - } else if (is_EOL(ch)) { - captureSegment(state, captureStart, captureEnd, true); - writeFoldedLines(state, skipSeparationSpace(state, false, nodeIndent)); - captureStart = captureEnd = state.position; - - } else if (state.position === state.lineStart && testDocumentSeparator(state)) { - throwError(state, 'unexpected end of the document within a double quoted scalar'); - - } else { - state.position++; - captureEnd = state.position; - } - } - - throwError(state, 'unexpected end of the stream within a double quoted scalar'); - } - - function readFlowCollection(state, nodeIndent) { - var readNext = true, - _line, - _lineStart, - _pos, - _tag = state.tag, - _result, - _anchor = state.anchor, - following, - terminator, - isPair, - isExplicitPair, - isMapping, - overridableKeys = Object.create(null), - keyNode, - keyTag, - valueNode, - ch; - - ch = state.input.charCodeAt(state.position); - - if (ch === 0x5B/* [ */) { - terminator = 0x5D;/* ] */ - isMapping = false; - _result = []; - } else if (ch === 0x7B/* { */) { - terminator = 0x7D;/* } */ - isMapping = true; - _result = {}; - } else { - return false; - } - - if (state.anchor !== null) { - state.anchorMap[state.anchor] = _result; - } - - ch = state.input.charCodeAt(++state.position); - - while (ch !== 0) { - skipSeparationSpace(state, true, nodeIndent); - - ch = state.input.charCodeAt(state.position); - - if (ch === terminator) { - state.position++; - state.tag = _tag; - state.anchor = _anchor; - state.kind = isMapping ? 'mapping' : 'sequence'; - state.result = _result; - return true; - } else if (!readNext) { - throwError(state, 'missed comma between flow collection entries'); - } else if (ch === 0x2C/* , */) { - // "flow collection entries can never be completely empty", as per YAML 1.2, section 7.4 - throwError(state, "expected the node content, but found ','"); - } - - keyTag = keyNode = valueNode = null; - isPair = isExplicitPair = false; - - if (ch === 0x3F/* ? */) { - following = state.input.charCodeAt(state.position + 1); - - if (is_WS_OR_EOL(following)) { - isPair = isExplicitPair = true; - state.position++; - skipSeparationSpace(state, true, nodeIndent); - } - } - - _line = state.line; // Save the current line. - _lineStart = state.lineStart; - _pos = state.position; - composeNode(state, nodeIndent, CONTEXT_FLOW_IN, false, true); - keyTag = state.tag; - keyNode = state.result; - skipSeparationSpace(state, true, nodeIndent); - - ch = state.input.charCodeAt(state.position); - - if ((isExplicitPair || state.line === _line) && ch === 0x3A/* : */) { - isPair = true; - ch = state.input.charCodeAt(++state.position); - skipSeparationSpace(state, true, nodeIndent); - composeNode(state, nodeIndent, CONTEXT_FLOW_IN, false, true); - valueNode = state.result; - } - - if (isMapping) { - storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, valueNode, _line, _lineStart, _pos); - } else if (isPair) { - _result.push(storeMappingPair(state, null, overridableKeys, keyTag, keyNode, valueNode, _line, _lineStart, _pos)); - } else { - _result.push(keyNode); - } - - skipSeparationSpace(state, true, nodeIndent); - - ch = state.input.charCodeAt(state.position); - - if (ch === 0x2C/* , */) { - readNext = true; - ch = state.input.charCodeAt(++state.position); - } else { - readNext = false; - } - } - - throwError(state, 'unexpected end of the stream within a flow collection'); - } - - function readBlockScalar(state, nodeIndent) { - var captureStart, - folding, - chomping = CHOMPING_CLIP, - didReadContent = false, - detectedIndent = false, - textIndent = nodeIndent, - emptyLines = 0, - atMoreIndented = false, - tmp, - ch; - - ch = state.input.charCodeAt(state.position); - - if (ch === 0x7C/* | */) { - folding = false; - } else if (ch === 0x3E/* > */) { - folding = true; - } else { - return false; - } - - state.kind = 'scalar'; - state.result = ''; - - while (ch !== 0) { - ch = state.input.charCodeAt(++state.position); - - if (ch === 0x2B/* + */ || ch === 0x2D/* - */) { - if (CHOMPING_CLIP === chomping) { - chomping = (ch === 0x2B/* + */) ? CHOMPING_KEEP : CHOMPING_STRIP; - } else { - throwError(state, 'repeat of a chomping mode identifier'); - } - - } else if ((tmp = fromDecimalCode(ch)) >= 0) { - if (tmp === 0) { - throwError(state, 'bad explicit indentation width of a block scalar; it cannot be less than one'); - } else if (!detectedIndent) { - textIndent = nodeIndent + tmp - 1; - detectedIndent = true; - } else { - throwError(state, 'repeat of an indentation width identifier'); - } - - } else { - break; - } - } - - if (is_WHITE_SPACE(ch)) { - do { ch = state.input.charCodeAt(++state.position); } - while (is_WHITE_SPACE(ch)); - - if (ch === 0x23/* # */) { - do { ch = state.input.charCodeAt(++state.position); } - while (!is_EOL(ch) && (ch !== 0)); - } - } - - while (ch !== 0) { - readLineBreak(state); - state.lineIndent = 0; - - ch = state.input.charCodeAt(state.position); - - while ((!detectedIndent || state.lineIndent < textIndent) && - (ch === 0x20/* Space */)) { - state.lineIndent++; - ch = state.input.charCodeAt(++state.position); - } - - if (!detectedIndent && state.lineIndent > textIndent) { - textIndent = state.lineIndent; - } - - if (is_EOL(ch)) { - emptyLines++; - continue; - } - - // End of the scalar. - if (state.lineIndent < textIndent) { - - // Perform the chomping. - if (chomping === CHOMPING_KEEP) { - state.result += common.repeat('\n', didReadContent ? 1 + emptyLines : emptyLines); - } else if (chomping === CHOMPING_CLIP) { - if (didReadContent) { // i.e. only if the scalar is not empty. - state.result += '\n'; - } - } - - // Break this `while` cycle and go to the funciton's epilogue. - break; - } - - // Folded style: use fancy rules to handle line breaks. - if (folding) { - - // Lines starting with white space characters (more-indented lines) are not folded. - if (is_WHITE_SPACE(ch)) { - atMoreIndented = true; - // except for the first content line (cf. Example 8.1) - state.result += common.repeat('\n', didReadContent ? 1 + emptyLines : emptyLines); - - // End of more-indented block. - } else if (atMoreIndented) { - atMoreIndented = false; - state.result += common.repeat('\n', emptyLines + 1); - - // Just one line break - perceive as the same line. - } else if (emptyLines === 0) { - if (didReadContent) { // i.e. only if we have already read some scalar content. - state.result += ' '; - } - - // Several line breaks - perceive as different lines. - } else { - state.result += common.repeat('\n', emptyLines); - } - - // Literal style: just add exact number of line breaks between content lines. - } else { - // Keep all line breaks except the header line break. - state.result += common.repeat('\n', didReadContent ? 1 + emptyLines : emptyLines); - } - - didReadContent = true; - detectedIndent = true; - emptyLines = 0; - captureStart = state.position; - - while (!is_EOL(ch) && (ch !== 0)) { - ch = state.input.charCodeAt(++state.position); - } - - captureSegment(state, captureStart, state.position, false); - } - - return true; - } - - function readBlockSequence(state, nodeIndent) { - var _line, - _tag = state.tag, - _anchor = state.anchor, - _result = [], - following, - detected = false, - ch; - - // there is a leading tab before this token, so it can't be a block sequence/mapping; - // it can still be flow sequence/mapping or a scalar - if (state.firstTabInLine !== -1) return false; - - if (state.anchor !== null) { - state.anchorMap[state.anchor] = _result; - } - - ch = state.input.charCodeAt(state.position); - - while (ch !== 0) { - if (state.firstTabInLine !== -1) { - state.position = state.firstTabInLine; - throwError(state, 'tab characters must not be used in indentation'); - } - - if (ch !== 0x2D/* - */) { - break; - } - - following = state.input.charCodeAt(state.position + 1); - - if (!is_WS_OR_EOL(following)) { - break; - } - - detected = true; - state.position++; - - if (skipSeparationSpace(state, true, -1)) { - if (state.lineIndent <= nodeIndent) { - _result.push(null); - ch = state.input.charCodeAt(state.position); - continue; - } - } - - _line = state.line; - composeNode(state, nodeIndent, CONTEXT_BLOCK_IN, false, true); - _result.push(state.result); - skipSeparationSpace(state, true, -1); - - ch = state.input.charCodeAt(state.position); - - if ((state.line === _line || state.lineIndent > nodeIndent) && (ch !== 0)) { - throwError(state, 'bad indentation of a sequence entry'); - } else if (state.lineIndent < nodeIndent) { - break; - } - } - - if (detected) { - state.tag = _tag; - state.anchor = _anchor; - state.kind = 'sequence'; - state.result = _result; - return true; - } - return false; - } - - function readBlockMapping(state, nodeIndent, flowIndent) { - var following, - allowCompact, - _line, - _keyLine, - _keyLineStart, - _keyPos, - _tag = state.tag, - _anchor = state.anchor, - _result = {}, - overridableKeys = Object.create(null), - keyTag = null, - keyNode = null, - valueNode = null, - atExplicitKey = false, - detected = false, - ch; - - // there is a leading tab before this token, so it can't be a block sequence/mapping; - // it can still be flow sequence/mapping or a scalar - if (state.firstTabInLine !== -1) return false; - - if (state.anchor !== null) { - state.anchorMap[state.anchor] = _result; - } - - ch = state.input.charCodeAt(state.position); - - while (ch !== 0) { - if (!atExplicitKey && state.firstTabInLine !== -1) { - state.position = state.firstTabInLine; - throwError(state, 'tab characters must not be used in indentation'); - } - - following = state.input.charCodeAt(state.position + 1); - _line = state.line; // Save the current line. - - // - // Explicit notation case. There are two separate blocks: - // first for the key (denoted by "?") and second for the value (denoted by ":") - // - if ((ch === 0x3F/* ? */ || ch === 0x3A/* : */) && is_WS_OR_EOL(following)) { - - if (ch === 0x3F/* ? */) { - if (atExplicitKey) { - storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, null, _keyLine, _keyLineStart, _keyPos); - keyTag = keyNode = valueNode = null; - } - - detected = true; - atExplicitKey = true; - allowCompact = true; - - } else if (atExplicitKey) { - // i.e. 0x3A/* : */ === character after the explicit key. - atExplicitKey = false; - allowCompact = true; - - } else { - throwError(state, 'incomplete explicit mapping pair; a key node is missed; or followed by a non-tabulated empty line'); - } - - state.position += 1; - ch = following; - - // - // Implicit notation case. Flow-style node as the key first, then ":", and the value. - // - } else { - _keyLine = state.line; - _keyLineStart = state.lineStart; - _keyPos = state.position; - - if (!composeNode(state, flowIndent, CONTEXT_FLOW_OUT, false, true)) { - // Neither implicit nor explicit notation. - // Reading is done. Go to the epilogue. - break; - } - - if (state.line === _line) { - ch = state.input.charCodeAt(state.position); - - while (is_WHITE_SPACE(ch)) { - ch = state.input.charCodeAt(++state.position); - } - - if (ch === 0x3A/* : */) { - ch = state.input.charCodeAt(++state.position); - - if (!is_WS_OR_EOL(ch)) { - throwError(state, 'a whitespace character is expected after the key-value separator within a block mapping'); - } - - if (atExplicitKey) { - storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, null, _keyLine, _keyLineStart, _keyPos); - keyTag = keyNode = valueNode = null; - } - - detected = true; - atExplicitKey = false; - allowCompact = false; - keyTag = state.tag; - keyNode = state.result; - - } else if (detected) { - throwError(state, 'can not read an implicit mapping pair; a colon is missed'); - - } else { - state.tag = _tag; - state.anchor = _anchor; - return true; // Keep the result of `composeNode`. - } - - } else if (detected) { - throwError(state, 'can not read a block mapping entry; a multiline key may not be an implicit key'); - - } else { - state.tag = _tag; - state.anchor = _anchor; - return true; // Keep the result of `composeNode`. - } - } - - // - // Common reading code for both explicit and implicit notations. - // - if (state.line === _line || state.lineIndent > nodeIndent) { - if (atExplicitKey) { - _keyLine = state.line; - _keyLineStart = state.lineStart; - _keyPos = state.position; - } - - if (composeNode(state, nodeIndent, CONTEXT_BLOCK_OUT, true, allowCompact)) { - if (atExplicitKey) { - keyNode = state.result; - } else { - valueNode = state.result; - } - } - - if (!atExplicitKey) { - storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, valueNode, _keyLine, _keyLineStart, _keyPos); - keyTag = keyNode = valueNode = null; - } - - skipSeparationSpace(state, true, -1); - ch = state.input.charCodeAt(state.position); - } - - if ((state.line === _line || state.lineIndent > nodeIndent) && (ch !== 0)) { - throwError(state, 'bad indentation of a mapping entry'); - } else if (state.lineIndent < nodeIndent) { - break; - } - } - - // - // Epilogue. - // - - // Special case: last mapping's node contains only the key in explicit notation. - if (atExplicitKey) { - storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, null, _keyLine, _keyLineStart, _keyPos); - } - - // Expose the resulting mapping. - if (detected) { - state.tag = _tag; - state.anchor = _anchor; - state.kind = 'mapping'; - state.result = _result; - } - - return detected; - } - - function readTagProperty(state) { - var _position, - isVerbatim = false, - isNamed = false, - tagHandle, - tagName, - ch; - - ch = state.input.charCodeAt(state.position); - - if (ch !== 0x21/* ! */) return false; - - if (state.tag !== null) { - throwError(state, 'duplication of a tag property'); - } - - ch = state.input.charCodeAt(++state.position); - - if (ch === 0x3C/* < */) { - isVerbatim = true; - ch = state.input.charCodeAt(++state.position); - - } else if (ch === 0x21/* ! */) { - isNamed = true; - tagHandle = '!!'; - ch = state.input.charCodeAt(++state.position); - - } else { - tagHandle = '!'; - } - - _position = state.position; - - if (isVerbatim) { - do { ch = state.input.charCodeAt(++state.position); } - while (ch !== 0 && ch !== 0x3E/* > */); - - if (state.position < state.length) { - tagName = state.input.slice(_position, state.position); - ch = state.input.charCodeAt(++state.position); - } else { - throwError(state, 'unexpected end of the stream within a verbatim tag'); - } - } else { - while (ch !== 0 && !is_WS_OR_EOL(ch)) { - - if (ch === 0x21/* ! */) { - if (!isNamed) { - tagHandle = state.input.slice(_position - 1, state.position + 1); - - if (!PATTERN_TAG_HANDLE.test(tagHandle)) { - throwError(state, 'named tag handle cannot contain such characters'); - } - - isNamed = true; - _position = state.position + 1; - } else { - throwError(state, 'tag suffix cannot contain exclamation marks'); - } - } - - ch = state.input.charCodeAt(++state.position); - } - - tagName = state.input.slice(_position, state.position); - - if (PATTERN_FLOW_INDICATORS.test(tagName)) { - throwError(state, 'tag suffix cannot contain flow indicator characters'); - } - } - - if (tagName && !PATTERN_TAG_URI.test(tagName)) { - throwError(state, 'tag name cannot contain such characters: ' + tagName); - } - - try { - tagName = decodeURIComponent(tagName); - } catch (err) { - throwError(state, 'tag name is malformed: ' + tagName); - } - - if (isVerbatim) { - state.tag = tagName; - - } else if (_hasOwnProperty$1.call(state.tagMap, tagHandle)) { - state.tag = state.tagMap[tagHandle] + tagName; - - } else if (tagHandle === '!') { - state.tag = '!' + tagName; - - } else if (tagHandle === '!!') { - state.tag = 'tag:yaml.org,2002:' + tagName; - - } else { - throwError(state, 'undeclared tag handle "' + tagHandle + '"'); - } - - return true; - } - - function readAnchorProperty(state) { - var _position, - ch; - - ch = state.input.charCodeAt(state.position); - - if (ch !== 0x26/* & */) return false; - - if (state.anchor !== null) { - throwError(state, 'duplication of an anchor property'); - } - - ch = state.input.charCodeAt(++state.position); - _position = state.position; - - while (ch !== 0 && !is_WS_OR_EOL(ch) && !is_FLOW_INDICATOR(ch)) { - ch = state.input.charCodeAt(++state.position); - } - - if (state.position === _position) { - throwError(state, 'name of an anchor node must contain at least one character'); - } - - state.anchor = state.input.slice(_position, state.position); - return true; - } - - function readAlias(state) { - var _position, alias, - ch; - - ch = state.input.charCodeAt(state.position); - - if (ch !== 0x2A/* * */) return false; - - ch = state.input.charCodeAt(++state.position); - _position = state.position; - - while (ch !== 0 && !is_WS_OR_EOL(ch) && !is_FLOW_INDICATOR(ch)) { - ch = state.input.charCodeAt(++state.position); - } - - if (state.position === _position) { - throwError(state, 'name of an alias node must contain at least one character'); - } - - alias = state.input.slice(_position, state.position); - - if (!_hasOwnProperty$1.call(state.anchorMap, alias)) { - throwError(state, 'unidentified alias "' + alias + '"'); - } - - state.result = state.anchorMap[alias]; - skipSeparationSpace(state, true, -1); - return true; - } - - function composeNode(state, parentIndent, nodeContext, allowToSeek, allowCompact) { - var allowBlockStyles, - allowBlockScalars, - allowBlockCollections, - indentStatus = 1, // 1: this>parent, 0: this=parent, -1: this<parent - atNewLine = false, - hasContent = false, - typeIndex, - typeQuantity, - typeList, - type, - flowIndent, - blockIndent; - - if (state.listener !== null) { - state.listener('open', state); - } - - state.tag = null; - state.anchor = null; - state.kind = null; - state.result = null; - - allowBlockStyles = allowBlockScalars = allowBlockCollections = - CONTEXT_BLOCK_OUT === nodeContext || - CONTEXT_BLOCK_IN === nodeContext; - - if (allowToSeek) { - if (skipSeparationSpace(state, true, -1)) { - atNewLine = true; - - if (state.lineIndent > parentIndent) { - indentStatus = 1; - } else if (state.lineIndent === parentIndent) { - indentStatus = 0; - } else if (state.lineIndent < parentIndent) { - indentStatus = -1; - } - } - } - - if (indentStatus === 1) { - while (readTagProperty(state) || readAnchorProperty(state)) { - if (skipSeparationSpace(state, true, -1)) { - atNewLine = true; - allowBlockCollections = allowBlockStyles; - - if (state.lineIndent > parentIndent) { - indentStatus = 1; - } else if (state.lineIndent === parentIndent) { - indentStatus = 0; - } else if (state.lineIndent < parentIndent) { - indentStatus = -1; - } - } else { - allowBlockCollections = false; - } - } - } - - if (allowBlockCollections) { - allowBlockCollections = atNewLine || allowCompact; - } - - if (indentStatus === 1 || CONTEXT_BLOCK_OUT === nodeContext) { - if (CONTEXT_FLOW_IN === nodeContext || CONTEXT_FLOW_OUT === nodeContext) { - flowIndent = parentIndent; - } else { - flowIndent = parentIndent + 1; - } - - blockIndent = state.position - state.lineStart; - - if (indentStatus === 1) { - if (allowBlockCollections && - (readBlockSequence(state, blockIndent) || - readBlockMapping(state, blockIndent, flowIndent)) || - readFlowCollection(state, flowIndent)) { - hasContent = true; - } else { - if ((allowBlockScalars && readBlockScalar(state, flowIndent)) || - readSingleQuotedScalar(state, flowIndent) || - readDoubleQuotedScalar(state, flowIndent)) { - hasContent = true; - - } else if (readAlias(state)) { - hasContent = true; - - if (state.tag !== null || state.anchor !== null) { - throwError(state, 'alias node should not have any properties'); - } - - } else if (readPlainScalar(state, flowIndent, CONTEXT_FLOW_IN === nodeContext)) { - hasContent = true; - - if (state.tag === null) { - state.tag = '?'; - } - } - - if (state.anchor !== null) { - state.anchorMap[state.anchor] = state.result; - } - } - } else if (indentStatus === 0) { - // Special case: block sequences are allowed to have same indentation level as the parent. - // http://www.yaml.org/spec/1.2/spec.html#id2799784 - hasContent = allowBlockCollections && readBlockSequence(state, blockIndent); - } - } - - if (state.tag === null) { - if (state.anchor !== null) { - state.anchorMap[state.anchor] = state.result; - } - - } else if (state.tag === '?') { - // Implicit resolving is not allowed for non-scalar types, and '?' - // non-specific tag is only automatically assigned to plain scalars. - // - // We only need to check kind conformity in case user explicitly assigns '?' - // tag, for example like this: "!<?> [0]" - // - if (state.result !== null && state.kind !== 'scalar') { - throwError(state, 'unacceptable node kind for !<?> tag; it should be "scalar", not "' + state.kind + '"'); - } - - for (typeIndex = 0, typeQuantity = state.implicitTypes.length; typeIndex < typeQuantity; typeIndex += 1) { - type = state.implicitTypes[typeIndex]; - - if (type.resolve(state.result)) { // `state.result` updated in resolver if matched - state.result = type.construct(state.result); - state.tag = type.tag; - if (state.anchor !== null) { - state.anchorMap[state.anchor] = state.result; - } - break; - } - } - } else if (state.tag !== '!') { - if (_hasOwnProperty$1.call(state.typeMap[state.kind || 'fallback'], state.tag)) { - type = state.typeMap[state.kind || 'fallback'][state.tag]; - } else { - // looking for multi type - type = null; - typeList = state.typeMap.multi[state.kind || 'fallback']; - - for (typeIndex = 0, typeQuantity = typeList.length; typeIndex < typeQuantity; typeIndex += 1) { - if (state.tag.slice(0, typeList[typeIndex].tag.length) === typeList[typeIndex].tag) { - type = typeList[typeIndex]; + else { break; - } + } + } + return pos; + } + function prevClusterBreak(str, pos, includeExtending) { + while (pos > 0) { + let found = nextClusterBreak(str, pos - 2, includeExtending); + if (found < pos) + return found; + pos--; + } + return 0; + } + function surrogateLow(ch) { return ch >= 0xDC00 && ch < 0xE000; } + function surrogateHigh(ch) { return ch >= 0xD800 && ch < 0xDC00; } + /** + Find the code point at the given position in a string (like the + [`codePointAt`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/codePointAt) + string method). + */ + function codePointAt(str, pos) { + let code0 = str.charCodeAt(pos); + if (!surrogateHigh(code0) || pos + 1 == str.length) + return code0; + let code1 = str.charCodeAt(pos + 1); + if (!surrogateLow(code1)) + return code0; + return ((code0 - 0xd800) << 10) + (code1 - 0xdc00) + 0x10000; + } + /** + Given a Unicode codepoint, return the JavaScript string that + respresents it (like + [`String.fromCodePoint`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/fromCodePoint)). + */ + function fromCodePoint(code) { + if (code <= 0xffff) + return String.fromCharCode(code); + code -= 0x10000; + return String.fromCharCode((code >> 10) + 0xd800, (code & 1023) + 0xdc00); + } + /** + The amount of positions a character takes up a JavaScript string. + */ + function codePointSize(code) { return code < 0x10000 ? 1 : 2; } + + const DefaultSplit = /\r\n?|\n/; + /** + Distinguishes different ways in which positions can be mapped. + */ + var MapMode = /*@__PURE__*/(function (MapMode) { + /** + Map a position to a valid new position, even when its context + was deleted. + */ + MapMode[MapMode["Simple"] = 0] = "Simple"; + /** + Return null if deletion happens across the position. + */ + MapMode[MapMode["TrackDel"] = 1] = "TrackDel"; + /** + Return null if the character _before_ the position is deleted. + */ + MapMode[MapMode["TrackBefore"] = 2] = "TrackBefore"; + /** + Return null if the character _after_ the position is deleted. + */ + MapMode[MapMode["TrackAfter"] = 3] = "TrackAfter"; + return MapMode})(MapMode || (MapMode = {})); + /** + A change description is a variant of [change set](https://codemirror.net/6/docs/ref/#state.ChangeSet) + that doesn't store the inserted text. As such, it can't be + applied, but is cheaper to store and manipulate. + */ + class ChangeDesc { + // Sections are encoded as pairs of integers. The first is the + // length in the current document, and the second is -1 for + // unaffected sections, and the length of the replacement content + // otherwise. So an insertion would be (0, n>0), a deletion (n>0, + // 0), and a replacement two positive numbers. + /** + @internal + */ + constructor( + /** + @internal + */ + sections) { + this.sections = sections; + } + /** + The length of the document before the change. + */ + get length() { + let result = 0; + for (let i = 0; i < this.sections.length; i += 2) + result += this.sections[i]; + return result; + } + /** + The length of the document after the change. + */ + get newLength() { + let result = 0; + for (let i = 0; i < this.sections.length; i += 2) { + let ins = this.sections[i + 1]; + result += ins < 0 ? this.sections[i] : ins; + } + return result; + } + /** + False when there are actual changes in this set. + */ + get empty() { return this.sections.length == 0 || this.sections.length == 2 && this.sections[1] < 0; } + /** + Iterate over the unchanged parts left by these changes. `posA` + provides the position of the range in the old document, `posB` + the new position in the changed document. + */ + iterGaps(f) { + for (let i = 0, posA = 0, posB = 0; i < this.sections.length;) { + let len = this.sections[i++], ins = this.sections[i++]; + if (ins < 0) { + f(posA, posB, len); + posB += len; + } + else { + posB += ins; + } + posA += len; + } + } + /** + Iterate over the ranges changed by these changes. (See + [`ChangeSet.iterChanges`](https://codemirror.net/6/docs/ref/#state.ChangeSet.iterChanges) for a + variant that also provides you with the inserted text.) + `fromA`/`toA` provides the extent of the change in the starting + document, `fromB`/`toB` the extent of the replacement in the + changed document. + + When `individual` is true, adjacent changes (which are kept + separate for [position mapping](https://codemirror.net/6/docs/ref/#state.ChangeDesc.mapPos)) are + reported separately. + */ + iterChangedRanges(f, individual = false) { + iterChanges(this, f, individual); + } + /** + Get a description of the inverted form of these changes. + */ + get invertedDesc() { + let sections = []; + for (let i = 0; i < this.sections.length;) { + let len = this.sections[i++], ins = this.sections[i++]; + if (ins < 0) + sections.push(len, ins); + else + sections.push(ins, len); + } + return new ChangeDesc(sections); + } + /** + Compute the combined effect of applying another set of changes + after this one. The length of the document after this set should + match the length before `other`. + */ + composeDesc(other) { return this.empty ? other : other.empty ? this : composeSets(this, other); } + /** + Map this description, which should start with the same document + as `other`, over another set of changes, so that it can be + applied after it. When `before` is true, map as if the changes + in `other` happened before the ones in `this`. + */ + mapDesc(other, before = false) { return other.empty ? this : mapSet(this, other, before); } + mapPos(pos, assoc = -1, mode = MapMode.Simple) { + let posA = 0, posB = 0; + for (let i = 0; i < this.sections.length;) { + let len = this.sections[i++], ins = this.sections[i++], endA = posA + len; + if (ins < 0) { + if (endA > pos) + return posB + (pos - posA); + posB += len; + } + else { + if (mode != MapMode.Simple && endA >= pos && + (mode == MapMode.TrackDel && posA < pos && endA > pos || + mode == MapMode.TrackBefore && posA < pos || + mode == MapMode.TrackAfter && endA > pos)) + return null; + if (endA > pos || endA == pos && assoc < 0 && !len) + return pos == posA || assoc < 0 ? posB : posB + ins; + posB += ins; + } + posA = endA; + } + if (pos > posA) + throw new RangeError(`Position ${pos} is out of range for changeset of length ${posA}`); + return posB; + } + /** + Check whether these changes touch a given range. When one of the + changes entirely covers the range, the string `"cover"` is + returned. + */ + touchesRange(from, to = from) { + for (let i = 0, pos = 0; i < this.sections.length && pos <= to;) { + let len = this.sections[i++], ins = this.sections[i++], end = pos + len; + if (ins >= 0 && pos <= to && end >= from) + return pos < from && end > to ? "cover" : true; + pos = end; + } + return false; + } + /** + @internal + */ + toString() { + let result = ""; + for (let i = 0; i < this.sections.length;) { + let len = this.sections[i++], ins = this.sections[i++]; + result += (result ? " " : "") + len + (ins >= 0 ? ":" + ins : ""); + } + return result; + } + /** + Serialize this change desc to a JSON-representable value. + */ + toJSON() { return this.sections; } + /** + Create a change desc from its JSON representation (as produced + by [`toJSON`](https://codemirror.net/6/docs/ref/#state.ChangeDesc.toJSON). + */ + static fromJSON(json) { + if (!Array.isArray(json) || json.length % 2 || json.some(a => typeof a != "number")) + throw new RangeError("Invalid JSON representation of ChangeDesc"); + return new ChangeDesc(json); + } + /** + @internal + */ + static create(sections) { return new ChangeDesc(sections); } + } + /** + A change set represents a group of modifications to a document. It + stores the document length, and can only be applied to documents + with exactly that length. + */ + class ChangeSet extends ChangeDesc { + constructor(sections, + /** + @internal + */ + inserted) { + super(sections); + this.inserted = inserted; + } + /** + Apply the changes to a document, returning the modified + document. + */ + apply(doc) { + if (this.length != doc.length) + throw new RangeError("Applying change set to a document with the wrong length"); + iterChanges(this, (fromA, toA, fromB, _toB, text) => doc = doc.replace(fromB, fromB + (toA - fromA), text), false); + return doc; + } + mapDesc(other, before = false) { return mapSet(this, other, before, true); } + /** + Given the document as it existed _before_ the changes, return a + change set that represents the inverse of this set, which could + be used to go from the document created by the changes back to + the document as it existed before the changes. + */ + invert(doc) { + let sections = this.sections.slice(), inserted = []; + for (let i = 0, pos = 0; i < sections.length; i += 2) { + let len = sections[i], ins = sections[i + 1]; + if (ins >= 0) { + sections[i] = ins; + sections[i + 1] = len; + let index = i >> 1; + while (inserted.length < index) + inserted.push(Text.empty); + inserted.push(len ? doc.slice(pos, pos + len) : Text.empty); + } + pos += len; + } + return new ChangeSet(sections, inserted); + } + /** + Combine two subsequent change sets into a single set. `other` + must start in the document produced by `this`. If `this` goes + `docA` → `docB` and `other` represents `docB` → `docC`, the + returned value will represent the change `docA` → `docC`. + */ + compose(other) { return this.empty ? other : other.empty ? this : composeSets(this, other, true); } + /** + Given another change set starting in the same document, maps this + change set over the other, producing a new change set that can be + applied to the document produced by applying `other`. When + `before` is `true`, order changes as if `this` comes before + `other`, otherwise (the default) treat `other` as coming first. + + Given two changes `A` and `B`, `A.compose(B.map(A))` and + `B.compose(A.map(B, true))` will produce the same document. This + provides a basic form of [operational + transformation](https://en.wikipedia.org/wiki/Operational_transformation), + and can be used for collaborative editing. + */ + map(other, before = false) { return other.empty ? this : mapSet(this, other, before, true); } + /** + Iterate over the changed ranges in the document, calling `f` for + each, with the range in the original document (`fromA`-`toA`) + and the range that replaces it in the new document + (`fromB`-`toB`). + + When `individual` is true, adjacent changes are reported + separately. + */ + iterChanges(f, individual = false) { + iterChanges(this, f, individual); + } + /** + Get a [change description](https://codemirror.net/6/docs/ref/#state.ChangeDesc) for this change + set. + */ + get desc() { return ChangeDesc.create(this.sections); } + /** + @internal + */ + filter(ranges) { + let resultSections = [], resultInserted = [], filteredSections = []; + let iter = new SectionIter(this); + done: for (let i = 0, pos = 0;;) { + let next = i == ranges.length ? 1e9 : ranges[i++]; + while (pos < next || pos == next && iter.len == 0) { + if (iter.done) + break done; + let len = Math.min(iter.len, next - pos); + addSection(filteredSections, len, -1); + let ins = iter.ins == -1 ? -1 : iter.off == 0 ? iter.ins : 0; + addSection(resultSections, len, ins); + if (ins > 0) + addInsert(resultInserted, resultSections, iter.text); + iter.forward(len); + pos += len; + } + let end = ranges[i++]; + while (pos < end) { + if (iter.done) + break done; + let len = Math.min(iter.len, end - pos); + addSection(resultSections, len, -1); + addSection(filteredSections, len, iter.ins == -1 ? -1 : iter.off == 0 ? iter.ins : 0); + iter.forward(len); + pos += len; + } + } + return { changes: new ChangeSet(resultSections, resultInserted), + filtered: ChangeDesc.create(filteredSections) }; + } + /** + Serialize this change set to a JSON-representable value. + */ + toJSON() { + let parts = []; + for (let i = 0; i < this.sections.length; i += 2) { + let len = this.sections[i], ins = this.sections[i + 1]; + if (ins < 0) + parts.push(len); + else if (ins == 0) + parts.push([len]); + else + parts.push([len].concat(this.inserted[i >> 1].toJSON())); + } + return parts; + } + /** + Create a change set for the given changes, for a document of the + given length, using `lineSep` as line separator. + */ + static of(changes, length, lineSep) { + let sections = [], inserted = [], pos = 0; + let total = null; + function flush(force = false) { + if (!force && !sections.length) + return; + if (pos < length) + addSection(sections, length - pos, -1); + let set = new ChangeSet(sections, inserted); + total = total ? total.compose(set.map(total)) : set; + sections = []; + inserted = []; + pos = 0; + } + function process(spec) { + if (Array.isArray(spec)) { + for (let sub of spec) + process(sub); + } + else if (spec instanceof ChangeSet) { + if (spec.length != length) + throw new RangeError(`Mismatched change set length (got ${spec.length}, expected ${length})`); + flush(); + total = total ? total.compose(spec.map(total)) : spec; + } + else { + let { from, to = from, insert } = spec; + if (from > to || from < 0 || to > length) + throw new RangeError(`Invalid change range ${from} to ${to} (in doc of length ${length})`); + let insText = !insert ? Text.empty : typeof insert == "string" ? Text.of(insert.split(lineSep || DefaultSplit)) : insert; + let insLen = insText.length; + if (from == to && insLen == 0) + return; + if (from < pos) + flush(); + if (from > pos) + addSection(sections, from - pos, -1); + addSection(sections, to - from, insLen); + addInsert(inserted, sections, insText); + pos = to; + } + } + process(changes); + flush(!total); + return total; + } + /** + Create an empty changeset of the given length. + */ + static empty(length) { + return new ChangeSet(length ? [length, -1] : [], []); + } + /** + Create a changeset from its JSON representation (as produced by + [`toJSON`](https://codemirror.net/6/docs/ref/#state.ChangeSet.toJSON). + */ + static fromJSON(json) { + if (!Array.isArray(json)) + throw new RangeError("Invalid JSON representation of ChangeSet"); + let sections = [], inserted = []; + for (let i = 0; i < json.length; i++) { + let part = json[i]; + if (typeof part == "number") { + sections.push(part, -1); + } + else if (!Array.isArray(part) || typeof part[0] != "number" || part.some((e, i) => i && typeof e != "string")) { + throw new RangeError("Invalid JSON representation of ChangeSet"); + } + else if (part.length == 1) { + sections.push(part[0], 0); + } + else { + while (inserted.length < i) + inserted.push(Text.empty); + inserted[i] = Text.of(part.slice(1)); + sections.push(part[0], inserted[i].length); + } + } + return new ChangeSet(sections, inserted); + } + /** + @internal + */ + static createSet(sections, inserted) { + return new ChangeSet(sections, inserted); + } + } + function addSection(sections, len, ins, forceJoin = false) { + if (len == 0 && ins <= 0) + return; + let last = sections.length - 2; + if (last >= 0 && ins <= 0 && ins == sections[last + 1]) + sections[last] += len; + else if (len == 0 && sections[last] == 0) + sections[last + 1] += ins; + else if (forceJoin) { + sections[last] += len; + sections[last + 1] += ins; + } + else + sections.push(len, ins); + } + function addInsert(values, sections, value) { + if (value.length == 0) + return; + let index = (sections.length - 2) >> 1; + if (index < values.length) { + values[values.length - 1] = values[values.length - 1].append(value); + } + else { + while (values.length < index) + values.push(Text.empty); + values.push(value); + } + } + function iterChanges(desc, f, individual) { + let inserted = desc.inserted; + for (let posA = 0, posB = 0, i = 0; i < desc.sections.length;) { + let len = desc.sections[i++], ins = desc.sections[i++]; + if (ins < 0) { + posA += len; + posB += len; + } + else { + let endA = posA, endB = posB, text = Text.empty; + for (;;) { + endA += len; + endB += ins; + if (ins && inserted) + text = text.append(inserted[(i - 2) >> 1]); + if (individual || i == desc.sections.length || desc.sections[i + 1] < 0) + break; + len = desc.sections[i++]; + ins = desc.sections[i++]; + } + f(posA, endA, posB, endB, text); + posA = endA; + posB = endB; + } + } + } + function mapSet(setA, setB, before, mkSet = false) { + // Produce a copy of setA that applies to the document after setB + // has been applied (assuming both start at the same document). + let sections = [], insert = mkSet ? [] : null; + let a = new SectionIter(setA), b = new SectionIter(setB); + // Iterate over both sets in parallel. inserted tracks, for changes + // in A that have to be processed piece-by-piece, whether their + // content has been inserted already, and refers to the section + // index. + for (let inserted = -1;;) { + if (a.ins == -1 && b.ins == -1) { + // Move across ranges skipped by both sets. + let len = Math.min(a.len, b.len); + addSection(sections, len, -1); + a.forward(len); + b.forward(len); + } + else if (b.ins >= 0 && (a.ins < 0 || inserted == a.i || a.off == 0 && (b.len < a.len || b.len == a.len && !before))) { + // If there's a change in B that comes before the next change in + // A (ordered by start pos, then len, then before flag), skip + // that (and process any changes in A it covers). + let len = b.len; + addSection(sections, b.ins, -1); + while (len) { + let piece = Math.min(a.len, len); + if (a.ins >= 0 && inserted < a.i && a.len <= piece) { + addSection(sections, 0, a.ins); + if (insert) + addInsert(insert, sections, a.text); + inserted = a.i; + } + a.forward(piece); + len -= piece; + } + b.next(); + } + else if (a.ins >= 0) { + // Process the part of a change in A up to the start of the next + // non-deletion change in B (if overlapping). + let len = 0, left = a.len; + while (left) { + if (b.ins == -1) { + let piece = Math.min(left, b.len); + len += piece; + left -= piece; + b.forward(piece); + } + else if (b.ins == 0 && b.len < left) { + left -= b.len; + b.next(); + } + else { + break; + } + } + addSection(sections, len, inserted < a.i ? a.ins : 0); + if (insert && inserted < a.i) + addInsert(insert, sections, a.text); + inserted = a.i; + a.forward(a.len - left); + } + else if (a.done && b.done) { + return insert ? ChangeSet.createSet(sections, insert) : ChangeDesc.create(sections); + } + else { + throw new Error("Mismatched change set lengths"); + } + } + } + function composeSets(setA, setB, mkSet = false) { + let sections = []; + let insert = mkSet ? [] : null; + let a = new SectionIter(setA), b = new SectionIter(setB); + for (let open = false;;) { + if (a.done && b.done) { + return insert ? ChangeSet.createSet(sections, insert) : ChangeDesc.create(sections); + } + else if (a.ins == 0) { // Deletion in A + addSection(sections, a.len, 0, open); + a.next(); + } + else if (b.len == 0 && !b.done) { // Insertion in B + addSection(sections, 0, b.ins, open); + if (insert) + addInsert(insert, sections, b.text); + b.next(); + } + else if (a.done || b.done) { + throw new Error("Mismatched change set lengths"); + } + else { + let len = Math.min(a.len2, b.len), sectionLen = sections.length; + if (a.ins == -1) { + let insB = b.ins == -1 ? -1 : b.off ? 0 : b.ins; + addSection(sections, len, insB, open); + if (insert && insB) + addInsert(insert, sections, b.text); + } + else if (b.ins == -1) { + addSection(sections, a.off ? 0 : a.len, len, open); + if (insert) + addInsert(insert, sections, a.textBit(len)); + } + else { + addSection(sections, a.off ? 0 : a.len, b.off ? 0 : b.ins, open); + if (insert && !b.off) + addInsert(insert, sections, b.text); + } + open = (a.ins > len || b.ins >= 0 && b.len > len) && (open || sections.length > sectionLen); + a.forward2(len); + b.forward(len); + } + } + } + class SectionIter { + constructor(set) { + this.set = set; + this.i = 0; + this.next(); + } + next() { + let { sections } = this.set; + if (this.i < sections.length) { + this.len = sections[this.i++]; + this.ins = sections[this.i++]; + } + else { + this.len = 0; + this.ins = -2; + } + this.off = 0; + } + get done() { return this.ins == -2; } + get len2() { return this.ins < 0 ? this.len : this.ins; } + get text() { + let { inserted } = this.set, index = (this.i - 2) >> 1; + return index >= inserted.length ? Text.empty : inserted[index]; + } + textBit(len) { + let { inserted } = this.set, index = (this.i - 2) >> 1; + return index >= inserted.length && !len ? Text.empty + : inserted[index].slice(this.off, len == null ? undefined : this.off + len); + } + forward(len) { + if (len == this.len) + this.next(); + else { + this.len -= len; + this.off += len; + } + } + forward2(len) { + if (this.ins == -1) + this.forward(len); + else if (len == this.ins) + this.next(); + else { + this.ins -= len; + this.off += len; + } + } + } + + /** + A single selection range. When + [`allowMultipleSelections`](https://codemirror.net/6/docs/ref/#state.EditorState^allowMultipleSelections) + is enabled, a [selection](https://codemirror.net/6/docs/ref/#state.EditorSelection) may hold + multiple ranges. By default, selections hold exactly one range. + */ + class SelectionRange { + constructor( + /** + The lower boundary of the range. + */ + from, + /** + The upper boundary of the range. + */ + to, flags) { + this.from = from; + this.to = to; + this.flags = flags; + } + /** + The anchor of the range—the side that doesn't move when you + extend it. + */ + get anchor() { return this.flags & 16 /* RangeFlag.Inverted */ ? this.to : this.from; } + /** + The head of the range, which is moved when the range is + [extended](https://codemirror.net/6/docs/ref/#state.SelectionRange.extend). + */ + get head() { return this.flags & 16 /* RangeFlag.Inverted */ ? this.from : this.to; } + /** + True when `anchor` and `head` are at the same position. + */ + get empty() { return this.from == this.to; } + /** + If this is a cursor that is explicitly associated with the + character on one of its sides, this returns the side. -1 means + the character before its position, 1 the character after, and 0 + means no association. + */ + get assoc() { return this.flags & 4 /* RangeFlag.AssocBefore */ ? -1 : this.flags & 8 /* RangeFlag.AssocAfter */ ? 1 : 0; } + /** + The bidirectional text level associated with this cursor, if + any. + */ + get bidiLevel() { + let level = this.flags & 3 /* RangeFlag.BidiLevelMask */; + return level == 3 ? null : level; + } + /** + The goal column (stored vertical offset) associated with a + cursor. This is used to preserve the vertical position when + [moving](https://codemirror.net/6/docs/ref/#view.EditorView.moveVertically) across + lines of different length. + */ + get goalColumn() { + let value = this.flags >> 5 /* RangeFlag.GoalColumnOffset */; + return value == 33554431 /* RangeFlag.NoGoalColumn */ ? undefined : value; + } + /** + Map this range through a change, producing a valid range in the + updated document. + */ + map(change, assoc = -1) { + let from, to; + if (this.empty) { + from = to = change.mapPos(this.from, assoc); + } + else { + from = change.mapPos(this.from, 1); + to = change.mapPos(this.to, -1); + } + return from == this.from && to == this.to ? this : new SelectionRange(from, to, this.flags); + } + /** + Extend this range to cover at least `from` to `to`. + */ + extend(from, to = from) { + if (from <= this.anchor && to >= this.anchor) + return EditorSelection.range(from, to); + let head = Math.abs(from - this.anchor) > Math.abs(to - this.anchor) ? from : to; + return EditorSelection.range(this.anchor, head); + } + /** + Compare this range to another range. + */ + eq(other) { + return this.anchor == other.anchor && this.head == other.head; + } + /** + Return a JSON-serializable object representing the range. + */ + toJSON() { return { anchor: this.anchor, head: this.head }; } + /** + Convert a JSON representation of a range to a `SelectionRange` + instance. + */ + static fromJSON(json) { + if (!json || typeof json.anchor != "number" || typeof json.head != "number") + throw new RangeError("Invalid JSON representation for SelectionRange"); + return EditorSelection.range(json.anchor, json.head); + } + /** + @internal + */ + static create(from, to, flags) { + return new SelectionRange(from, to, flags); + } + } + /** + An editor selection holds one or more selection ranges. + */ + class EditorSelection { + constructor( + /** + The ranges in the selection, sorted by position. Ranges cannot + overlap (but they may touch, if they aren't empty). + */ + ranges, + /** + The index of the _main_ range in the selection (which is + usually the range that was added last). + */ + mainIndex) { + this.ranges = ranges; + this.mainIndex = mainIndex; + } + /** + Map a selection through a change. Used to adjust the selection + position for changes. + */ + map(change, assoc = -1) { + if (change.empty) + return this; + return EditorSelection.create(this.ranges.map(r => r.map(change, assoc)), this.mainIndex); + } + /** + Compare this selection to another selection. + */ + eq(other) { + if (this.ranges.length != other.ranges.length || + this.mainIndex != other.mainIndex) + return false; + for (let i = 0; i < this.ranges.length; i++) + if (!this.ranges[i].eq(other.ranges[i])) + return false; + return true; + } + /** + Get the primary selection range. Usually, you should make sure + your code applies to _all_ ranges, by using methods like + [`changeByRange`](https://codemirror.net/6/docs/ref/#state.EditorState.changeByRange). + */ + get main() { return this.ranges[this.mainIndex]; } + /** + Make sure the selection only has one range. Returns a selection + holding only the main range from this selection. + */ + asSingle() { + return this.ranges.length == 1 ? this : new EditorSelection([this.main], 0); + } + /** + Extend this selection with an extra range. + */ + addRange(range, main = true) { + return EditorSelection.create([range].concat(this.ranges), main ? 0 : this.mainIndex + 1); + } + /** + Replace a given range with another range, and then normalize the + selection to merge and sort ranges if necessary. + */ + replaceRange(range, which = this.mainIndex) { + let ranges = this.ranges.slice(); + ranges[which] = range; + return EditorSelection.create(ranges, this.mainIndex); + } + /** + Convert this selection to an object that can be serialized to + JSON. + */ + toJSON() { + return { ranges: this.ranges.map(r => r.toJSON()), main: this.mainIndex }; + } + /** + Create a selection from a JSON representation. + */ + static fromJSON(json) { + if (!json || !Array.isArray(json.ranges) || typeof json.main != "number" || json.main >= json.ranges.length) + throw new RangeError("Invalid JSON representation for EditorSelection"); + return new EditorSelection(json.ranges.map((r) => SelectionRange.fromJSON(r)), json.main); + } + /** + Create a selection holding a single range. + */ + static single(anchor, head = anchor) { + return new EditorSelection([EditorSelection.range(anchor, head)], 0); + } + /** + Sort and merge the given set of ranges, creating a valid + selection. + */ + static create(ranges, mainIndex = 0) { + if (ranges.length == 0) + throw new RangeError("A selection needs at least one range"); + for (let pos = 0, i = 0; i < ranges.length; i++) { + let range = ranges[i]; + if (range.empty ? range.from <= pos : range.from < pos) + return EditorSelection.normalized(ranges.slice(), mainIndex); + pos = range.to; + } + return new EditorSelection(ranges, mainIndex); + } + /** + Create a cursor selection range at the given position. You can + safely ignore the optional arguments in most situations. + */ + static cursor(pos, assoc = 0, bidiLevel, goalColumn) { + return SelectionRange.create(pos, pos, (assoc == 0 ? 0 : assoc < 0 ? 4 /* RangeFlag.AssocBefore */ : 8 /* RangeFlag.AssocAfter */) | + (bidiLevel == null ? 3 : Math.min(2, bidiLevel)) | + ((goalColumn !== null && goalColumn !== void 0 ? goalColumn : 33554431 /* RangeFlag.NoGoalColumn */) << 5 /* RangeFlag.GoalColumnOffset */)); + } + /** + Create a selection range. + */ + static range(anchor, head, goalColumn) { + let goal = (goalColumn !== null && goalColumn !== void 0 ? goalColumn : 33554431 /* RangeFlag.NoGoalColumn */) << 5 /* RangeFlag.GoalColumnOffset */; + return head < anchor ? SelectionRange.create(head, anchor, 16 /* RangeFlag.Inverted */ | goal | 8 /* RangeFlag.AssocAfter */) + : SelectionRange.create(anchor, head, goal | (head > anchor ? 4 /* RangeFlag.AssocBefore */ : 0)); + } + /** + @internal + */ + static normalized(ranges, mainIndex = 0) { + let main = ranges[mainIndex]; + ranges.sort((a, b) => a.from - b.from); + mainIndex = ranges.indexOf(main); + for (let i = 1; i < ranges.length; i++) { + let range = ranges[i], prev = ranges[i - 1]; + if (range.empty ? range.from <= prev.to : range.from < prev.to) { + let from = prev.from, to = Math.max(range.to, prev.to); + if (i <= mainIndex) + mainIndex--; + ranges.splice(--i, 2, range.anchor > range.head ? EditorSelection.range(to, from) : EditorSelection.range(from, to)); + } + } + return new EditorSelection(ranges, mainIndex); + } + } + function checkSelection(selection, docLength) { + for (let range of selection.ranges) + if (range.to > docLength) + throw new RangeError("Selection points outside of document"); + } + + let nextID = 0; + /** + A facet is a labeled value that is associated with an editor + state. It takes inputs from any number of extensions, and combines + those into a single output value. + + Examples of uses of facets are the [tab + size](https://codemirror.net/6/docs/ref/#state.EditorState^tabSize), [editor + attributes](https://codemirror.net/6/docs/ref/#view.EditorView^editorAttributes), and [update + listeners](https://codemirror.net/6/docs/ref/#view.EditorView^updateListener). + */ + class Facet { + constructor( + /** + @internal + */ + combine, + /** + @internal + */ + compareInput, + /** + @internal + */ + compare, isStatic, enables) { + this.combine = combine; + this.compareInput = compareInput; + this.compare = compare; + this.isStatic = isStatic; + /** + @internal + */ + this.id = nextID++; + this.default = combine([]); + this.extensions = typeof enables == "function" ? enables(this) : enables; + } + /** + Define a new facet. + */ + static define(config = {}) { + return new Facet(config.combine || ((a) => a), config.compareInput || ((a, b) => a === b), config.compare || (!config.combine ? sameArray$1 : (a, b) => a === b), !!config.static, config.enables); + } + /** + Returns an extension that adds the given value to this facet. + */ + of(value) { + return new FacetProvider([], this, 0 /* Provider.Static */, value); + } + /** + Create an extension that computes a value for the facet from a + state. You must take care to declare the parts of the state that + this value depends on, since your function is only called again + for a new state when one of those parts changed. + + In cases where your value depends only on a single field, you'll + want to use the [`from`](https://codemirror.net/6/docs/ref/#state.Facet.from) method instead. + */ + compute(deps, get) { + if (this.isStatic) + throw new Error("Can't compute a static facet"); + return new FacetProvider(deps, this, 1 /* Provider.Single */, get); + } + /** + Create an extension that computes zero or more values for this + facet from a state. + */ + computeN(deps, get) { + if (this.isStatic) + throw new Error("Can't compute a static facet"); + return new FacetProvider(deps, this, 2 /* Provider.Multi */, get); + } + from(field, get) { + if (!get) + get = x => x; + return this.compute([field], state => get(state.field(field))); + } + } + function sameArray$1(a, b) { + return a == b || a.length == b.length && a.every((e, i) => e === b[i]); + } + class FacetProvider { + constructor(dependencies, facet, type, value) { + this.dependencies = dependencies; + this.facet = facet; + this.type = type; + this.value = value; + this.id = nextID++; + } + dynamicSlot(addresses) { + var _a; + let getter = this.value; + let compare = this.facet.compareInput; + let id = this.id, idx = addresses[id] >> 1, multi = this.type == 2 /* Provider.Multi */; + let depDoc = false, depSel = false, depAddrs = []; + for (let dep of this.dependencies) { + if (dep == "doc") + depDoc = true; + else if (dep == "selection") + depSel = true; + else if ((((_a = addresses[dep.id]) !== null && _a !== void 0 ? _a : 1) & 1) == 0) + depAddrs.push(addresses[dep.id]); + } + return { + create(state) { + state.values[idx] = getter(state); + return 1 /* SlotStatus.Changed */; + }, + update(state, tr) { + if ((depDoc && tr.docChanged) || (depSel && (tr.docChanged || tr.selection)) || ensureAll(state, depAddrs)) { + let newVal = getter(state); + if (multi ? !compareArray(newVal, state.values[idx], compare) : !compare(newVal, state.values[idx])) { + state.values[idx] = newVal; + return 1 /* SlotStatus.Changed */; + } + } + return 0; + }, + reconfigure: (state, oldState) => { + let newVal = getter(state); + let oldAddr = oldState.config.address[id]; + if (oldAddr != null) { + let oldVal = getAddr(oldState, oldAddr); + if (this.dependencies.every(dep => { + return dep instanceof Facet ? oldState.facet(dep) === state.facet(dep) : + dep instanceof StateField ? oldState.field(dep, false) == state.field(dep, false) : true; + }) || (multi ? compareArray(newVal, oldVal, compare) : compare(newVal, oldVal))) { + state.values[idx] = oldVal; + return 0; + } + } + state.values[idx] = newVal; + return 1 /* SlotStatus.Changed */; + } + }; + } + } + function compareArray(a, b, compare) { + if (a.length != b.length) + return false; + for (let i = 0; i < a.length; i++) + if (!compare(a[i], b[i])) + return false; + return true; + } + function ensureAll(state, addrs) { + let changed = false; + for (let addr of addrs) + if (ensureAddr(state, addr) & 1 /* SlotStatus.Changed */) + changed = true; + return changed; + } + function dynamicFacetSlot(addresses, facet, providers) { + let providerAddrs = providers.map(p => addresses[p.id]); + let providerTypes = providers.map(p => p.type); + let dynamic = providerAddrs.filter(p => !(p & 1)); + let idx = addresses[facet.id] >> 1; + function get(state) { + let values = []; + for (let i = 0; i < providerAddrs.length; i++) { + let value = getAddr(state, providerAddrs[i]); + if (providerTypes[i] == 2 /* Provider.Multi */) + for (let val of value) + values.push(val); + else + values.push(value); + } + return facet.combine(values); + } + return { + create(state) { + for (let addr of providerAddrs) + ensureAddr(state, addr); + state.values[idx] = get(state); + return 1 /* SlotStatus.Changed */; + }, + update(state, tr) { + if (!ensureAll(state, dynamic)) + return 0; + let value = get(state); + if (facet.compare(value, state.values[idx])) + return 0; + state.values[idx] = value; + return 1 /* SlotStatus.Changed */; + }, + reconfigure(state, oldState) { + let depChanged = ensureAll(state, providerAddrs); + let oldProviders = oldState.config.facets[facet.id], oldValue = oldState.facet(facet); + if (oldProviders && !depChanged && sameArray$1(providers, oldProviders)) { + state.values[idx] = oldValue; + return 0; + } + let value = get(state); + if (facet.compare(value, oldValue)) { + state.values[idx] = oldValue; + return 0; + } + state.values[idx] = value; + return 1 /* SlotStatus.Changed */; + } + }; + } + const initField = /*@__PURE__*/Facet.define({ static: true }); + /** + Fields can store additional information in an editor state, and + keep it in sync with the rest of the state. + */ + class StateField { + constructor( + /** + @internal + */ + id, createF, updateF, compareF, + /** + @internal + */ + spec) { + this.id = id; + this.createF = createF; + this.updateF = updateF; + this.compareF = compareF; + this.spec = spec; + /** + @internal + */ + this.provides = undefined; + } + /** + Define a state field. + */ + static define(config) { + let field = new StateField(nextID++, config.create, config.update, config.compare || ((a, b) => a === b), config); + if (config.provide) + field.provides = config.provide(field); + return field; + } + create(state) { + let init = state.facet(initField).find(i => i.field == this); + return ((init === null || init === void 0 ? void 0 : init.create) || this.createF)(state); + } + /** + @internal + */ + slot(addresses) { + let idx = addresses[this.id] >> 1; + return { + create: (state) => { + state.values[idx] = this.create(state); + return 1 /* SlotStatus.Changed */; + }, + update: (state, tr) => { + let oldVal = state.values[idx]; + let value = this.updateF(oldVal, tr); + if (this.compareF(oldVal, value)) + return 0; + state.values[idx] = value; + return 1 /* SlotStatus.Changed */; + }, + reconfigure: (state, oldState) => { + if (oldState.config.address[this.id] != null) { + state.values[idx] = oldState.field(this); + return 0; + } + state.values[idx] = this.create(state); + return 1 /* SlotStatus.Changed */; + } + }; + } + /** + Returns an extension that enables this field and overrides the + way it is initialized. Can be useful when you need to provide a + non-default starting value for the field. + */ + init(create) { + return [this, initField.of({ field: this, create })]; + } + /** + State field instances can be used as + [`Extension`](https://codemirror.net/6/docs/ref/#state.Extension) values to enable the field in a + given state. + */ + get extension() { return this; } + } + const Prec_ = { lowest: 4, low: 3, default: 2, high: 1, highest: 0 }; + function prec(value) { + return (ext) => new PrecExtension(ext, value); + } + /** + By default extensions are registered in the order they are found + in the flattened form of nested array that was provided. + Individual extension values can be assigned a precedence to + override this. Extensions that do not have a precedence set get + the precedence of the nearest parent with a precedence, or + [`default`](https://codemirror.net/6/docs/ref/#state.Prec.default) if there is no such parent. The + final ordering of extensions is determined by first sorting by + precedence and then by order within each precedence. + */ + const Prec = { + /** + The highest precedence level, for extensions that should end up + near the start of the precedence ordering. + */ + highest: /*@__PURE__*/prec(Prec_.highest), + /** + A higher-than-default precedence, for extensions that should + come before those with default precedence. + */ + high: /*@__PURE__*/prec(Prec_.high), + /** + The default precedence, which is also used for extensions + without an explicit precedence. + */ + default: /*@__PURE__*/prec(Prec_.default), + /** + A lower-than-default precedence. + */ + low: /*@__PURE__*/prec(Prec_.low), + /** + The lowest precedence level. Meant for things that should end up + near the end of the extension order. + */ + lowest: /*@__PURE__*/prec(Prec_.lowest) + }; + class PrecExtension { + constructor(inner, prec) { + this.inner = inner; + this.prec = prec; + } + } + /** + Extension compartments can be used to make a configuration + dynamic. By [wrapping](https://codemirror.net/6/docs/ref/#state.Compartment.of) part of your + configuration in a compartment, you can later + [replace](https://codemirror.net/6/docs/ref/#state.Compartment.reconfigure) that part through a + transaction. + */ + class Compartment { + /** + Create an instance of this compartment to add to your [state + configuration](https://codemirror.net/6/docs/ref/#state.EditorStateConfig.extensions). + */ + of(ext) { return new CompartmentInstance(this, ext); } + /** + Create an [effect](https://codemirror.net/6/docs/ref/#state.TransactionSpec.effects) that + reconfigures this compartment. + */ + reconfigure(content) { + return Compartment.reconfigure.of({ compartment: this, extension: content }); + } + /** + Get the current content of the compartment in the state, or + `undefined` if it isn't present. + */ + get(state) { + return state.config.compartments.get(this); + } + } + class CompartmentInstance { + constructor(compartment, inner) { + this.compartment = compartment; + this.inner = inner; + } + } + class Configuration { + constructor(base, compartments, dynamicSlots, address, staticValues, facets) { + this.base = base; + this.compartments = compartments; + this.dynamicSlots = dynamicSlots; + this.address = address; + this.staticValues = staticValues; + this.facets = facets; + this.statusTemplate = []; + while (this.statusTemplate.length < dynamicSlots.length) + this.statusTemplate.push(0 /* SlotStatus.Unresolved */); + } + staticFacet(facet) { + let addr = this.address[facet.id]; + return addr == null ? facet.default : this.staticValues[addr >> 1]; + } + static resolve(base, compartments, oldState) { + let fields = []; + let facets = Object.create(null); + let newCompartments = new Map(); + for (let ext of flatten(base, compartments, newCompartments)) { + if (ext instanceof StateField) + fields.push(ext); + else + (facets[ext.facet.id] || (facets[ext.facet.id] = [])).push(ext); + } + let address = Object.create(null); + let staticValues = []; + let dynamicSlots = []; + for (let field of fields) { + address[field.id] = dynamicSlots.length << 1; + dynamicSlots.push(a => field.slot(a)); + } + let oldFacets = oldState === null || oldState === void 0 ? void 0 : oldState.config.facets; + for (let id in facets) { + let providers = facets[id], facet = providers[0].facet; + let oldProviders = oldFacets && oldFacets[id] || []; + if (providers.every(p => p.type == 0 /* Provider.Static */)) { + address[facet.id] = (staticValues.length << 1) | 1; + if (sameArray$1(oldProviders, providers)) { + staticValues.push(oldState.facet(facet)); + } + else { + let value = facet.combine(providers.map(p => p.value)); + staticValues.push(oldState && facet.compare(value, oldState.facet(facet)) ? oldState.facet(facet) : value); + } + } + else { + for (let p of providers) { + if (p.type == 0 /* Provider.Static */) { + address[p.id] = (staticValues.length << 1) | 1; + staticValues.push(p.value); + } + else { + address[p.id] = dynamicSlots.length << 1; + dynamicSlots.push(a => p.dynamicSlot(a)); + } + } + address[facet.id] = dynamicSlots.length << 1; + dynamicSlots.push(a => dynamicFacetSlot(a, facet, providers)); + } + } + let dynamic = dynamicSlots.map(f => f(address)); + return new Configuration(base, newCompartments, dynamic, address, staticValues, facets); + } + } + function flatten(extension, compartments, newCompartments) { + let result = [[], [], [], [], []]; + let seen = new Map(); + function inner(ext, prec) { + let known = seen.get(ext); + if (known != null) { + if (known <= prec) + return; + let found = result[known].indexOf(ext); + if (found > -1) + result[known].splice(found, 1); + if (ext instanceof CompartmentInstance) + newCompartments.delete(ext.compartment); + } + seen.set(ext, prec); + if (Array.isArray(ext)) { + for (let e of ext) + inner(e, prec); + } + else if (ext instanceof CompartmentInstance) { + if (newCompartments.has(ext.compartment)) + throw new RangeError(`Duplicate use of compartment in extensions`); + let content = compartments.get(ext.compartment) || ext.inner; + newCompartments.set(ext.compartment, content); + inner(content, prec); + } + else if (ext instanceof PrecExtension) { + inner(ext.inner, ext.prec); + } + else if (ext instanceof StateField) { + result[prec].push(ext); + if (ext.provides) + inner(ext.provides, prec); + } + else if (ext instanceof FacetProvider) { + result[prec].push(ext); + if (ext.facet.extensions) + inner(ext.facet.extensions, Prec_.default); + } + else { + let content = ext.extension; + if (!content) + throw new Error(`Unrecognized extension value in extension set (${ext}). This sometimes happens because multiple instances of @codemirror/state are loaded, breaking instanceof checks.`); + inner(content, prec); + } + } + inner(extension, Prec_.default); + return result.reduce((a, b) => a.concat(b)); + } + function ensureAddr(state, addr) { + if (addr & 1) + return 2 /* SlotStatus.Computed */; + let idx = addr >> 1; + let status = state.status[idx]; + if (status == 4 /* SlotStatus.Computing */) + throw new Error("Cyclic dependency between fields and/or facets"); + if (status & 2 /* SlotStatus.Computed */) + return status; + state.status[idx] = 4 /* SlotStatus.Computing */; + let changed = state.computeSlot(state, state.config.dynamicSlots[idx]); + return state.status[idx] = 2 /* SlotStatus.Computed */ | changed; + } + function getAddr(state, addr) { + return addr & 1 ? state.config.staticValues[addr >> 1] : state.values[addr >> 1]; + } + + const languageData = /*@__PURE__*/Facet.define(); + const allowMultipleSelections = /*@__PURE__*/Facet.define({ + combine: values => values.some(v => v), + static: true + }); + const lineSeparator = /*@__PURE__*/Facet.define({ + combine: values => values.length ? values[0] : undefined, + static: true + }); + const changeFilter = /*@__PURE__*/Facet.define(); + const transactionFilter = /*@__PURE__*/Facet.define(); + const transactionExtender = /*@__PURE__*/Facet.define(); + const readOnly = /*@__PURE__*/Facet.define({ + combine: values => values.length ? values[0] : false + }); + + /** + Annotations are tagged values that are used to add metadata to + transactions in an extensible way. They should be used to model + things that effect the entire transaction (such as its [time + stamp](https://codemirror.net/6/docs/ref/#state.Transaction^time) or information about its + [origin](https://codemirror.net/6/docs/ref/#state.Transaction^userEvent)). For effects that happen + _alongside_ the other changes made by the transaction, [state + effects](https://codemirror.net/6/docs/ref/#state.StateEffect) are more appropriate. + */ + class Annotation { + /** + @internal + */ + constructor( + /** + The annotation type. + */ + type, + /** + The value of this annotation. + */ + value) { + this.type = type; + this.value = value; + } + /** + Define a new type of annotation. + */ + static define() { return new AnnotationType(); } + } + /** + Marker that identifies a type of [annotation](https://codemirror.net/6/docs/ref/#state.Annotation). + */ + class AnnotationType { + /** + Create an instance of this annotation. + */ + of(value) { return new Annotation(this, value); } + } + /** + Representation of a type of state effect. Defined with + [`StateEffect.define`](https://codemirror.net/6/docs/ref/#state.StateEffect^define). + */ + class StateEffectType { + /** + @internal + */ + constructor( + // The `any` types in these function types are there to work + // around TypeScript issue #37631, where the type guard on + // `StateEffect.is` mysteriously stops working when these properly + // have type `Value`. + /** + @internal + */ + map) { + this.map = map; + } + /** + Create a [state effect](https://codemirror.net/6/docs/ref/#state.StateEffect) instance of this + type. + */ + of(value) { return new StateEffect(this, value); } + } + /** + State effects can be used to represent additional effects + associated with a [transaction](https://codemirror.net/6/docs/ref/#state.Transaction.effects). They + are often useful to model changes to custom [state + fields](https://codemirror.net/6/docs/ref/#state.StateField), when those changes aren't implicit in + document or selection changes. + */ + class StateEffect { + /** + @internal + */ + constructor( + /** + @internal + */ + type, + /** + The value of this effect. + */ + value) { + this.type = type; + this.value = value; + } + /** + Map this effect through a position mapping. Will return + `undefined` when that ends up deleting the effect. + */ + map(mapping) { + let mapped = this.type.map(this.value, mapping); + return mapped === undefined ? undefined : mapped == this.value ? this : new StateEffect(this.type, mapped); + } + /** + Tells you whether this effect object is of a given + [type](https://codemirror.net/6/docs/ref/#state.StateEffectType). + */ + is(type) { return this.type == type; } + /** + Define a new effect type. The type parameter indicates the type + of values that his effect holds. + */ + static define(spec = {}) { + return new StateEffectType(spec.map || (v => v)); + } + /** + Map an array of effects through a change set. + */ + static mapEffects(effects, mapping) { + if (!effects.length) + return effects; + let result = []; + for (let effect of effects) { + let mapped = effect.map(mapping); + if (mapped) + result.push(mapped); + } + return result; + } + } + /** + This effect can be used to reconfigure the root extensions of + the editor. Doing this will discard any extensions + [appended](https://codemirror.net/6/docs/ref/#state.StateEffect^appendConfig), but does not reset + the content of [reconfigured](https://codemirror.net/6/docs/ref/#state.Compartment.reconfigure) + compartments. + */ + StateEffect.reconfigure = /*@__PURE__*/StateEffect.define(); + /** + Append extensions to the top-level configuration of the editor. + */ + StateEffect.appendConfig = /*@__PURE__*/StateEffect.define(); + /** + Changes to the editor state are grouped into transactions. + Typically, a user action creates a single transaction, which may + contain any number of document changes, may change the selection, + or have other effects. Create a transaction by calling + [`EditorState.update`](https://codemirror.net/6/docs/ref/#state.EditorState.update), or immediately + dispatch one by calling + [`EditorView.dispatch`](https://codemirror.net/6/docs/ref/#view.EditorView.dispatch). + */ + class Transaction { + constructor( + /** + The state from which the transaction starts. + */ + startState, + /** + The document changes made by this transaction. + */ + changes, + /** + The selection set by this transaction, or undefined if it + doesn't explicitly set a selection. + */ + selection, + /** + The effects added to the transaction. + */ + effects, + /** + @internal + */ + annotations, + /** + Whether the selection should be scrolled into view after this + transaction is dispatched. + */ + scrollIntoView) { + this.startState = startState; + this.changes = changes; + this.selection = selection; + this.effects = effects; + this.annotations = annotations; + this.scrollIntoView = scrollIntoView; + /** + @internal + */ + this._doc = null; + /** + @internal + */ + this._state = null; + if (selection) + checkSelection(selection, changes.newLength); + if (!annotations.some((a) => a.type == Transaction.time)) + this.annotations = annotations.concat(Transaction.time.of(Date.now())); + } + /** + @internal + */ + static create(startState, changes, selection, effects, annotations, scrollIntoView) { + return new Transaction(startState, changes, selection, effects, annotations, scrollIntoView); + } + /** + The new document produced by the transaction. Contrary to + [`.state`](https://codemirror.net/6/docs/ref/#state.Transaction.state)`.doc`, accessing this won't + force the entire new state to be computed right away, so it is + recommended that [transaction + filters](https://codemirror.net/6/docs/ref/#state.EditorState^transactionFilter) use this getter + when they need to look at the new document. + */ + get newDoc() { + return this._doc || (this._doc = this.changes.apply(this.startState.doc)); + } + /** + The new selection produced by the transaction. If + [`this.selection`](https://codemirror.net/6/docs/ref/#state.Transaction.selection) is undefined, + this will [map](https://codemirror.net/6/docs/ref/#state.EditorSelection.map) the start state's + current selection through the changes made by the transaction. + */ + get newSelection() { + return this.selection || this.startState.selection.map(this.changes); + } + /** + The new state created by the transaction. Computed on demand + (but retained for subsequent access), so it is recommended not to + access it in [transaction + filters](https://codemirror.net/6/docs/ref/#state.EditorState^transactionFilter) when possible. + */ + get state() { + if (!this._state) + this.startState.applyTransaction(this); + return this._state; + } + /** + Get the value of the given annotation type, if any. + */ + annotation(type) { + for (let ann of this.annotations) + if (ann.type == type) + return ann.value; + return undefined; + } + /** + Indicates whether the transaction changed the document. + */ + get docChanged() { return !this.changes.empty; } + /** + Indicates whether this transaction reconfigures the state + (through a [configuration compartment](https://codemirror.net/6/docs/ref/#state.Compartment) or + with a top-level configuration + [effect](https://codemirror.net/6/docs/ref/#state.StateEffect^reconfigure). + */ + get reconfigured() { return this.startState.config != this.state.config; } + /** + Returns true if the transaction has a [user + event](https://codemirror.net/6/docs/ref/#state.Transaction^userEvent) annotation that is equal to + or more specific than `event`. For example, if the transaction + has `"select.pointer"` as user event, `"select"` and + `"select.pointer"` will match it. + */ + isUserEvent(event) { + let e = this.annotation(Transaction.userEvent); + return !!(e && (e == event || e.length > event.length && e.slice(0, event.length) == event && e[event.length] == ".")); + } + } + /** + Annotation used to store transaction timestamps. Automatically + added to every transaction, holding `Date.now()`. + */ + Transaction.time = /*@__PURE__*/Annotation.define(); + /** + Annotation used to associate a transaction with a user interface + event. Holds a string identifying the event, using a + dot-separated format to support attaching more specific + information. The events used by the core libraries are: + + - `"input"` when content is entered + - `"input.type"` for typed input + - `"input.type.compose"` for composition + - `"input.paste"` for pasted input + - `"input.drop"` when adding content with drag-and-drop + - `"input.complete"` when autocompleting + - `"delete"` when the user deletes content + - `"delete.selection"` when deleting the selection + - `"delete.forward"` when deleting forward from the selection + - `"delete.backward"` when deleting backward from the selection + - `"delete.cut"` when cutting to the clipboard + - `"move"` when content is moved + - `"move.drop"` when content is moved within the editor through drag-and-drop + - `"select"` when explicitly changing the selection + - `"select.pointer"` when selecting with a mouse or other pointing device + - `"undo"` and `"redo"` for history actions + + Use [`isUserEvent`](https://codemirror.net/6/docs/ref/#state.Transaction.isUserEvent) to check + whether the annotation matches a given event. + */ + Transaction.userEvent = /*@__PURE__*/Annotation.define(); + /** + Annotation indicating whether a transaction should be added to + the undo history or not. + */ + Transaction.addToHistory = /*@__PURE__*/Annotation.define(); + /** + Annotation indicating (when present and true) that a transaction + represents a change made by some other actor, not the user. This + is used, for example, to tag other people's changes in + collaborative editing. + */ + Transaction.remote = /*@__PURE__*/Annotation.define(); + function joinRanges(a, b) { + let result = []; + for (let iA = 0, iB = 0;;) { + let from, to; + if (iA < a.length && (iB == b.length || b[iB] >= a[iA])) { + from = a[iA++]; + to = a[iA++]; + } + else if (iB < b.length) { + from = b[iB++]; + to = b[iB++]; + } + else + return result; + if (!result.length || result[result.length - 1] < from) + result.push(from, to); + else if (result[result.length - 1] < to) + result[result.length - 1] = to; + } + } + function mergeTransaction(a, b, sequential) { + var _a; + let mapForA, mapForB, changes; + if (sequential) { + mapForA = b.changes; + mapForB = ChangeSet.empty(b.changes.length); + changes = a.changes.compose(b.changes); + } + else { + mapForA = b.changes.map(a.changes); + mapForB = a.changes.mapDesc(b.changes, true); + changes = a.changes.compose(mapForA); + } + return { + changes, + selection: b.selection ? b.selection.map(mapForB) : (_a = a.selection) === null || _a === void 0 ? void 0 : _a.map(mapForA), + effects: StateEffect.mapEffects(a.effects, mapForA).concat(StateEffect.mapEffects(b.effects, mapForB)), + annotations: a.annotations.length ? a.annotations.concat(b.annotations) : b.annotations, + scrollIntoView: a.scrollIntoView || b.scrollIntoView + }; + } + function resolveTransactionInner(state, spec, docSize) { + let sel = spec.selection, annotations = asArray$1(spec.annotations); + if (spec.userEvent) + annotations = annotations.concat(Transaction.userEvent.of(spec.userEvent)); + return { + changes: spec.changes instanceof ChangeSet ? spec.changes + : ChangeSet.of(spec.changes || [], docSize, state.facet(lineSeparator)), + selection: sel && (sel instanceof EditorSelection ? sel : EditorSelection.single(sel.anchor, sel.head)), + effects: asArray$1(spec.effects), + annotations, + scrollIntoView: !!spec.scrollIntoView + }; + } + function resolveTransaction(state, specs, filter) { + let s = resolveTransactionInner(state, specs.length ? specs[0] : {}, state.doc.length); + if (specs.length && specs[0].filter === false) + filter = false; + for (let i = 1; i < specs.length; i++) { + if (specs[i].filter === false) + filter = false; + let seq = !!specs[i].sequential; + s = mergeTransaction(s, resolveTransactionInner(state, specs[i], seq ? s.changes.newLength : state.doc.length), seq); + } + let tr = Transaction.create(state, s.changes, s.selection, s.effects, s.annotations, s.scrollIntoView); + return extendTransaction(filter ? filterTransaction(tr) : tr); + } + // Finish a transaction by applying filters if necessary. + function filterTransaction(tr) { + let state = tr.startState; + // Change filters + let result = true; + for (let filter of state.facet(changeFilter)) { + let value = filter(tr); + if (value === false) { + result = false; + break; + } + if (Array.isArray(value)) + result = result === true ? value : joinRanges(result, value); + } + if (result !== true) { + let changes, back; + if (result === false) { + back = tr.changes.invertedDesc; + changes = ChangeSet.empty(state.doc.length); + } + else { + let filtered = tr.changes.filter(result); + changes = filtered.changes; + back = filtered.filtered.mapDesc(filtered.changes).invertedDesc; + } + tr = Transaction.create(state, changes, tr.selection && tr.selection.map(back), StateEffect.mapEffects(tr.effects, back), tr.annotations, tr.scrollIntoView); + } + // Transaction filters + let filters = state.facet(transactionFilter); + for (let i = filters.length - 1; i >= 0; i--) { + let filtered = filters[i](tr); + if (filtered instanceof Transaction) + tr = filtered; + else if (Array.isArray(filtered) && filtered.length == 1 && filtered[0] instanceof Transaction) + tr = filtered[0]; + else + tr = resolveTransaction(state, asArray$1(filtered), false); + } + return tr; + } + function extendTransaction(tr) { + let state = tr.startState, extenders = state.facet(transactionExtender), spec = tr; + for (let i = extenders.length - 1; i >= 0; i--) { + let extension = extenders[i](tr); + if (extension && Object.keys(extension).length) + spec = mergeTransaction(spec, resolveTransactionInner(state, extension, tr.changes.newLength), true); + } + return spec == tr ? tr : Transaction.create(state, tr.changes, tr.selection, spec.effects, spec.annotations, spec.scrollIntoView); + } + const none$2 = []; + function asArray$1(value) { + return value == null ? none$2 : Array.isArray(value) ? value : [value]; + } + + /** + The categories produced by a [character + categorizer](https://codemirror.net/6/docs/ref/#state.EditorState.charCategorizer). These are used + do things like selecting by word. + */ + var CharCategory = /*@__PURE__*/(function (CharCategory) { + /** + Word characters. + */ + CharCategory[CharCategory["Word"] = 0] = "Word"; + /** + Whitespace. + */ + CharCategory[CharCategory["Space"] = 1] = "Space"; + /** + Anything else. + */ + CharCategory[CharCategory["Other"] = 2] = "Other"; + return CharCategory})(CharCategory || (CharCategory = {})); + const nonASCIISingleCaseWordChar = /[\u00df\u0587\u0590-\u05f4\u0600-\u06ff\u3040-\u309f\u30a0-\u30ff\u3400-\u4db5\u4e00-\u9fcc\uac00-\ud7af]/; + let wordChar; + try { + wordChar = /*@__PURE__*/new RegExp("[\\p{Alphabetic}\\p{Number}_]", "u"); + } + catch (_) { } + function hasWordChar(str) { + if (wordChar) + return wordChar.test(str); + for (let i = 0; i < str.length; i++) { + let ch = str[i]; + if (/\w/.test(ch) || ch > "\x80" && (ch.toUpperCase() != ch.toLowerCase() || nonASCIISingleCaseWordChar.test(ch))) + return true; + } + return false; + } + function makeCategorizer(wordChars) { + return (char) => { + if (!/\S/.test(char)) + return CharCategory.Space; + if (hasWordChar(char)) + return CharCategory.Word; + for (let i = 0; i < wordChars.length; i++) + if (char.indexOf(wordChars[i]) > -1) + return CharCategory.Word; + return CharCategory.Other; + }; + } + + /** + The editor state class is a persistent (immutable) data structure. + To update a state, you [create](https://codemirror.net/6/docs/ref/#state.EditorState.update) a + [transaction](https://codemirror.net/6/docs/ref/#state.Transaction), which produces a _new_ state + instance, without modifying the original object. + + As such, _never_ mutate properties of a state directly. That'll + just break things. + */ + class EditorState { + constructor( + /** + @internal + */ + config, + /** + The current document. + */ + doc, + /** + The current selection. + */ + selection, + /** + @internal + */ + values, computeSlot, tr) { + this.config = config; + this.doc = doc; + this.selection = selection; + this.values = values; + this.status = config.statusTemplate.slice(); + this.computeSlot = computeSlot; + // Fill in the computed state immediately, so that further queries + // for it made during the update return this state + if (tr) + tr._state = this; + for (let i = 0; i < this.config.dynamicSlots.length; i++) + ensureAddr(this, i << 1); + this.computeSlot = null; + } + field(field, require = true) { + let addr = this.config.address[field.id]; + if (addr == null) { + if (require) + throw new RangeError("Field is not present in this state"); + return undefined; + } + ensureAddr(this, addr); + return getAddr(this, addr); + } + /** + Create a [transaction](https://codemirror.net/6/docs/ref/#state.Transaction) that updates this + state. Any number of [transaction specs](https://codemirror.net/6/docs/ref/#state.TransactionSpec) + can be passed. Unless + [`sequential`](https://codemirror.net/6/docs/ref/#state.TransactionSpec.sequential) is set, the + [changes](https://codemirror.net/6/docs/ref/#state.TransactionSpec.changes) (if any) of each spec + are assumed to start in the _current_ document (not the document + produced by previous specs), and its + [selection](https://codemirror.net/6/docs/ref/#state.TransactionSpec.selection) and + [effects](https://codemirror.net/6/docs/ref/#state.TransactionSpec.effects) are assumed to refer + to the document created by its _own_ changes. The resulting + transaction contains the combined effect of all the different + specs. For [selection](https://codemirror.net/6/docs/ref/#state.TransactionSpec.selection), later + specs take precedence over earlier ones. + */ + update(...specs) { + return resolveTransaction(this, specs, true); + } + /** + @internal + */ + applyTransaction(tr) { + let conf = this.config, { base, compartments } = conf; + for (let effect of tr.effects) { + if (effect.is(Compartment.reconfigure)) { + if (conf) { + compartments = new Map; + conf.compartments.forEach((val, key) => compartments.set(key, val)); + conf = null; + } + compartments.set(effect.value.compartment, effect.value.extension); + } + else if (effect.is(StateEffect.reconfigure)) { + conf = null; + base = effect.value; + } + else if (effect.is(StateEffect.appendConfig)) { + conf = null; + base = asArray$1(base).concat(effect.value); + } + } + let startValues; + if (!conf) { + conf = Configuration.resolve(base, compartments, this); + let intermediateState = new EditorState(conf, this.doc, this.selection, conf.dynamicSlots.map(() => null), (state, slot) => slot.reconfigure(state, this), null); + startValues = intermediateState.values; + } + else { + startValues = tr.startState.values.slice(); + } + new EditorState(conf, tr.newDoc, tr.newSelection, startValues, (state, slot) => slot.update(state, tr), tr); + } + /** + Create a [transaction spec](https://codemirror.net/6/docs/ref/#state.TransactionSpec) that + replaces every selection range with the given content. + */ + replaceSelection(text) { + if (typeof text == "string") + text = this.toText(text); + return this.changeByRange(range => ({ changes: { from: range.from, to: range.to, insert: text }, + range: EditorSelection.cursor(range.from + text.length) })); + } + /** + Create a set of changes and a new selection by running the given + function for each range in the active selection. The function + can return an optional set of changes (in the coordinate space + of the start document), plus an updated range (in the coordinate + space of the document produced by the call's own changes). This + method will merge all the changes and ranges into a single + changeset and selection, and return it as a [transaction + spec](https://codemirror.net/6/docs/ref/#state.TransactionSpec), which can be passed to + [`update`](https://codemirror.net/6/docs/ref/#state.EditorState.update). + */ + changeByRange(f) { + let sel = this.selection; + let result1 = f(sel.ranges[0]); + let changes = this.changes(result1.changes), ranges = [result1.range]; + let effects = asArray$1(result1.effects); + for (let i = 1; i < sel.ranges.length; i++) { + let result = f(sel.ranges[i]); + let newChanges = this.changes(result.changes), newMapped = newChanges.map(changes); + for (let j = 0; j < i; j++) + ranges[j] = ranges[j].map(newMapped); + let mapBy = changes.mapDesc(newChanges, true); + ranges.push(result.range.map(mapBy)); + changes = changes.compose(newMapped); + effects = StateEffect.mapEffects(effects, newMapped).concat(StateEffect.mapEffects(asArray$1(result.effects), mapBy)); + } + return { + changes, + selection: EditorSelection.create(ranges, sel.mainIndex), + effects + }; + } + /** + Create a [change set](https://codemirror.net/6/docs/ref/#state.ChangeSet) from the given change + description, taking the state's document length and line + separator into account. + */ + changes(spec = []) { + if (spec instanceof ChangeSet) + return spec; + return ChangeSet.of(spec, this.doc.length, this.facet(EditorState.lineSeparator)); + } + /** + Using the state's [line + separator](https://codemirror.net/6/docs/ref/#state.EditorState^lineSeparator), create a + [`Text`](https://codemirror.net/6/docs/ref/#state.Text) instance from the given string. + */ + toText(string) { + return Text.of(string.split(this.facet(EditorState.lineSeparator) || DefaultSplit)); + } + /** + Return the given range of the document as a string. + */ + sliceDoc(from = 0, to = this.doc.length) { + return this.doc.sliceString(from, to, this.lineBreak); + } + /** + Get the value of a state [facet](https://codemirror.net/6/docs/ref/#state.Facet). + */ + facet(facet) { + let addr = this.config.address[facet.id]; + if (addr == null) + return facet.default; + ensureAddr(this, addr); + return getAddr(this, addr); + } + /** + Convert this state to a JSON-serializable object. When custom + fields should be serialized, you can pass them in as an object + mapping property names (in the resulting object, which should + not use `doc` or `selection`) to fields. + */ + toJSON(fields) { + let result = { + doc: this.sliceDoc(), + selection: this.selection.toJSON() + }; + if (fields) + for (let prop in fields) { + let value = fields[prop]; + if (value instanceof StateField && this.config.address[value.id] != null) + result[prop] = value.spec.toJSON(this.field(fields[prop]), this); + } + return result; + } + /** + Deserialize a state from its JSON representation. When custom + fields should be deserialized, pass the same object you passed + to [`toJSON`](https://codemirror.net/6/docs/ref/#state.EditorState.toJSON) when serializing as + third argument. + */ + static fromJSON(json, config = {}, fields) { + if (!json || typeof json.doc != "string") + throw new RangeError("Invalid JSON representation for EditorState"); + let fieldInit = []; + if (fields) + for (let prop in fields) { + if (Object.prototype.hasOwnProperty.call(json, prop)) { + let field = fields[prop], value = json[prop]; + fieldInit.push(field.init(state => field.spec.fromJSON(value, state))); + } + } + return EditorState.create({ + doc: json.doc, + selection: EditorSelection.fromJSON(json.selection), + extensions: config.extensions ? fieldInit.concat([config.extensions]) : fieldInit + }); + } + /** + Create a new state. You'll usually only need this when + initializing an editor—updated states are created by applying + transactions. + */ + static create(config = {}) { + let configuration = Configuration.resolve(config.extensions || [], new Map); + let doc = config.doc instanceof Text ? config.doc + : Text.of((config.doc || "").split(configuration.staticFacet(EditorState.lineSeparator) || DefaultSplit)); + let selection = !config.selection ? EditorSelection.single(0) + : config.selection instanceof EditorSelection ? config.selection + : EditorSelection.single(config.selection.anchor, config.selection.head); + checkSelection(selection, doc.length); + if (!configuration.staticFacet(allowMultipleSelections)) + selection = selection.asSingle(); + return new EditorState(configuration, doc, selection, configuration.dynamicSlots.map(() => null), (state, slot) => slot.create(state), null); + } + /** + The size (in columns) of a tab in the document, determined by + the [`tabSize`](https://codemirror.net/6/docs/ref/#state.EditorState^tabSize) facet. + */ + get tabSize() { return this.facet(EditorState.tabSize); } + /** + Get the proper [line-break](https://codemirror.net/6/docs/ref/#state.EditorState^lineSeparator) + string for this state. + */ + get lineBreak() { return this.facet(EditorState.lineSeparator) || "\n"; } + /** + Returns true when the editor is + [configured](https://codemirror.net/6/docs/ref/#state.EditorState^readOnly) to be read-only. + */ + get readOnly() { return this.facet(readOnly); } + /** + Look up a translation for the given phrase (via the + [`phrases`](https://codemirror.net/6/docs/ref/#state.EditorState^phrases) facet), or return the + original string if no translation is found. + + If additional arguments are passed, they will be inserted in + place of markers like `$1` (for the first value) and `$2`, etc. + A single `$` is equivalent to `$1`, and `$$` will produce a + literal dollar sign. + */ + phrase(phrase, ...insert) { + for (let map of this.facet(EditorState.phrases)) + if (Object.prototype.hasOwnProperty.call(map, phrase)) { + phrase = map[phrase]; + break; + } + if (insert.length) + phrase = phrase.replace(/\$(\$|\d*)/g, (m, i) => { + if (i == "$") + return "$"; + let n = +(i || 1); + return !n || n > insert.length ? m : insert[n - 1]; + }); + return phrase; + } + /** + Find the values for a given language data field, provided by the + the [`languageData`](https://codemirror.net/6/docs/ref/#state.EditorState^languageData) facet. + */ + languageDataAt(name, pos, side = -1) { + let values = []; + for (let provider of this.facet(languageData)) { + for (let result of provider(this, pos, side)) { + if (Object.prototype.hasOwnProperty.call(result, name)) + values.push(result[name]); + } + } + return values; + } + /** + Return a function that can categorize strings (expected to + represent a single [grapheme cluster](https://codemirror.net/6/docs/ref/#state.findClusterBreak)) + into one of: + + - Word (contains an alphanumeric character or a character + explicitly listed in the local language's `"wordChars"` + language data, which should be a string) + - Space (contains only whitespace) + - Other (anything else) + */ + charCategorizer(at) { + return makeCategorizer(this.languageDataAt("wordChars", at).join("")); + } + /** + Find the word at the given position, meaning the range + containing all [word](https://codemirror.net/6/docs/ref/#state.CharCategory.Word) characters + around it. If no word characters are adjacent to the position, + this returns null. + */ + wordAt(pos) { + let { text, from, length } = this.doc.lineAt(pos); + let cat = this.charCategorizer(pos); + let start = pos - from, end = pos - from; + while (start > 0) { + let prev = findClusterBreak(text, start, false); + if (cat(text.slice(prev, start)) != CharCategory.Word) + break; + start = prev; + } + while (end < length) { + let next = findClusterBreak(text, end); + if (cat(text.slice(end, next)) != CharCategory.Word) + break; + end = next; + } + return start == end ? null : EditorSelection.range(start + from, end + from); + } + } + /** + A facet that, when enabled, causes the editor to allow multiple + ranges to be selected. Be careful though, because by default the + editor relies on the native DOM selection, which cannot handle + multiple selections. An extension like + [`drawSelection`](https://codemirror.net/6/docs/ref/#view.drawSelection) can be used to make + secondary selections visible to the user. + */ + EditorState.allowMultipleSelections = allowMultipleSelections; + /** + Configures the tab size to use in this state. The first + (highest-precedence) value of the facet is used. If no value is + given, this defaults to 4. + */ + EditorState.tabSize = /*@__PURE__*/Facet.define({ + combine: values => values.length ? values[0] : 4 + }); + /** + The line separator to use. By default, any of `"\n"`, `"\r\n"` + and `"\r"` is treated as a separator when splitting lines, and + lines are joined with `"\n"`. + + When you configure a value here, only that precise separator + will be used, allowing you to round-trip documents through the + editor without normalizing line separators. + */ + EditorState.lineSeparator = lineSeparator; + /** + This facet controls the value of the + [`readOnly`](https://codemirror.net/6/docs/ref/#state.EditorState.readOnly) getter, which is + consulted by commands and extensions that implement editing + functionality to determine whether they should apply. It + defaults to false, but when its highest-precedence value is + `true`, such functionality disables itself. + + Not to be confused with + [`EditorView.editable`](https://codemirror.net/6/docs/ref/#view.EditorView^editable), which + controls whether the editor's DOM is set to be editable (and + thus focusable). + */ + EditorState.readOnly = readOnly; + /** + Registers translation phrases. The + [`phrase`](https://codemirror.net/6/docs/ref/#state.EditorState.phrase) method will look through + all objects registered with this facet to find translations for + its argument. + */ + EditorState.phrases = /*@__PURE__*/Facet.define({ + compare(a, b) { + let kA = Object.keys(a), kB = Object.keys(b); + return kA.length == kB.length && kA.every(k => a[k] == b[k]); + } + }); + /** + A facet used to register [language + data](https://codemirror.net/6/docs/ref/#state.EditorState.languageDataAt) providers. + */ + EditorState.languageData = languageData; + /** + Facet used to register change filters, which are called for each + transaction (unless explicitly + [disabled](https://codemirror.net/6/docs/ref/#state.TransactionSpec.filter)), and can suppress + part of the transaction's changes. + + Such a function can return `true` to indicate that it doesn't + want to do anything, `false` to completely stop the changes in + the transaction, or a set of ranges in which changes should be + suppressed. Such ranges are represented as an array of numbers, + with each pair of two numbers indicating the start and end of a + range. So for example `[10, 20, 100, 110]` suppresses changes + between 10 and 20, and between 100 and 110. + */ + EditorState.changeFilter = changeFilter; + /** + Facet used to register a hook that gets a chance to update or + replace transaction specs before they are applied. This will + only be applied for transactions that don't have + [`filter`](https://codemirror.net/6/docs/ref/#state.TransactionSpec.filter) set to `false`. You + can either return a single transaction spec (possibly the input + transaction), or an array of specs (which will be combined in + the same way as the arguments to + [`EditorState.update`](https://codemirror.net/6/docs/ref/#state.EditorState.update)). + + When possible, it is recommended to avoid accessing + [`Transaction.state`](https://codemirror.net/6/docs/ref/#state.Transaction.state) in a filter, + since it will force creation of a state that will then be + discarded again, if the transaction is actually filtered. + + (This functionality should be used with care. Indiscriminately + modifying transaction is likely to break something or degrade + the user experience.) + */ + EditorState.transactionFilter = transactionFilter; + /** + This is a more limited form of + [`transactionFilter`](https://codemirror.net/6/docs/ref/#state.EditorState^transactionFilter), + which can only add + [annotations](https://codemirror.net/6/docs/ref/#state.TransactionSpec.annotations) and + [effects](https://codemirror.net/6/docs/ref/#state.TransactionSpec.effects). _But_, this type + of filter runs even if the transaction has disabled regular + [filtering](https://codemirror.net/6/docs/ref/#state.TransactionSpec.filter), making it suitable + for effects that don't need to touch the changes or selection, + but do want to process every transaction. + + Extenders run _after_ filters, when both are present. + */ + EditorState.transactionExtender = transactionExtender; + Compartment.reconfigure = /*@__PURE__*/StateEffect.define(); + + /** + Utility function for combining behaviors to fill in a config + object from an array of provided configs. `defaults` should hold + default values for all optional fields in `Config`. + + The function will, by default, error + when a field gets two values that aren't `===`-equal, but you can + provide combine functions per field to do something else. + */ + function combineConfig(configs, defaults, // Should hold only the optional properties of Config, but I haven't managed to express that + combine = {}) { + let result = {}; + for (let config of configs) + for (let key of Object.keys(config)) { + let value = config[key], current = result[key]; + if (current === undefined) + result[key] = value; + else if (current === value || value === undefined) ; // No conflict + else if (Object.hasOwnProperty.call(combine, key)) + result[key] = combine[key](current, value); + else + throw new Error("Config merge conflict for field " + key); + } + for (let key in defaults) + if (result[key] === undefined) + result[key] = defaults[key]; + return result; + } + + /** + Each range is associated with a value, which must inherit from + this class. + */ + class RangeValue { + /** + Compare this value with another value. Used when comparing + rangesets. The default implementation compares by identity. + Unless you are only creating a fixed number of unique instances + of your value type, it is a good idea to implement this + properly. + */ + eq(other) { return this == other; } + /** + Create a [range](https://codemirror.net/6/docs/ref/#state.Range) with this value. + */ + range(from, to = from) { return Range$1.create(from, to, this); } + } + RangeValue.prototype.startSide = RangeValue.prototype.endSide = 0; + RangeValue.prototype.point = false; + RangeValue.prototype.mapMode = MapMode.TrackDel; + /** + A range associates a value with a range of positions. + */ + class Range$1 { + constructor( + /** + The range's start position. + */ + from, + /** + Its end position. + */ + to, + /** + The value associated with this range. + */ + value) { + this.from = from; + this.to = to; + this.value = value; + } + /** + @internal + */ + static create(from, to, value) { + return new Range$1(from, to, value); + } + } + function cmpRange(a, b) { + return a.from - b.from || a.value.startSide - b.value.startSide; + } + class Chunk { + constructor(from, to, value, + // Chunks are marked with the largest point that occurs + // in them (or -1 for no points), so that scans that are + // only interested in points (such as the + // heightmap-related logic) can skip range-only chunks. + maxPoint) { + this.from = from; + this.to = to; + this.value = value; + this.maxPoint = maxPoint; + } + get length() { return this.to[this.to.length - 1]; } + // Find the index of the given position and side. Use the ranges' + // `from` pos when `end == false`, `to` when `end == true`. + findIndex(pos, side, end, startAt = 0) { + let arr = end ? this.to : this.from; + for (let lo = startAt, hi = arr.length;;) { + if (lo == hi) + return lo; + let mid = (lo + hi) >> 1; + let diff = arr[mid] - pos || (end ? this.value[mid].endSide : this.value[mid].startSide) - side; + if (mid == lo) + return diff >= 0 ? lo : hi; + if (diff >= 0) + hi = mid; + else + lo = mid + 1; + } + } + between(offset, from, to, f) { + for (let i = this.findIndex(from, -1000000000 /* C.Far */, true), e = this.findIndex(to, 1000000000 /* C.Far */, false, i); i < e; i++) + if (f(this.from[i] + offset, this.to[i] + offset, this.value[i]) === false) + return false; + } + map(offset, changes) { + let value = [], from = [], to = [], newPos = -1, maxPoint = -1; + for (let i = 0; i < this.value.length; i++) { + let val = this.value[i], curFrom = this.from[i] + offset, curTo = this.to[i] + offset, newFrom, newTo; + if (curFrom == curTo) { + let mapped = changes.mapPos(curFrom, val.startSide, val.mapMode); + if (mapped == null) + continue; + newFrom = newTo = mapped; + if (val.startSide != val.endSide) { + newTo = changes.mapPos(curFrom, val.endSide); + if (newTo < newFrom) + continue; + } + } + else { + newFrom = changes.mapPos(curFrom, val.startSide); + newTo = changes.mapPos(curTo, val.endSide); + if (newFrom > newTo || newFrom == newTo && val.startSide > 0 && val.endSide <= 0) + continue; + } + if ((newTo - newFrom || val.endSide - val.startSide) < 0) + continue; + if (newPos < 0) + newPos = newFrom; + if (val.point) + maxPoint = Math.max(maxPoint, newTo - newFrom); + value.push(val); + from.push(newFrom - newPos); + to.push(newTo - newPos); + } + return { mapped: value.length ? new Chunk(from, to, value, maxPoint) : null, pos: newPos }; + } + } + /** + A range set stores a collection of [ranges](https://codemirror.net/6/docs/ref/#state.Range) in a + way that makes them efficient to [map](https://codemirror.net/6/docs/ref/#state.RangeSet.map) and + [update](https://codemirror.net/6/docs/ref/#state.RangeSet.update). This is an immutable data + structure. + */ + class RangeSet { + constructor( + /** + @internal + */ + chunkPos, + /** + @internal + */ + chunk, + /** + @internal + */ + nextLayer, + /** + @internal + */ + maxPoint) { + this.chunkPos = chunkPos; + this.chunk = chunk; + this.nextLayer = nextLayer; + this.maxPoint = maxPoint; + } + /** + @internal + */ + static create(chunkPos, chunk, nextLayer, maxPoint) { + return new RangeSet(chunkPos, chunk, nextLayer, maxPoint); + } + /** + @internal + */ + get length() { + let last = this.chunk.length - 1; + return last < 0 ? 0 : Math.max(this.chunkEnd(last), this.nextLayer.length); + } + /** + The number of ranges in the set. + */ + get size() { + if (this.isEmpty) + return 0; + let size = this.nextLayer.size; + for (let chunk of this.chunk) + size += chunk.value.length; + return size; + } + /** + @internal + */ + chunkEnd(index) { + return this.chunkPos[index] + this.chunk[index].length; + } + /** + Update the range set, optionally adding new ranges or filtering + out existing ones. + + (Note: The type parameter is just there as a kludge to work + around TypeScript variance issues that prevented `RangeSet<X>` + from being a subtype of `RangeSet<Y>` when `X` is a subtype of + `Y`.) + */ + update(updateSpec) { + let { add = [], sort = false, filterFrom = 0, filterTo = this.length } = updateSpec; + let filter = updateSpec.filter; + if (add.length == 0 && !filter) + return this; + if (sort) + add = add.slice().sort(cmpRange); + if (this.isEmpty) + return add.length ? RangeSet.of(add) : this; + let cur = new LayerCursor(this, null, -1).goto(0), i = 0, spill = []; + let builder = new RangeSetBuilder(); + while (cur.value || i < add.length) { + if (i < add.length && (cur.from - add[i].from || cur.startSide - add[i].value.startSide) >= 0) { + let range = add[i++]; + if (!builder.addInner(range.from, range.to, range.value)) + spill.push(range); + } + else if (cur.rangeIndex == 1 && cur.chunkIndex < this.chunk.length && + (i == add.length || this.chunkEnd(cur.chunkIndex) < add[i].from) && + (!filter || filterFrom > this.chunkEnd(cur.chunkIndex) || filterTo < this.chunkPos[cur.chunkIndex]) && + builder.addChunk(this.chunkPos[cur.chunkIndex], this.chunk[cur.chunkIndex])) { + cur.nextChunk(); + } + else { + if (!filter || filterFrom > cur.to || filterTo < cur.from || filter(cur.from, cur.to, cur.value)) { + if (!builder.addInner(cur.from, cur.to, cur.value)) + spill.push(Range$1.create(cur.from, cur.to, cur.value)); + } + cur.next(); + } + } + return builder.finishInner(this.nextLayer.isEmpty && !spill.length ? RangeSet.empty + : this.nextLayer.update({ add: spill, filter, filterFrom, filterTo })); + } + /** + Map this range set through a set of changes, return the new set. + */ + map(changes) { + if (changes.empty || this.isEmpty) + return this; + let chunks = [], chunkPos = [], maxPoint = -1; + for (let i = 0; i < this.chunk.length; i++) { + let start = this.chunkPos[i], chunk = this.chunk[i]; + let touch = changes.touchesRange(start, start + chunk.length); + if (touch === false) { + maxPoint = Math.max(maxPoint, chunk.maxPoint); + chunks.push(chunk); + chunkPos.push(changes.mapPos(start)); + } + else if (touch === true) { + let { mapped, pos } = chunk.map(start, changes); + if (mapped) { + maxPoint = Math.max(maxPoint, mapped.maxPoint); + chunks.push(mapped); + chunkPos.push(pos); + } + } + } + let next = this.nextLayer.map(changes); + return chunks.length == 0 ? next : new RangeSet(chunkPos, chunks, next || RangeSet.empty, maxPoint); + } + /** + Iterate over the ranges that touch the region `from` to `to`, + calling `f` for each. There is no guarantee that the ranges will + be reported in any specific order. When the callback returns + `false`, iteration stops. + */ + between(from, to, f) { + if (this.isEmpty) + return; + for (let i = 0; i < this.chunk.length; i++) { + let start = this.chunkPos[i], chunk = this.chunk[i]; + if (to >= start && from <= start + chunk.length && + chunk.between(start, from - start, to - start, f) === false) + return; + } + this.nextLayer.between(from, to, f); + } + /** + Iterate over the ranges in this set, in order, including all + ranges that end at or after `from`. + */ + iter(from = 0) { + return HeapCursor.from([this]).goto(from); + } + /** + @internal + */ + get isEmpty() { return this.nextLayer == this; } + /** + Iterate over the ranges in a collection of sets, in order, + starting from `from`. + */ + static iter(sets, from = 0) { + return HeapCursor.from(sets).goto(from); + } + /** + Iterate over two groups of sets, calling methods on `comparator` + to notify it of possible differences. + */ + static compare(oldSets, newSets, + /** + This indicates how the underlying data changed between these + ranges, and is needed to synchronize the iteration. `from` and + `to` are coordinates in the _new_ space, after these changes. + */ + textDiff, comparator, + /** + Can be used to ignore all non-point ranges, and points below + the given size. When -1, all ranges are compared. + */ + minPointSize = -1) { + let a = oldSets.filter(set => set.maxPoint > 0 || !set.isEmpty && set.maxPoint >= minPointSize); + let b = newSets.filter(set => set.maxPoint > 0 || !set.isEmpty && set.maxPoint >= minPointSize); + let sharedChunks = findSharedChunks(a, b, textDiff); + let sideA = new SpanCursor(a, sharedChunks, minPointSize); + let sideB = new SpanCursor(b, sharedChunks, minPointSize); + textDiff.iterGaps((fromA, fromB, length) => compare(sideA, fromA, sideB, fromB, length, comparator)); + if (textDiff.empty && textDiff.length == 0) + compare(sideA, 0, sideB, 0, 0, comparator); + } + /** + Compare the contents of two groups of range sets, returning true + if they are equivalent in the given range. + */ + static eq(oldSets, newSets, from = 0, to) { + if (to == null) + to = 1000000000 /* C.Far */; + let a = oldSets.filter(set => !set.isEmpty && newSets.indexOf(set) < 0); + let b = newSets.filter(set => !set.isEmpty && oldSets.indexOf(set) < 0); + if (a.length != b.length) + return false; + if (!a.length) + return true; + let sharedChunks = findSharedChunks(a, b); + let sideA = new SpanCursor(a, sharedChunks, 0).goto(from), sideB = new SpanCursor(b, sharedChunks, 0).goto(from); + for (;;) { + if (sideA.to != sideB.to || + !sameValues(sideA.active, sideB.active) || + sideA.point && (!sideB.point || !sideA.point.eq(sideB.point))) + return false; + if (sideA.to > to) + return true; + sideA.next(); + sideB.next(); + } + } + /** + Iterate over a group of range sets at the same time, notifying + the iterator about the ranges covering every given piece of + content. Returns the open count (see + [`SpanIterator.span`](https://codemirror.net/6/docs/ref/#state.SpanIterator.span)) at the end + of the iteration. + */ + static spans(sets, from, to, iterator, + /** + When given and greater than -1, only points of at least this + size are taken into account. + */ + minPointSize = -1) { + let cursor = new SpanCursor(sets, null, minPointSize).goto(from), pos = from; + let open = cursor.openStart; + for (;;) { + let curTo = Math.min(cursor.to, to); + if (cursor.point) { + iterator.point(pos, curTo, cursor.point, cursor.activeForPoint(cursor.to), open, cursor.pointRank); + open = cursor.openEnd(curTo) + (cursor.to > curTo ? 1 : 0); + } + else if (curTo > pos) { + iterator.span(pos, curTo, cursor.active, open); + open = cursor.openEnd(curTo); + } + if (cursor.to > to) + break; + pos = cursor.to; + cursor.next(); + } + return open; + } + /** + Create a range set for the given range or array of ranges. By + default, this expects the ranges to be _sorted_ (by start + position and, if two start at the same position, + `value.startSide`). You can pass `true` as second argument to + cause the method to sort them. + */ + static of(ranges, sort = false) { + let build = new RangeSetBuilder(); + for (let range of ranges instanceof Range$1 ? [ranges] : sort ? lazySort(ranges) : ranges) + build.add(range.from, range.to, range.value); + return build.finish(); + } + } + /** + The empty set of ranges. + */ + RangeSet.empty = /*@__PURE__*/new RangeSet([], [], null, -1); + function lazySort(ranges) { + if (ranges.length > 1) + for (let prev = ranges[0], i = 1; i < ranges.length; i++) { + let cur = ranges[i]; + if (cmpRange(prev, cur) > 0) + return ranges.slice().sort(cmpRange); + prev = cur; + } + return ranges; + } + RangeSet.empty.nextLayer = RangeSet.empty; + /** + A range set builder is a data structure that helps build up a + [range set](https://codemirror.net/6/docs/ref/#state.RangeSet) directly, without first allocating + an array of [`Range`](https://codemirror.net/6/docs/ref/#state.Range) objects. + */ + class RangeSetBuilder { + /** + Create an empty builder. + */ + constructor() { + this.chunks = []; + this.chunkPos = []; + this.chunkStart = -1; + this.last = null; + this.lastFrom = -1000000000 /* C.Far */; + this.lastTo = -1000000000 /* C.Far */; + this.from = []; + this.to = []; + this.value = []; + this.maxPoint = -1; + this.setMaxPoint = -1; + this.nextLayer = null; + } + finishChunk(newArrays) { + this.chunks.push(new Chunk(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; + if (newArrays) { + this.from = []; + this.to = []; + this.value = []; + } + } + /** + Add a range. Ranges should be added in sorted (by `from` and + `value.startSide`) order. + */ + add(from, to, value) { + if (!this.addInner(from, to, value)) + (this.nextLayer || (this.nextLayer = new RangeSetBuilder)).add(from, to, value); + } + /** + @internal + */ + addInner(from, to, value) { + let diff = from - this.lastTo || value.startSide - this.last.endSide; + if (diff <= 0 && (from - this.lastFrom || value.startSide - this.last.startSide) < 0) + throw new Error("Ranges must be added sorted by `from` position and `startSide`"); + if (diff < 0) + return false; + if (this.from.length == 250 /* C.ChunkSize */) + this.finishChunk(true); + if (this.chunkStart < 0) + this.chunkStart = from; + this.from.push(from - this.chunkStart); + this.to.push(to - this.chunkStart); + this.last = value; + this.lastFrom = from; + this.lastTo = to; + this.value.push(value); + if (value.point) + this.maxPoint = Math.max(this.maxPoint, to - from); + return true; + } + /** + @internal + */ + addChunk(from, chunk) { + if ((from - this.lastTo || chunk.value[0].startSide - this.last.endSide) < 0) + return false; + if (this.from.length) + this.finishChunk(true); + this.setMaxPoint = Math.max(this.setMaxPoint, chunk.maxPoint); + this.chunks.push(chunk); + this.chunkPos.push(from); + let last = chunk.value.length - 1; + this.last = chunk.value[last]; + this.lastFrom = chunk.from[last] + from; + this.lastTo = chunk.to[last] + from; + return true; + } + /** + Finish the range set. Returns the new set. The builder can't be + used anymore after this has been called. + */ + finish() { return this.finishInner(RangeSet.empty); } + /** + @internal + */ + finishInner(next) { + if (this.from.length) + this.finishChunk(false); + if (this.chunks.length == 0) + return next; + let result = RangeSet.create(this.chunkPos, this.chunks, this.nextLayer ? this.nextLayer.finishInner(next) : next, this.setMaxPoint); + this.from = null; // Make sure further `add` calls produce errors + return result; + } + } + function findSharedChunks(a, b, textDiff) { + let inA = new Map(); + for (let set of a) + for (let i = 0; i < set.chunk.length; i++) + if (set.chunk[i].maxPoint <= 0) + inA.set(set.chunk[i], set.chunkPos[i]); + let shared = new Set(); + for (let set of b) + for (let i = 0; i < set.chunk.length; i++) { + let known = inA.get(set.chunk[i]); + if (known != null && (textDiff ? textDiff.mapPos(known) : known) == set.chunkPos[i] && + !(textDiff === null || textDiff === void 0 ? void 0 : textDiff.touchesRange(known, known + set.chunk[i].length))) + shared.add(set.chunk[i]); + } + return shared; + } + class LayerCursor { + constructor(layer, skip, minPoint, rank = 0) { + this.layer = layer; + this.skip = skip; + this.minPoint = minPoint; + this.rank = rank; + } + get startSide() { return this.value ? this.value.startSide : 0; } + get endSide() { return this.value ? this.value.endSide : 0; } + goto(pos, side = -1000000000 /* C.Far */) { + this.chunkIndex = this.rangeIndex = 0; + this.gotoInner(pos, side, false); + return this; + } + gotoInner(pos, side, forward) { + while (this.chunkIndex < this.layer.chunk.length) { + let next = this.layer.chunk[this.chunkIndex]; + if (!(this.skip && this.skip.has(next) || + this.layer.chunkEnd(this.chunkIndex) < pos || + next.maxPoint < this.minPoint)) + break; + this.chunkIndex++; + forward = false; + } + if (this.chunkIndex < this.layer.chunk.length) { + let rangeIndex = this.layer.chunk[this.chunkIndex].findIndex(pos - this.layer.chunkPos[this.chunkIndex], side, true); + if (!forward || this.rangeIndex < rangeIndex) + this.setRangeIndex(rangeIndex); + } + this.next(); + } + forward(pos, side) { + if ((this.to - pos || this.endSide - side) < 0) + this.gotoInner(pos, side, true); + } + next() { + for (;;) { + if (this.chunkIndex == this.layer.chunk.length) { + this.from = this.to = 1000000000 /* C.Far */; + this.value = null; + break; + } + else { + let chunkPos = this.layer.chunkPos[this.chunkIndex], chunk = this.layer.chunk[this.chunkIndex]; + let from = chunkPos + chunk.from[this.rangeIndex]; + this.from = from; + this.to = chunkPos + chunk.to[this.rangeIndex]; + this.value = chunk.value[this.rangeIndex]; + this.setRangeIndex(this.rangeIndex + 1); + if (this.minPoint < 0 || this.value.point && this.to - this.from >= this.minPoint) + break; + } + } + } + setRangeIndex(index) { + if (index == this.layer.chunk[this.chunkIndex].value.length) { + this.chunkIndex++; + if (this.skip) { + while (this.chunkIndex < this.layer.chunk.length && this.skip.has(this.layer.chunk[this.chunkIndex])) + this.chunkIndex++; + } + this.rangeIndex = 0; + } + else { + this.rangeIndex = index; + } + } + nextChunk() { + this.chunkIndex++; + this.rangeIndex = 0; + this.next(); + } + compare(other) { + return this.from - other.from || this.startSide - other.startSide || this.rank - other.rank || + this.to - other.to || this.endSide - other.endSide; + } + } + class HeapCursor { + constructor(heap) { + this.heap = heap; + } + static from(sets, skip = null, minPoint = -1) { + let heap = []; + for (let i = 0; i < sets.length; i++) { + for (let cur = sets[i]; !cur.isEmpty; cur = cur.nextLayer) { + if (cur.maxPoint >= minPoint) + heap.push(new LayerCursor(cur, skip, minPoint, i)); + } + } + return heap.length == 1 ? heap[0] : new HeapCursor(heap); + } + get startSide() { return this.value ? this.value.startSide : 0; } + goto(pos, side = -1000000000 /* C.Far */) { + for (let cur of this.heap) + cur.goto(pos, side); + for (let i = this.heap.length >> 1; i >= 0; i--) + heapBubble(this.heap, i); + this.next(); + return this; + } + forward(pos, side) { + for (let cur of this.heap) + cur.forward(pos, side); + for (let i = this.heap.length >> 1; i >= 0; i--) + heapBubble(this.heap, i); + if ((this.to - pos || this.value.endSide - side) < 0) + this.next(); + } + next() { + if (this.heap.length == 0) { + this.from = this.to = 1000000000 /* C.Far */; + this.value = null; + this.rank = -1; + } + else { + let top = this.heap[0]; + this.from = top.from; + this.to = top.to; + this.value = top.value; + this.rank = top.rank; + if (top.value) + top.next(); + heapBubble(this.heap, 0); + } + } + } + function heapBubble(heap, index) { + for (let cur = heap[index];;) { + let childIndex = (index << 1) + 1; + if (childIndex >= heap.length) + break; + let child = heap[childIndex]; + if (childIndex + 1 < heap.length && child.compare(heap[childIndex + 1]) >= 0) { + child = heap[childIndex + 1]; + childIndex++; + } + if (cur.compare(child) < 0) + break; + heap[childIndex] = cur; + heap[index] = child; + index = childIndex; + } + } + class SpanCursor { + constructor(sets, skip, minPoint) { + this.minPoint = minPoint; + this.active = []; + this.activeTo = []; + this.activeRank = []; + this.minActive = -1; + // A currently active point range, if any + this.point = null; + this.pointFrom = 0; + this.pointRank = 0; + this.to = -1000000000 /* C.Far */; + this.endSide = 0; + this.openStart = -1; + this.cursor = HeapCursor.from(sets, skip, minPoint); + } + goto(pos, side = -1000000000 /* C.Far */) { + this.cursor.goto(pos, side); + this.active.length = this.activeTo.length = this.activeRank.length = 0; + this.minActive = -1; + this.to = pos; + this.endSide = side; + this.openStart = -1; + this.next(); + return this; + } + forward(pos, side) { + while (this.minActive > -1 && (this.activeTo[this.minActive] - pos || this.active[this.minActive].endSide - side) < 0) + this.removeActive(this.minActive); + this.cursor.forward(pos, side); + } + removeActive(index) { + remove(this.active, index); + remove(this.activeTo, index); + remove(this.activeRank, index); + this.minActive = findMinIndex(this.active, this.activeTo); + } + addActive(trackOpen) { + let i = 0, { value, to, rank } = this.cursor; + while (i < this.activeRank.length && this.activeRank[i] <= rank) + i++; + insert(this.active, i, value); + insert(this.activeTo, i, to); + insert(this.activeRank, i, rank); + if (trackOpen) + insert(trackOpen, i, this.cursor.from); + this.minActive = findMinIndex(this.active, this.activeTo); + } + // After calling this, if `this.point` != null, the next range is a + // point. Otherwise, it's a regular range, covered by `this.active`. + next() { + let from = this.to, wasPoint = this.point; + this.point = null; + let trackOpen = this.openStart < 0 ? [] : null, trackExtra = 0; + for (;;) { + let a = this.minActive; + if (a > -1 && (this.activeTo[a] - this.cursor.from || this.active[a].endSide - this.cursor.startSide) < 0) { + if (this.activeTo[a] > from) { + this.to = this.activeTo[a]; + this.endSide = this.active[a].endSide; + break; + } + this.removeActive(a); + if (trackOpen) + remove(trackOpen, a); + } + else if (!this.cursor.value) { + this.to = this.endSide = 1000000000 /* C.Far */; + break; + } + else if (this.cursor.from > from) { + this.to = this.cursor.from; + this.endSide = this.cursor.startSide; + break; + } + else { + let nextVal = this.cursor.value; + if (!nextVal.point) { // Opening a range + this.addActive(trackOpen); + if (this.cursor.from < from && this.cursor.to > from) + trackExtra++; + this.cursor.next(); + } + else if (wasPoint && this.cursor.to == this.to && this.cursor.from < this.cursor.to) { + // Ignore any non-empty points that end precisely at the end of the prev point + this.cursor.next(); + } + else { // New point + this.point = nextVal; + this.pointFrom = this.cursor.from; + this.pointRank = this.cursor.rank; + this.to = this.cursor.to; + this.endSide = nextVal.endSide; + if (this.cursor.from < from) + trackExtra = 1; + this.cursor.next(); + this.forward(this.to, this.endSide); + break; + } + } + } + if (trackOpen) { + let openStart = 0; + while (openStart < trackOpen.length && trackOpen[openStart] < from) + openStart++; + this.openStart = openStart + trackExtra; + } + } + activeForPoint(to) { + if (!this.active.length) + return this.active; + let active = []; + for (let i = this.active.length - 1; i >= 0; i--) { + if (this.activeRank[i] < this.pointRank) + break; + if (this.activeTo[i] > to || this.activeTo[i] == to && this.active[i].endSide >= this.point.endSide) + active.push(this.active[i]); + } + return active.reverse(); + } + openEnd(to) { + let open = 0; + for (let i = this.activeTo.length - 1; i >= 0 && this.activeTo[i] > to; i--) + open++; + return open; + } + } + function compare(a, startA, b, startB, length, comparator) { + a.goto(startA); + b.goto(startB); + let endB = startB + length; + let pos = startB, dPos = startB - startA; + for (;;) { + let diff = (a.to + dPos) - b.to || a.endSide - b.endSide; + let end = diff < 0 ? a.to + dPos : b.to, clipEnd = Math.min(end, endB); + if (a.point || b.point) { + if (!(a.point && b.point && (a.point == b.point || a.point.eq(b.point)) && + sameValues(a.activeForPoint(a.to + dPos), b.activeForPoint(b.to)))) + comparator.comparePoint(pos, clipEnd, a.point, b.point); + } + else { + if (clipEnd > pos && !sameValues(a.active, b.active)) + comparator.compareRange(pos, clipEnd, a.active, b.active); + } + if (end > endB) + break; + pos = end; + if (diff <= 0) + a.next(); + if (diff >= 0) + b.next(); + } + } + function sameValues(a, b) { + if (a.length != b.length) + return false; + for (let i = 0; i < a.length; i++) + if (a[i] != b[i] && !a[i].eq(b[i])) + return false; + return true; + } + function remove(array, index) { + for (let i = index, e = array.length - 1; i < e; i++) + array[i] = array[i + 1]; + array.pop(); + } + function insert(array, index, value) { + for (let i = array.length - 1; i >= index; i--) + array[i + 1] = array[i]; + array[index] = value; + } + function findMinIndex(value, array) { + let found = -1, foundPos = 1000000000 /* C.Far */; + for (let i = 0; i < array.length; i++) + if ((array[i] - foundPos || value[i].endSide - value[found].endSide) < 0) { + found = i; + foundPos = array[i]; + } + return found; + } + + /** + Count the column position at the given offset into the string, + taking extending characters and tab size into account. + */ + function countColumn(string, tabSize, to = string.length) { + let n = 0; + for (let i = 0; i < to;) { + if (string.charCodeAt(i) == 9) { + n += tabSize - (n % tabSize); + i++; + } + else { + n++; + i = findClusterBreak(string, i); + } + } + return n; + } + /** + Find the offset that corresponds to the given column position in a + string, taking extending characters and tab size into account. By + default, the string length is returned when it is too short to + reach the column. Pass `strict` true to make it return -1 in that + situation. + */ + function findColumn(string, col, tabSize, strict) { + for (let i = 0, n = 0;;) { + if (n >= col) + return i; + if (i == string.length) + break; + n += string.charCodeAt(i) == 9 ? tabSize - (n % tabSize) : 1; + i = findClusterBreak(string, i); + } + return strict === true ? -1 : string.length; + } + + const C = "\u037c"; + const COUNT = typeof Symbol == "undefined" ? "__" + C : Symbol.for(C); + const SET = typeof Symbol == "undefined" ? "__styleSet" + Math.floor(Math.random() * 1e8) : Symbol("styleSet"); + const top = typeof globalThis != "undefined" ? globalThis : typeof window != "undefined" ? window : {}; + + // :: - Style modules encapsulate a set of CSS rules defined from + // JavaScript. Their definitions are only available in a given DOM + // root after it has been _mounted_ there with `StyleModule.mount`. + // + // Style modules should be created once and stored somewhere, as + // opposed to re-creating them every time you need them. The amount of + // CSS rules generated for a given DOM root is bounded by the amount + // of style modules that were used. So to avoid leaking rules, don't + // create these dynamically, but treat them as one-time allocations. + class StyleModule { + // :: (Object<Style>, ?{finish: ?(string) → string}) + // Create a style module from the given spec. + // + // When `finish` is given, it is called on regular (non-`@`) + // selectors (after `&` expansion) to compute the final selector. + constructor(spec, options) { + this.rules = []; + let {finish} = options || {}; + + function splitSelector(selector) { + return /^@/.test(selector) ? [selector] : selector.split(/,\s*/) + } + + function render(selectors, spec, target, isKeyframes) { + let local = [], isAt = /^@(\w+)\b/.exec(selectors[0]), keyframes = isAt && isAt[1] == "keyframes"; + if (isAt && spec == null) return target.push(selectors[0] + ";") + for (let prop in spec) { + let value = spec[prop]; + if (/&/.test(prop)) { + render(prop.split(/,\s*/).map(part => selectors.map(sel => part.replace(/&/, sel))).reduce((a, b) => a.concat(b)), + value, target); + } else if (value && typeof value == "object") { + if (!isAt) throw new RangeError("The value of a property (" + prop + ") should be a primitive value.") + render(splitSelector(prop), value, local, keyframes); + } else if (value != null) { + local.push(prop.replace(/_.*/, "").replace(/[A-Z]/g, l => "-" + l.toLowerCase()) + ": " + value + ";"); } } - - if (!type) { - throwError(state, 'unknown tag !<' + state.tag + '>'); - } - - if (state.result !== null && type.kind !== state.kind) { - throwError(state, 'unacceptable node kind for !<' + state.tag + '> tag; it should be "' + type.kind + '", not "' + state.kind + '"'); - } - - if (!type.resolve(state.result, state.tag)) { // `state.result` updated in resolver if matched - throwError(state, 'cannot resolve a node with !<' + state.tag + '> explicit tag'); - } else { - state.result = type.construct(state.result, state.tag); - if (state.anchor !== null) { - state.anchorMap[state.anchor] = state.result; - } + if (local.length || keyframes) { + target.push((finish && !isAt && !isKeyframes ? selectors.map(finish) : selectors).join(", ") + + " {" + local.join(" ") + "}"); } } - if (state.listener !== null) { - state.listener('close', state); - } - return state.tag !== null || state.anchor !== null || hasContent; + for (let prop in spec) render(splitSelector(prop), spec[prop], this.rules); } - function readDocument(state) { - var documentStart = state.position, - _position, - directiveName, - directiveArgs, - hasDirectives = false, - ch; + // :: () → string + // Returns a string containing the module's CSS rules. + getRules() { return this.rules.join("\n") } - state.version = null; - state.checkLineBreaks = state.legacy; - state.tagMap = Object.create(null); - state.anchorMap = Object.create(null); + // :: () → string + // Generate a new unique CSS class name. + static newName() { + let id = top[COUNT] || 1; + top[COUNT] = id + 1; + return C + id.toString(36) + } - while ((ch = state.input.charCodeAt(state.position)) !== 0) { - skipSeparationSpace(state, true, -1); + // :: (union<Document, ShadowRoot>, union<[StyleModule], StyleModule>) + // + // Mount the given set of modules in the given DOM root, which ensures + // that the CSS rules defined by the module are available in that + // context. + // + // Rules are only added to the document once per root. + // + // Rule order will follow the order of the modules, so that rules from + // modules later in the array take precedence of those from earlier + // modules. If you call this function multiple times for the same root + // in a way that changes the order of already mounted modules, the old + // order will be changed. + static mount(root, modules) { + (root[SET] || new StyleSet(root)).mount(Array.isArray(modules) ? modules : [modules]); + } + } - ch = state.input.charCodeAt(state.position); + let adoptedSet = null; - if (state.lineIndent > 0 || ch !== 0x25/* % */) { - break; + class StyleSet { + constructor(root) { + if (!root.head && root.adoptedStyleSheets && typeof CSSStyleSheet != "undefined") { + if (adoptedSet) { + root.adoptedStyleSheets = [adoptedSet.sheet].concat(root.adoptedStyleSheets); + return root[SET] = adoptedSet } - - hasDirectives = true; - ch = state.input.charCodeAt(++state.position); - _position = state.position; - - while (ch !== 0 && !is_WS_OR_EOL(ch)) { - ch = state.input.charCodeAt(++state.position); - } - - directiveName = state.input.slice(_position, state.position); - directiveArgs = []; - - if (directiveName.length < 1) { - throwError(state, 'directive name must not be less than one character in length'); - } - - while (ch !== 0) { - while (is_WHITE_SPACE(ch)) { - ch = state.input.charCodeAt(++state.position); - } - - if (ch === 0x23/* # */) { - do { ch = state.input.charCodeAt(++state.position); } - while (ch !== 0 && !is_EOL(ch)); - break; - } - - if (is_EOL(ch)) break; - - _position = state.position; - - while (ch !== 0 && !is_WS_OR_EOL(ch)) { - ch = state.input.charCodeAt(++state.position); - } - - directiveArgs.push(state.input.slice(_position, state.position)); - } - - if (ch !== 0) readLineBreak(state); - - if (_hasOwnProperty$1.call(directiveHandlers, directiveName)) { - directiveHandlers[directiveName](state, directiveName, directiveArgs); - } else { - throwWarning(state, 'unknown document directive "' + directiveName + '"'); - } - } - - skipSeparationSpace(state, true, -1); - - if (state.lineIndent === 0 && - state.input.charCodeAt(state.position) === 0x2D/* - */ && - state.input.charCodeAt(state.position + 1) === 0x2D/* - */ && - state.input.charCodeAt(state.position + 2) === 0x2D/* - */) { - state.position += 3; - skipSeparationSpace(state, true, -1); - - } else if (hasDirectives) { - throwError(state, 'directives end mark is expected'); - } - - composeNode(state, state.lineIndent - 1, CONTEXT_BLOCK_OUT, false, true); - skipSeparationSpace(state, true, -1); - - if (state.checkLineBreaks && - PATTERN_NON_ASCII_LINE_BREAKS.test(state.input.slice(documentStart, state.position))) { - throwWarning(state, 'non-ASCII line breaks are interpreted as content'); - } - - state.documents.push(state.result); - - if (state.position === state.lineStart && testDocumentSeparator(state)) { - - if (state.input.charCodeAt(state.position) === 0x2E/* . */) { - state.position += 3; - skipSeparationSpace(state, true, -1); - } - return; - } - - if (state.position < (state.length - 1)) { - throwError(state, 'end of the stream or a document separator is expected'); + this.sheet = new CSSStyleSheet; + root.adoptedStyleSheets = [this.sheet].concat(root.adoptedStyleSheets); + adoptedSet = this; } else { - return; + this.styleTag = (root.ownerDocument || root).createElement("style"); + let target = root.head || root; + target.insertBefore(this.styleTag, target.firstChild); } + this.modules = []; + root[SET] = this; } - - function loadDocuments(input, options) { - input = String(input); - options = options || {}; - - if (input.length !== 0) { - - // Add tailing `\n` if not exists - if (input.charCodeAt(input.length - 1) !== 0x0A/* LF */ && - input.charCodeAt(input.length - 1) !== 0x0D/* CR */) { - input += '\n'; + mount(modules) { + let sheet = this.sheet; + let pos = 0 /* Current rule offset */, j = 0; /* Index into this.modules */ + for (let i = 0; i < modules.length; i++) { + let mod = modules[i], index = this.modules.indexOf(mod); + if (index < j && index > -1) { // Ordering conflict + this.modules.splice(index, 1); + j--; + index = -1; } - - // Strip BOM - if (input.charCodeAt(0) === 0xFEFF) { - input = input.slice(1); + if (index == -1) { + this.modules.splice(j++, 0, mod); + if (sheet) for (let k = 0; k < mod.rules.length; k++) + sheet.insertRule(mod.rules[k], pos++); + } else { + while (j < index) pos += this.modules[j++].rules.length; + pos += mod.rules.length; + j++; } } - var state = new State$1(input, options); - - var nullpos = input.indexOf('\0'); - - if (nullpos !== -1) { - state.position = nullpos; - throwError(state, 'null byte is not allowed in input'); - } - - // Use 0 as string terminator. That significantly simplifies bounds check. - state.input += '\0'; - - while (state.input.charCodeAt(state.position) === 0x20/* Space */) { - state.lineIndent += 1; - state.position += 1; - } - - while (state.position < (state.length - 1)) { - readDocument(state); - } - - return state.documents; - } - - - function loadAll$1(input, iterator, options) { - if (iterator !== null && typeof iterator === 'object' && typeof options === 'undefined') { - options = iterator; - iterator = null; - } - - var documents = loadDocuments(input, options); - - if (typeof iterator !== 'function') { - return documents; - } - - for (var index = 0, length = documents.length; index < length; index += 1) { - iterator(documents[index]); + if (!sheet) { + let text = ""; + for (let i = 0; i < this.modules.length; i++) + text += this.modules[i].getRules() + "\n"; + this.styleTag.textContent = text; } } + } + // Style::Object<union<Style,string>> + // + // A style is an object that, in the simple case, maps CSS property + // names to strings holding their values, as in `{color: "red", + // fontWeight: "bold"}`. The property names can be given in + // camel-case—the library will insert a dash before capital letters + // when converting them to CSS. + // + // If you include an underscore in a property name, it and everything + // after it will be removed from the output, which can be useful when + // providing a property multiple times, for browser compatibility + // reasons. + // + // A property in a style object can also be a sub-selector, which + // extends the current context to add a pseudo-selector or a child + // selector. Such a property should contain a `&` character, which + // will be replaced by the current selector. For example `{"&:before": + // {content: '"hi"'}}`. Sub-selectors and regular properties can + // freely be mixed in a given object. Any property containing a `&` is + // assumed to be a sub-selector. + // + // Finally, a property can specify an @-block to be wrapped around the + // styles defined inside the object that's the property's value. For + // example to create a media query you can do `{"@media screen and + // (min-width: 400px)": {...}}`. - function load$1(input, options) { - var documents = loadDocuments(input, options); + var base = { + 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: "'" + }; - if (documents.length === 0) { - /*eslint-disable no-undefined*/ - return undefined; - } else if (documents.length === 1) { - return documents[0]; + var shift = { + 48: ")", + 49: "!", + 50: "@", + 51: "#", + 52: "$", + 53: "%", + 54: "^", + 55: "&", + 56: "*", + 57: "(", + 59: ":", + 61: "+", + 173: "_", + 186: ":", + 187: "+", + 188: "<", + 189: "_", + 190: ">", + 191: "?", + 192: "~", + 219: "{", + 220: "|", + 221: "}", + 222: "\"" + }; + + var chrome$1 = typeof navigator != "undefined" && /Chrome\/(\d+)/.exec(navigator.userAgent); + typeof navigator != "undefined" && /Gecko\/\d+/.test(navigator.userAgent); + var mac = typeof navigator != "undefined" && /Mac/.test(navigator.platform); + var ie$1 = typeof navigator != "undefined" && /MSIE \d|Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(navigator.userAgent); + var brokenModifierNames = mac || chrome$1 && +chrome$1[1] < 57; + + // Fill in the digit keys + for (var i = 0; i < 10; i++) base[48 + i] = base[96 + i] = String(i); + + // The function keys + for (var i = 1; i <= 24; i++) base[i + 111] = "F" + i; + + // And the alphabetic keys + for (var i = 65; i <= 90; i++) { + base[i] = String.fromCharCode(i + 32); + shift[i] = String.fromCharCode(i); + } + + // For each code that doesn't have a shift-equivalent, copy the base name + for (var code in base) if (!shift.hasOwnProperty(code)) shift[code] = base[code]; + + function keyName(event) { + var ignoreKey = brokenModifierNames && (event.ctrlKey || event.altKey || event.metaKey) || + ie$1 && event.shiftKey && event.key && event.key.length == 1 || + event.key == "Unidentified"; + var name = (!ignoreKey && event.key) || + (event.shiftKey ? shift : base)[event.keyCode] || + event.key || "Unidentified"; + // Edge sometimes produces wrong names (Issue #3) + if (name == "Esc") name = "Escape"; + if (name == "Del") name = "Delete"; + // https://developer.microsoft.com/en-us/microsoft-edge/platform/issues/8860571/ + if (name == "Left") name = "ArrowLeft"; + if (name == "Up") name = "ArrowUp"; + if (name == "Right") name = "ArrowRight"; + if (name == "Down") name = "ArrowDown"; + return name + } + + function getSelection(root) { + let target; + // Browsers differ on whether shadow roots have a getSelection + // method. If it exists, use that, otherwise, call it on the + // document. + if (root.nodeType == 11) { // Shadow root + target = root.getSelection ? root : root.ownerDocument; } - throw new exception('expected a single document in the stream, but found more'); + else { + target = root; + } + return target.getSelection(); + } + function contains(dom, node) { + return node ? dom == node || dom.contains(node.nodeType != 1 ? node.parentNode : node) : false; + } + function deepActiveElement(doc) { + let elt = doc.activeElement; + while (elt && elt.shadowRoot) + elt = elt.shadowRoot.activeElement; + return elt; + } + function hasSelection(dom, selection) { + if (!selection.anchorNode) + return false; + try { + // Firefox will raise 'permission denied' errors when accessing + // properties of `sel.anchorNode` when it's in a generated CSS + // element. + return contains(dom, selection.anchorNode); + } + catch (_) { + return false; + } + } + function clientRectsFor(dom) { + if (dom.nodeType == 3) + return textRange(dom, 0, dom.nodeValue.length).getClientRects(); + else if (dom.nodeType == 1) + return dom.getClientRects(); + else + return []; + } + // Scans forward and backward through DOM positions equivalent to the + // given one to see if the two are in the same place (i.e. after a + // text node vs at the end of that text node) + function isEquivalentPosition(node, off, targetNode, targetOff) { + return targetNode ? (scanFor(node, off, targetNode, targetOff, -1) || + scanFor(node, off, targetNode, targetOff, 1)) : false; + } + function domIndex(node) { + for (var index = 0;; index++) { + node = node.previousSibling; + if (!node) + return index; + } + } + function scanFor(node, off, targetNode, targetOff, dir) { + for (;;) { + if (node == targetNode && off == targetOff) + return true; + if (off == (dir < 0 ? 0 : maxOffset(node))) { + if (node.nodeName == "DIV") + return false; + let parent = node.parentNode; + if (!parent || parent.nodeType != 1) + return false; + off = domIndex(node) + (dir < 0 ? 0 : 1); + node = parent; + } + else if (node.nodeType == 1) { + node = node.childNodes[off + (dir < 0 ? -1 : 0)]; + if (node.nodeType == 1 && node.contentEditable == "false") + return false; + off = dir < 0 ? maxOffset(node) : 0; + } + else { + return false; + } + } + } + function maxOffset(node) { + return node.nodeType == 3 ? node.nodeValue.length : node.childNodes.length; + } + const Rect0 = { left: 0, right: 0, top: 0, bottom: 0 }; + function flattenRect(rect, left) { + let x = left ? rect.left : rect.right; + return { left: x, right: x, top: rect.top, bottom: rect.bottom }; + } + function windowRect(win) { + return { left: 0, right: win.innerWidth, + top: 0, bottom: win.innerHeight }; + } + function scrollRectIntoView(dom, rect, side, x, y, xMargin, yMargin, ltr) { + let doc = dom.ownerDocument, win = doc.defaultView || window; + for (let cur = dom; cur;) { + if (cur.nodeType == 1) { // Element + let bounding, top = cur == doc.body; + if (top) { + bounding = windowRect(win); + } + else { + if (cur.scrollHeight <= cur.clientHeight && cur.scrollWidth <= cur.clientWidth) { + cur = cur.assignedSlot || cur.parentNode; + continue; + } + let rect = cur.getBoundingClientRect(); + // Make sure scrollbar width isn't included in the rectangle + bounding = { left: rect.left, right: rect.left + cur.clientWidth, + top: rect.top, bottom: rect.top + cur.clientHeight }; + } + let moveX = 0, moveY = 0; + if (y == "nearest") { + if (rect.top < bounding.top) { + moveY = -(bounding.top - rect.top + yMargin); + if (side > 0 && rect.bottom > bounding.bottom + moveY) + moveY = rect.bottom - bounding.bottom + moveY + yMargin; + } + else if (rect.bottom > bounding.bottom) { + moveY = rect.bottom - bounding.bottom + yMargin; + if (side < 0 && (rect.top - moveY) < bounding.top) + moveY = -(bounding.top + moveY - rect.top + yMargin); + } + } + else { + let rectHeight = rect.bottom - rect.top, boundingHeight = bounding.bottom - bounding.top; + let targetTop = y == "center" && rectHeight <= boundingHeight ? rect.top + rectHeight / 2 - boundingHeight / 2 : + y == "start" || y == "center" && side < 0 ? rect.top - yMargin : + rect.bottom - boundingHeight + yMargin; + moveY = targetTop - bounding.top; + } + if (x == "nearest") { + if (rect.left < bounding.left) { + moveX = -(bounding.left - rect.left + xMargin); + if (side > 0 && rect.right > bounding.right + moveX) + moveX = rect.right - bounding.right + moveX + xMargin; + } + else if (rect.right > bounding.right) { + moveX = rect.right - bounding.right + xMargin; + if (side < 0 && rect.left < bounding.left + moveX) + moveX = -(bounding.left + moveX - rect.left + xMargin); + } + } + else { + let targetLeft = x == "center" ? rect.left + (rect.right - rect.left) / 2 - (bounding.right - bounding.left) / 2 : + (x == "start") == ltr ? rect.left - xMargin : + rect.right - (bounding.right - bounding.left) + xMargin; + moveX = targetLeft - bounding.left; + } + if (moveX || moveY) { + if (top) { + win.scrollBy(moveX, moveY); + } + else { + let movedX = 0, movedY = 0; + if (moveY) { + let start = cur.scrollTop; + cur.scrollTop += moveY; + movedY = cur.scrollTop - start; + } + if (moveX) { + let start = cur.scrollLeft; + cur.scrollLeft += moveX; + movedX = cur.scrollLeft - start; + } + rect = { left: rect.left - movedX, top: rect.top - movedY, + right: rect.right - movedX, bottom: rect.bottom - movedY }; + if (movedX && Math.abs(movedX - moveX) < 1) + x = "nearest"; + if (movedY && Math.abs(movedY - moveY) < 1) + y = "nearest"; + } + } + if (top) + break; + cur = cur.assignedSlot || cur.parentNode; + } + else if (cur.nodeType == 11) { // A shadow root + cur = cur.host; + } + else { + break; + } + } + } + class DOMSelectionState { + constructor() { + this.anchorNode = null; + this.anchorOffset = 0; + this.focusNode = null; + this.focusOffset = 0; + } + eq(domSel) { + return this.anchorNode == domSel.anchorNode && this.anchorOffset == domSel.anchorOffset && + this.focusNode == domSel.focusNode && this.focusOffset == domSel.focusOffset; + } + setRange(range) { + this.set(range.anchorNode, range.anchorOffset, range.focusNode, range.focusOffset); + } + set(anchorNode, anchorOffset, focusNode, focusOffset) { + this.anchorNode = anchorNode; + this.anchorOffset = anchorOffset; + this.focusNode = focusNode; + this.focusOffset = focusOffset; + } + } + let preventScrollSupported = null; + // Feature-detects support for .focus({preventScroll: true}), and uses + // a fallback kludge when not supported. + function focusPreventScroll(dom) { + if (dom.setActive) + return dom.setActive(); // in IE + if (preventScrollSupported) + return dom.focus(preventScrollSupported); + let stack = []; + for (let cur = dom; cur; cur = cur.parentNode) { + stack.push(cur, cur.scrollTop, cur.scrollLeft); + if (cur == cur.ownerDocument) + break; + } + dom.focus(preventScrollSupported == null ? { + get preventScroll() { + preventScrollSupported = { preventScroll: true }; + return true; + } + } : undefined); + if (!preventScrollSupported) { + preventScrollSupported = false; + for (let i = 0; i < stack.length;) { + let elt = stack[i++], top = stack[i++], left = stack[i++]; + if (elt.scrollTop != top) + elt.scrollTop = top; + if (elt.scrollLeft != left) + elt.scrollLeft = left; + } + } + } + let scratchRange; + function textRange(node, from, to = from) { + let range = scratchRange || (scratchRange = document.createRange()); + range.setEnd(node, to); + range.setStart(node, from); + return range; + } + function dispatchKey(elt, name, code) { + let options = { key: name, code: name, keyCode: code, which: code, cancelable: true }; + let down = new KeyboardEvent("keydown", options); + down.synthetic = true; + elt.dispatchEvent(down); + let up = new KeyboardEvent("keyup", options); + up.synthetic = true; + elt.dispatchEvent(up); + return down.defaultPrevented || up.defaultPrevented; + } + function getRoot(node) { + while (node) { + if (node && (node.nodeType == 9 || node.nodeType == 11 && node.host)) + return node; + node = node.assignedSlot || node.parentNode; + } + return null; + } + function clearAttributes(node) { + while (node.attributes.length) + node.removeAttributeNode(node.attributes[0]); + } + function atElementStart(doc, selection) { + let node = selection.focusNode, offset = selection.focusOffset; + if (!node || selection.anchorNode != node || selection.anchorOffset != offset) + return false; + for (;;) { + if (offset) { + if (node.nodeType != 1) + return false; + let prev = node.childNodes[offset - 1]; + if (prev.contentEditable == "false") + offset--; + else { + node = prev; + offset = maxOffset(node); + } + } + else if (node == doc) { + return true; + } + else { + offset = domIndex(node); + node = node.parentNode; + } + } + } + + class DOMPos { + constructor(node, offset, precise = true) { + this.node = node; + this.offset = offset; + this.precise = precise; + } + static before(dom, precise) { return new DOMPos(dom.parentNode, domIndex(dom), precise); } + static after(dom, precise) { return new DOMPos(dom.parentNode, domIndex(dom) + 1, precise); } + } + const noChildren = []; + class ContentView { + constructor() { + this.parent = null; + this.dom = null; + this.dirty = 2 /* Dirty.Node */; + } + get editorView() { + if (!this.parent) + throw new Error("Accessing view in orphan content view"); + return this.parent.editorView; + } + get overrideDOMText() { return null; } + get posAtStart() { + return this.parent ? this.parent.posBefore(this) : 0; + } + get posAtEnd() { + return this.posAtStart + this.length; + } + posBefore(view) { + let pos = this.posAtStart; + for (let child of this.children) { + if (child == view) + return pos; + pos += child.length + child.breakAfter; + } + throw new RangeError("Invalid child in posBefore"); + } + posAfter(view) { + return this.posBefore(view) + view.length; + } + // Will return a rectangle directly before (when side < 0), after + // (side > 0) or directly on (when the browser supports it) the + // given position. + coordsAt(_pos, _side) { return null; } + sync(track) { + if (this.dirty & 2 /* Dirty.Node */) { + let parent = this.dom; + let prev = null, next; + for (let child of this.children) { + if (child.dirty) { + if (!child.dom && (next = prev ? prev.nextSibling : parent.firstChild)) { + let contentView = ContentView.get(next); + if (!contentView || !contentView.parent && contentView.canReuseDOM(child)) + child.reuseDOM(next); + } + child.sync(track); + child.dirty = 0 /* Dirty.Not */; + } + next = prev ? prev.nextSibling : parent.firstChild; + if (track && !track.written && track.node == parent && next != child.dom) + track.written = true; + if (child.dom.parentNode == parent) { + while (next && next != child.dom) + next = rm$1(next); + } + else { + parent.insertBefore(child.dom, next); + } + prev = child.dom; + } + next = prev ? prev.nextSibling : parent.firstChild; + if (next && track && track.node == parent) + track.written = true; + while (next) + next = rm$1(next); + } + else if (this.dirty & 1 /* Dirty.Child */) { + for (let child of this.children) + if (child.dirty) { + child.sync(track); + child.dirty = 0 /* Dirty.Not */; + } + } + } + reuseDOM(_dom) { } + localPosFromDOM(node, offset) { + let after; + if (node == this.dom) { + after = this.dom.childNodes[offset]; + } + else { + let bias = maxOffset(node) == 0 ? 0 : offset == 0 ? -1 : 1; + for (;;) { + let parent = node.parentNode; + if (parent == this.dom) + break; + if (bias == 0 && parent.firstChild != parent.lastChild) { + if (node == parent.firstChild) + bias = -1; + else + bias = 1; + } + node = parent; + } + if (bias < 0) + after = node; + else + after = node.nextSibling; + } + if (after == this.dom.firstChild) + return 0; + while (after && !ContentView.get(after)) + after = after.nextSibling; + if (!after) + return this.length; + for (let i = 0, pos = 0;; i++) { + let child = this.children[i]; + if (child.dom == after) + return pos; + pos += child.length + child.breakAfter; + } + } + domBoundsAround(from, to, offset = 0) { + let fromI = -1, fromStart = -1, toI = -1, toEnd = -1; + for (let i = 0, pos = offset, prevEnd = offset; i < this.children.length; i++) { + let child = this.children[i], end = pos + child.length; + if (pos < from && end > to) + return child.domBoundsAround(from, to, pos); + if (end >= from && fromI == -1) { + fromI = i; + fromStart = pos; + } + if (pos > to && child.dom.parentNode == this.dom) { + toI = i; + toEnd = prevEnd; + break; + } + prevEnd = end; + pos = end + child.breakAfter; + } + return { from: fromStart, to: toEnd < 0 ? offset + this.length : toEnd, + startDOM: (fromI ? this.children[fromI - 1].dom.nextSibling : null) || this.dom.firstChild, + endDOM: toI < this.children.length && toI >= 0 ? this.children[toI].dom : null }; + } + markDirty(andParent = false) { + this.dirty |= 2 /* Dirty.Node */; + this.markParentsDirty(andParent); + } + markParentsDirty(childList) { + for (let parent = this.parent; parent; parent = parent.parent) { + if (childList) + parent.dirty |= 2 /* Dirty.Node */; + if (parent.dirty & 1 /* Dirty.Child */) + return; + parent.dirty |= 1 /* Dirty.Child */; + childList = false; + } + } + setParent(parent) { + if (this.parent != parent) { + this.parent = parent; + if (this.dirty) + this.markParentsDirty(true); + } + } + setDOM(dom) { + if (this.dom) + this.dom.cmView = null; + this.dom = dom; + dom.cmView = this; + } + get rootView() { + for (let v = this;;) { + let parent = v.parent; + if (!parent) + return v; + v = parent; + } + } + replaceChildren(from, to, children = noChildren) { + this.markDirty(); + for (let i = from; i < to; i++) { + let child = this.children[i]; + if (child.parent == this) + child.destroy(); + } + this.children.splice(from, to - from, ...children); + for (let i = 0; i < children.length; i++) + children[i].setParent(this); + } + ignoreMutation(_rec) { return false; } + ignoreEvent(_event) { return false; } + childCursor(pos = this.length) { + return new ChildCursor(this.children, pos, this.children.length); + } + childPos(pos, bias = 1) { + return this.childCursor().findPos(pos, bias); + } + toString() { + let name = this.constructor.name.replace("View", ""); + return name + (this.children.length ? "(" + this.children.join() + ")" : + this.length ? "[" + (name == "Text" ? this.text : this.length) + "]" : "") + + (this.breakAfter ? "#" : ""); + } + static get(node) { return node.cmView; } + get isEditable() { return true; } + merge(from, to, source, hasStart, openStart, openEnd) { + return false; + } + become(other) { return false; } + canReuseDOM(other) { return other.constructor == this.constructor; } + // When this is a zero-length view with a side, this should return a + // number <= 0 to indicate it is before its position, or a + // number > 0 when after its position. + getSide() { return 0; } + destroy() { + this.parent = null; + } + } + ContentView.prototype.breakAfter = 0; + // Remove a DOM node and return its next sibling. + function rm$1(dom) { + let next = dom.nextSibling; + dom.parentNode.removeChild(dom); + return next; + } + class ChildCursor { + constructor(children, pos, i) { + this.children = children; + this.pos = pos; + this.i = i; + this.off = 0; + } + findPos(pos, bias = 1) { + for (;;) { + if (pos > this.pos || pos == this.pos && + (bias > 0 || this.i == 0 || this.children[this.i - 1].breakAfter)) { + this.off = pos - this.pos; + return this; + } + let next = this.children[--this.i]; + this.pos -= next.length + next.breakAfter; + } + } + } + function replaceRange(parent, fromI, fromOff, toI, toOff, insert, breakAtStart, openStart, openEnd) { + let { children } = parent; + let before = children.length ? children[fromI] : null; + let last = insert.length ? insert[insert.length - 1] : null; + let breakAtEnd = last ? last.breakAfter : breakAtStart; + // Change within a single child + if (fromI == toI && before && !breakAtStart && !breakAtEnd && insert.length < 2 && + before.merge(fromOff, toOff, insert.length ? last : null, fromOff == 0, openStart, openEnd)) + return; + if (toI < children.length) { + let after = children[toI]; + // Make sure the end of the child after the update is preserved in `after` + if (after && toOff < after.length) { + // If we're splitting a child, separate part of it to avoid that + // being mangled when updating the child before the update. + if (fromI == toI) { + after = after.split(toOff); + toOff = 0; + } + // If the element after the replacement should be merged with + // the last replacing element, update `content` + if (!breakAtEnd && last && after.merge(0, toOff, last, true, 0, openEnd)) { + insert[insert.length - 1] = after; + } + else { + // Remove the start of the after element, if necessary, and + // add it to `content`. + if (toOff) + after.merge(0, toOff, null, false, 0, openEnd); + insert.push(after); + } + } + else if (after === null || after === void 0 ? void 0 : after.breakAfter) { + // The element at `toI` is entirely covered by this range. + // Preserve its line break, if any. + if (last) + last.breakAfter = 1; + else + breakAtStart = 1; + } + // Since we've handled the next element from the current elements + // now, make sure `toI` points after that. + toI++; + } + if (before) { + before.breakAfter = breakAtStart; + if (fromOff > 0) { + if (!breakAtStart && insert.length && before.merge(fromOff, before.length, insert[0], false, openStart, 0)) { + before.breakAfter = insert.shift().breakAfter; + } + else if (fromOff < before.length || before.children.length && before.children[before.children.length - 1].length == 0) { + before.merge(fromOff, before.length, null, false, openStart, 0); + } + fromI++; + } + } + // Try to merge widgets on the boundaries of the replacement + while (fromI < toI && insert.length) { + if (children[toI - 1].become(insert[insert.length - 1])) { + toI--; + insert.pop(); + openEnd = insert.length ? 0 : openStart; + } + else if (children[fromI].become(insert[0])) { + fromI++; + insert.shift(); + openStart = insert.length ? 0 : openEnd; + } + else { + break; + } + } + if (!insert.length && fromI && toI < children.length && !children[fromI - 1].breakAfter && + children[toI].merge(0, 0, children[fromI - 1], false, openStart, openEnd)) + fromI--; + if (fromI < toI || insert.length) + parent.replaceChildren(fromI, toI, insert); + } + function mergeChildrenInto(parent, from, to, insert, openStart, openEnd) { + let cur = parent.childCursor(); + let { i: toI, off: toOff } = cur.findPos(to, 1); + let { i: fromI, off: fromOff } = cur.findPos(from, -1); + let dLen = from - to; + for (let view of insert) + dLen += view.length; + parent.length += dLen; + replaceRange(parent, fromI, fromOff, toI, toOff, insert, 0, openStart, openEnd); + } + + let nav = typeof navigator != "undefined" ? navigator : { userAgent: "", vendor: "", platform: "" }; + let doc = typeof document != "undefined" ? document : { documentElement: { style: {} } }; + const ie_edge = /*@__PURE__*//Edge\/(\d+)/.exec(nav.userAgent); + const ie_upto10 = /*@__PURE__*//MSIE \d/.test(nav.userAgent); + const ie_11up = /*@__PURE__*//Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(nav.userAgent); + const ie = !!(ie_upto10 || ie_11up || ie_edge); + const gecko = !ie && /*@__PURE__*//gecko\/(\d+)/i.test(nav.userAgent); + const chrome = !ie && /*@__PURE__*//Chrome\/(\d+)/.exec(nav.userAgent); + const webkit = "webkitFontSmoothing" in doc.documentElement.style; + const safari = !ie && /*@__PURE__*//Apple Computer/.test(nav.vendor); + const ios = safari && (/*@__PURE__*//Mobile\/\w+/.test(nav.userAgent) || nav.maxTouchPoints > 2); + var browser = { + mac: ios || /*@__PURE__*//Mac/.test(nav.platform), + windows: /*@__PURE__*//Win/.test(nav.platform), + linux: /*@__PURE__*//Linux|X11/.test(nav.platform), + ie, + ie_version: ie_upto10 ? doc.documentMode || 6 : ie_11up ? +ie_11up[1] : ie_edge ? +ie_edge[1] : 0, + gecko, + gecko_version: gecko ? +(/*@__PURE__*//Firefox\/(\d+)/.exec(nav.userAgent) || [0, 0])[1] : 0, + chrome: !!chrome, + chrome_version: chrome ? +chrome[1] : 0, + ios, + android: /*@__PURE__*//Android\b/.test(nav.userAgent), + webkit, + safari, + webkit_version: webkit ? +(/*@__PURE__*//\bAppleWebKit\/(\d+)/.exec(navigator.userAgent) || [0, 0])[1] : 0, + tabSize: doc.documentElement.style.tabSize != null ? "tab-size" : "-moz-tab-size" + }; + + const MaxJoinLen = 256; + class TextView extends ContentView { + constructor(text) { + super(); + this.text = text; + } + get length() { return this.text.length; } + createDOM(textDOM) { + this.setDOM(textDOM || document.createTextNode(this.text)); + } + sync(track) { + if (!this.dom) + this.createDOM(); + if (this.dom.nodeValue != this.text) { + if (track && track.node == this.dom) + track.written = true; + this.dom.nodeValue = this.text; + } + } + reuseDOM(dom) { + if (dom.nodeType == 3) + this.createDOM(dom); + } + merge(from, to, source) { + if (source && (!(source instanceof TextView) || this.length - (to - from) + source.length > MaxJoinLen)) + return false; + this.text = this.text.slice(0, from) + (source ? source.text : "") + this.text.slice(to); + this.markDirty(); + return true; + } + split(from) { + let result = new TextView(this.text.slice(from)); + this.text = this.text.slice(0, from); + this.markDirty(); + return result; + } + localPosFromDOM(node, offset) { + return node == this.dom ? offset : offset ? this.text.length : 0; + } + domAtPos(pos) { return new DOMPos(this.dom, pos); } + domBoundsAround(_from, _to, offset) { + return { from: offset, to: offset + this.length, startDOM: this.dom, endDOM: this.dom.nextSibling }; + } + coordsAt(pos, side) { + return textCoords(this.dom, pos, side); + } + } + class MarkView extends ContentView { + constructor(mark, children = [], length = 0) { + super(); + this.mark = mark; + this.children = children; + this.length = length; + for (let ch of children) + ch.setParent(this); + } + setAttrs(dom) { + clearAttributes(dom); + if (this.mark.class) + dom.className = this.mark.class; + if (this.mark.attrs) + for (let name in this.mark.attrs) + dom.setAttribute(name, this.mark.attrs[name]); + return dom; + } + reuseDOM(node) { + if (node.nodeName == this.mark.tagName.toUpperCase()) { + this.setDOM(node); + this.dirty |= 4 /* Dirty.Attrs */ | 2 /* Dirty.Node */; + } + } + sync(track) { + if (!this.dom) + this.setDOM(this.setAttrs(document.createElement(this.mark.tagName))); + else if (this.dirty & 4 /* Dirty.Attrs */) + this.setAttrs(this.dom); + super.sync(track); + } + merge(from, to, source, _hasStart, openStart, openEnd) { + if (source && (!(source instanceof MarkView && source.mark.eq(this.mark)) || + (from && openStart <= 0) || (to < this.length && openEnd <= 0))) + return false; + mergeChildrenInto(this, from, to, source ? source.children : [], openStart - 1, openEnd - 1); + this.markDirty(); + return true; + } + split(from) { + let result = [], off = 0, detachFrom = -1, i = 0; + for (let elt of this.children) { + let end = off + elt.length; + if (end > from) + result.push(off < from ? elt.split(from - off) : elt); + if (detachFrom < 0 && off >= from) + detachFrom = i; + off = end; + i++; + } + let length = this.length - from; + this.length = from; + if (detachFrom > -1) { + this.children.length = detachFrom; + this.markDirty(); + } + return new MarkView(this.mark, result, length); + } + domAtPos(pos) { + return inlineDOMAtPos(this, pos); + } + coordsAt(pos, side) { + return coordsInChildren(this, pos, side); + } + } + function textCoords(text, pos, side) { + let length = text.nodeValue.length; + if (pos > length) + pos = length; + let from = pos, to = pos, flatten = 0; + if (pos == 0 && side < 0 || pos == length && side >= 0) { + if (!(browser.chrome || browser.gecko)) { // These browsers reliably return valid rectangles for empty ranges + if (pos) { + from--; + flatten = 1; + } // FIXME this is wrong in RTL text + else if (to < length) { + to++; + flatten = -1; + } + } + } + else { + if (side < 0) + from--; + else if (to < length) + to++; + } + let rects = textRange(text, from, to).getClientRects(); + if (!rects.length) + return Rect0; + let rect = rects[(flatten ? flatten < 0 : side >= 0) ? 0 : rects.length - 1]; + if (browser.safari && !flatten && rect.width == 0) + rect = Array.prototype.find.call(rects, r => r.width) || rect; + return flatten ? flattenRect(rect, flatten < 0) : rect || null; + } + // Also used for collapsed ranges that don't have a placeholder widget! + class WidgetView extends ContentView { + constructor(widget, length, side) { + super(); + this.widget = widget; + this.length = length; + this.side = side; + this.prevWidget = null; + } + static create(widget, length, side) { + return new (widget.customView || WidgetView)(widget, length, side); + } + split(from) { + let result = WidgetView.create(this.widget, this.length - from, this.side); + this.length -= from; + return result; + } + sync() { + if (!this.dom || !this.widget.updateDOM(this.dom)) { + if (this.dom && this.prevWidget) + this.prevWidget.destroy(this.dom); + this.prevWidget = null; + this.setDOM(this.widget.toDOM(this.editorView)); + this.dom.contentEditable = "false"; + } + } + getSide() { return this.side; } + merge(from, to, source, hasStart, openStart, openEnd) { + if (source && (!(source instanceof WidgetView) || !this.widget.compare(source.widget) || + from > 0 && openStart <= 0 || to < this.length && openEnd <= 0)) + return false; + this.length = from + (source ? source.length : 0) + (this.length - to); + return true; + } + become(other) { + if (other.length == this.length && other instanceof WidgetView && other.side == this.side) { + if (this.widget.constructor == other.widget.constructor) { + if (!this.widget.eq(other.widget)) + this.markDirty(true); + if (this.dom && !this.prevWidget) + this.prevWidget = this.widget; + this.widget = other.widget; + return true; + } + } + return false; + } + ignoreMutation() { return true; } + ignoreEvent(event) { return this.widget.ignoreEvent(event); } + get overrideDOMText() { + if (this.length == 0) + return Text.empty; + let top = this; + while (top.parent) + top = top.parent; + let view = top.editorView, text = view && view.state.doc, start = this.posAtStart; + return text ? text.slice(start, start + this.length) : Text.empty; + } + domAtPos(pos) { + return pos == 0 ? DOMPos.before(this.dom) : DOMPos.after(this.dom, pos == this.length); + } + domBoundsAround() { return null; } + coordsAt(pos, side) { + let rects = this.dom.getClientRects(), rect = null; + if (!rects.length) + return Rect0; + for (let i = pos > 0 ? rects.length - 1 : 0;; i += (pos > 0 ? -1 : 1)) { + rect = rects[i]; + if (pos > 0 ? i == 0 : i == rects.length - 1 || rect.top < rect.bottom) + break; + } + return (pos == 0 && side > 0 || pos == this.length && side <= 0) ? rect : flattenRect(rect, pos == 0); + } + get isEditable() { return false; } + destroy() { + super.destroy(); + if (this.dom) + this.widget.destroy(this.dom); + } + } + class CompositionView extends WidgetView { + domAtPos(pos) { + let { topView, text } = this.widget; + if (!topView) + return new DOMPos(text, Math.min(pos, text.nodeValue.length)); + return scanCompositionTree(pos, 0, topView, text, (v, p) => v.domAtPos(p), p => new DOMPos(text, Math.min(p, text.nodeValue.length))); + } + sync() { this.setDOM(this.widget.toDOM()); } + localPosFromDOM(node, offset) { + let { topView, text } = this.widget; + if (!topView) + return Math.min(offset, this.length); + return posFromDOMInCompositionTree(node, offset, topView, text); + } + ignoreMutation() { return false; } + get overrideDOMText() { return null; } + coordsAt(pos, side) { + let { topView, text } = this.widget; + if (!topView) + return textCoords(text, pos, side); + return scanCompositionTree(pos, side, topView, text, (v, pos, side) => v.coordsAt(pos, side), (pos, side) => textCoords(text, pos, side)); + } + destroy() { + var _a; + super.destroy(); + (_a = this.widget.topView) === null || _a === void 0 ? void 0 : _a.destroy(); + } + get isEditable() { return true; } + canReuseDOM() { return true; } + } + // Uses the old structure of a chunk of content view frozen for + // composition to try and find a reasonable DOM location for the given + // offset. + function scanCompositionTree(pos, side, view, text, enterView, fromText) { + if (view instanceof MarkView) { + for (let child = view.dom.firstChild; child; child = child.nextSibling) { + let desc = ContentView.get(child); + if (!desc) + return fromText(pos, side); + let hasComp = contains(child, text); + let len = desc.length + (hasComp ? text.nodeValue.length : 0); + if (pos < len || pos == len && desc.getSide() <= 0) + return hasComp ? scanCompositionTree(pos, side, desc, text, enterView, fromText) : enterView(desc, pos, side); + pos -= len; + } + return enterView(view, view.length, -1); + } + else if (view.dom == text) { + return fromText(pos, side); + } + else { + return enterView(view, pos, side); + } + } + function posFromDOMInCompositionTree(node, offset, view, text) { + if (view instanceof MarkView) { + for (let child of view.children) { + let pos = 0, hasComp = contains(child.dom, text); + if (contains(child.dom, node)) + return pos + (hasComp ? posFromDOMInCompositionTree(node, offset, child, text) : child.localPosFromDOM(node, offset)); + pos += hasComp ? text.nodeValue.length : child.length; + } + } + else if (view.dom == text) { + return Math.min(offset, text.nodeValue.length); + } + return view.localPosFromDOM(node, offset); + } + // These are drawn around uneditable widgets to avoid a number of + // browser bugs that show up when the cursor is directly next to + // uneditable inline content. + class WidgetBufferView extends ContentView { + constructor(side) { + super(); + this.side = side; + } + get length() { return 0; } + merge() { return false; } + become(other) { + return other instanceof WidgetBufferView && other.side == this.side; + } + split() { return new WidgetBufferView(this.side); } + sync() { + if (!this.dom) { + let dom = document.createElement("img"); + dom.className = "cm-widgetBuffer"; + dom.setAttribute("aria-hidden", "true"); + this.setDOM(dom); + } + } + getSide() { return this.side; } + domAtPos(pos) { return DOMPos.before(this.dom); } + localPosFromDOM() { return 0; } + domBoundsAround() { return null; } + coordsAt(pos) { + let imgRect = this.dom.getBoundingClientRect(); + // Since the <img> height doesn't correspond to text height, try + // to borrow the height from some sibling node. + let siblingRect = inlineSiblingRect(this, this.side > 0 ? -1 : 1); + return siblingRect && siblingRect.top < imgRect.bottom && siblingRect.bottom > imgRect.top + ? { left: imgRect.left, right: imgRect.right, top: siblingRect.top, bottom: siblingRect.bottom } : imgRect; + } + get overrideDOMText() { + return Text.empty; + } + } + TextView.prototype.children = WidgetView.prototype.children = WidgetBufferView.prototype.children = noChildren; + function inlineSiblingRect(view, side) { + let parent = view.parent, index = parent ? parent.children.indexOf(view) : -1; + while (parent && index >= 0) { + if (side < 0 ? index > 0 : index < parent.children.length) { + let next = parent.children[index + side]; + if (next instanceof TextView) { + let nextRect = next.coordsAt(side < 0 ? next.length : 0, side); + if (nextRect) + return nextRect; + } + index += side; + } + else if (parent instanceof MarkView && parent.parent) { + index = parent.parent.children.indexOf(parent) + (side < 0 ? 0 : 1); + parent = parent.parent; + } + else { + let last = parent.dom.lastChild; + if (last && last.nodeName == "BR") + return last.getClientRects()[0]; + break; + } + } + return undefined; + } + function inlineDOMAtPos(parent, pos) { + let dom = parent.dom, { children } = parent, i = 0; + for (let off = 0; i < children.length; i++) { + let child = children[i], end = off + child.length; + if (end == off && child.getSide() <= 0) + continue; + if (pos > off && pos < end && child.dom.parentNode == dom) + return child.domAtPos(pos - off); + if (pos <= off) + break; + off = end; + } + // if (i) return DOMPos.after(children[i - 1].dom!) + for (let j = i; j > 0; j--) { + let prev = children[j - 1]; + if (prev.dom.parentNode == dom) + return prev.domAtPos(prev.length); + } + for (let j = i; j < children.length; j++) { + let next = children[j]; + if (next.dom.parentNode == dom) + return next.domAtPos(0); + } + return new DOMPos(dom, 0); + } + // Assumes `view`, if a mark view, has precisely 1 child. + function joinInlineInto(parent, view, open) { + let last, { children } = parent; + if (open > 0 && view instanceof MarkView && children.length && + (last = children[children.length - 1]) instanceof MarkView && last.mark.eq(view.mark)) { + joinInlineInto(last, view.children[0], open - 1); + } + else { + children.push(view); + view.setParent(parent); + } + parent.length += view.length; + } + function coordsInChildren(view, pos, side) { + for (let off = 0, i = 0; i < view.children.length; i++) { + let child = view.children[i], end = off + child.length, next; + if ((side <= 0 || end == view.length || child.getSide() > 0 ? end >= pos : end > pos) && + (pos < end || i + 1 == view.children.length || (next = view.children[i + 1]).length || next.getSide() > 0)) { + let flatten = 0; + if (end == off) { + if (child.getSide() <= 0) + continue; + flatten = side = -child.getSide(); + } + let rect = child.coordsAt(Math.max(0, pos - off), side); + return flatten && rect ? flattenRect(rect, side < 0) : rect; + } + off = end; + } + let last = view.dom.lastChild; + if (!last) + return view.dom.getBoundingClientRect(); + let rects = clientRectsFor(last); + return rects[rects.length - 1] || null; + } + + function combineAttrs(source, target) { + for (let name in source) { + if (name == "class" && target.class) + target.class += " " + source.class; + else if (name == "style" && target.style) + target.style += ";" + source.style; + else + target[name] = source[name]; + } + return target; + } + function attrsEq(a, b) { + if (a == b) + return true; + if (!a || !b) + return false; + let keysA = Object.keys(a), keysB = Object.keys(b); + if (keysA.length != keysB.length) + return false; + for (let key of keysA) { + if (keysB.indexOf(key) == -1 || a[key] !== b[key]) + return false; + } + return true; + } + function updateAttrs(dom, prev, attrs) { + let changed = null; + if (prev) + for (let name in prev) + if (!(attrs && name in attrs)) + dom.removeAttribute(changed = name); + if (attrs) + for (let name in attrs) + if (!(prev && prev[name] == attrs[name])) + dom.setAttribute(changed = name, attrs[name]); + return !!changed; + } + + /** + Widgets added to the content are described by subclasses of this + class. Using a description object like that makes it possible to + delay creating of the DOM structure for a widget until it is + needed, and to avoid redrawing widgets even if the decorations + that define them are recreated. + */ + class WidgetType { + /** + Compare this instance to another instance of the same type. + (TypeScript can't express this, but only instances of the same + specific class will be passed to this method.) This is used to + avoid redrawing widgets when they are replaced by a new + decoration of the same type. The default implementation just + returns `false`, which will cause new instances of the widget to + always be redrawn. + */ + eq(widget) { return false; } + /** + Update a DOM element created by a widget of the same type (but + different, non-`eq` content) to reflect this widget. May return + true to indicate that it could update, false to indicate it + couldn't (in which case the widget will be redrawn). The default + implementation just returns false. + */ + updateDOM(dom) { return false; } + /** + @internal + */ + compare(other) { + return this == other || this.constructor == other.constructor && this.eq(other); + } + /** + The estimated height this widget will have, to be used when + estimating the height of content that hasn't been drawn. May + return -1 to indicate you don't know. The default implementation + returns -1. + */ + get estimatedHeight() { return -1; } + /** + Can be used to configure which kinds of events inside the widget + should be ignored by the editor. The default is to ignore all + events. + */ + ignoreEvent(event) { return true; } + /** + @internal + */ + get customView() { return null; } + /** + This is called when the an instance of the widget is removed + from the editor view. + */ + destroy(dom) { } + } + /** + The different types of blocks that can occur in an editor view. + */ + var BlockType = /*@__PURE__*/(function (BlockType) { + /** + A line of text. + */ + BlockType[BlockType["Text"] = 0] = "Text"; + /** + A block widget associated with the position after it. + */ + BlockType[BlockType["WidgetBefore"] = 1] = "WidgetBefore"; + /** + A block widget associated with the position before it. + */ + BlockType[BlockType["WidgetAfter"] = 2] = "WidgetAfter"; + /** + A block widget [replacing](https://codemirror.net/6/docs/ref/#view.Decoration^replace) a range of content. + */ + BlockType[BlockType["WidgetRange"] = 3] = "WidgetRange"; + return BlockType})(BlockType || (BlockType = {})); + /** + A decoration provides information on how to draw or style a piece + of content. You'll usually use it wrapped in a + [`Range`](https://codemirror.net/6/docs/ref/#state.Range), which adds a start and end position. + @nonabstract + */ + class Decoration extends RangeValue { + constructor( + /** + @internal + */ + startSide, + /** + @internal + */ + endSide, + /** + @internal + */ + widget, + /** + The config object used to create this decoration. You can + include additional properties in there to store metadata about + your decoration. + */ + spec) { + super(); + this.startSide = startSide; + this.endSide = endSide; + this.widget = widget; + this.spec = spec; + } + /** + @internal + */ + get heightRelevant() { return false; } + /** + Create a mark decoration, which influences the styling of the + content in its range. Nested mark decorations will cause nested + DOM elements to be created. Nesting order is determined by + precedence of the [facet](https://codemirror.net/6/docs/ref/#view.EditorView^decorations), with + the higher-precedence decorations creating the inner DOM nodes. + Such elements are split on line boundaries and on the boundaries + of lower-precedence decorations. + */ + static mark(spec) { + return new MarkDecoration(spec); + } + /** + Create a widget decoration, which displays a DOM element at the + given position. + */ + static widget(spec) { + let side = spec.side || 0, block = !!spec.block; + side += block ? (side > 0 ? 300000000 /* Side.BlockAfter */ : -400000000 /* Side.BlockBefore */) : (side > 0 ? 100000000 /* Side.InlineAfter */ : -100000000 /* Side.InlineBefore */); + return new PointDecoration(spec, side, side, block, spec.widget || null, false); + } + /** + Create a replace decoration which replaces the given range with + a widget, or simply hides it. + */ + static replace(spec) { + let block = !!spec.block, startSide, endSide; + if (spec.isBlockGap) { + startSide = -500000000 /* Side.GapStart */; + endSide = 400000000 /* Side.GapEnd */; + } + else { + let { start, end } = getInclusive(spec, block); + startSide = (start ? (block ? -300000000 /* Side.BlockIncStart */ : -1 /* Side.InlineIncStart */) : 500000000 /* Side.NonIncStart */) - 1; + endSide = (end ? (block ? 200000000 /* Side.BlockIncEnd */ : 1 /* Side.InlineIncEnd */) : -600000000 /* Side.NonIncEnd */) + 1; + } + return new PointDecoration(spec, startSide, endSide, block, spec.widget || null, true); + } + /** + Create a line decoration, which can add DOM attributes to the + line starting at the given position. + */ + static line(spec) { + return new LineDecoration(spec); + } + /** + Build a [`DecorationSet`](https://codemirror.net/6/docs/ref/#view.DecorationSet) from the given + decorated range or ranges. If the ranges aren't already sorted, + pass `true` for `sort` to make the library sort them for you. + */ + static set(of, sort = false) { + return RangeSet.of(of, sort); + } + /** + @internal + */ + hasHeight() { return this.widget ? this.widget.estimatedHeight > -1 : false; } + } + /** + The empty set of decorations. + */ + Decoration.none = RangeSet.empty; + class MarkDecoration extends Decoration { + constructor(spec) { + let { start, end } = getInclusive(spec); + super(start ? -1 /* Side.InlineIncStart */ : 500000000 /* Side.NonIncStart */, end ? 1 /* Side.InlineIncEnd */ : -600000000 /* Side.NonIncEnd */, null, spec); + this.tagName = spec.tagName || "span"; + this.class = spec.class || ""; + this.attrs = spec.attributes || null; + } + eq(other) { + return this == other || + other instanceof MarkDecoration && + this.tagName == other.tagName && + this.class == other.class && + attrsEq(this.attrs, other.attrs); + } + range(from, to = from) { + if (from >= to) + throw new RangeError("Mark decorations may not be empty"); + return super.range(from, to); + } + } + MarkDecoration.prototype.point = false; + class LineDecoration extends Decoration { + constructor(spec) { + super(-200000000 /* Side.Line */, -200000000 /* Side.Line */, null, spec); + } + eq(other) { + return other instanceof LineDecoration && attrsEq(this.spec.attributes, other.spec.attributes); + } + range(from, to = from) { + if (to != from) + throw new RangeError("Line decoration ranges must be zero-length"); + return super.range(from, to); + } + } + LineDecoration.prototype.mapMode = MapMode.TrackBefore; + LineDecoration.prototype.point = true; + class PointDecoration extends Decoration { + constructor(spec, startSide, endSide, block, widget, isReplace) { + super(startSide, endSide, widget, spec); + this.block = block; + this.isReplace = isReplace; + this.mapMode = !block ? MapMode.TrackDel : startSide <= 0 ? MapMode.TrackBefore : MapMode.TrackAfter; + } + // Only relevant when this.block == true + get type() { + return this.startSide < this.endSide ? BlockType.WidgetRange + : this.startSide <= 0 ? BlockType.WidgetBefore : BlockType.WidgetAfter; + } + get heightRelevant() { return this.block || !!this.widget && this.widget.estimatedHeight >= 5; } + eq(other) { + return other instanceof PointDecoration && + widgetsEq(this.widget, other.widget) && + this.block == other.block && + this.startSide == other.startSide && this.endSide == other.endSide; + } + range(from, to = from) { + if (this.isReplace && (from > to || (from == to && this.startSide > 0 && this.endSide <= 0))) + throw new RangeError("Invalid range for replacement decoration"); + if (!this.isReplace && to != from) + throw new RangeError("Widget decorations can only have zero-length ranges"); + return super.range(from, to); + } + } + PointDecoration.prototype.point = true; + function getInclusive(spec, block = false) { + let { inclusiveStart: start, inclusiveEnd: end } = spec; + if (start == null) + start = spec.inclusive; + if (end == null) + end = spec.inclusive; + return { start: start !== null && start !== void 0 ? start : block, end: end !== null && end !== void 0 ? end : block }; + } + function widgetsEq(a, b) { + return a == b || !!(a && b && a.compare(b)); + } + function addRange(from, to, ranges, margin = 0) { + let last = ranges.length - 1; + if (last >= 0 && ranges[last] + margin >= from) + ranges[last] = Math.max(ranges[last], to); + else + ranges.push(from, to); + } + + class LineView extends ContentView { + constructor() { + super(...arguments); + this.children = []; + this.length = 0; + this.prevAttrs = undefined; + this.attrs = null; + this.breakAfter = 0; + } + // Consumes source + merge(from, to, source, hasStart, openStart, openEnd) { + if (source) { + if (!(source instanceof LineView)) + return false; + if (!this.dom) + source.transferDOM(this); // Reuse source.dom when appropriate + } + if (hasStart) + this.setDeco(source ? source.attrs : null); + mergeChildrenInto(this, from, to, source ? source.children : [], openStart, openEnd); + return true; + } + split(at) { + let end = new LineView; + end.breakAfter = this.breakAfter; + if (this.length == 0) + return end; + let { i, off } = this.childPos(at); + if (off) { + end.append(this.children[i].split(off), 0); + this.children[i].merge(off, this.children[i].length, null, false, 0, 0); + i++; + } + for (let j = i; j < this.children.length; j++) + end.append(this.children[j], 0); + while (i > 0 && this.children[i - 1].length == 0) + this.children[--i].destroy(); + this.children.length = i; + this.markDirty(); + this.length = at; + return end; + } + transferDOM(other) { + if (!this.dom) + return; + this.markDirty(); + other.setDOM(this.dom); + other.prevAttrs = this.prevAttrs === undefined ? this.attrs : this.prevAttrs; + this.prevAttrs = undefined; + this.dom = null; + } + setDeco(attrs) { + if (!attrsEq(this.attrs, attrs)) { + if (this.dom) { + this.prevAttrs = this.attrs; + this.markDirty(); + } + this.attrs = attrs; + } + } + append(child, openStart) { + joinInlineInto(this, child, openStart); + } + // Only called when building a line view in ContentBuilder + addLineDeco(deco) { + let attrs = deco.spec.attributes, cls = deco.spec.class; + if (attrs) + this.attrs = combineAttrs(attrs, this.attrs || {}); + if (cls) + this.attrs = combineAttrs({ class: cls }, this.attrs || {}); + } + domAtPos(pos) { + return inlineDOMAtPos(this, pos); + } + reuseDOM(node) { + if (node.nodeName == "DIV") { + this.setDOM(node); + this.dirty |= 4 /* Dirty.Attrs */ | 2 /* Dirty.Node */; + } + } + sync(track) { + var _a; + if (!this.dom) { + this.setDOM(document.createElement("div")); + this.dom.className = "cm-line"; + this.prevAttrs = this.attrs ? null : undefined; + } + else if (this.dirty & 4 /* Dirty.Attrs */) { + clearAttributes(this.dom); + this.dom.className = "cm-line"; + this.prevAttrs = this.attrs ? null : undefined; + } + if (this.prevAttrs !== undefined) { + updateAttrs(this.dom, this.prevAttrs, this.attrs); + this.dom.classList.add("cm-line"); + this.prevAttrs = undefined; + } + super.sync(track); + let last = this.dom.lastChild; + while (last && ContentView.get(last) instanceof MarkView) + last = last.lastChild; + if (!last || !this.length || + last.nodeName != "BR" && ((_a = ContentView.get(last)) === null || _a === void 0 ? void 0 : _a.isEditable) == false && + (!browser.ios || !this.children.some(ch => ch instanceof TextView))) { + let hack = document.createElement("BR"); + hack.cmIgnore = true; + this.dom.appendChild(hack); + } + } + measureTextSize() { + if (this.children.length == 0 || this.length > 20) + return null; + let totalWidth = 0; + for (let child of this.children) { + if (!(child instanceof TextView) || /[^ -~]/.test(child.text)) + return null; + let rects = clientRectsFor(child.dom); + if (rects.length != 1) + return null; + totalWidth += rects[0].width; + } + return !totalWidth ? null : { + lineHeight: this.dom.getBoundingClientRect().height, + charWidth: totalWidth / this.length + }; + } + coordsAt(pos, side) { + return coordsInChildren(this, pos, side); + } + become(_other) { return false; } + get type() { return BlockType.Text; } + static find(docView, pos) { + for (let i = 0, off = 0; i < docView.children.length; i++) { + let block = docView.children[i], end = off + block.length; + if (end >= pos) { + if (block instanceof LineView) + return block; + if (end > pos) + break; + } + off = end + block.breakAfter; + } + return null; + } + } + class BlockWidgetView extends ContentView { + constructor(widget, length, type) { + super(); + this.widget = widget; + this.length = length; + this.type = type; + this.breakAfter = 0; + this.prevWidget = null; + } + merge(from, to, source, _takeDeco, openStart, openEnd) { + if (source && (!(source instanceof BlockWidgetView) || !this.widget.compare(source.widget) || + from > 0 && openStart <= 0 || to < this.length && openEnd <= 0)) + return false; + this.length = from + (source ? source.length : 0) + (this.length - to); + return true; + } + domAtPos(pos) { + return pos == 0 ? DOMPos.before(this.dom) : DOMPos.after(this.dom, pos == this.length); + } + split(at) { + let len = this.length - at; + this.length = at; + let end = new BlockWidgetView(this.widget, len, this.type); + end.breakAfter = this.breakAfter; + return end; + } + get children() { return noChildren; } + sync() { + if (!this.dom || !this.widget.updateDOM(this.dom)) { + if (this.dom && this.prevWidget) + this.prevWidget.destroy(this.dom); + this.prevWidget = null; + this.setDOM(this.widget.toDOM(this.editorView)); + this.dom.contentEditable = "false"; + } + } + get overrideDOMText() { + return this.parent ? this.parent.view.state.doc.slice(this.posAtStart, this.posAtEnd) : Text.empty; + } + domBoundsAround() { return null; } + become(other) { + if (other instanceof BlockWidgetView && other.type == this.type && + other.widget.constructor == this.widget.constructor) { + if (!other.widget.eq(this.widget)) + this.markDirty(true); + if (this.dom && !this.prevWidget) + this.prevWidget = this.widget; + this.widget = other.widget; + this.length = other.length; + this.breakAfter = other.breakAfter; + return true; + } + return false; + } + ignoreMutation() { return true; } + ignoreEvent(event) { return this.widget.ignoreEvent(event); } + destroy() { + super.destroy(); + if (this.dom) + this.widget.destroy(this.dom); + } + } + + class ContentBuilder { + constructor(doc, pos, end, disallowBlockEffectsFor) { + this.doc = doc; + this.pos = pos; + this.end = end; + this.disallowBlockEffectsFor = disallowBlockEffectsFor; + this.content = []; + this.curLine = null; + this.breakAtStart = 0; + this.pendingBuffer = 0 /* Buf.No */; + // Set to false directly after a widget that covers the position after it + this.atCursorPos = true; + this.openStart = -1; + this.openEnd = -1; + this.text = ""; + this.textOff = 0; + this.cursor = doc.iter(); + this.skip = pos; + } + posCovered() { + if (this.content.length == 0) + return !this.breakAtStart && this.doc.lineAt(this.pos).from != this.pos; + let last = this.content[this.content.length - 1]; + return !last.breakAfter && !(last instanceof BlockWidgetView && last.type == BlockType.WidgetBefore); + } + getLine() { + if (!this.curLine) { + this.content.push(this.curLine = new LineView); + this.atCursorPos = true; + } + return this.curLine; + } + flushBuffer(active) { + if (this.pendingBuffer) { + this.curLine.append(wrapMarks(new WidgetBufferView(-1), active), active.length); + this.pendingBuffer = 0 /* Buf.No */; + } + } + addBlockWidget(view) { + this.flushBuffer([]); + this.curLine = null; + this.content.push(view); + } + finish(openEnd) { + if (!openEnd) + this.flushBuffer([]); + else + this.pendingBuffer = 0 /* Buf.No */; + if (!this.posCovered()) + this.getLine(); + } + buildText(length, active, openStart) { + while (length > 0) { + if (this.textOff == this.text.length) { + let { value, lineBreak, done } = this.cursor.next(this.skip); + this.skip = 0; + if (done) + throw new Error("Ran out of text content when drawing inline views"); + if (lineBreak) { + if (!this.posCovered()) + this.getLine(); + if (this.content.length) + this.content[this.content.length - 1].breakAfter = 1; + else + this.breakAtStart = 1; + this.flushBuffer([]); + this.curLine = null; + length--; + continue; + } + else { + this.text = value; + this.textOff = 0; + } + } + let take = Math.min(this.text.length - this.textOff, length, 512 /* T.Chunk */); + this.flushBuffer(active.slice(0, openStart)); + this.getLine().append(wrapMarks(new TextView(this.text.slice(this.textOff, this.textOff + take)), active), openStart); + this.atCursorPos = true; + this.textOff += take; + length -= take; + openStart = 0; + } + } + span(from, to, active, openStart) { + this.buildText(to - from, active, openStart); + this.pos = to; + if (this.openStart < 0) + this.openStart = openStart; + } + point(from, to, deco, active, openStart, index) { + if (this.disallowBlockEffectsFor[index] && deco instanceof PointDecoration) { + if (deco.block) + throw new RangeError("Block decorations may not be specified via plugins"); + if (to > this.doc.lineAt(this.pos).to) + throw new RangeError("Decorations that replace line breaks may not be specified via plugins"); + } + let len = to - from; + if (deco instanceof PointDecoration) { + if (deco.block) { + let { type } = deco; + if (type == BlockType.WidgetAfter && !this.posCovered()) + this.getLine(); + this.addBlockWidget(new BlockWidgetView(deco.widget || new NullWidget("div"), len, type)); + } + else { + let view = WidgetView.create(deco.widget || new NullWidget("span"), len, deco.startSide); + let cursorBefore = this.atCursorPos && !view.isEditable && openStart <= active.length && (from < to || deco.startSide > 0); + let cursorAfter = !view.isEditable && (from < to || deco.startSide <= 0); + let line = this.getLine(); + if (this.pendingBuffer == 2 /* Buf.IfCursor */ && !cursorBefore) + this.pendingBuffer = 0 /* Buf.No */; + this.flushBuffer(active); + if (cursorBefore) { + line.append(wrapMarks(new WidgetBufferView(1), active), openStart); + openStart = active.length + Math.max(0, openStart - active.length); + } + line.append(wrapMarks(view, active), openStart); + this.atCursorPos = cursorAfter; + this.pendingBuffer = !cursorAfter ? 0 /* Buf.No */ : from < to ? 1 /* Buf.Yes */ : 2 /* Buf.IfCursor */; + } + } + else if (this.doc.lineAt(this.pos).from == this.pos) { // Line decoration + this.getLine().addLineDeco(deco); + } + if (len) { + // Advance the iterator past the replaced content + if (this.textOff + len <= this.text.length) { + this.textOff += len; + } + else { + this.skip += len - (this.text.length - this.textOff); + this.text = ""; + this.textOff = 0; + } + this.pos = to; + } + if (this.openStart < 0) + this.openStart = openStart; + } + static build(text, from, to, decorations, dynamicDecorationMap) { + let builder = new ContentBuilder(text, from, to, dynamicDecorationMap); + builder.openEnd = RangeSet.spans(decorations, from, to, builder); + if (builder.openStart < 0) + builder.openStart = builder.openEnd; + builder.finish(builder.openEnd); + return builder; + } + } + function wrapMarks(view, active) { + for (let mark of active) + view = new MarkView(mark, [view], view.length); + return view; + } + class NullWidget extends WidgetType { + constructor(tag) { + super(); + this.tag = tag; + } + eq(other) { return other.tag == this.tag; } + toDOM() { return document.createElement(this.tag); } + updateDOM(elt) { return elt.nodeName.toLowerCase() == this.tag; } + } + + const clickAddsSelectionRange = /*@__PURE__*/Facet.define(); + const dragMovesSelection$1 = /*@__PURE__*/Facet.define(); + const mouseSelectionStyle = /*@__PURE__*/Facet.define(); + const exceptionSink = /*@__PURE__*/Facet.define(); + const updateListener = /*@__PURE__*/Facet.define(); + const inputHandler$1 = /*@__PURE__*/Facet.define(); + const perLineTextDirection = /*@__PURE__*/Facet.define({ + combine: values => values.some(x => x) + }); + class ScrollTarget { + constructor(range, y = "nearest", x = "nearest", yMargin = 5, xMargin = 5) { + this.range = range; + this.y = y; + this.x = x; + this.yMargin = yMargin; + this.xMargin = xMargin; + } + map(changes) { + return changes.empty ? this : new ScrollTarget(this.range.map(changes), this.y, this.x, this.yMargin, this.xMargin); + } + } + const scrollIntoView$1 = /*@__PURE__*/StateEffect.define({ map: (t, ch) => t.map(ch) }); + /** + Log or report an unhandled exception in client code. Should + probably only be used by extension code that allows client code to + provide functions, and calls those functions in a context where an + exception can't be propagated to calling code in a reasonable way + (for example when in an event handler). + + Either calls a handler registered with + [`EditorView.exceptionSink`](https://codemirror.net/6/docs/ref/#view.EditorView^exceptionSink), + `window.onerror`, if defined, or `console.error` (in which case + it'll pass `context`, when given, as first argument). + */ + function logException(state, exception, context) { + let handler = state.facet(exceptionSink); + if (handler.length) + handler[0](exception); + else if (window.onerror) + window.onerror(String(exception), context, undefined, undefined, exception); + else if (context) + console.error(context + ":", exception); + else + console.error(exception); + } + const editable = /*@__PURE__*/Facet.define({ combine: values => values.length ? values[0] : true }); + let nextPluginID = 0; + const viewPlugin = /*@__PURE__*/Facet.define(); + /** + View plugins associate stateful values with a view. They can + influence the way the content is drawn, and are notified of things + that happen in the view. + */ + class ViewPlugin { + constructor( + /** + @internal + */ + id, + /** + @internal + */ + create, + /** + @internal + */ + domEventHandlers, buildExtensions) { + this.id = id; + this.create = create; + this.domEventHandlers = domEventHandlers; + this.extension = buildExtensions(this); + } + /** + Define a plugin from a constructor function that creates the + plugin's value, given an editor view. + */ + static define(create, spec) { + const { eventHandlers, provide, decorations: deco } = spec || {}; + return new ViewPlugin(nextPluginID++, create, eventHandlers, plugin => { + let ext = [viewPlugin.of(plugin)]; + if (deco) + ext.push(decorations.of(view => { + let pluginInst = view.plugin(plugin); + return pluginInst ? deco(pluginInst) : Decoration.none; + })); + if (provide) + ext.push(provide(plugin)); + return ext; + }); + } + /** + Create a plugin for a class whose constructor takes a single + editor view as argument. + */ + static fromClass(cls, spec) { + return ViewPlugin.define(view => new cls(view), spec); + } + } + class PluginInstance { + constructor(spec) { + this.spec = spec; + // When starting an update, all plugins have this field set to the + // update object, indicating they need to be updated. When finished + // updating, it is set to `false`. Retrieving a plugin that needs to + // be updated with `view.plugin` forces an eager update. + this.mustUpdate = null; + // This is null when the plugin is initially created, but + // initialized on the first update. + this.value = null; + } + update(view) { + if (!this.value) { + if (this.spec) { + try { + this.value = this.spec.create(view); + } + catch (e) { + logException(view.state, e, "CodeMirror plugin crashed"); + this.deactivate(); + } + } + } + else if (this.mustUpdate) { + let update = this.mustUpdate; + this.mustUpdate = null; + if (this.value.update) { + try { + this.value.update(update); + } + catch (e) { + logException(update.state, e, "CodeMirror plugin crashed"); + if (this.value.destroy) + try { + this.value.destroy(); + } + catch (_) { } + this.deactivate(); + } + } + } + return this; + } + destroy(view) { + var _a; + if ((_a = this.value) === null || _a === void 0 ? void 0 : _a.destroy) { + try { + this.value.destroy(); + } + catch (e) { + logException(view.state, e, "CodeMirror plugin crashed"); + } + } + } + deactivate() { + this.spec = this.value = null; + } + } + const editorAttributes = /*@__PURE__*/Facet.define(); + const contentAttributes = /*@__PURE__*/Facet.define(); + // Provide decorations + const decorations = /*@__PURE__*/Facet.define(); + const atomicRanges = /*@__PURE__*/Facet.define(); + const scrollMargins = /*@__PURE__*/Facet.define(); + const styleModule = /*@__PURE__*/Facet.define(); + class ChangedRange { + constructor(fromA, toA, fromB, toB) { + this.fromA = fromA; + this.toA = toA; + this.fromB = fromB; + this.toB = toB; + } + join(other) { + return new ChangedRange(Math.min(this.fromA, other.fromA), Math.max(this.toA, other.toA), Math.min(this.fromB, other.fromB), Math.max(this.toB, other.toB)); + } + addToSet(set) { + let i = set.length, me = this; + for (; i > 0; i--) { + let range = set[i - 1]; + if (range.fromA > me.toA) + continue; + if (range.toA < me.fromA) + break; + me = me.join(range); + set.splice(i - 1, 1); + } + set.splice(i, 0, me); + return set; + } + static extendWithRanges(diff, ranges) { + if (ranges.length == 0) + return diff; + let result = []; + for (let dI = 0, rI = 0, posA = 0, posB = 0;; dI++) { + let next = dI == diff.length ? null : diff[dI], off = posA - posB; + let end = next ? next.fromB : 1e9; + while (rI < ranges.length && ranges[rI] < end) { + let from = ranges[rI], to = ranges[rI + 1]; + let fromB = Math.max(posB, from), toB = Math.min(end, to); + if (fromB <= toB) + new ChangedRange(fromB + off, toB + off, fromB, toB).addToSet(result); + if (to > end) + break; + else + rI += 2; + } + if (!next) + return result; + new ChangedRange(next.fromA, next.toA, next.fromB, next.toB).addToSet(result); + posA = next.toA; + posB = next.toB; + } + } + } + /** + View [plugins](https://codemirror.net/6/docs/ref/#view.ViewPlugin) are given instances of this + class, which describe what happened, whenever the view is updated. + */ + class ViewUpdate { + constructor( + /** + The editor view that the update is associated with. + */ + view, + /** + The new editor state. + */ + state, + /** + The transactions involved in the update. May be empty. + */ + transactions) { + this.view = view; + this.state = state; + this.transactions = transactions; + /** + @internal + */ + this.flags = 0; + this.startState = view.state; + this.changes = ChangeSet.empty(this.startState.doc.length); + for (let tr of transactions) + this.changes = this.changes.compose(tr.changes); + let changedRanges = []; + this.changes.iterChangedRanges((fromA, toA, fromB, toB) => changedRanges.push(new ChangedRange(fromA, toA, fromB, toB))); + this.changedRanges = changedRanges; + let focus = view.hasFocus; + if (focus != view.inputState.notifiedFocused) { + view.inputState.notifiedFocused = focus; + this.flags |= 1 /* UpdateFlag.Focus */; + } + } + /** + @internal + */ + static create(view, state, transactions) { + return new ViewUpdate(view, state, transactions); + } + /** + Tells you whether the [viewport](https://codemirror.net/6/docs/ref/#view.EditorView.viewport) or + [visible ranges](https://codemirror.net/6/docs/ref/#view.EditorView.visibleRanges) changed in this + update. + */ + get viewportChanged() { + return (this.flags & 4 /* UpdateFlag.Viewport */) > 0; + } + /** + Indicates whether the height of a block element in the editor + changed in this update. + */ + get heightChanged() { + return (this.flags & 2 /* UpdateFlag.Height */) > 0; + } + /** + Returns true when the document was modified or the size of the + editor, or elements within the editor, changed. + */ + get geometryChanged() { + return this.docChanged || (this.flags & (8 /* UpdateFlag.Geometry */ | 2 /* UpdateFlag.Height */)) > 0; + } + /** + True when this update indicates a focus change. + */ + get focusChanged() { + return (this.flags & 1 /* UpdateFlag.Focus */) > 0; + } + /** + Whether the document changed in this update. + */ + get docChanged() { + return !this.changes.empty; + } + /** + Whether the selection was explicitly set in this update. + */ + get selectionSet() { + return this.transactions.some(tr => tr.selection); + } + /** + @internal + */ + get empty() { return this.flags == 0 && this.transactions.length == 0; } + } + + /** + Used to indicate [text direction](https://codemirror.net/6/docs/ref/#view.EditorView.textDirection). + */ + var Direction = /*@__PURE__*/(function (Direction) { + // (These are chosen to match the base levels, in bidi algorithm + // terms, of spans in that direction.) + /** + Left-to-right. + */ + Direction[Direction["LTR"] = 0] = "LTR"; + /** + Right-to-left. + */ + Direction[Direction["RTL"] = 1] = "RTL"; + return Direction})(Direction || (Direction = {})); + const LTR = Direction.LTR, RTL = Direction.RTL; + // Decode a string with each type encoded as log2(type) + function dec(str) { + let result = []; + for (let i = 0; i < str.length; i++) + result.push(1 << +str[i]); + return result; + } + // Character types for codepoints 0 to 0xf8 + const LowTypes = /*@__PURE__*/dec("88888888888888888888888888888888888666888888787833333333337888888000000000000000000000000008888880000000000000000000000000088888888888888888888888888888888888887866668888088888663380888308888800000000000000000000000800000000000000000000000000000008"); + // Character types for codepoints 0x600 to 0x6f9 + const ArabicTypes = /*@__PURE__*/dec("4444448826627288999999999992222222222222222222222222222222222222222222222229999999999999999999994444444444644222822222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222999999949999999229989999223333333333"); + const Brackets = /*@__PURE__*/Object.create(null), BracketStack = []; + // There's a lot more in + // https://www.unicode.org/Public/UCD/latest/ucd/BidiBrackets.txt, + // which are left out to keep code size down. + for (let p of ["()", "[]", "{}"]) { + let l = /*@__PURE__*/p.charCodeAt(0), r = /*@__PURE__*/p.charCodeAt(1); + Brackets[l] = r; + Brackets[r] = -l; + } + function charType(ch) { + return ch <= 0xf7 ? LowTypes[ch] : + 0x590 <= ch && ch <= 0x5f4 ? 2 /* T.R */ : + 0x600 <= ch && ch <= 0x6f9 ? ArabicTypes[ch - 0x600] : + 0x6ee <= ch && ch <= 0x8ac ? 4 /* T.AL */ : + 0x2000 <= ch && ch <= 0x200b ? 256 /* T.NI */ : + 0xfb50 <= ch && ch <= 0xfdff ? 4 /* T.AL */ : + ch == 0x200c ? 256 /* T.NI */ : 1 /* T.L */; + } + const BidiRE = /[\u0590-\u05f4\u0600-\u06ff\u0700-\u08ac\ufb50-\ufdff]/; + /** + Represents a contiguous range of text that has a single direction + (as in left-to-right or right-to-left). + */ + class BidiSpan { + /** + @internal + */ + constructor( + /** + The start of the span (relative to the start of the line). + */ + from, + /** + The end of the span. + */ + to, + /** + The ["bidi + level"](https://unicode.org/reports/tr9/#Basic_Display_Algorithm) + of the span (in this context, 0 means + left-to-right, 1 means right-to-left, 2 means left-to-right + number inside right-to-left text). + */ + level) { + this.from = from; + this.to = to; + this.level = level; + } + /** + The direction of this span. + */ + get dir() { return this.level % 2 ? RTL : LTR; } + /** + @internal + */ + side(end, dir) { return (this.dir == dir) == end ? this.to : this.from; } + /** + @internal + */ + static find(order, index, level, assoc) { + let maybe = -1; + for (let i = 0; i < order.length; i++) { + let span = order[i]; + if (span.from <= index && span.to >= index) { + if (span.level == level) + return i; + // When multiple spans match, if assoc != 0, take the one that + // covers that side, otherwise take the one with the minimum + // level. + if (maybe < 0 || (assoc != 0 ? (assoc < 0 ? span.from < index : span.to > index) : order[maybe].level > span.level)) + maybe = i; + } + } + if (maybe < 0) + throw new RangeError("Index out of range"); + return maybe; + } + } + // Reused array of character types + const types = []; + function computeOrder(line, direction) { + let len = line.length, outerType = direction == LTR ? 1 /* T.L */ : 2 /* T.R */, oppositeType = direction == LTR ? 2 /* T.R */ : 1 /* T.L */; + if (!line || outerType == 1 /* T.L */ && !BidiRE.test(line)) + return trivialOrder(len); + // 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. + // 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. + // (Left after this: L, R, EN, AN, ET, CS, NI) + for (let i = 0, prev = outerType, prevStrong = outerType; i < len; i++) { + let type = charType(line.charCodeAt(i)); + if (type == 512 /* T.NSM */) + type = prev; + else if (type == 8 /* T.EN */ && prevStrong == 4 /* T.AL */) + type = 16 /* T.AN */; + types[i] = type == 4 /* T.AL */ ? 2 /* T.R */ : type; + if (type & 7 /* T.Strong */) + prevStrong = type; + prev = type; + } + // W5. A sequence of European terminators adjacent to European + // numbers changes to all European numbers. + // W6. Otherwise, separators and terminators change to Other + // Neutral. + // 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. + // (Left after this: L, R, EN+AN, NI) + for (let i = 0, prev = outerType, prevStrong = outerType; i < len; i++) { + let type = types[i]; + if (type == 128 /* T.CS */) { + if (i < len - 1 && prev == types[i + 1] && (prev & 24 /* T.Num */)) + type = types[i] = prev; + else + types[i] = 256 /* T.NI */; + } + else if (type == 64 /* T.ET */) { + let end = i + 1; + while (end < len && types[end] == 64 /* T.ET */) + end++; + let replace = (i && prev == 8 /* T.EN */) || (end < len && types[end] == 8 /* T.EN */) ? (prevStrong == 1 /* T.L */ ? 1 /* T.L */ : 8 /* T.EN */) : 256 /* T.NI */; + for (let j = i; j < end; j++) + types[j] = replace; + i = end - 1; + } + else if (type == 8 /* T.EN */ && prevStrong == 1 /* T.L */) { + types[i] = 1 /* T.L */; + } + prev = type; + if (type & 7 /* T.Strong */) + prevStrong = type; + } + // N0. Process bracket pairs in an isolating run sequence + // sequentially in the logical order of the text positions of the + // opening paired brackets using the logic given below. Within this + // scope, bidirectional types EN and AN are treated as R. + for (let i = 0, sI = 0, context = 0, ch, br, type; i < len; i++) { + // Keeps [startIndex, type, strongSeen] triples for each open + // bracket on BracketStack. + if (br = Brackets[ch = line.charCodeAt(i)]) { + if (br < 0) { // Closing bracket + for (let sJ = sI - 3; sJ >= 0; sJ -= 3) { + if (BracketStack[sJ + 1] == -br) { + let flags = BracketStack[sJ + 2]; + let type = (flags & 2 /* Bracketed.EmbedInside */) ? outerType : + !(flags & 4 /* Bracketed.OppositeInside */) ? 0 : + (flags & 1 /* Bracketed.OppositeBefore */) ? oppositeType : outerType; + if (type) + types[i] = types[BracketStack[sJ]] = type; + sI = sJ; + break; + } + } + } + else if (BracketStack.length == 189 /* Bracketed.MaxDepth */) { + break; + } + else { + BracketStack[sI++] = i; + BracketStack[sI++] = ch; + BracketStack[sI++] = context; + } + } + else if ((type = types[i]) == 2 /* T.R */ || type == 1 /* T.L */) { + let embed = type == outerType; + context = embed ? 0 : 1 /* Bracketed.OppositeBefore */; + for (let sJ = sI - 3; sJ >= 0; sJ -= 3) { + let cur = BracketStack[sJ + 2]; + if (cur & 2 /* Bracketed.EmbedInside */) + break; + if (embed) { + BracketStack[sJ + 2] |= 2 /* Bracketed.EmbedInside */; + } + else { + if (cur & 4 /* Bracketed.OppositeInside */) + break; + BracketStack[sJ + 2] |= 4 /* Bracketed.OppositeInside */; + } + } + } + } + // 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. + // (Left after this: L, R, EN+AN) + for (let i = 0; i < len; i++) { + if (types[i] == 256 /* T.NI */) { + let end = i + 1; + while (end < len && types[end] == 256 /* T.NI */) + end++; + let beforeL = (i ? types[i - 1] : outerType) == 1 /* T.L */; + let afterL = (end < len ? types[end] : outerType) == 1 /* T.L */; + let replace = beforeL == afterL ? (beforeL ? 1 /* T.L */ : 2 /* T.R */) : outerType; + for (let j = i; j < end; j++) + types[j] = replace; + i = end - 1; + } + } + // Here we depart from the documented algorithm, in order to avoid + // building up an actual levels array. Since there are only three + // levels (0, 1, 2) in an implementation that doesn't take + // explicit embedding into account, we can build up the order on + // the fly, without following the level-based algorithm. + let order = []; + if (outerType == 1 /* T.L */) { + for (let i = 0; i < len;) { + let start = i, rtl = types[i++] != 1 /* T.L */; + while (i < len && rtl == (types[i] != 1 /* T.L */)) + i++; + if (rtl) { + for (let j = i; j > start;) { + let end = j, l = types[--j] != 2 /* T.R */; + while (j > start && l == (types[j - 1] != 2 /* T.R */)) + j--; + order.push(new BidiSpan(j, end, l ? 2 : 1)); + } + } + else { + order.push(new BidiSpan(start, i, 0)); + } + } + } + else { + for (let i = 0; i < len;) { + let start = i, rtl = types[i++] == 2 /* T.R */; + while (i < len && rtl == (types[i] == 2 /* T.R */)) + i++; + order.push(new BidiSpan(start, i, rtl ? 1 : 2)); + } + } + return order; + } + function trivialOrder(length) { + return [new BidiSpan(0, length, 0)]; + } + let movedOver = ""; + function moveVisually(line, order, dir, start, forward) { + var _a; + let startIndex = start.head - line.from, spanI = -1; + if (startIndex == 0) { + if (!forward || !line.length) + return null; + if (order[0].level != dir) { + startIndex = order[0].side(false, dir); + spanI = 0; + } + } + else if (startIndex == line.length) { + if (forward) + return null; + let last = order[order.length - 1]; + if (last.level != dir) { + startIndex = last.side(true, dir); + spanI = order.length - 1; + } + } + if (spanI < 0) + spanI = BidiSpan.find(order, startIndex, (_a = start.bidiLevel) !== null && _a !== void 0 ? _a : -1, start.assoc); + let span = order[spanI]; + // End of span. (But not end of line--that was checked for above.) + if (startIndex == span.side(forward, dir)) { + span = order[spanI += forward ? 1 : -1]; + startIndex = span.side(!forward, dir); + } + let indexForward = forward == (span.dir == dir); + let nextIndex = findClusterBreak(line.text, startIndex, indexForward); + movedOver = line.text.slice(Math.min(startIndex, nextIndex), Math.max(startIndex, nextIndex)); + if (nextIndex != span.side(forward, dir)) + return EditorSelection.cursor(nextIndex + line.from, indexForward ? -1 : 1, span.level); + let nextSpan = spanI == (forward ? order.length - 1 : 0) ? null : order[spanI + (forward ? 1 : -1)]; + if (!nextSpan && span.level != dir) + return EditorSelection.cursor(forward ? line.to : line.from, forward ? -1 : 1, dir); + if (nextSpan && nextSpan.level < span.level) + return EditorSelection.cursor(nextSpan.side(!forward, dir) + line.from, forward ? 1 : -1, nextSpan.level); + return EditorSelection.cursor(nextIndex + line.from, forward ? -1 : 1, span.level); + } + + const LineBreakPlaceholder = "\uffff"; + class DOMReader { + constructor(points, state) { + this.points = points; + this.text = ""; + this.lineSeparator = state.facet(EditorState.lineSeparator); + } + append(text) { + this.text += text; + } + lineBreak() { + this.text += LineBreakPlaceholder; + } + readRange(start, end) { + if (!start) + return this; + let parent = start.parentNode; + for (let cur = start;;) { + this.findPointBefore(parent, cur); + this.readNode(cur); + let next = cur.nextSibling; + if (next == end) + break; + let view = ContentView.get(cur), nextView = ContentView.get(next); + if (view && nextView ? view.breakAfter : + (view ? view.breakAfter : isBlockElement(cur)) || + (isBlockElement(next) && (cur.nodeName != "BR" || cur.cmIgnore))) + this.lineBreak(); + cur = next; + } + this.findPointBefore(parent, end); + return this; + } + readTextNode(node) { + let text = node.nodeValue; + for (let point of this.points) + if (point.node == node) + point.pos = this.text.length + Math.min(point.offset, text.length); + for (let off = 0, re = this.lineSeparator ? null : /\r\n?|\n/g;;) { + let nextBreak = -1, breakSize = 1, m; + if (this.lineSeparator) { + nextBreak = text.indexOf(this.lineSeparator, off); + breakSize = this.lineSeparator.length; + } + else if (m = re.exec(text)) { + nextBreak = m.index; + breakSize = m[0].length; + } + this.append(text.slice(off, nextBreak < 0 ? text.length : nextBreak)); + if (nextBreak < 0) + break; + this.lineBreak(); + if (breakSize > 1) + for (let point of this.points) + if (point.node == node && point.pos > this.text.length) + point.pos -= breakSize - 1; + off = nextBreak + breakSize; + } + } + readNode(node) { + if (node.cmIgnore) + return; + let view = ContentView.get(node); + let fromView = view && view.overrideDOMText; + if (fromView != null) { + this.findPointInside(node, fromView.length); + for (let i = fromView.iter(); !i.next().done;) { + if (i.lineBreak) + this.lineBreak(); + else + this.append(i.value); + } + } + else if (node.nodeType == 3) { + this.readTextNode(node); + } + else if (node.nodeName == "BR") { + if (node.nextSibling) + this.lineBreak(); + } + else if (node.nodeType == 1) { + this.readRange(node.firstChild, null); + } + } + findPointBefore(node, next) { + for (let point of this.points) + if (point.node == node && node.childNodes[point.offset] == next) + point.pos = this.text.length; + } + findPointInside(node, maxLen) { + for (let point of this.points) + if (node.nodeType == 3 ? point.node == node : node.contains(point.node)) + point.pos = this.text.length + Math.min(maxLen, point.offset); + } + } + function isBlockElement(node) { + return node.nodeType == 1 && /^(DIV|P|LI|UL|OL|BLOCKQUOTE|DD|DT|H\d|SECTION|PRE)$/.test(node.nodeName); + } + class DOMPoint { + constructor(node, offset) { + this.node = node; + this.offset = offset; + this.pos = -1; + } + } + + class DocView extends ContentView { + constructor(view) { + super(); + this.view = view; + this.compositionDeco = Decoration.none; + this.decorations = []; + this.dynamicDecorationMap = []; + // Track a minimum width for the editor. When measuring sizes in + // measureVisibleLineHeights, this is updated to point at the width + // of a given element and its extent in the document. When a change + // happens in that range, these are reset. That way, once we've seen + // a line/element of a given length, we keep the editor wide enough + // to fit at least that element, until it is changed, at which point + // we forget it again. + this.minWidth = 0; + this.minWidthFrom = 0; + this.minWidthTo = 0; + // Track whether the DOM selection was set in a lossy way, so that + // we don't mess it up when reading it back it + this.impreciseAnchor = null; + this.impreciseHead = null; + this.forceSelection = false; + // Used by the resize observer to ignore resizes that we caused + // ourselves + this.lastUpdate = Date.now(); + this.setDOM(view.contentDOM); + this.children = [new LineView]; + this.children[0].setParent(this); + this.updateDeco(); + this.updateInner([new ChangedRange(0, 0, 0, view.state.doc.length)], 0); + } + get editorView() { return this.view; } + get length() { return this.view.state.doc.length; } + // Update the document view to a given state. scrollIntoView can be + // used as a hint to compute a new viewport that includes that + // position, if we know the editor is going to scroll that position + // into view. + update(update) { + let changedRanges = update.changedRanges; + if (this.minWidth > 0 && changedRanges.length) { + if (!changedRanges.every(({ fromA, toA }) => toA < this.minWidthFrom || fromA > this.minWidthTo)) { + this.minWidth = this.minWidthFrom = this.minWidthTo = 0; + } + else { + this.minWidthFrom = update.changes.mapPos(this.minWidthFrom, 1); + this.minWidthTo = update.changes.mapPos(this.minWidthTo, 1); + } + } + if (this.view.inputState.composing < 0) + this.compositionDeco = Decoration.none; + else if (update.transactions.length || this.dirty) + this.compositionDeco = computeCompositionDeco(this.view, update.changes); + // When the DOM nodes around the selection are moved to another + // parent, Chrome sometimes reports a different selection through + // getSelection than the one that it actually shows to the user. + // This forces a selection update when lines are joined to work + // around that. Issue #54 + if ((browser.ie || browser.chrome) && !this.compositionDeco.size && update && + update.state.doc.lines != update.startState.doc.lines) + this.forceSelection = true; + let prevDeco = this.decorations, deco = this.updateDeco(); + let decoDiff = findChangedDeco(prevDeco, deco, update.changes); + changedRanges = ChangedRange.extendWithRanges(changedRanges, decoDiff); + if (this.dirty == 0 /* Dirty.Not */ && changedRanges.length == 0) { + return false; + } + else { + this.updateInner(changedRanges, update.startState.doc.length); + if (update.transactions.length) + this.lastUpdate = Date.now(); + return true; + } + } + // Used by update and the constructor do perform the actual DOM + // update + updateInner(changes, oldLength) { + this.view.viewState.mustMeasureContent = true; + this.updateChildren(changes, oldLength); + let { observer } = this.view; + observer.ignore(() => { + // Lock the height during redrawing, since Chrome sometimes + // messes with the scroll position during DOM mutation (though + // no relayout is triggered and I cannot imagine how it can + // recompute the scroll position without a layout) + this.dom.style.height = this.view.viewState.contentHeight + "px"; + this.dom.style.flexBasis = this.minWidth ? this.minWidth + "px" : ""; + // Chrome will sometimes, when DOM mutations occur directly + // around the selection, get confused and report a different + // selection from the one it displays (issue #218). This tries + // to detect that situation. + let track = browser.chrome || browser.ios ? { node: observer.selectionRange.focusNode, written: false } : undefined; + this.sync(track); + this.dirty = 0 /* Dirty.Not */; + if (track && (track.written || observer.selectionRange.focusNode != track.node)) + this.forceSelection = true; + this.dom.style.height = ""; + }); + let gaps = []; + if (this.view.viewport.from || this.view.viewport.to < this.view.state.doc.length) + for (let child of this.children) + if (child instanceof BlockWidgetView && child.widget instanceof BlockGapWidget) + gaps.push(child.dom); + observer.updateGaps(gaps); + } + updateChildren(changes, oldLength) { + let cursor = this.childCursor(oldLength); + for (let i = changes.length - 1;; i--) { + let next = i >= 0 ? changes[i] : null; + if (!next) + break; + let { fromA, toA, fromB, toB } = next; + let { content, breakAtStart, openStart, openEnd } = ContentBuilder.build(this.view.state.doc, fromB, toB, this.decorations, this.dynamicDecorationMap); + let { i: toI, off: toOff } = cursor.findPos(toA, 1); + let { i: fromI, off: fromOff } = cursor.findPos(fromA, -1); + replaceRange(this, fromI, fromOff, toI, toOff, content, breakAtStart, openStart, openEnd); + } + } + // Sync the DOM selection to this.state.selection + updateSelection(mustRead = false, fromPointer = false) { + if (mustRead || !this.view.observer.selectionRange.focusNode) + this.view.observer.readSelectionRange(); + if (!(fromPointer || this.mayControlSelection())) + return; + let force = this.forceSelection; + this.forceSelection = false; + let main = this.view.state.selection.main; + // FIXME need to handle the case where the selection falls inside a block range + let anchor = this.domAtPos(main.anchor); + let head = main.empty ? anchor : this.domAtPos(main.head); + // Always reset on Firefox when next to an uneditable node to + // avoid invisible cursor bugs (#111) + if (browser.gecko && main.empty && betweenUneditable(anchor)) { + let dummy = document.createTextNode(""); + this.view.observer.ignore(() => anchor.node.insertBefore(dummy, anchor.node.childNodes[anchor.offset] || null)); + anchor = head = new DOMPos(dummy, 0); + force = true; + } + let domSel = this.view.observer.selectionRange; + // If the selection is already here, or in an equivalent position, don't touch it + if (force || !domSel.focusNode || + !isEquivalentPosition(anchor.node, anchor.offset, domSel.anchorNode, domSel.anchorOffset) || + !isEquivalentPosition(head.node, head.offset, domSel.focusNode, domSel.focusOffset)) { + this.view.observer.ignore(() => { + // Chrome Android will hide the virtual keyboard when tapping + // inside an uneditable node, and not bring it back when we + // move the cursor to its proper position. This tries to + // restore the keyboard by cycling focus. + if (browser.android && browser.chrome && this.dom.contains(domSel.focusNode) && + inUneditable(domSel.focusNode, this.dom)) { + this.dom.blur(); + this.dom.focus({ preventScroll: true }); + } + let rawSel = getSelection(this.view.root); + if (!rawSel) ; + else if (main.empty) { + // Work around https://bugzilla.mozilla.org/show_bug.cgi?id=1612076 + if (browser.gecko) { + let nextTo = nextToUneditable(anchor.node, anchor.offset); + if (nextTo && nextTo != (1 /* NextTo.Before */ | 2 /* NextTo.After */)) { + let text = nearbyTextNode(anchor.node, anchor.offset, nextTo == 1 /* NextTo.Before */ ? 1 : -1); + if (text) + anchor = new DOMPos(text, nextTo == 1 /* NextTo.Before */ ? 0 : text.nodeValue.length); + } + } + rawSel.collapse(anchor.node, anchor.offset); + if (main.bidiLevel != null && domSel.cursorBidiLevel != null) + domSel.cursorBidiLevel = main.bidiLevel; + } + else if (rawSel.extend) { + // Selection.extend can be used to create an 'inverted' selection + // (one where the focus is before the anchor), but not all + // browsers support it yet. + rawSel.collapse(anchor.node, anchor.offset); + // Safari will ignore the call above when the editor is + // hidden, and then raise an error on the call to extend + // (#940). + try { + rawSel.extend(head.node, head.offset); + } + catch (_) { } + } + else { + // Primitive (IE) way + let range = document.createRange(); + if (main.anchor > main.head) + [anchor, head] = [head, anchor]; + range.setEnd(head.node, head.offset); + range.setStart(anchor.node, anchor.offset); + rawSel.removeAllRanges(); + rawSel.addRange(range); + } + }); + this.view.observer.setSelectionRange(anchor, head); + } + this.impreciseAnchor = anchor.precise ? null : new DOMPos(domSel.anchorNode, domSel.anchorOffset); + this.impreciseHead = head.precise ? null : new DOMPos(domSel.focusNode, domSel.focusOffset); + } + enforceCursorAssoc() { + if (this.compositionDeco.size) + return; + let cursor = this.view.state.selection.main; + let sel = getSelection(this.view.root); + if (!sel || !cursor.empty || !cursor.assoc || !sel.modify) + return; + let line = LineView.find(this, cursor.head); + if (!line) + return; + let lineStart = line.posAtStart; + if (cursor.head == lineStart || cursor.head == lineStart + line.length) + return; + let before = this.coordsAt(cursor.head, -1), after = this.coordsAt(cursor.head, 1); + if (!before || !after || before.bottom > after.top) + return; + let dom = this.domAtPos(cursor.head + cursor.assoc); + sel.collapse(dom.node, dom.offset); + sel.modify("move", cursor.assoc < 0 ? "forward" : "backward", "lineboundary"); + } + mayControlSelection() { + let active = this.view.root.activeElement; + return active == this.dom || + hasSelection(this.dom, this.view.observer.selectionRange) && !(active && this.dom.contains(active)); + } + nearest(dom) { + for (let cur = dom; cur;) { + let domView = ContentView.get(cur); + if (domView && domView.rootView == this) + return domView; + cur = cur.parentNode; + } + return null; + } + posFromDOM(node, offset) { + let view = this.nearest(node); + if (!view) + throw new RangeError("Trying to find position for a DOM position outside of the document"); + return view.localPosFromDOM(node, offset) + view.posAtStart; + } + domAtPos(pos) { + let { i, off } = this.childCursor().findPos(pos, -1); + for (; i < this.children.length - 1;) { + let child = this.children[i]; + if (off < child.length || child instanceof LineView) + break; + i++; + off = 0; + } + return this.children[i].domAtPos(off); + } + coordsAt(pos, side) { + for (let off = this.length, i = this.children.length - 1;; i--) { + let child = this.children[i], start = off - child.breakAfter - child.length; + if (pos > start || + (pos == start && child.type != BlockType.WidgetBefore && child.type != BlockType.WidgetAfter && + (!i || side == 2 || this.children[i - 1].breakAfter || + (this.children[i - 1].type == BlockType.WidgetBefore && side > -2)))) + return child.coordsAt(pos - start, side); + off = start; + } + } + measureVisibleLineHeights(viewport) { + let result = [], { from, to } = viewport; + let contentWidth = this.view.contentDOM.clientWidth; + let isWider = contentWidth > Math.max(this.view.scrollDOM.clientWidth, this.minWidth) + 1; + let widest = -1, ltr = this.view.textDirection == Direction.LTR; + for (let pos = 0, i = 0; i < this.children.length; i++) { + let child = this.children[i], end = pos + child.length; + if (end > to) + break; + if (pos >= from) { + let childRect = child.dom.getBoundingClientRect(); + result.push(childRect.height); + if (isWider) { + let last = child.dom.lastChild; + let rects = last ? clientRectsFor(last) : []; + if (rects.length) { + let rect = rects[rects.length - 1]; + let width = ltr ? rect.right - childRect.left : childRect.right - rect.left; + if (width > widest) { + widest = width; + this.minWidth = contentWidth; + this.minWidthFrom = pos; + this.minWidthTo = end; + } + } + } + } + pos = end + child.breakAfter; + } + return result; + } + textDirectionAt(pos) { + let { i } = this.childPos(pos, 1); + return getComputedStyle(this.children[i].dom).direction == "rtl" ? Direction.RTL : Direction.LTR; + } + measureTextSize() { + for (let child of this.children) { + if (child instanceof LineView) { + let measure = child.measureTextSize(); + if (measure) + return measure; + } + } + // If no workable line exists, force a layout of a measurable element + let dummy = document.createElement("div"), lineHeight, charWidth; + dummy.className = "cm-line"; + dummy.style.width = "99999px"; + dummy.textContent = "abc def ghi jkl mno pqr stu"; + this.view.observer.ignore(() => { + this.dom.appendChild(dummy); + let rect = clientRectsFor(dummy.firstChild)[0]; + lineHeight = dummy.getBoundingClientRect().height; + charWidth = rect ? rect.width / 27 : 7; + dummy.remove(); + }); + return { lineHeight, charWidth }; + } + childCursor(pos = this.length) { + // Move back to start of last element when possible, so that + // `ChildCursor.findPos` doesn't have to deal with the edge case + // of being after the last element. + let i = this.children.length; + if (i) + pos -= this.children[--i].length; + return new ChildCursor(this.children, pos, i); + } + computeBlockGapDeco() { + let deco = [], vs = this.view.viewState; + for (let pos = 0, i = 0;; i++) { + let next = i == vs.viewports.length ? null : vs.viewports[i]; + let end = next ? next.from - 1 : this.length; + if (end > pos) { + let height = vs.lineBlockAt(end).bottom - vs.lineBlockAt(pos).top; + deco.push(Decoration.replace({ + widget: new BlockGapWidget(height), + block: true, + inclusive: true, + isBlockGap: true, + }).range(pos, end)); + } + if (!next) + break; + pos = next.to + 1; + } + return Decoration.set(deco); + } + updateDeco() { + let allDeco = this.view.state.facet(decorations).map((d, i) => { + let dynamic = this.dynamicDecorationMap[i] = typeof d == "function"; + return dynamic ? d(this.view) : d; + }); + for (let i = allDeco.length; i < allDeco.length + 3; i++) + this.dynamicDecorationMap[i] = false; + return this.decorations = [ + ...allDeco, + this.compositionDeco, + this.computeBlockGapDeco(), + this.view.viewState.lineGapDeco + ]; + } + scrollIntoView(target) { + let { range } = target; + let rect = this.coordsAt(range.head, range.empty ? range.assoc : range.head > range.anchor ? -1 : 1), other; + if (!rect) + return; + if (!range.empty && (other = this.coordsAt(range.anchor, range.anchor > range.head ? -1 : 1))) + rect = { left: Math.min(rect.left, other.left), top: Math.min(rect.top, other.top), + right: Math.max(rect.right, other.right), bottom: Math.max(rect.bottom, other.bottom) }; + let mLeft = 0, mRight = 0, mTop = 0, mBottom = 0; + for (let margins of this.view.state.facet(scrollMargins).map(f => f(this.view))) + if (margins) { + let { left, right, top, bottom } = margins; + if (left != null) + mLeft = Math.max(mLeft, left); + if (right != null) + mRight = Math.max(mRight, right); + if (top != null) + mTop = Math.max(mTop, top); + if (bottom != null) + mBottom = Math.max(mBottom, bottom); + } + let targetRect = { + left: rect.left - mLeft, top: rect.top - mTop, + right: rect.right + mRight, bottom: rect.bottom + mBottom + }; + scrollRectIntoView(this.view.scrollDOM, targetRect, range.head < range.anchor ? -1 : 1, target.x, target.y, target.xMargin, target.yMargin, this.view.textDirection == Direction.LTR); + } + } + function betweenUneditable(pos) { + return pos.node.nodeType == 1 && pos.node.firstChild && + (pos.offset == 0 || pos.node.childNodes[pos.offset - 1].contentEditable == "false") && + (pos.offset == pos.node.childNodes.length || pos.node.childNodes[pos.offset].contentEditable == "false"); + } + class BlockGapWidget extends WidgetType { + constructor(height) { + super(); + this.height = height; + } + toDOM() { + let elt = document.createElement("div"); + this.updateDOM(elt); + return elt; + } + eq(other) { return other.height == this.height; } + updateDOM(elt) { + elt.style.height = this.height + "px"; + return true; + } + get estimatedHeight() { return this.height; } + } + function compositionSurroundingNode(view) { + let sel = view.observer.selectionRange; + let textNode = sel.focusNode && nearbyTextNode(sel.focusNode, sel.focusOffset, 0); + if (!textNode) + return null; + let cView = view.docView.nearest(textNode); + if (!cView) + return null; + if (cView instanceof LineView) { + let topNode = textNode; + while (topNode.parentNode != cView.dom) + topNode = topNode.parentNode; + let prev = topNode.previousSibling; + while (prev && !ContentView.get(prev)) + prev = prev.previousSibling; + let pos = prev ? ContentView.get(prev).posAtEnd : cView.posAtStart; + return { from: pos, to: pos, node: topNode, text: textNode }; + } + else { + for (;;) { + let { parent } = cView; + if (!parent) + return null; + if (parent instanceof LineView) + break; + cView = parent; + } + let from = cView.posAtStart; + return { from, to: from + cView.length, node: cView.dom, text: textNode }; + } + } + function computeCompositionDeco(view, changes) { + let surrounding = compositionSurroundingNode(view); + if (!surrounding) + return Decoration.none; + let { from, to, node, text: textNode } = surrounding; + let newFrom = changes.mapPos(from, 1), newTo = Math.max(newFrom, changes.mapPos(to, -1)); + let { state } = view, text = node.nodeType == 3 ? node.nodeValue : + new DOMReader([], state).readRange(node.firstChild, null).text; + if (newTo - newFrom < text.length) { + if (state.doc.sliceString(newFrom, Math.min(state.doc.length, newFrom + text.length), LineBreakPlaceholder) == text) + newTo = newFrom + text.length; + else if (state.doc.sliceString(Math.max(0, newTo - text.length), newTo, LineBreakPlaceholder) == text) + newFrom = newTo - text.length; + else + return Decoration.none; + } + else if (state.doc.sliceString(newFrom, newTo, LineBreakPlaceholder) != text) { + return Decoration.none; + } + let topView = ContentView.get(node); + if (topView instanceof CompositionView) + topView = topView.widget.topView; + else if (topView) + topView.parent = null; + return Decoration.set(Decoration.replace({ widget: new CompositionWidget(node, textNode, topView), inclusive: true }) + .range(newFrom, newTo)); + } + class CompositionWidget extends WidgetType { + constructor(top, text, topView) { + super(); + this.top = top; + this.text = text; + this.topView = topView; + } + eq(other) { return this.top == other.top && this.text == other.text; } + toDOM() { return this.top; } + ignoreEvent() { return false; } + get customView() { return CompositionView; } + } + function nearbyTextNode(node, offset, side) { + for (;;) { + if (node.nodeType == 3) + return node; + if (node.nodeType == 1 && offset > 0 && side <= 0) { + node = node.childNodes[offset - 1]; + offset = maxOffset(node); + } + else if (node.nodeType == 1 && offset < node.childNodes.length && side >= 0) { + node = node.childNodes[offset]; + offset = 0; + } + else { + return null; + } + } + } + function nextToUneditable(node, offset) { + if (node.nodeType != 1) + return 0; + return (offset && node.childNodes[offset - 1].contentEditable == "false" ? 1 /* NextTo.Before */ : 0) | + (offset < node.childNodes.length && node.childNodes[offset].contentEditable == "false" ? 2 /* NextTo.After */ : 0); + } + class DecorationComparator$1 { + constructor() { + this.changes = []; + } + compareRange(from, to) { addRange(from, to, this.changes); } + comparePoint(from, to) { addRange(from, to, this.changes); } + } + function findChangedDeco(a, b, diff) { + let comp = new DecorationComparator$1; + RangeSet.compare(a, b, diff, comp); + return comp.changes; + } + function inUneditable(node, inside) { + for (let cur = node; cur && cur != inside; cur = cur.assignedSlot || cur.parentNode) { + if (cur.nodeType == 1 && cur.contentEditable == 'false') { + return true; + } + } + return false; + } + + function groupAt(state, pos, bias = 1) { + let categorize = state.charCategorizer(pos); + let line = state.doc.lineAt(pos), linePos = pos - line.from; + if (line.length == 0) + return EditorSelection.cursor(pos); + if (linePos == 0) + bias = 1; + else if (linePos == line.length) + bias = -1; + let from = linePos, to = linePos; + if (bias < 0) + from = findClusterBreak(line.text, linePos, false); + else + to = findClusterBreak(line.text, linePos); + let cat = categorize(line.text.slice(from, to)); + while (from > 0) { + let prev = findClusterBreak(line.text, from, false); + if (categorize(line.text.slice(prev, from)) != cat) + break; + from = prev; + } + while (to < line.length) { + let next = findClusterBreak(line.text, to); + if (categorize(line.text.slice(to, next)) != cat) + break; + to = next; + } + return EditorSelection.range(from + line.from, to + line.from); + } + // Search the DOM for the {node, offset} position closest to the given + // coordinates. Very inefficient and crude, but can usually be avoided + // by calling caret(Position|Range)FromPoint instead. + function getdx(x, rect) { + return rect.left > x ? rect.left - x : Math.max(0, x - rect.right); + } + function getdy(y, rect) { + return rect.top > y ? rect.top - y : Math.max(0, y - rect.bottom); + } + function yOverlap(a, b) { + return a.top < b.bottom - 1 && a.bottom > b.top + 1; + } + function upTop(rect, top) { + return top < rect.top ? { top, left: rect.left, right: rect.right, bottom: rect.bottom } : rect; + } + function upBot(rect, bottom) { + return bottom > rect.bottom ? { top: rect.top, left: rect.left, right: rect.right, bottom } : rect; + } + function domPosAtCoords(parent, x, y) { + let closest, closestRect, closestX, closestY, closestOverlap = false; + let above, below, aboveRect, belowRect; + for (let child = parent.firstChild; child; child = child.nextSibling) { + let rects = clientRectsFor(child); + for (let i = 0; i < rects.length; i++) { + let rect = rects[i]; + if (closestRect && yOverlap(closestRect, rect)) + rect = upTop(upBot(rect, closestRect.bottom), closestRect.top); + let dx = getdx(x, rect), dy = getdy(y, rect); + if (dx == 0 && dy == 0) + return child.nodeType == 3 ? domPosInText(child, x, y) : domPosAtCoords(child, x, y); + if (!closest || closestY > dy || closestY == dy && closestX > dx) { + closest = child; + closestRect = rect; + closestX = dx; + closestY = dy; + closestOverlap = !dx || (dx > 0 ? i < rects.length - 1 : i > 0); + } + if (dx == 0) { + if (y > rect.bottom && (!aboveRect || aboveRect.bottom < rect.bottom)) { + above = child; + aboveRect = rect; + } + else if (y < rect.top && (!belowRect || belowRect.top > rect.top)) { + below = child; + belowRect = rect; + } + } + else if (aboveRect && yOverlap(aboveRect, rect)) { + aboveRect = upBot(aboveRect, rect.bottom); + } + else if (belowRect && yOverlap(belowRect, rect)) { + belowRect = upTop(belowRect, rect.top); + } + } + } + if (aboveRect && aboveRect.bottom >= y) { + closest = above; + closestRect = aboveRect; + } + else if (belowRect && belowRect.top <= y) { + closest = below; + closestRect = belowRect; + } + if (!closest) + return { node: parent, offset: 0 }; + let clipX = Math.max(closestRect.left, Math.min(closestRect.right, x)); + if (closest.nodeType == 3) + return domPosInText(closest, clipX, y); + if (closestOverlap && closest.contentEditable != "false") + return domPosAtCoords(closest, clipX, y); + let offset = Array.prototype.indexOf.call(parent.childNodes, closest) + + (x >= (closestRect.left + closestRect.right) / 2 ? 1 : 0); + return { node: parent, offset }; + } + function domPosInText(node, x, y) { + let len = node.nodeValue.length; + let closestOffset = -1, closestDY = 1e9, generalSide = 0; + for (let i = 0; i < len; i++) { + let rects = textRange(node, i, i + 1).getClientRects(); + for (let j = 0; j < rects.length; j++) { + let rect = rects[j]; + if (rect.top == rect.bottom) + continue; + if (!generalSide) + generalSide = x - rect.left; + let dy = (rect.top > y ? rect.top - y : y - rect.bottom) - 1; + if (rect.left - 1 <= x && rect.right + 1 >= x && dy < closestDY) { + let right = x >= (rect.left + rect.right) / 2, after = right; + if (browser.chrome || browser.gecko) { + // Check for RTL on browsers that support getting client + // rects for empty ranges. + let rectBefore = textRange(node, i).getBoundingClientRect(); + if (rectBefore.left == rect.right) + after = !right; + } + if (dy <= 0) + return { node, offset: i + (after ? 1 : 0) }; + closestOffset = i + (after ? 1 : 0); + closestDY = dy; + } + } + } + return { node, offset: closestOffset > -1 ? closestOffset : generalSide > 0 ? node.nodeValue.length : 0 }; + } + function posAtCoords(view, { x, y }, precise, bias = -1) { + var _a; + let content = view.contentDOM.getBoundingClientRect(), docTop = content.top + view.viewState.paddingTop; + let block, { docHeight } = view.viewState; + let yOffset = y - docTop; + if (yOffset < 0) + return 0; + if (yOffset > docHeight) + return view.state.doc.length; + // Scan for a text block near the queried y position + for (let halfLine = view.defaultLineHeight / 2, bounced = false;;) { + block = view.elementAtHeight(yOffset); + if (block.type == BlockType.Text) + break; + for (;;) { + // Move the y position out of this block + yOffset = bias > 0 ? block.bottom + halfLine : block.top - halfLine; + if (yOffset >= 0 && yOffset <= docHeight) + break; + // If the document consists entirely of replaced widgets, we + // won't find a text block, so return 0 + if (bounced) + return precise ? null : 0; + bounced = true; + bias = -bias; + } + } + y = docTop + yOffset; + let lineStart = block.from; + // If this is outside of the rendered viewport, we can't determine a position + if (lineStart < view.viewport.from) + return view.viewport.from == 0 ? 0 : precise ? null : posAtCoordsImprecise(view, content, block, x, y); + if (lineStart > view.viewport.to) + return view.viewport.to == view.state.doc.length ? view.state.doc.length : + precise ? null : posAtCoordsImprecise(view, content, block, x, y); + // Prefer ShadowRootOrDocument.elementFromPoint if present, fall back to document if not + let doc = view.dom.ownerDocument; + let root = view.root.elementFromPoint ? view.root : doc; + let element = root.elementFromPoint(x, y); + if (element && !view.contentDOM.contains(element)) + element = null; + // If the element is unexpected, clip x at the sides of the content area and try again + if (!element) { + x = Math.max(content.left + 1, Math.min(content.right - 1, x)); + element = root.elementFromPoint(x, y); + if (element && !view.contentDOM.contains(element)) + element = null; + } + // There's visible editor content under the point, so we can try + // using caret(Position|Range)FromPoint as a shortcut + let node, offset = -1; + if (element && ((_a = view.docView.nearest(element)) === null || _a === void 0 ? void 0 : _a.isEditable) != false) { + if (doc.caretPositionFromPoint) { + let pos = doc.caretPositionFromPoint(x, y); + if (pos) + ({ offsetNode: node, offset } = pos); + } + else if (doc.caretRangeFromPoint) { + let range = doc.caretRangeFromPoint(x, y); + if (range) { + ({ startContainer: node, startOffset: offset } = range); + if (!view.contentDOM.contains(node) || + browser.safari && isSuspiciousSafariCaretResult(node, offset, x) || + browser.chrome && isSuspiciousChromeCaretResult(node, offset, x)) + node = undefined; + } + } + } + // No luck, do our own (potentially expensive) search + if (!node || !view.docView.dom.contains(node)) { + let line = LineView.find(view.docView, lineStart); + if (!line) + return yOffset > block.top + block.height / 2 ? block.to : block.from; + ({ node, offset } = domPosAtCoords(line.dom, x, y)); + } + return view.docView.posFromDOM(node, offset); + } + function posAtCoordsImprecise(view, contentRect, block, x, y) { + let into = Math.round((x - contentRect.left) * view.defaultCharacterWidth); + if (view.lineWrapping && block.height > view.defaultLineHeight * 1.5) { + let line = Math.floor((y - block.top) / view.defaultLineHeight); + into += line * view.viewState.heightOracle.lineLength; + } + let content = view.state.sliceDoc(block.from, block.to); + return block.from + findColumn(content, into, view.state.tabSize); + } + // In case of a high line height, Safari's caretRangeFromPoint treats + // the space between lines as belonging to the last character of the + // line before. This is used to detect such a result so that it can be + // ignored (issue #401). + function isSuspiciousSafariCaretResult(node, offset, x) { + let len; + if (node.nodeType != 3 || offset != (len = node.nodeValue.length)) + return false; + for (let next = node.nextSibling; next; next = next.nextSibling) + if (next.nodeType != 1 || next.nodeName != "BR") + return false; + return textRange(node, len - 1, len).getBoundingClientRect().left > x; + } + // Chrome will move positions between lines to the start of the next line + function isSuspiciousChromeCaretResult(node, offset, x) { + if (offset != 0) + return false; + for (let cur = node;;) { + let parent = cur.parentNode; + if (!parent || parent.nodeType != 1 || parent.firstChild != cur) + return false; + if (parent.classList.contains("cm-line")) + break; + cur = parent; + } + let rect = node.nodeType == 1 ? node.getBoundingClientRect() + : textRange(node, 0, Math.max(node.nodeValue.length, 1)).getBoundingClientRect(); + return x - rect.left > 5; + } + function moveToLineBoundary(view, start, forward, includeWrap) { + let line = view.state.doc.lineAt(start.head); + let coords = !includeWrap || !view.lineWrapping ? null + : view.coordsAtPos(start.assoc < 0 && start.head > line.from ? start.head - 1 : start.head); + if (coords) { + let editorRect = view.dom.getBoundingClientRect(); + let direction = view.textDirectionAt(line.from); + let pos = view.posAtCoords({ x: forward == (direction == Direction.LTR) ? editorRect.right - 1 : editorRect.left + 1, + y: (coords.top + coords.bottom) / 2 }); + if (pos != null) + return EditorSelection.cursor(pos, forward ? -1 : 1); + } + let lineView = LineView.find(view.docView, start.head); + let end = lineView ? (forward ? lineView.posAtEnd : lineView.posAtStart) : (forward ? line.to : line.from); + return EditorSelection.cursor(end, forward ? -1 : 1); + } + function moveByChar(view, start, forward, by) { + let line = view.state.doc.lineAt(start.head), spans = view.bidiSpans(line); + let direction = view.textDirectionAt(line.from); + for (let cur = start, check = null;;) { + let next = moveVisually(line, spans, direction, cur, forward), char = movedOver; + if (!next) { + if (line.number == (forward ? view.state.doc.lines : 1)) + return cur; + char = "\n"; + line = view.state.doc.line(line.number + (forward ? 1 : -1)); + spans = view.bidiSpans(line); + next = EditorSelection.cursor(forward ? line.from : line.to); + } + if (!check) { + if (!by) + return next; + check = by(char); + } + else if (!check(char)) { + return cur; + } + cur = next; + } + } + function byGroup(view, pos, start) { + let categorize = view.state.charCategorizer(pos); + let cat = categorize(start); + return (next) => { + let nextCat = categorize(next); + if (cat == CharCategory.Space) + cat = nextCat; + return cat == nextCat; + }; + } + function moveVertically(view, start, forward, distance) { + let startPos = start.head, dir = forward ? 1 : -1; + if (startPos == (forward ? view.state.doc.length : 0)) + return EditorSelection.cursor(startPos, start.assoc); + let goal = start.goalColumn, startY; + let rect = view.contentDOM.getBoundingClientRect(); + let startCoords = view.coordsAtPos(startPos), docTop = view.documentTop; + if (startCoords) { + if (goal == null) + goal = startCoords.left - rect.left; + startY = dir < 0 ? startCoords.top : startCoords.bottom; + } + else { + let line = view.viewState.lineBlockAt(startPos); + if (goal == null) + goal = Math.min(rect.right - rect.left, view.defaultCharacterWidth * (startPos - line.from)); + startY = (dir < 0 ? line.top : line.bottom) + docTop; + } + let resolvedGoal = rect.left + goal; + let dist = distance !== null && distance !== void 0 ? distance : (view.defaultLineHeight >> 1); + for (let extra = 0;; extra += 10) { + let curY = startY + (dist + extra) * dir; + let pos = posAtCoords(view, { x: resolvedGoal, y: curY }, false, dir); + if (curY < rect.top || curY > rect.bottom || (dir < 0 ? pos < startPos : pos > startPos)) + return EditorSelection.cursor(pos, start.assoc, undefined, goal); + } + } + function skipAtoms(view, oldPos, pos) { + let atoms = view.state.facet(atomicRanges).map(f => f(view)); + for (;;) { + let moved = false; + for (let set of atoms) { + set.between(pos.from - 1, pos.from + 1, (from, to, value) => { + if (pos.from > from && pos.from < to) { + pos = oldPos.head > pos.from ? EditorSelection.cursor(from, 1) : EditorSelection.cursor(to, -1); + moved = true; + } + }); + } + if (!moved) + return pos; + } + } + + // This will also be where dragging info and such goes + class InputState { + constructor(view) { + this.lastKeyCode = 0; + this.lastKeyTime = 0; + this.lastTouchTime = 0; + this.lastFocusTime = 0; + this.lastScrollTop = 0; + this.lastScrollLeft = 0; + this.chromeScrollHack = -1; + // On iOS, some keys need to have their default behavior happen + // (after which we retroactively handle them and reset the DOM) to + // avoid messing up the virtual keyboard state. + this.pendingIOSKey = undefined; + this.lastSelectionOrigin = null; + this.lastSelectionTime = 0; + this.lastEscPress = 0; + this.lastContextMenu = 0; + this.scrollHandlers = []; + this.registeredEvents = []; + this.customHandlers = []; + // -1 means not in a composition. Otherwise, this counts the number + // of changes made during the composition. The count is used to + // avoid treating the start state of the composition, before any + // changes have been made, as part of the composition. + this.composing = -1; + // Tracks whether the next change should be marked as starting the + // composition (null means no composition, true means next is the + // first, false means first has already been marked for this + // composition) + this.compositionFirstChange = null; + this.compositionEndedAt = 0; + this.mouseSelection = null; + for (let type in handlers) { + let handler = handlers[type]; + view.contentDOM.addEventListener(type, (event) => { + if (!eventBelongsToEditor(view, event) || this.ignoreDuringComposition(event)) + return; + if (type == "keydown" && this.keydown(view, event)) + return; + if (this.mustFlushObserver(event)) + view.observer.forceFlush(); + if (this.runCustomHandlers(type, view, event)) + event.preventDefault(); + else + handler(view, event); + }, handlerOptions[type]); + this.registeredEvents.push(type); + } + if (browser.chrome && browser.chrome_version == 102) { // FIXME remove at some point + // On Chrome 102, viewport updates somehow stop wheel-based + // scrolling. Turning off pointer events during the scroll seems + // to avoid the issue. + view.scrollDOM.addEventListener("wheel", () => { + if (this.chromeScrollHack < 0) + view.contentDOM.style.pointerEvents = "none"; + else + window.clearTimeout(this.chromeScrollHack); + this.chromeScrollHack = setTimeout(() => { + this.chromeScrollHack = -1; + view.contentDOM.style.pointerEvents = ""; + }, 100); + }, { passive: true }); + } + this.notifiedFocused = view.hasFocus; + // On Safari adding an input event handler somehow prevents an + // issue where the composition vanishes when you press enter. + if (browser.safari) + view.contentDOM.addEventListener("input", () => null); + } + setSelectionOrigin(origin) { + this.lastSelectionOrigin = origin; + this.lastSelectionTime = Date.now(); + } + ensureHandlers(view, plugins) { + var _a; + let handlers; + this.customHandlers = []; + for (let plugin of plugins) + if (handlers = (_a = plugin.update(view).spec) === null || _a === void 0 ? void 0 : _a.domEventHandlers) { + this.customHandlers.push({ plugin: plugin.value, handlers }); + for (let type in handlers) + if (this.registeredEvents.indexOf(type) < 0 && type != "scroll") { + this.registeredEvents.push(type); + view.contentDOM.addEventListener(type, (event) => { + if (!eventBelongsToEditor(view, event)) + return; + if (this.runCustomHandlers(type, view, event)) + event.preventDefault(); + }); + } + } + } + runCustomHandlers(type, view, event) { + for (let set of this.customHandlers) { + let handler = set.handlers[type]; + if (handler) { + try { + if (handler.call(set.plugin, event, view) || event.defaultPrevented) + return true; + } + catch (e) { + logException(view.state, e); + } + } + } + return false; + } + runScrollHandlers(view, event) { + this.lastScrollTop = view.scrollDOM.scrollTop; + this.lastScrollLeft = view.scrollDOM.scrollLeft; + for (let set of this.customHandlers) { + let handler = set.handlers.scroll; + if (handler) { + try { + handler.call(set.plugin, event, view); + } + catch (e) { + logException(view.state, e); + } + } + } + } + keydown(view, event) { + // Must always run, even if a custom handler handled the event + this.lastKeyCode = event.keyCode; + this.lastKeyTime = Date.now(); + if (event.keyCode == 9 && Date.now() < this.lastEscPress + 2000) + return true; + // Chrome for Android usually doesn't fire proper key events, but + // occasionally does, usually surrounded by a bunch of complicated + // composition changes. When an enter or backspace key event is + // seen, hold off on handling DOM events for a bit, and then + // dispatch it. + if (browser.android && browser.chrome && !event.synthetic && + (event.keyCode == 13 || event.keyCode == 8)) { + view.observer.delayAndroidKey(event.key, event.keyCode); + return true; + } + // Prevent the default behavior of Enter on iOS makes the + // virtual keyboard get stuck in the wrong (lowercase) + // state. So we let it go through, and then, in + // applyDOMChange, notify key handlers of it and reset to + // the state they produce. + let pending; + if (browser.ios && !event.synthetic && !event.altKey && !event.metaKey && + ((pending = PendingKeys.find(key => key.keyCode == event.keyCode)) && !event.ctrlKey || + EmacsyPendingKeys.indexOf(event.key) > -1 && event.ctrlKey && !event.shiftKey)) { + this.pendingIOSKey = pending || event; + setTimeout(() => this.flushIOSKey(view), 250); + return true; + } + return false; + } + flushIOSKey(view) { + let key = this.pendingIOSKey; + if (!key) + return false; + this.pendingIOSKey = undefined; + return dispatchKey(view.contentDOM, key.key, key.keyCode); + } + ignoreDuringComposition(event) { + if (!/^key/.test(event.type)) + return false; + if (this.composing > 0) + return true; + // See https://www.stum.de/2016/06/24/handling-ime-events-in-javascript/. + // On some input method editors (IMEs), the Enter key is used to + // confirm character selection. On Safari, when Enter is pressed, + // compositionend and keydown events are sometimes emitted in the + // wrong order. The key event should still be ignored, even when + // it happens after the compositionend event. + if (browser.safari && !browser.ios && Date.now() - this.compositionEndedAt < 100) { + this.compositionEndedAt = 0; + return true; + } + return false; + } + mustFlushObserver(event) { + return event.type == "keydown" && event.keyCode != 229; + } + startMouseSelection(mouseSelection) { + if (this.mouseSelection) + this.mouseSelection.destroy(); + this.mouseSelection = mouseSelection; + } + update(update) { + if (this.mouseSelection) + this.mouseSelection.update(update); + if (update.transactions.length) + this.lastKeyCode = this.lastSelectionTime = 0; + } + destroy() { + if (this.mouseSelection) + this.mouseSelection.destroy(); + } + } + const PendingKeys = [ + { key: "Backspace", keyCode: 8, inputType: "deleteContentBackward" }, + { key: "Enter", keyCode: 13, inputType: "insertParagraph" }, + { key: "Delete", keyCode: 46, inputType: "deleteContentForward" } + ]; + const EmacsyPendingKeys = "dthko"; + // Key codes for modifier keys + const modifierCodes = [16, 17, 18, 20, 91, 92, 224, 225]; + class MouseSelection { + constructor(view, startEvent, style, mustSelect) { + this.view = view; + this.style = style; + this.mustSelect = mustSelect; + this.lastEvent = startEvent; + let doc = view.contentDOM.ownerDocument; + doc.addEventListener("mousemove", this.move = this.move.bind(this)); + doc.addEventListener("mouseup", this.up = this.up.bind(this)); + this.extend = startEvent.shiftKey; + this.multiple = view.state.facet(EditorState.allowMultipleSelections) && addsSelectionRange(view, startEvent); + this.dragMove = dragMovesSelection(view, startEvent); + this.dragging = isInPrimarySelection(view, startEvent) && getClickType(startEvent) == 1 ? null : false; + // When clicking outside of the selection, immediately apply the + // effect of starting the selection + if (this.dragging === false) { + startEvent.preventDefault(); + this.select(startEvent); + } + } + move(event) { + if (event.buttons == 0) + return this.destroy(); + if (this.dragging !== false) + return; + this.select(this.lastEvent = event); + } + up(event) { + if (this.dragging == null) + this.select(this.lastEvent); + if (!this.dragging) + event.preventDefault(); + this.destroy(); + } + destroy() { + let doc = this.view.contentDOM.ownerDocument; + doc.removeEventListener("mousemove", this.move); + doc.removeEventListener("mouseup", this.up); + this.view.inputState.mouseSelection = null; + } + select(event) { + let selection = this.style.get(event, this.extend, this.multiple); + if (this.mustSelect || !selection.eq(this.view.state.selection) || + selection.main.assoc != this.view.state.selection.main.assoc) + this.view.dispatch({ + selection, + userEvent: "select.pointer", + scrollIntoView: true + }); + this.mustSelect = false; + } + update(update) { + if (update.docChanged && this.dragging) + this.dragging = this.dragging.map(update.changes); + if (this.style.update(update)) + setTimeout(() => this.select(this.lastEvent), 20); + } + } + function addsSelectionRange(view, event) { + let facet = view.state.facet(clickAddsSelectionRange); + return facet.length ? facet[0](event) : browser.mac ? event.metaKey : event.ctrlKey; + } + function dragMovesSelection(view, event) { + let facet = view.state.facet(dragMovesSelection$1); + return facet.length ? facet[0](event) : browser.mac ? !event.altKey : !event.ctrlKey; + } + function isInPrimarySelection(view, event) { + let { main } = view.state.selection; + if (main.empty) + return false; + // On boundary clicks, check whether the coordinates are inside the + // selection's client rectangles + let sel = getSelection(view.root); + if (!sel || sel.rangeCount == 0) + return true; + let rects = sel.getRangeAt(0).getClientRects(); + for (let i = 0; i < rects.length; i++) { + let rect = rects[i]; + if (rect.left <= event.clientX && rect.right >= event.clientX && + rect.top <= event.clientY && rect.bottom >= event.clientY) + return true; + } + return false; + } + function eventBelongsToEditor(view, event) { + if (!event.bubbles) + return true; + if (event.defaultPrevented) + return false; + for (let node = event.target, cView; node != view.contentDOM; node = node.parentNode) + if (!node || node.nodeType == 11 || ((cView = ContentView.get(node)) && cView.ignoreEvent(event))) + return false; + return true; + } + const handlers = /*@__PURE__*/Object.create(null); + const handlerOptions = /*@__PURE__*/Object.create(null); + // This is very crude, but unfortunately both these browsers _pretend_ + // that they have a clipboard API—all the objects and methods are + // there, they just don't work, and they are hard to test. + const brokenClipboardAPI = (browser.ie && browser.ie_version < 15) || + (browser.ios && browser.webkit_version < 604); + function capturePaste(view) { + let parent = view.dom.parentNode; + if (!parent) + return; + let target = parent.appendChild(document.createElement("textarea")); + target.style.cssText = "position: fixed; left: -10000px; top: 10px"; + target.focus(); + setTimeout(() => { + view.focus(); + target.remove(); + doPaste(view, target.value); + }, 50); + } + function doPaste(view, input) { + let { state } = view, changes, i = 1, text = state.toText(input); + let byLine = text.lines == state.selection.ranges.length; + let linewise = lastLinewiseCopy != null && state.selection.ranges.every(r => r.empty) && lastLinewiseCopy == text.toString(); + if (linewise) { + let lastLine = -1; + changes = state.changeByRange(range => { + let line = state.doc.lineAt(range.from); + if (line.from == lastLine) + return { range }; + lastLine = line.from; + let insert = state.toText((byLine ? text.line(i++).text : input) + state.lineBreak); + return { changes: { from: line.from, insert }, + range: EditorSelection.cursor(range.from + insert.length) }; + }); + } + else if (byLine) { + changes = state.changeByRange(range => { + let line = text.line(i++); + return { changes: { from: range.from, to: range.to, insert: line.text }, + range: EditorSelection.cursor(range.from + line.length) }; + }); + } + else { + changes = state.replaceSelection(text); + } + view.dispatch(changes, { + userEvent: "input.paste", + scrollIntoView: true + }); + } + handlers.keydown = (view, event) => { + view.inputState.setSelectionOrigin("select"); + if (event.keyCode == 27) + view.inputState.lastEscPress = Date.now(); + else if (modifierCodes.indexOf(event.keyCode) < 0) + view.inputState.lastEscPress = 0; + }; + handlers.touchstart = (view, e) => { + view.inputState.lastTouchTime = Date.now(); + view.inputState.setSelectionOrigin("select.pointer"); + }; + handlers.touchmove = view => { + view.inputState.setSelectionOrigin("select.pointer"); + }; + handlerOptions.touchstart = handlerOptions.touchmove = { passive: true }; + handlers.mousedown = (view, event) => { + view.observer.flush(); + if (view.inputState.lastTouchTime > Date.now() - 2000) + return; // Ignore touch interaction + let style = null; + for (let makeStyle of view.state.facet(mouseSelectionStyle)) { + style = makeStyle(view, event); + if (style) + break; + } + if (!style && event.button == 0) + style = basicMouseSelection(view, event); + if (style) { + let mustFocus = view.root.activeElement != view.contentDOM; + if (mustFocus) + view.observer.ignore(() => focusPreventScroll(view.contentDOM)); + view.inputState.startMouseSelection(new MouseSelection(view, event, style, mustFocus)); + } + }; + function rangeForClick(view, pos, bias, type) { + if (type == 1) { // Single click + return EditorSelection.cursor(pos, bias); + } + else if (type == 2) { // Double click + return groupAt(view.state, pos, bias); + } + else { // Triple click + let visual = LineView.find(view.docView, pos), line = view.state.doc.lineAt(visual ? visual.posAtEnd : pos); + let from = visual ? visual.posAtStart : line.from, to = visual ? visual.posAtEnd : line.to; + if (to < view.state.doc.length && to == line.to) + to++; + return EditorSelection.range(from, to); + } + } + let insideY = (y, rect) => y >= rect.top && y <= rect.bottom; + let inside = (x, y, rect) => insideY(y, rect) && x >= rect.left && x <= rect.right; + // Try to determine, for the given coordinates, associated with the + // given position, whether they are related to the element before or + // the element after the position. + function findPositionSide(view, pos, x, y) { + let line = LineView.find(view.docView, pos); + if (!line) + return 1; + let off = pos - line.posAtStart; + // Line boundaries point into the line + if (off == 0) + return 1; + if (off == line.length) + return -1; + // Positions on top of an element point at that element + let before = line.coordsAt(off, -1); + if (before && inside(x, y, before)) + return -1; + let after = line.coordsAt(off, 1); + if (after && inside(x, y, after)) + return 1; + // This is probably a line wrap point. Pick before if the point is + // beside it. + return before && insideY(y, before) ? -1 : 1; + } + function queryPos(view, event) { + let pos = view.posAtCoords({ x: event.clientX, y: event.clientY }, false); + return { pos, bias: findPositionSide(view, pos, event.clientX, event.clientY) }; + } + const BadMouseDetail = browser.ie && browser.ie_version <= 11; + let lastMouseDown = null, lastMouseDownCount = 0, lastMouseDownTime = 0; + function getClickType(event) { + if (!BadMouseDetail) + return event.detail; + let last = lastMouseDown, lastTime = lastMouseDownTime; + lastMouseDown = event; + lastMouseDownTime = Date.now(); + return lastMouseDownCount = !last || (lastTime > Date.now() - 400 && Math.abs(last.clientX - event.clientX) < 2 && + Math.abs(last.clientY - event.clientY) < 2) ? (lastMouseDownCount + 1) % 3 : 1; + } + function basicMouseSelection(view, event) { + let start = queryPos(view, event), type = getClickType(event); + let startSel = view.state.selection; + let last = start, lastEvent = event; + return { + update(update) { + if (update.docChanged) { + start.pos = update.changes.mapPos(start.pos); + startSel = startSel.map(update.changes); + lastEvent = null; + } + }, + get(event, extend, multiple) { + let cur; + if (lastEvent && event.clientX == lastEvent.clientX && event.clientY == lastEvent.clientY) + cur = last; + else { + cur = last = queryPos(view, event); + lastEvent = event; + } + let range = rangeForClick(view, cur.pos, cur.bias, type); + if (start.pos != cur.pos && !extend) { + let startRange = rangeForClick(view, start.pos, start.bias, type); + let from = Math.min(startRange.from, range.from), to = Math.max(startRange.to, range.to); + range = from < range.from ? EditorSelection.range(from, to) : EditorSelection.range(to, from); + } + if (extend) + return startSel.replaceRange(startSel.main.extend(range.from, range.to)); + else if (multiple && startSel.ranges.length > 1 && startSel.ranges.some(r => r.eq(range))) + return removeRange(startSel, range); + else if (multiple) + return startSel.addRange(range); + else + return EditorSelection.create([range]); + } + }; + } + function removeRange(sel, range) { + for (let i = 0;; i++) { + if (sel.ranges[i].eq(range)) + return EditorSelection.create(sel.ranges.slice(0, i).concat(sel.ranges.slice(i + 1)), sel.mainIndex == i ? 0 : sel.mainIndex - (sel.mainIndex > i ? 1 : 0)); + } + } + handlers.dragstart = (view, event) => { + let { selection: { main } } = view.state; + let { mouseSelection } = view.inputState; + if (mouseSelection) + mouseSelection.dragging = main; + if (event.dataTransfer) { + event.dataTransfer.setData("Text", view.state.sliceDoc(main.from, main.to)); + event.dataTransfer.effectAllowed = "copyMove"; + } + }; + function dropText(view, event, text, direct) { + if (!text) + return; + let dropPos = view.posAtCoords({ x: event.clientX, y: event.clientY }, false); + event.preventDefault(); + let { mouseSelection } = view.inputState; + let del = direct && mouseSelection && mouseSelection.dragging && mouseSelection.dragMove ? + { from: mouseSelection.dragging.from, to: mouseSelection.dragging.to } : null; + let ins = { from: dropPos, insert: text }; + let changes = view.state.changes(del ? [del, ins] : ins); + view.focus(); + view.dispatch({ + changes, + selection: { anchor: changes.mapPos(dropPos, -1), head: changes.mapPos(dropPos, 1) }, + userEvent: del ? "move.drop" : "input.drop" + }); + } + handlers.drop = (view, event) => { + if (!event.dataTransfer) + return; + if (view.state.readOnly) + return event.preventDefault(); + let files = event.dataTransfer.files; + if (files && files.length) { // For a file drop, read the file's text. + event.preventDefault(); + let text = Array(files.length), read = 0; + let finishFile = () => { + if (++read == files.length) + dropText(view, event, text.filter(s => s != null).join(view.state.lineBreak), false); + }; + for (let i = 0; i < files.length; i++) { + let reader = new FileReader; + reader.onerror = finishFile; + reader.onload = () => { + if (!/[\x00-\x08\x0e-\x1f]{2}/.test(reader.result)) + text[i] = reader.result; + finishFile(); + }; + reader.readAsText(files[i]); + } + } + else { + dropText(view, event, event.dataTransfer.getData("Text"), true); + } + }; + handlers.paste = (view, event) => { + if (view.state.readOnly) + return event.preventDefault(); + view.observer.flush(); + let data = brokenClipboardAPI ? null : event.clipboardData; + if (data) { + doPaste(view, data.getData("text/plain")); + event.preventDefault(); + } + else { + capturePaste(view); + } + }; + function captureCopy(view, text) { + // The extra wrapper is somehow necessary on IE/Edge to prevent the + // content from being mangled when it is put onto the clipboard + let parent = view.dom.parentNode; + if (!parent) + return; + let target = parent.appendChild(document.createElement("textarea")); + target.style.cssText = "position: fixed; left: -10000px; top: 10px"; + target.value = text; + target.focus(); + target.selectionEnd = text.length; + target.selectionStart = 0; + setTimeout(() => { + target.remove(); + view.focus(); + }, 50); + } + function copiedRange(state) { + let content = [], ranges = [], linewise = false; + for (let range of state.selection.ranges) + if (!range.empty) { + content.push(state.sliceDoc(range.from, range.to)); + ranges.push(range); + } + if (!content.length) { + // Nothing selected, do a line-wise copy + let upto = -1; + for (let { from } of state.selection.ranges) { + let line = state.doc.lineAt(from); + if (line.number > upto) { + content.push(line.text); + ranges.push({ from: line.from, to: Math.min(state.doc.length, line.to + 1) }); + } + upto = line.number; + } + linewise = true; + } + return { text: content.join(state.lineBreak), ranges, linewise }; + } + let lastLinewiseCopy = null; + handlers.copy = handlers.cut = (view, event) => { + let { text, ranges, linewise } = copiedRange(view.state); + if (!text && !linewise) + return; + lastLinewiseCopy = linewise ? text : null; + let data = brokenClipboardAPI ? null : event.clipboardData; + if (data) { + event.preventDefault(); + data.clearData(); + data.setData("text/plain", text); + } + else { + captureCopy(view, text); + } + if (event.type == "cut" && !view.state.readOnly) + view.dispatch({ + changes: ranges, + scrollIntoView: true, + userEvent: "delete.cut" + }); + }; + function updateForFocusChange(view) { + setTimeout(() => { + if (view.hasFocus != view.inputState.notifiedFocused) + view.update([]); + }, 10); + } + handlers.focus = view => { + view.inputState.lastFocusTime = Date.now(); + // When focusing reset the scroll position, move it back to where it was + if (!view.scrollDOM.scrollTop && (view.inputState.lastScrollTop || view.inputState.lastScrollLeft)) { + view.scrollDOM.scrollTop = view.inputState.lastScrollTop; + view.scrollDOM.scrollLeft = view.inputState.lastScrollLeft; + } + updateForFocusChange(view); + }; + handlers.blur = view => { + view.observer.clearSelectionRange(); + updateForFocusChange(view); + }; + handlers.compositionstart = handlers.compositionupdate = view => { + if (view.inputState.compositionFirstChange == null) + view.inputState.compositionFirstChange = true; + if (view.inputState.composing < 0) { + // FIXME possibly set a timeout to clear it again on Android + view.inputState.composing = 0; + } + }; + handlers.compositionend = view => { + view.inputState.composing = -1; + view.inputState.compositionEndedAt = Date.now(); + view.inputState.compositionFirstChange = null; + if (browser.chrome && browser.android) + view.observer.flushSoon(); + setTimeout(() => { + // Force the composition state to be cleared if it hasn't already been + if (view.inputState.composing < 0 && view.docView.compositionDeco.size) + view.update([]); + }, 50); + }; + handlers.contextmenu = view => { + view.inputState.lastContextMenu = Date.now(); + }; + handlers.beforeinput = (view, event) => { + var _a; + // Because Chrome Android doesn't fire useful key events, use + // beforeinput to detect backspace (and possibly enter and delete, + // but those usually don't even seem to fire beforeinput events at + // the moment) and fake a key event for it. + // + // (preventDefault on beforeinput, though supported in the spec, + // seems to do nothing at all on Chrome). + let pending; + if (browser.chrome && browser.android && (pending = PendingKeys.find(key => key.inputType == event.inputType))) { + view.observer.delayAndroidKey(pending.key, pending.keyCode); + if (pending.key == "Backspace" || pending.key == "Delete") { + let startViewHeight = ((_a = window.visualViewport) === null || _a === void 0 ? void 0 : _a.height) || 0; + setTimeout(() => { + var _a; + // Backspacing near uneditable nodes on Chrome Android sometimes + // closes the virtual keyboard. This tries to crudely detect + // that and refocus to get it back. + if ((((_a = window.visualViewport) === null || _a === void 0 ? void 0 : _a.height) || 0) > startViewHeight + 10 && view.hasFocus) { + view.contentDOM.blur(); + view.focus(); + } + }, 100); + } + } + }; + + const wrappingWhiteSpace = ["pre-wrap", "normal", "pre-line", "break-spaces"]; + class HeightOracle { + constructor() { + this.doc = Text.empty; + this.lineWrapping = false; + this.heightSamples = {}; + this.lineHeight = 14; + this.charWidth = 7; + this.lineLength = 30; + // Used to track, during updateHeight, if any actual heights changed + this.heightChanged = false; + } + heightForGap(from, to) { + let lines = this.doc.lineAt(to).number - this.doc.lineAt(from).number + 1; + if (this.lineWrapping) + lines += Math.ceil(((to - from) - (lines * this.lineLength * 0.5)) / this.lineLength); + return this.lineHeight * lines; + } + heightForLine(length) { + if (!this.lineWrapping) + return this.lineHeight; + let lines = 1 + Math.max(0, Math.ceil((length - this.lineLength) / (this.lineLength - 5))); + return lines * this.lineHeight; + } + setDoc(doc) { this.doc = doc; return this; } + mustRefreshForWrapping(whiteSpace) { + return (wrappingWhiteSpace.indexOf(whiteSpace) > -1) != this.lineWrapping; + } + mustRefreshForHeights(lineHeights) { + let newHeight = false; + for (let i = 0; i < lineHeights.length; i++) { + let h = lineHeights[i]; + if (h < 0) { + i++; + } + else if (!this.heightSamples[Math.floor(h * 10)]) { // Round to .1 pixels + newHeight = true; + this.heightSamples[Math.floor(h * 10)] = true; + } + } + return newHeight; + } + refresh(whiteSpace, lineHeight, charWidth, lineLength, knownHeights) { + let lineWrapping = wrappingWhiteSpace.indexOf(whiteSpace) > -1; + let changed = Math.round(lineHeight) != Math.round(this.lineHeight) || this.lineWrapping != lineWrapping; + this.lineWrapping = lineWrapping; + this.lineHeight = lineHeight; + this.charWidth = charWidth; + this.lineLength = lineLength; + if (changed) { + this.heightSamples = {}; + for (let i = 0; i < knownHeights.length; i++) { + let h = knownHeights[i]; + if (h < 0) + i++; + else + this.heightSamples[Math.floor(h * 10)] = true; + } + } + return changed; + } + } + // This object is used by `updateHeight` to make DOM measurements + // arrive at the right nides. The `heights` array is a sequence of + // block heights, starting from position `from`. + class MeasuredHeights { + constructor(from, heights) { + this.from = from; + this.heights = heights; + this.index = 0; + } + get more() { return this.index < this.heights.length; } + } + /** + Record used to represent information about a block-level element + in the editor view. + */ + class BlockInfo { + /** + @internal + */ + constructor( + /** + The start of the element in the document. + */ + from, + /** + The length of the element. + */ + length, + /** + The top position of the element (relative to the top of the + document). + */ + top, + /** + Its height. + */ + height, + /** + The type of element this is. When querying lines, this may be + an array of all the blocks that make up the line. + */ + type) { + this.from = from; + this.length = length; + this.top = top; + this.height = height; + this.type = type; + } + /** + The end of the element as a document position. + */ + get to() { return this.from + this.length; } + /** + The bottom position of the element. + */ + get bottom() { return this.top + this.height; } + /** + @internal + */ + join(other) { + let detail = (Array.isArray(this.type) ? this.type : [this]) + .concat(Array.isArray(other.type) ? other.type : [other]); + return new BlockInfo(this.from, this.length + other.length, this.top, this.height + other.height, detail); + } + } + var QueryType$1 = /*@__PURE__*/(function (QueryType) { + QueryType[QueryType["ByPos"] = 0] = "ByPos"; + QueryType[QueryType["ByHeight"] = 1] = "ByHeight"; + QueryType[QueryType["ByPosNoHeight"] = 2] = "ByPosNoHeight"; + return QueryType})(QueryType$1 || (QueryType$1 = {})); + const Epsilon = 1e-3; + class HeightMap { + constructor(length, // The number of characters covered + height, // Height of this part of the document + flags = 2 /* Flag.Outdated */) { + this.length = length; + this.height = height; + this.flags = flags; + } + get outdated() { return (this.flags & 2 /* Flag.Outdated */) > 0; } + set outdated(value) { this.flags = (value ? 2 /* Flag.Outdated */ : 0) | (this.flags & ~2 /* Flag.Outdated */); } + setHeight(oracle, height) { + if (this.height != height) { + if (Math.abs(this.height - height) > Epsilon) + oracle.heightChanged = true; + this.height = height; + } + } + // Base case is to replace a leaf node, which simply builds a tree + // from the new nodes and returns that (HeightMapBranch and + // HeightMapGap override this to actually use from/to) + replace(_from, _to, nodes) { + return HeightMap.of(nodes); + } + // Again, these are base cases, and are overridden for branch and gap nodes. + decomposeLeft(_to, result) { result.push(this); } + decomposeRight(_from, result) { result.push(this); } + applyChanges(decorations, oldDoc, oracle, changes) { + let me = this; + for (let i = changes.length - 1; i >= 0; i--) { + let { fromA, toA, fromB, toB } = changes[i]; + let start = me.lineAt(fromA, QueryType$1.ByPosNoHeight, oldDoc, 0, 0); + let end = start.to >= toA ? start : me.lineAt(toA, QueryType$1.ByPosNoHeight, oldDoc, 0, 0); + toB += end.to - toA; + toA = end.to; + while (i > 0 && start.from <= changes[i - 1].toA) { + fromA = changes[i - 1].fromA; + fromB = changes[i - 1].fromB; + i--; + if (fromA < start.from) + start = me.lineAt(fromA, QueryType$1.ByPosNoHeight, oldDoc, 0, 0); + } + fromB += start.from - fromA; + fromA = start.from; + let nodes = NodeBuilder.build(oracle, decorations, fromB, toB); + me = me.replace(fromA, toA, nodes); + } + return me.updateHeight(oracle, 0); + } + static empty() { return new HeightMapText(0, 0); } + // nodes uses null values to indicate the position of line breaks. + // There are never line breaks at the start or end of the array, or + // two line breaks next to each other, and the array isn't allowed + // to be empty (same restrictions as return value from the builder). + static of(nodes) { + if (nodes.length == 1) + return nodes[0]; + let i = 0, j = nodes.length, before = 0, after = 0; + for (;;) { + if (i == j) { + if (before > after * 2) { + let split = nodes[i - 1]; + if (split.break) + nodes.splice(--i, 1, split.left, null, split.right); + else + nodes.splice(--i, 1, split.left, split.right); + j += 1 + split.break; + before -= split.size; + } + else if (after > before * 2) { + let split = nodes[j]; + if (split.break) + nodes.splice(j, 1, split.left, null, split.right); + else + nodes.splice(j, 1, split.left, split.right); + j += 2 + split.break; + after -= split.size; + } + else { + break; + } + } + else if (before < after) { + let next = nodes[i++]; + if (next) + before += next.size; + } + else { + let next = nodes[--j]; + if (next) + after += next.size; + } + } + let brk = 0; + if (nodes[i - 1] == null) { + brk = 1; + i--; + } + else if (nodes[i] == null) { + brk = 1; + j++; + } + return new HeightMapBranch(HeightMap.of(nodes.slice(0, i)), brk, HeightMap.of(nodes.slice(j))); + } + } + HeightMap.prototype.size = 1; + class HeightMapBlock extends HeightMap { + constructor(length, height, type) { + super(length, height); + this.type = type; + } + blockAt(_height, _doc, top, offset) { + return new BlockInfo(offset, this.length, top, this.height, this.type); + } + lineAt(_value, _type, doc, top, offset) { + return this.blockAt(0, doc, top, offset); + } + forEachLine(from, to, doc, top, offset, f) { + if (from <= offset + this.length && to >= offset) + f(this.blockAt(0, doc, top, offset)); + } + updateHeight(oracle, offset = 0, _force = false, measured) { + if (measured && measured.from <= offset && measured.more) + this.setHeight(oracle, measured.heights[measured.index++]); + this.outdated = false; + return this; + } + toString() { return `block(${this.length})`; } + } + class HeightMapText extends HeightMapBlock { + constructor(length, height) { + super(length, height, BlockType.Text); + this.collapsed = 0; // Amount of collapsed content in the line + this.widgetHeight = 0; // Maximum inline widget height + } + replace(_from, _to, nodes) { + let node = nodes[0]; + if (nodes.length == 1 && (node instanceof HeightMapText || node instanceof HeightMapGap && (node.flags & 4 /* Flag.SingleLine */)) && + Math.abs(this.length - node.length) < 10) { + if (node instanceof HeightMapGap) + node = new HeightMapText(node.length, this.height); + else + node.height = this.height; + if (!this.outdated) + node.outdated = false; + return node; + } + else { + return HeightMap.of(nodes); + } + } + updateHeight(oracle, offset = 0, force = false, measured) { + if (measured && measured.from <= offset && measured.more) + this.setHeight(oracle, measured.heights[measured.index++]); + else if (force || this.outdated) + this.setHeight(oracle, Math.max(this.widgetHeight, oracle.heightForLine(this.length - this.collapsed))); + this.outdated = false; + return this; + } + toString() { + return `line(${this.length}${this.collapsed ? -this.collapsed : ""}${this.widgetHeight ? ":" + this.widgetHeight : ""})`; + } + } + class HeightMapGap extends HeightMap { + constructor(length) { super(length, 0); } + lines(doc, offset) { + let firstLine = doc.lineAt(offset).number, lastLine = doc.lineAt(offset + this.length).number; + return { firstLine, lastLine, lineHeight: this.height / (lastLine - firstLine + 1) }; + } + blockAt(height, doc, top, offset) { + let { firstLine, lastLine, lineHeight } = this.lines(doc, offset); + let line = Math.max(0, Math.min(lastLine - firstLine, Math.floor((height - top) / lineHeight))); + let { from, length } = doc.line(firstLine + line); + return new BlockInfo(from, length, top + lineHeight * line, lineHeight, BlockType.Text); + } + lineAt(value, type, doc, top, offset) { + if (type == QueryType$1.ByHeight) + return this.blockAt(value, doc, top, offset); + if (type == QueryType$1.ByPosNoHeight) { + let { from, to } = doc.lineAt(value); + return new BlockInfo(from, to - from, 0, 0, BlockType.Text); + } + let { firstLine, lineHeight } = this.lines(doc, offset); + let { from, length, number } = doc.lineAt(value); + return new BlockInfo(from, length, top + lineHeight * (number - firstLine), lineHeight, BlockType.Text); + } + forEachLine(from, to, doc, top, offset, f) { + let { firstLine, lineHeight } = this.lines(doc, offset); + for (let pos = Math.max(from, offset), end = Math.min(offset + this.length, to); pos <= end;) { + let line = doc.lineAt(pos); + if (pos == from) + top += lineHeight * (line.number - firstLine); + f(new BlockInfo(line.from, line.length, top, lineHeight, BlockType.Text)); + top += lineHeight; + pos = line.to + 1; + } + } + replace(from, to, nodes) { + let after = this.length - to; + if (after > 0) { + let last = nodes[nodes.length - 1]; + if (last instanceof HeightMapGap) + nodes[nodes.length - 1] = new HeightMapGap(last.length + after); + else + nodes.push(null, new HeightMapGap(after - 1)); + } + if (from > 0) { + let first = nodes[0]; + if (first instanceof HeightMapGap) + nodes[0] = new HeightMapGap(from + first.length); + else + nodes.unshift(new HeightMapGap(from - 1), null); + } + return HeightMap.of(nodes); + } + decomposeLeft(to, result) { + result.push(new HeightMapGap(to - 1), null); + } + decomposeRight(from, result) { + result.push(null, new HeightMapGap(this.length - from - 1)); + } + updateHeight(oracle, offset = 0, force = false, measured) { + let end = offset + this.length; + if (measured && measured.from <= offset + this.length && measured.more) { + // Fill in part of this gap with measured lines. We know there + // can't be widgets or collapsed ranges in those lines, because + // they would already have been added to the heightmap (gaps + // only contain plain text). + let nodes = [], pos = Math.max(offset, measured.from), singleHeight = -1; + let wasChanged = oracle.heightChanged; + if (measured.from > offset) + nodes.push(new HeightMapGap(measured.from - offset - 1).updateHeight(oracle, offset)); + while (pos <= end && measured.more) { + let len = oracle.doc.lineAt(pos).length; + if (nodes.length) + nodes.push(null); + let height = measured.heights[measured.index++]; + if (singleHeight == -1) + singleHeight = height; + else if (Math.abs(height - singleHeight) >= Epsilon) + singleHeight = -2; + let line = new HeightMapText(len, height); + line.outdated = false; + nodes.push(line); + pos += len + 1; + } + if (pos <= end) + nodes.push(null, new HeightMapGap(end - pos).updateHeight(oracle, pos)); + let result = HeightMap.of(nodes); + oracle.heightChanged = wasChanged || singleHeight < 0 || Math.abs(result.height - this.height) >= Epsilon || + Math.abs(singleHeight - this.lines(oracle.doc, offset).lineHeight) >= Epsilon; + return result; + } + else if (force || this.outdated) { + this.setHeight(oracle, oracle.heightForGap(offset, offset + this.length)); + this.outdated = false; + } + return this; + } + toString() { return `gap(${this.length})`; } + } + class HeightMapBranch extends HeightMap { + constructor(left, brk, right) { + super(left.length + brk + right.length, left.height + right.height, brk | (left.outdated || right.outdated ? 2 /* Flag.Outdated */ : 0)); + this.left = left; + this.right = right; + this.size = left.size + right.size; + } + get break() { return this.flags & 1 /* Flag.Break */; } + blockAt(height, doc, top, offset) { + let mid = top + this.left.height; + return height < mid ? this.left.blockAt(height, doc, top, offset) + : this.right.blockAt(height, doc, mid, offset + this.left.length + this.break); + } + lineAt(value, type, doc, top, offset) { + let rightTop = top + this.left.height, rightOffset = offset + this.left.length + this.break; + let left = type == QueryType$1.ByHeight ? value < rightTop : value < rightOffset; + let base = left ? this.left.lineAt(value, type, doc, top, offset) + : this.right.lineAt(value, type, doc, rightTop, rightOffset); + if (this.break || (left ? base.to < rightOffset : base.from > rightOffset)) + return base; + let subQuery = type == QueryType$1.ByPosNoHeight ? QueryType$1.ByPosNoHeight : QueryType$1.ByPos; + if (left) + return base.join(this.right.lineAt(rightOffset, subQuery, doc, rightTop, rightOffset)); + else + return this.left.lineAt(rightOffset, subQuery, doc, top, offset).join(base); + } + forEachLine(from, to, doc, top, offset, f) { + let rightTop = top + this.left.height, rightOffset = offset + this.left.length + this.break; + if (this.break) { + if (from < rightOffset) + this.left.forEachLine(from, to, doc, top, offset, f); + if (to >= rightOffset) + this.right.forEachLine(from, to, doc, rightTop, rightOffset, f); + } + else { + let mid = this.lineAt(rightOffset, QueryType$1.ByPos, doc, top, offset); + if (from < mid.from) + this.left.forEachLine(from, mid.from - 1, doc, top, offset, f); + if (mid.to >= from && mid.from <= to) + f(mid); + if (to > mid.to) + this.right.forEachLine(mid.to + 1, to, doc, rightTop, rightOffset, f); + } + } + replace(from, to, nodes) { + let rightStart = this.left.length + this.break; + if (to < rightStart) + return this.balanced(this.left.replace(from, to, nodes), this.right); + if (from > this.left.length) + return this.balanced(this.left, this.right.replace(from - rightStart, to - rightStart, nodes)); + let result = []; + if (from > 0) + this.decomposeLeft(from, result); + let left = result.length; + for (let node of nodes) + result.push(node); + if (from > 0) + mergeGaps(result, left - 1); + if (to < this.length) { + let right = result.length; + this.decomposeRight(to, result); + mergeGaps(result, right); + } + return HeightMap.of(result); + } + decomposeLeft(to, result) { + let left = this.left.length; + if (to <= left) + return this.left.decomposeLeft(to, result); + result.push(this.left); + if (this.break) { + left++; + if (to >= left) + result.push(null); + } + if (to > left) + this.right.decomposeLeft(to - left, result); + } + decomposeRight(from, result) { + let left = this.left.length, right = left + this.break; + if (from >= right) + return this.right.decomposeRight(from - right, result); + if (from < left) + this.left.decomposeRight(from, result); + if (this.break && from < right) + result.push(null); + result.push(this.right); + } + balanced(left, right) { + if (left.size > 2 * right.size || right.size > 2 * left.size) + return HeightMap.of(this.break ? [left, null, right] : [left, right]); + this.left = left; + this.right = right; + this.height = left.height + right.height; + this.outdated = left.outdated || right.outdated; + this.size = left.size + right.size; + this.length = left.length + this.break + right.length; + return this; + } + updateHeight(oracle, offset = 0, force = false, measured) { + let { left, right } = this, rightStart = offset + left.length + this.break, rebalance = null; + if (measured && measured.from <= offset + left.length && measured.more) + rebalance = left = left.updateHeight(oracle, offset, force, measured); + else + left.updateHeight(oracle, offset, force); + if (measured && measured.from <= rightStart + right.length && measured.more) + rebalance = right = right.updateHeight(oracle, rightStart, force, measured); + else + right.updateHeight(oracle, rightStart, force); + if (rebalance) + return this.balanced(left, right); + this.height = this.left.height + this.right.height; + this.outdated = false; + return this; + } + toString() { return this.left + (this.break ? " " : "-") + this.right; } + } + function mergeGaps(nodes, around) { + let before, after; + if (nodes[around] == null && + (before = nodes[around - 1]) instanceof HeightMapGap && + (after = nodes[around + 1]) instanceof HeightMapGap) + nodes.splice(around - 1, 3, new HeightMapGap(before.length + 1 + after.length)); + } + const relevantWidgetHeight = 5; + class NodeBuilder { + constructor(pos, oracle) { + this.pos = pos; + this.oracle = oracle; + this.nodes = []; + this.lineStart = -1; + this.lineEnd = -1; + this.covering = null; + this.writtenTo = pos; + } + get isCovered() { + return this.covering && this.nodes[this.nodes.length - 1] == this.covering; + } + span(_from, to) { + if (this.lineStart > -1) { + let end = Math.min(to, this.lineEnd), last = this.nodes[this.nodes.length - 1]; + if (last instanceof HeightMapText) + last.length += end - this.pos; + else if (end > this.pos || !this.isCovered) + this.nodes.push(new HeightMapText(end - this.pos, -1)); + this.writtenTo = end; + if (to > end) { + this.nodes.push(null); + this.writtenTo++; + this.lineStart = -1; + } + } + this.pos = to; + } + point(from, to, deco) { + if (from < to || deco.heightRelevant) { + let height = deco.widget ? deco.widget.estimatedHeight : 0; + if (height < 0) + height = this.oracle.lineHeight; + let len = to - from; + if (deco.block) { + this.addBlock(new HeightMapBlock(len, height, deco.type)); + } + else if (len || height >= relevantWidgetHeight) { + this.addLineDeco(height, len); + } + } + else if (to > from) { + this.span(from, to); + } + if (this.lineEnd > -1 && this.lineEnd < this.pos) + this.lineEnd = this.oracle.doc.lineAt(this.pos).to; + } + enterLine() { + if (this.lineStart > -1) + return; + let { from, to } = this.oracle.doc.lineAt(this.pos); + this.lineStart = from; + this.lineEnd = to; + if (this.writtenTo < from) { + if (this.writtenTo < from - 1 || this.nodes[this.nodes.length - 1] == null) + this.nodes.push(this.blankContent(this.writtenTo, from - 1)); + this.nodes.push(null); + } + if (this.pos > from) + this.nodes.push(new HeightMapText(this.pos - from, -1)); + this.writtenTo = this.pos; + } + blankContent(from, to) { + let gap = new HeightMapGap(to - from); + if (this.oracle.doc.lineAt(from).to == to) + gap.flags |= 4 /* Flag.SingleLine */; + return gap; + } + ensureLine() { + this.enterLine(); + let last = this.nodes.length ? this.nodes[this.nodes.length - 1] : null; + if (last instanceof HeightMapText) + return last; + let line = new HeightMapText(0, -1); + this.nodes.push(line); + return line; + } + addBlock(block) { + this.enterLine(); + if (block.type == BlockType.WidgetAfter && !this.isCovered) + this.ensureLine(); + this.nodes.push(block); + this.writtenTo = this.pos = this.pos + block.length; + if (block.type != BlockType.WidgetBefore) + this.covering = block; + } + addLineDeco(height, length) { + let line = this.ensureLine(); + line.length += length; + line.collapsed += length; + line.widgetHeight = Math.max(line.widgetHeight, height); + this.writtenTo = this.pos = this.pos + length; + } + finish(from) { + let last = this.nodes.length == 0 ? null : this.nodes[this.nodes.length - 1]; + if (this.lineStart > -1 && !(last instanceof HeightMapText) && !this.isCovered) + this.nodes.push(new HeightMapText(0, -1)); + else if (this.writtenTo < this.pos || last == null) + this.nodes.push(this.blankContent(this.writtenTo, this.pos)); + let pos = from; + for (let node of this.nodes) { + if (node instanceof HeightMapText) + node.updateHeight(this.oracle, pos); + pos += node ? node.length : 1; + } + return this.nodes; + } + // Always called with a region that on both sides either stretches + // to a line break or the end of the document. + // The returned array uses null to indicate line breaks, but never + // starts or ends in a line break, or has multiple line breaks next + // to each other. + static build(oracle, decorations, from, to) { + let builder = new NodeBuilder(from, oracle); + RangeSet.spans(decorations, from, to, builder, 0); + return builder.finish(from); + } + } + function heightRelevantDecoChanges(a, b, diff) { + let comp = new DecorationComparator; + RangeSet.compare(a, b, diff, comp, 0); + return comp.changes; + } + class DecorationComparator { + constructor() { + this.changes = []; + } + compareRange() { } + comparePoint(from, to, a, b) { + if (from < to || a && a.heightRelevant || b && b.heightRelevant) + addRange(from, to, this.changes, 5); + } + } + + function visiblePixelRange(dom, paddingTop) { + let rect = dom.getBoundingClientRect(); + let doc = dom.ownerDocument, win = doc.defaultView || window; + let left = Math.max(0, rect.left), right = Math.min(win.innerWidth, rect.right); + let top = Math.max(0, rect.top), bottom = Math.min(win.innerHeight, rect.bottom); + for (let parent = dom.parentNode; parent && parent != doc.body;) { + if (parent.nodeType == 1) { + let elt = parent; + let style = window.getComputedStyle(elt); + if ((elt.scrollHeight > elt.clientHeight || elt.scrollWidth > elt.clientWidth) && + style.overflow != "visible") { + let parentRect = elt.getBoundingClientRect(); + left = Math.max(left, parentRect.left); + right = Math.min(right, parentRect.right); + top = Math.max(top, parentRect.top); + bottom = parent == dom.parentNode ? parentRect.bottom : Math.min(bottom, parentRect.bottom); + } + parent = style.position == "absolute" || style.position == "fixed" ? elt.offsetParent : elt.parentNode; + } + else if (parent.nodeType == 11) { // Shadow root + parent = parent.host; + } + else { + break; + } + } + return { left: left - rect.left, right: Math.max(left, right) - rect.left, + top: top - (rect.top + paddingTop), bottom: Math.max(top, bottom) - (rect.top + paddingTop) }; + } + function fullPixelRange(dom, paddingTop) { + let rect = dom.getBoundingClientRect(); + return { left: 0, right: rect.right - rect.left, + top: paddingTop, bottom: rect.bottom - (rect.top + paddingTop) }; + } + // Line gaps are placeholder widgets used to hide pieces of overlong + // lines within the viewport, as a kludge to keep the editor + // responsive when a ridiculously long line is loaded into it. + class LineGap { + constructor(from, to, size) { + this.from = from; + this.to = to; + this.size = size; + } + static same(a, b) { + if (a.length != b.length) + return false; + for (let i = 0; i < a.length; i++) { + let gA = a[i], gB = b[i]; + if (gA.from != gB.from || gA.to != gB.to || gA.size != gB.size) + return false; + } + return true; + } + draw(wrapping) { + return Decoration.replace({ widget: new LineGapWidget(this.size, wrapping) }).range(this.from, this.to); + } + } + class LineGapWidget extends WidgetType { + constructor(size, vertical) { + super(); + this.size = size; + this.vertical = vertical; + } + eq(other) { return other.size == this.size && other.vertical == this.vertical; } + toDOM() { + let elt = document.createElement("div"); + if (this.vertical) { + elt.style.height = this.size + "px"; + } + else { + elt.style.width = this.size + "px"; + elt.style.height = "2px"; + elt.style.display = "inline-block"; + } + return elt; + } + get estimatedHeight() { return this.vertical ? this.size : -1; } + } + class ViewState { + constructor(state) { + this.state = state; + // These are contentDOM-local coordinates + this.pixelViewport = { left: 0, right: window.innerWidth, top: 0, bottom: 0 }; + this.inView = true; + this.paddingTop = 0; + this.paddingBottom = 0; + this.contentDOMWidth = 0; + this.contentDOMHeight = 0; + this.editorHeight = 0; + this.editorWidth = 0; + this.heightOracle = new HeightOracle; + // See VP.MaxDOMHeight + this.scaler = IdScaler; + this.scrollTarget = null; + // Briefly set to true when printing, to disable viewport limiting + this.printing = false; + // Flag set when editor content was redrawn, so that the next + // measure stage knows it must read DOM layout + this.mustMeasureContent = true; + this.defaultTextDirection = Direction.RTL; + this.visibleRanges = []; + // Cursor 'assoc' is only significant when the cursor is on a line + // wrap point, where it must stick to the character that it is + // associated with. Since browsers don't provide a reasonable + // interface to set or query this, when a selection is set that + // might cause this to be significant, this flag is set. The next + // measure phase will check whether the cursor is on a line-wrapping + // boundary and, if so, reset it to make sure it is positioned in + // the right place. + this.mustEnforceCursorAssoc = false; + this.stateDeco = state.facet(decorations).filter(d => typeof d != "function"); + this.heightMap = HeightMap.empty().applyChanges(this.stateDeco, Text.empty, this.heightOracle.setDoc(state.doc), [new ChangedRange(0, 0, 0, state.doc.length)]); + this.viewport = this.getViewport(0, null); + this.updateViewportLines(); + this.updateForViewport(); + this.lineGaps = this.ensureLineGaps([]); + this.lineGapDeco = Decoration.set(this.lineGaps.map(gap => gap.draw(false))); + this.computeVisibleRanges(); + } + updateForViewport() { + let viewports = [this.viewport], { main } = this.state.selection; + for (let i = 0; i <= 1; i++) { + let pos = i ? main.head : main.anchor; + if (!viewports.some(({ from, to }) => pos >= from && pos <= to)) { + let { from, to } = this.lineBlockAt(pos); + viewports.push(new Viewport(from, to)); + } + } + this.viewports = viewports.sort((a, b) => a.from - b.from); + this.scaler = this.heightMap.height <= 7000000 /* VP.MaxDOMHeight */ ? IdScaler : + new BigScaler(this.heightOracle.doc, this.heightMap, this.viewports); + } + updateViewportLines() { + this.viewportLines = []; + this.heightMap.forEachLine(this.viewport.from, this.viewport.to, this.state.doc, 0, 0, block => { + this.viewportLines.push(this.scaler.scale == 1 ? block : scaleBlock(block, this.scaler)); + }); + } + update(update, scrollTarget = null) { + this.state = update.state; + let prevDeco = this.stateDeco; + this.stateDeco = this.state.facet(decorations).filter(d => typeof d != "function"); + let contentChanges = update.changedRanges; + let heightChanges = ChangedRange.extendWithRanges(contentChanges, heightRelevantDecoChanges(prevDeco, this.stateDeco, update ? update.changes : ChangeSet.empty(this.state.doc.length))); + let prevHeight = this.heightMap.height; + this.heightMap = this.heightMap.applyChanges(this.stateDeco, update.startState.doc, this.heightOracle.setDoc(this.state.doc), heightChanges); + if (this.heightMap.height != prevHeight) + update.flags |= 2 /* UpdateFlag.Height */; + let viewport = heightChanges.length ? this.mapViewport(this.viewport, update.changes) : this.viewport; + if (scrollTarget && (scrollTarget.range.head < viewport.from || scrollTarget.range.head > viewport.to) || + !this.viewportIsAppropriate(viewport)) + viewport = this.getViewport(0, scrollTarget); + let updateLines = !update.changes.empty || (update.flags & 2 /* UpdateFlag.Height */) || + viewport.from != this.viewport.from || viewport.to != this.viewport.to; + this.viewport = viewport; + this.updateForViewport(); + if (updateLines) + this.updateViewportLines(); + if (this.lineGaps.length || this.viewport.to - this.viewport.from > (2000 /* LG.Margin */ << 1)) + this.updateLineGaps(this.ensureLineGaps(this.mapLineGaps(this.lineGaps, update.changes))); + update.flags |= this.computeVisibleRanges(); + if (scrollTarget) + this.scrollTarget = scrollTarget; + if (!this.mustEnforceCursorAssoc && update.selectionSet && update.view.lineWrapping && + update.state.selection.main.empty && update.state.selection.main.assoc) + this.mustEnforceCursorAssoc = true; + } + measure(view) { + let dom = view.contentDOM, style = window.getComputedStyle(dom); + let oracle = this.heightOracle; + let whiteSpace = style.whiteSpace; + this.defaultTextDirection = style.direction == "rtl" ? Direction.RTL : Direction.LTR; + let refresh = this.heightOracle.mustRefreshForWrapping(whiteSpace); + let measureContent = refresh || this.mustMeasureContent || this.contentDOMHeight != dom.clientHeight; + this.contentDOMHeight = dom.clientHeight; + this.mustMeasureContent = false; + let result = 0, bias = 0; + // Vertical padding + let paddingTop = parseInt(style.paddingTop) || 0, paddingBottom = parseInt(style.paddingBottom) || 0; + if (this.paddingTop != paddingTop || this.paddingBottom != paddingBottom) { + this.paddingTop = paddingTop; + this.paddingBottom = paddingBottom; + result |= 8 /* UpdateFlag.Geometry */ | 2 /* UpdateFlag.Height */; + } + if (this.editorWidth != view.scrollDOM.clientWidth) { + if (oracle.lineWrapping) + measureContent = true; + this.editorWidth = view.scrollDOM.clientWidth; + result |= 8 /* UpdateFlag.Geometry */; + } + // Pixel viewport + let pixelViewport = (this.printing ? fullPixelRange : visiblePixelRange)(dom, this.paddingTop); + let dTop = pixelViewport.top - this.pixelViewport.top, dBottom = pixelViewport.bottom - this.pixelViewport.bottom; + this.pixelViewport = pixelViewport; + let inView = this.pixelViewport.bottom > this.pixelViewport.top && this.pixelViewport.right > this.pixelViewport.left; + if (inView != this.inView) { + this.inView = inView; + if (inView) + measureContent = true; + } + if (!this.inView && !this.scrollTarget) + return 0; + let contentWidth = dom.clientWidth; + if (this.contentDOMWidth != contentWidth || this.editorHeight != view.scrollDOM.clientHeight) { + this.contentDOMWidth = contentWidth; + this.editorHeight = view.scrollDOM.clientHeight; + result |= 8 /* UpdateFlag.Geometry */; + } + if (measureContent) { + let lineHeights = view.docView.measureVisibleLineHeights(this.viewport); + if (oracle.mustRefreshForHeights(lineHeights)) + refresh = true; + if (refresh || oracle.lineWrapping && Math.abs(contentWidth - this.contentDOMWidth) > oracle.charWidth) { + let { lineHeight, charWidth } = view.docView.measureTextSize(); + refresh = oracle.refresh(whiteSpace, lineHeight, charWidth, contentWidth / charWidth, lineHeights); + if (refresh) { + view.docView.minWidth = 0; + result |= 8 /* UpdateFlag.Geometry */; + } + } + if (dTop > 0 && dBottom > 0) + bias = Math.max(dTop, dBottom); + else if (dTop < 0 && dBottom < 0) + bias = Math.min(dTop, dBottom); + oracle.heightChanged = false; + for (let vp of this.viewports) { + let heights = vp.from == this.viewport.from ? lineHeights : view.docView.measureVisibleLineHeights(vp); + this.heightMap = this.heightMap.updateHeight(oracle, 0, refresh, new MeasuredHeights(vp.from, heights)); + } + if (oracle.heightChanged) + result |= 2 /* UpdateFlag.Height */; + } + let viewportChange = !this.viewportIsAppropriate(this.viewport, bias) || + this.scrollTarget && (this.scrollTarget.range.head < this.viewport.from || this.scrollTarget.range.head > this.viewport.to); + if (viewportChange) + this.viewport = this.getViewport(bias, this.scrollTarget); + this.updateForViewport(); + if ((result & 2 /* UpdateFlag.Height */) || viewportChange) + this.updateViewportLines(); + if (this.lineGaps.length || this.viewport.to - this.viewport.from > (2000 /* LG.Margin */ << 1)) + this.updateLineGaps(this.ensureLineGaps(refresh ? [] : this.lineGaps, view)); + result |= this.computeVisibleRanges(); + if (this.mustEnforceCursorAssoc) { + this.mustEnforceCursorAssoc = false; + // This is done in the read stage, because moving the selection + // to a line end is going to trigger a layout anyway, so it + // can't be a pure write. It should be rare that it does any + // writing. + view.docView.enforceCursorAssoc(); + } + return result; + } + get visibleTop() { return this.scaler.fromDOM(this.pixelViewport.top); } + get visibleBottom() { return this.scaler.fromDOM(this.pixelViewport.bottom); } + getViewport(bias, scrollTarget) { + // This will divide VP.Margin between the top and the + // bottom, depending on the bias (the change in viewport position + // since the last update). It'll hold a number between 0 and 1 + let marginTop = 0.5 - Math.max(-0.5, Math.min(0.5, bias / 1000 /* VP.Margin */ / 2)); + let map = this.heightMap, doc = this.state.doc, { visibleTop, visibleBottom } = this; + let viewport = new Viewport(map.lineAt(visibleTop - marginTop * 1000 /* VP.Margin */, QueryType$1.ByHeight, doc, 0, 0).from, map.lineAt(visibleBottom + (1 - marginTop) * 1000 /* VP.Margin */, QueryType$1.ByHeight, doc, 0, 0).to); + // If scrollTarget is given, make sure the viewport includes that position + if (scrollTarget) { + let { head } = scrollTarget.range; + if (head < viewport.from || head > viewport.to) { + let viewHeight = Math.min(this.editorHeight, this.pixelViewport.bottom - this.pixelViewport.top); + let block = map.lineAt(head, QueryType$1.ByPos, doc, 0, 0), topPos; + if (scrollTarget.y == "center") + topPos = (block.top + block.bottom) / 2 - viewHeight / 2; + else if (scrollTarget.y == "start" || scrollTarget.y == "nearest" && head < viewport.from) + topPos = block.top; + else + topPos = block.bottom - viewHeight; + viewport = new Viewport(map.lineAt(topPos - 1000 /* VP.Margin */ / 2, QueryType$1.ByHeight, doc, 0, 0).from, map.lineAt(topPos + viewHeight + 1000 /* VP.Margin */ / 2, QueryType$1.ByHeight, doc, 0, 0).to); + } + } + return viewport; + } + mapViewport(viewport, changes) { + let from = changes.mapPos(viewport.from, -1), to = changes.mapPos(viewport.to, 1); + return new Viewport(this.heightMap.lineAt(from, QueryType$1.ByPos, this.state.doc, 0, 0).from, this.heightMap.lineAt(to, QueryType$1.ByPos, this.state.doc, 0, 0).to); + } + // Checks if a given viewport covers the visible part of the + // document and not too much beyond that. + viewportIsAppropriate({ from, to }, bias = 0) { + if (!this.inView) + return true; + let { top } = this.heightMap.lineAt(from, QueryType$1.ByPos, this.state.doc, 0, 0); + let { bottom } = this.heightMap.lineAt(to, QueryType$1.ByPos, this.state.doc, 0, 0); + let { visibleTop, visibleBottom } = this; + return (from == 0 || top <= visibleTop - Math.max(10 /* VP.MinCoverMargin */, Math.min(-bias, 250 /* VP.MaxCoverMargin */))) && + (to == this.state.doc.length || + bottom >= visibleBottom + Math.max(10 /* VP.MinCoverMargin */, Math.min(bias, 250 /* VP.MaxCoverMargin */))) && + (top > visibleTop - 2 * 1000 /* VP.Margin */ && bottom < visibleBottom + 2 * 1000 /* VP.Margin */); + } + mapLineGaps(gaps, changes) { + if (!gaps.length || changes.empty) + return gaps; + let mapped = []; + for (let gap of gaps) + if (!changes.touchesRange(gap.from, gap.to)) + mapped.push(new LineGap(changes.mapPos(gap.from), changes.mapPos(gap.to), gap.size)); + return mapped; + } + // Computes positions in the viewport where the start or end of a + // line should be hidden, trying to reuse existing line gaps when + // appropriate to avoid unneccesary redraws. + // Uses crude character-counting for the positioning and sizing, + // since actual DOM coordinates aren't always available and + // predictable. Relies on generous margins (see LG.Margin) to hide + // the artifacts this might produce from the user. + ensureLineGaps(current, mayMeasure) { + let wrapping = this.heightOracle.lineWrapping; + let margin = wrapping ? 10000 /* LG.MarginWrap */ : 2000 /* LG.Margin */, halfMargin = margin >> 1, doubleMargin = margin << 1; + // The non-wrapping logic won't work at all in predominantly right-to-left text. + if (this.defaultTextDirection != Direction.LTR && !wrapping) + return []; + let gaps = []; + let addGap = (from, to, line, structure) => { + if (to - from < halfMargin) + return; + let sel = this.state.selection.main, avoid = [sel.from]; + if (!sel.empty) + avoid.push(sel.to); + for (let pos of avoid) { + if (pos > from && pos < to) { + addGap(from, pos - 10 /* LG.SelectionMargin */, line, structure); + addGap(pos + 10 /* LG.SelectionMargin */, to, line, structure); + return; + } + } + let gap = find(current, gap => gap.from >= line.from && gap.to <= line.to && + Math.abs(gap.from - from) < halfMargin && Math.abs(gap.to - to) < halfMargin && + !avoid.some(pos => gap.from < pos && gap.to > pos)); + if (!gap) { + // When scrolling down, snap gap ends to line starts to avoid shifts in wrapping + if (to < line.to && mayMeasure && wrapping && + mayMeasure.visibleRanges.some(r => r.from <= to && r.to >= to)) { + let lineStart = mayMeasure.moveToLineBoundary(EditorSelection.cursor(to), false, true).head; + if (lineStart > from) + to = lineStart; + } + gap = new LineGap(from, to, this.gapSize(line, from, to, structure)); + } + gaps.push(gap); + }; + for (let line of this.viewportLines) { + if (line.length < doubleMargin) + continue; + let structure = lineStructure(line.from, line.to, this.stateDeco); + if (structure.total < doubleMargin) + continue; + let target = this.scrollTarget ? this.scrollTarget.range.head : null; + let viewFrom, viewTo; + if (wrapping) { + let marginHeight = (margin / this.heightOracle.lineLength) * this.heightOracle.lineHeight; + let top, bot; + if (target != null) { + top = Math.max(line.from, target - margin); + bot = Math.min(line.to, target + margin); + } + else { + top = (this.visibleTop - line.top - marginHeight) / line.height; + bot = (this.visibleBottom - line.top + marginHeight) / line.height; + } + viewFrom = findPosition(structure, top); + viewTo = findPosition(structure, bot); + } + else { + let left, right; + if (target != null) { + left = Math.max(line.from, target - doubleMargin); + right = Math.min(line.to, target + doubleMargin); + } + else { + let totalWidth = structure.total * this.heightOracle.charWidth; + let marginWidth = margin * this.heightOracle.charWidth; + left = (this.pixelViewport.left - marginWidth) / totalWidth; + right = (this.pixelViewport.right + marginWidth) / totalWidth; + } + viewFrom = findPosition(structure, left); + viewTo = findPosition(structure, right); + } + if (viewFrom > line.from) + addGap(line.from, viewFrom, line, structure); + if (viewTo < line.to) + addGap(viewTo, line.to, line, structure); + } + return gaps; + } + gapSize(line, from, to, structure) { + let fraction = findFraction(structure, to) - findFraction(structure, from); + if (this.heightOracle.lineWrapping) { + return line.height * fraction; + } + else { + return structure.total * this.heightOracle.charWidth * fraction; + } + } + updateLineGaps(gaps) { + if (!LineGap.same(gaps, this.lineGaps)) { + this.lineGaps = gaps; + this.lineGapDeco = Decoration.set(gaps.map(gap => gap.draw(this.heightOracle.lineWrapping))); + } + } + computeVisibleRanges() { + let deco = this.stateDeco; + if (this.lineGaps.length) + deco = deco.concat(this.lineGapDeco); + let ranges = []; + RangeSet.spans(deco, this.viewport.from, this.viewport.to, { + span(from, to) { ranges.push({ from, to }); }, + point() { } + }, 20); + let changed = ranges.length != this.visibleRanges.length || + this.visibleRanges.some((r, i) => r.from != ranges[i].from || r.to != ranges[i].to); + this.visibleRanges = ranges; + return changed ? 4 /* UpdateFlag.Viewport */ : 0; + } + lineBlockAt(pos) { + return (pos >= this.viewport.from && pos <= this.viewport.to && this.viewportLines.find(b => b.from <= pos && b.to >= pos)) || + scaleBlock(this.heightMap.lineAt(pos, QueryType$1.ByPos, this.state.doc, 0, 0), this.scaler); + } + lineBlockAtHeight(height) { + return scaleBlock(this.heightMap.lineAt(this.scaler.fromDOM(height), QueryType$1.ByHeight, this.state.doc, 0, 0), this.scaler); + } + elementAtHeight(height) { + return scaleBlock(this.heightMap.blockAt(this.scaler.fromDOM(height), this.state.doc, 0, 0), this.scaler); + } + get docHeight() { + return this.scaler.toDOM(this.heightMap.height); + } + get contentHeight() { + return this.docHeight + this.paddingTop + this.paddingBottom; + } + } + class Viewport { + constructor(from, to) { + this.from = from; + this.to = to; + } + } + function lineStructure(from, to, stateDeco) { + let ranges = [], pos = from, total = 0; + RangeSet.spans(stateDeco, from, to, { + span() { }, + point(from, to) { + if (from > pos) { + ranges.push({ from: pos, to: from }); + total += from - pos; + } + pos = to; + } + }, 20); // We're only interested in collapsed ranges of a significant size + if (pos < to) { + ranges.push({ from: pos, to }); + total += to - pos; + } + return { total, ranges }; + } + function findPosition({ total, ranges }, ratio) { + if (ratio <= 0) + return ranges[0].from; + if (ratio >= 1) + return ranges[ranges.length - 1].to; + let dist = Math.floor(total * ratio); + for (let i = 0;; i++) { + let { from, to } = ranges[i], size = to - from; + if (dist <= size) + return from + dist; + dist -= size; + } + } + function findFraction(structure, pos) { + let counted = 0; + for (let { from, to } of structure.ranges) { + if (pos <= to) { + counted += pos - from; + break; + } + counted += to - from; + } + return counted / structure.total; + } + function find(array, f) { + for (let val of array) + if (f(val)) + return val; + return undefined; + } + // Don't scale when the document height is within the range of what + // the DOM can handle. + const IdScaler = { + toDOM(n) { return n; }, + fromDOM(n) { return n; }, + scale: 1 + }; + // When the height is too big (> VP.MaxDOMHeight), scale down the + // regions outside the viewports so that the total height is + // VP.MaxDOMHeight. + class BigScaler { + constructor(doc, heightMap, viewports) { + let vpHeight = 0, base = 0, domBase = 0; + this.viewports = viewports.map(({ from, to }) => { + let top = heightMap.lineAt(from, QueryType$1.ByPos, doc, 0, 0).top; + let bottom = heightMap.lineAt(to, QueryType$1.ByPos, doc, 0, 0).bottom; + vpHeight += bottom - top; + return { from, to, top, bottom, domTop: 0, domBottom: 0 }; + }); + this.scale = (7000000 /* VP.MaxDOMHeight */ - vpHeight) / (heightMap.height - vpHeight); + for (let obj of this.viewports) { + obj.domTop = domBase + (obj.top - base) * this.scale; + domBase = obj.domBottom = obj.domTop + (obj.bottom - obj.top); + base = obj.bottom; + } + } + toDOM(n) { + for (let i = 0, base = 0, domBase = 0;; i++) { + let vp = i < this.viewports.length ? this.viewports[i] : null; + if (!vp || n < vp.top) + return domBase + (n - base) * this.scale; + if (n <= vp.bottom) + return vp.domTop + (n - vp.top); + base = vp.bottom; + domBase = vp.domBottom; + } + } + fromDOM(n) { + for (let i = 0, base = 0, domBase = 0;; i++) { + let vp = i < this.viewports.length ? this.viewports[i] : null; + if (!vp || n < vp.domTop) + return base + (n - domBase) / this.scale; + if (n <= vp.domBottom) + return vp.top + (n - vp.domTop); + base = vp.bottom; + domBase = vp.domBottom; + } + } + } + function scaleBlock(block, scaler) { + if (scaler.scale == 1) + return block; + let bTop = scaler.toDOM(block.top), bBottom = scaler.toDOM(block.bottom); + return new BlockInfo(block.from, block.length, bTop, bBottom - bTop, Array.isArray(block.type) ? block.type.map(b => scaleBlock(b, scaler)) : block.type); + } + + const theme = /*@__PURE__*/Facet.define({ combine: strs => strs.join(" ") }); + const darkTheme = /*@__PURE__*/Facet.define({ combine: values => values.indexOf(true) > -1 }); + const baseThemeID = /*@__PURE__*/StyleModule.newName(), baseLightID = /*@__PURE__*/StyleModule.newName(), baseDarkID = /*@__PURE__*/StyleModule.newName(); + const lightDarkIDs = { "&light": "." + baseLightID, "&dark": "." + baseDarkID }; + function buildTheme(main, spec, scopes) { + return new StyleModule(spec, { + finish(sel) { + return /&/.test(sel) ? sel.replace(/&\w*/, m => { + if (m == "&") + return main; + if (!scopes || !scopes[m]) + throw new RangeError(`Unsupported selector: ${m}`); + return scopes[m]; + }) : main + " " + sel; + } + }); + } + const baseTheme$1$3 = /*@__PURE__*/buildTheme("." + baseThemeID, { + "&.cm-editor": { + position: "relative !important", + boxSizing: "border-box", + "&.cm-focused": { + // Provide a simple default outline to make sure a focused + // editor is visually distinct. Can't leave the default behavior + // because that will apply to the content element, which is + // inside the scrollable container and doesn't include the + // gutters. We also can't use an 'auto' outline, since those + // are, for some reason, drawn behind the element content, which + // will cause things like the active line background to cover + // the outline (#297). + 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, + minHeight: "100%", + display: "block", + whiteSpace: "pre", + wordWrap: "normal", + boxSizing: "border-box", + 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 4px" + }, + ".cm-selectionLayer": { + zIndex: -1, + contain: "size style" + }, + ".cm-selectionBackground": { + position: "absolute", + }, + "&light .cm-selectionBackground": { + background: "#d9d9d9" + }, + "&dark .cm-selectionBackground": { + background: "#222" + }, + "&light.cm-focused .cm-selectionBackground": { + background: "#d7d4f0" + }, + "&dark.cm-focused .cm-selectionBackground": { + background: "#233" + }, + ".cm-cursorLayer": { + zIndex: 100, + contain: "size style", + pointerEvents: "none" + }, + "&.cm-focused .cm-cursorLayer": { + animation: "steps(1) cm-blink 1.2s infinite" + }, + // Two animations defined so that we can switch between them to + // restart the animation without forcing another style + // recomputation. + "@keyframes cm-blink": { "0%": {}, "50%": { opacity: 0 }, "100%": {} }, + "@keyframes cm-blink2": { "0%": {}, "50%": { opacity: 0 }, "100%": {} }, + ".cm-cursor, .cm-dropCursor": { + position: "absolute", + borderLeft: "1.2px solid black", + marginLeft: "-0.6px", + pointerEvents: "none", + }, + ".cm-cursor": { + display: "none" + }, + "&dark .cm-cursor": { + borderLeftColor: "#444" + }, + "&.cm-focused .cm-cursor": { + display: "block" + }, + "&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", + left: 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-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" + } + }, lightDarkIDs); + + const observeOptions = { + childList: true, + characterData: true, + subtree: true, + attributes: true, + characterDataOldValue: true + }; + // IE11 has very broken mutation observers, so we also listen to + // DOMCharacterDataModified there + const useCharData = browser.ie && browser.ie_version <= 11; + class DOMObserver { + constructor(view, onChange, onScrollChanged) { + this.view = view; + this.onChange = onChange; + this.onScrollChanged = onScrollChanged; + this.active = false; + // The known selection. Kept in our own object, as opposed to just + // directly accessing the selection because: + // - Safari doesn't report the right selection in shadow DOM + // - Reading from the selection forces a DOM layout + // - This way, we can ignore selectionchange events if we have + // already seen the 'new' selection + this.selectionRange = new DOMSelectionState; + // Set when a selection change is detected, cleared on flush + this.selectionChanged = false; + this.delayedFlush = -1; + this.resizeTimeout = -1; + this.queue = []; + this.delayedAndroidKey = null; + this.lastChange = 0; + this.scrollTargets = []; + this.intersection = null; + this.resize = null; + this.intersecting = false; + this.gapIntersection = null; + this.gaps = []; + // Timeout for scheduling check of the parents that need scroll handlers + this.parentCheck = -1; + this.dom = view.contentDOM; + this.observer = new MutationObserver(mutations => { + for (let mut of mutations) + this.queue.push(mut); + // IE11 will sometimes (on typing over a selection or + // backspacing out a single character text node) call the + // observer callback before actually updating the DOM. + // + // Unrelatedly, iOS Safari will, when ending a composition, + // sometimes first clear it, deliver the mutations, and then + // reinsert the finished text. CodeMirror's handling of the + // deletion will prevent the reinsertion from happening, + // breaking composition. + if ((browser.ie && browser.ie_version <= 11 || browser.ios && view.composing) && + mutations.some(m => m.type == "childList" && m.removedNodes.length || + m.type == "characterData" && m.oldValue.length > m.target.nodeValue.length)) + this.flushSoon(); + else + this.flush(); + }); + if (useCharData) + this.onCharData = (event) => { + this.queue.push({ target: event.target, + type: "characterData", + oldValue: event.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); + if (typeof ResizeObserver == "function") { + this.resize = new ResizeObserver(() => { + if (this.view.docView.lastUpdate < Date.now() - 75) + this.onResize(); + }); + this.resize.observe(view.scrollDOM); + } + this.addWindowListeners(this.win = view.win); + this.start(); + if (typeof IntersectionObserver == "function") { + this.intersection = new IntersectionObserver(entries => { + if (this.parentCheck < 0) + this.parentCheck = setTimeout(this.listenForScroll.bind(this), 1000); + if (entries.length > 0 && (entries[entries.length - 1].intersectionRatio > 0) != this.intersecting) { + this.intersecting = !this.intersecting; + if (this.intersecting != this.view.inView) + this.onScrollChanged(document.createEvent("Event")); + } + }, {}); + this.intersection.observe(this.dom); + this.gapIntersection = new IntersectionObserver(entries => { + if (entries.length > 0 && entries[entries.length - 1].intersectionRatio > 0) + this.onScrollChanged(document.createEvent("Event")); + }, {}); + } + this.listenForScroll(); + this.readSelectionRange(); + } + onScroll(e) { + if (this.intersecting) + this.flush(false); + this.onScrollChanged(e); + } + onResize() { + if (this.resizeTimeout < 0) + this.resizeTimeout = setTimeout(() => { + this.resizeTimeout = -1; + this.view.requestMeasure(); + }, 50); + } + onPrint() { + this.view.viewState.printing = true; + this.view.measure(); + setTimeout(() => { + this.view.viewState.printing = false; + this.view.requestMeasure(); + }, 500); + } + updateGaps(gaps) { + if (this.gapIntersection && (gaps.length != this.gaps.length || this.gaps.some((g, i) => g != gaps[i]))) { + this.gapIntersection.disconnect(); + for (let gap of gaps) + this.gapIntersection.observe(gap); + this.gaps = gaps; + } + } + onSelectionChange(event) { + let wasChanged = this.selectionChanged; + if (!this.readSelectionRange() || this.delayedAndroidKey) + return; + let { view } = this, sel = this.selectionRange; + if (view.state.facet(editable) ? view.root.activeElement != this.dom : !hasSelection(view.dom, sel)) + return; + let context = sel.anchorNode && view.docView.nearest(sel.anchorNode); + if (context && context.ignoreEvent(event)) { + if (!wasChanged) + this.selectionChanged = false; + return; + } + // Deletions on IE11 fire their events in the wrong order, giving + // us a selection change event before the DOM changes are + // reported. + // Chrome Android has a similar issue when backspacing out a + // selection (#645). + if ((browser.ie && browser.ie_version <= 11 || browser.android && browser.chrome) && !view.state.selection.main.empty && + // (Selection.isCollapsed isn't reliable on IE) + sel.focusNode && isEquivalentPosition(sel.focusNode, sel.focusOffset, sel.anchorNode, sel.anchorOffset)) + this.flushSoon(); + else + this.flush(false); + } + readSelectionRange() { + let { view } = this; + // The Selection object is broken in shadow roots in Safari. See + // https://github.com/codemirror/dev/issues/414 + let range = browser.safari && view.root.nodeType == 11 && + deepActiveElement(this.dom.ownerDocument) == this.dom && + safariSelectionRangeHack(this.view) || getSelection(view.root); + if (!range || this.selectionRange.eq(range)) + return false; + let local = hasSelection(this.dom, range); + // Detect the situation where the browser has, on focus, moved the + // selection to the start of the content element. Reset it to the + // position from the editor state. + if (local && !this.selectionChanged && + view.inputState.lastFocusTime > Date.now() - 200 && + view.inputState.lastTouchTime < Date.now() - 300 && + atElementStart(this.dom, range)) { + this.view.inputState.lastFocusTime = 0; + view.docView.updateSelection(); + return false; + } + this.selectionRange.setRange(range); + if (local) + this.selectionChanged = true; + return true; + } + setSelectionRange(anchor, head) { + this.selectionRange.set(anchor.node, anchor.offset, head.node, head.offset); + this.selectionChanged = false; + } + clearSelectionRange() { + this.selectionRange.set(null, 0, null, 0); + } + listenForScroll() { + this.parentCheck = -1; + let i = 0, changed = null; + for (let dom = this.dom; dom;) { + if (dom.nodeType == 1) { + if (!changed && i < this.scrollTargets.length && this.scrollTargets[i] == dom) + i++; + else if (!changed) + changed = this.scrollTargets.slice(0, i); + if (changed) + changed.push(dom); + dom = dom.assignedSlot || dom.parentNode; + } + else if (dom.nodeType == 11) { // Shadow root + dom = dom.host; + } + else { + break; + } + } + if (i < this.scrollTargets.length && !changed) + changed = this.scrollTargets.slice(0, i); + if (changed) { + for (let dom of this.scrollTargets) + dom.removeEventListener("scroll", this.onScroll); + for (let dom of this.scrollTargets = changed) + dom.addEventListener("scroll", this.onScroll); + } + } + ignore(f) { + if (!this.active) + return f(); + try { + this.stop(); + return f(); + } + finally { + this.start(); + this.clear(); + } + } + start() { + if (this.active) + return; + this.observer.observe(this.dom, observeOptions); + if (useCharData) + this.dom.addEventListener("DOMCharacterDataModified", this.onCharData); + this.active = true; + } + stop() { + if (!this.active) + return; + this.active = false; + this.observer.disconnect(); + if (useCharData) + this.dom.removeEventListener("DOMCharacterDataModified", this.onCharData); + } + // Throw away any pending changes + clear() { + this.processRecords(); + this.queue.length = 0; + this.selectionChanged = false; + } + // Chrome Android, especially in combination with GBoard, not only + // doesn't reliably fire regular key events, but also often + // surrounds the effect of enter or backspace with a bunch of + // composition events that, when interrupted, cause text duplication + // or other kinds of corruption. This hack makes the editor back off + // from handling DOM changes for a moment when such a key is + // detected (via beforeinput or keydown), and then tries to flush + // them or, if that has no effect, dispatches the given key. + delayAndroidKey(key, keyCode) { + var _a; + if (!this.delayedAndroidKey) + this.view.win.requestAnimationFrame(() => { + let key = this.delayedAndroidKey; + this.delayedAndroidKey = null; + this.delayedFlush = -1; + if (!this.flush() && key.force) + dispatchKey(this.dom, key.key, key.keyCode); + }); + // Since backspace beforeinput is sometimes signalled spuriously, + // Enter always takes precedence. + if (!this.delayedAndroidKey || key == "Enter") + this.delayedAndroidKey = { + key, keyCode, + // Only run the key handler when no changes are detected if + // this isn't coming right after another change, in which case + // it is probably part of a weird chain of updates, and should + // be ignored if it returns the DOM to its previous state. + force: this.lastChange < Date.now() - 50 || !!((_a = this.delayedAndroidKey) === null || _a === void 0 ? void 0 : _a.force) + }; + } + flushSoon() { + if (this.delayedFlush < 0) + this.delayedFlush = this.view.win.requestAnimationFrame(() => { this.delayedFlush = -1; this.flush(); }); + } + forceFlush() { + if (this.delayedFlush >= 0) { + this.view.win.cancelAnimationFrame(this.delayedFlush); + this.delayedFlush = -1; + } + this.flush(); + } + processRecords() { + let records = this.queue; + for (let mut of this.observer.takeRecords()) + records.push(mut); + if (records.length) + this.queue = []; + let from = -1, to = -1, typeOver = false; + for (let record of records) { + let range = this.readMutation(record); + if (!range) + continue; + if (range.typeOver) + typeOver = true; + if (from == -1) { + ({ from, to } = range); + } + else { + from = Math.min(range.from, from); + to = Math.max(range.to, to); + } + } + return { from, to, typeOver }; + } + // Apply pending changes, if any + flush(readSelection = true) { + // Completely hold off flushing when pending keys are set—the code + // managing those will make sure processRecords is called and the + // view is resynchronized after + if (this.delayedFlush >= 0 || this.delayedAndroidKey) + return false; + if (readSelection) + this.readSelectionRange(); + let { from, to, typeOver } = this.processRecords(); + let newSel = this.selectionChanged && hasSelection(this.dom, this.selectionRange); + if (from < 0 && !newSel) + return false; + if (from > -1) + this.lastChange = Date.now(); + this.view.inputState.lastFocusTime = 0; + this.selectionChanged = false; + let startState = this.view.state; + let handled = this.onChange(from, to, typeOver); + // The view wasn't updated + if (this.view.state == startState) + this.view.update([]); + return handled; + } + readMutation(rec) { + let cView = this.view.docView.nearest(rec.target); + if (!cView || cView.ignoreMutation(rec)) + return null; + cView.markDirty(rec.type == "attributes"); + if (rec.type == "attributes") + cView.dirty |= 4 /* Dirty.Attrs */; + if (rec.type == "childList") { + let childBefore = findChild(cView, rec.previousSibling || rec.target.previousSibling, -1); + let childAfter = findChild(cView, rec.nextSibling || rec.target.nextSibling, 1); + return { from: childBefore ? cView.posAfter(childBefore) : cView.posAtStart, + to: childAfter ? cView.posBefore(childAfter) : cView.posAtEnd, typeOver: false }; + } + else if (rec.type == "characterData") { + return { from: cView.posAtStart, to: cView.posAtEnd, typeOver: rec.target.nodeValue == rec.oldValue }; + } + else { + return null; + } + } + setWindow(win) { + if (win != this.win) { + this.removeWindowListeners(this.win); + this.win = win; + this.addWindowListeners(this.win); + } + } + addWindowListeners(win) { + win.addEventListener("resize", this.onResize); + win.addEventListener("beforeprint", this.onPrint); + win.addEventListener("scroll", this.onScroll); + win.document.addEventListener("selectionchange", this.onSelectionChange); + } + removeWindowListeners(win) { + win.removeEventListener("scroll", this.onScroll); + win.removeEventListener("resize", this.onResize); + win.removeEventListener("beforeprint", this.onPrint); + win.document.removeEventListener("selectionchange", this.onSelectionChange); + } + destroy() { + var _a, _b, _c; + this.stop(); + (_a = this.intersection) === null || _a === void 0 ? void 0 : _a.disconnect(); + (_b = this.gapIntersection) === null || _b === void 0 ? void 0 : _b.disconnect(); + (_c = this.resize) === null || _c === void 0 ? void 0 : _c.disconnect(); + for (let dom of this.scrollTargets) + dom.removeEventListener("scroll", this.onScroll); + this.removeWindowListeners(this.win); + clearTimeout(this.parentCheck); + clearTimeout(this.resizeTimeout); + } + } + function findChild(cView, dom, dir) { + while (dom) { + let curView = ContentView.get(dom); + if (curView && curView.parent == cView) + return curView; + let parent = dom.parentNode; + dom = parent != cView.dom ? parent : dir > 0 ? dom.nextSibling : dom.previousSibling; + } + return null; + } + // Used to work around a Safari Selection/shadow DOM bug (#414) + function safariSelectionRangeHack(view) { + let found = null; + // Because Safari (at least in 2018-2021) doesn't provide regular + // access to the selection inside a shadowroot, we have to perform a + // ridiculous hack to get at it—using `execCommand` to trigger a + // `beforeInput` event so that we can read the target range from the + // event. + function read(event) { + event.preventDefault(); + event.stopImmediatePropagation(); + found = event.getTargetRanges()[0]; + } + view.contentDOM.addEventListener("beforeinput", read, true); + view.dom.ownerDocument.execCommand("indent"); + view.contentDOM.removeEventListener("beforeinput", read, true); + if (!found) + return null; + let anchorNode = found.startContainer, anchorOffset = found.startOffset; + let focusNode = found.endContainer, focusOffset = found.endOffset; + let curAnchor = view.docView.domAtPos(view.state.selection.main.anchor); + // Since such a range doesn't distinguish between anchor and head, + // use a heuristic that flips it around if its end matches the + // current anchor. + if (isEquivalentPosition(curAnchor.node, curAnchor.offset, focusNode, focusOffset)) + [anchorNode, anchorOffset, focusNode, focusOffset] = [focusNode, focusOffset, anchorNode, anchorOffset]; + return { anchorNode, anchorOffset, focusNode, focusOffset }; + } + + function applyDOMChange(view, start, end, typeOver) { + let change, newSel; + let sel = view.state.selection.main; + if (start > -1) { + let bounds = view.docView.domBoundsAround(start, end, 0); + if (!bounds || view.state.readOnly) + return false; + let { from, to } = bounds; + let selPoints = view.docView.impreciseHead || view.docView.impreciseAnchor ? [] : selectionPoints(view); + let reader = new DOMReader(selPoints, view.state); + reader.readRange(bounds.startDOM, bounds.endDOM); + let preferredPos = sel.from, preferredSide = null; + // Prefer anchoring to end when Backspace is pressed (or, on + // Android, when something was deleted) + if (view.inputState.lastKeyCode === 8 && view.inputState.lastKeyTime > Date.now() - 100 || + browser.android && reader.text.length < to - from) { + preferredPos = sel.to; + preferredSide = "end"; + } + let diff = findDiff(view.state.doc.sliceString(from, to, LineBreakPlaceholder), reader.text, preferredPos - from, preferredSide); + if (diff) { + // Chrome inserts two newlines when pressing shift-enter at the + // end of a line. This drops one of those. + if (browser.chrome && view.inputState.lastKeyCode == 13 && + diff.toB == diff.from + 2 && reader.text.slice(diff.from, diff.toB) == LineBreakPlaceholder + LineBreakPlaceholder) + diff.toB--; + change = { from: from + diff.from, to: from + diff.toA, + insert: Text.of(reader.text.slice(diff.from, diff.toB).split(LineBreakPlaceholder)) }; + } + newSel = selectionFromPoints(selPoints, from); + } + else if (view.hasFocus || !view.state.facet(editable)) { + let domSel = view.observer.selectionRange; + let { impreciseHead: iHead, impreciseAnchor: iAnchor } = view.docView; + let head = iHead && iHead.node == domSel.focusNode && iHead.offset == domSel.focusOffset || + !contains(view.contentDOM, domSel.focusNode) + ? view.state.selection.main.head + : view.docView.posFromDOM(domSel.focusNode, domSel.focusOffset); + let anchor = iAnchor && iAnchor.node == domSel.anchorNode && iAnchor.offset == domSel.anchorOffset || + !contains(view.contentDOM, domSel.anchorNode) + ? view.state.selection.main.anchor + : view.docView.posFromDOM(domSel.anchorNode, domSel.anchorOffset); + if (head != sel.head || anchor != sel.anchor) + newSel = EditorSelection.single(anchor, head); + } + if (!change && !newSel) + return false; + if (!change && typeOver && !sel.empty && newSel && newSel.main.empty) { + // Heuristic to notice typing over a selected character + change = { from: sel.from, to: sel.to, insert: view.state.doc.slice(sel.from, sel.to) }; + } + else if (change && change.from >= sel.from && change.to <= sel.to && + (change.from != sel.from || change.to != sel.to) && + (sel.to - sel.from) - (change.to - change.from) <= 4) { + // If the change is inside the selection and covers most of it, + // assume it is a selection replace (with identical characters at + // the start/end not included in the diff) + change = { + from: sel.from, to: sel.to, + insert: view.state.doc.slice(sel.from, change.from).append(change.insert).append(view.state.doc.slice(change.to, sel.to)) + }; + } + else if ((browser.mac || browser.android) && change && change.from == change.to && change.from == sel.head - 1 && + /^\. ?$/.test(change.insert.toString())) { + // Detect insert-period-on-double-space Mac and Android behavior, + // and transform it into a regular space insert. + if (newSel && change.insert.length == 2) + newSel = EditorSelection.single(newSel.main.anchor - 1, newSel.main.head - 1); + change = { from: sel.from, to: sel.to, insert: Text.of([" "]) }; + } + if (change) { + let startState = view.state; + if (browser.ios && view.inputState.flushIOSKey(view)) + return true; + // Android browsers don't fire reasonable key events for enter, + // backspace, or delete. So this detects changes that look like + // they're caused by those keys, and reinterprets them as key + // events. (Some of these keys are also handled by beforeinput + // events and the pendingAndroidKey mechanism, but that's not + // reliable in all situations.) + if (browser.android && + ((change.from == sel.from && change.to == sel.to && + change.insert.length == 1 && change.insert.lines == 2 && + dispatchKey(view.contentDOM, "Enter", 13)) || + (change.from == sel.from - 1 && change.to == sel.to && change.insert.length == 0 && + dispatchKey(view.contentDOM, "Backspace", 8)) || + (change.from == sel.from && change.to == sel.to + 1 && change.insert.length == 0 && + dispatchKey(view.contentDOM, "Delete", 46)))) + return true; + let text = change.insert.toString(); + if (view.state.facet(inputHandler$1).some(h => h(view, change.from, change.to, text))) + return true; + if (view.inputState.composing >= 0) + view.inputState.composing++; + let tr; + if (change.from >= sel.from && change.to <= sel.to && change.to - change.from >= (sel.to - sel.from) / 3 && + (!newSel || newSel.main.empty && newSel.main.from == change.from + change.insert.length) && + view.inputState.composing < 0) { + let before = sel.from < change.from ? startState.sliceDoc(sel.from, change.from) : ""; + let after = sel.to > change.to ? startState.sliceDoc(change.to, sel.to) : ""; + tr = startState.replaceSelection(view.state.toText(before + change.insert.sliceString(0, undefined, view.state.lineBreak) + after)); + } + else { + let changes = startState.changes(change); + let mainSel = newSel && !startState.selection.main.eq(newSel.main) && newSel.main.to <= changes.newLength + ? newSel.main : undefined; + // Try to apply a composition change to all cursors + if (startState.selection.ranges.length > 1 && view.inputState.composing >= 0 && + change.to <= sel.to && change.to >= sel.to - 10) { + let replaced = view.state.sliceDoc(change.from, change.to); + let compositionRange = compositionSurroundingNode(view) || view.state.doc.lineAt(sel.head); + let offset = sel.to - change.to, size = sel.to - sel.from; + tr = startState.changeByRange(range => { + if (range.from == sel.from && range.to == sel.to) + return { changes, range: mainSel || range.map(changes) }; + let to = range.to - offset, from = to - replaced.length; + if (range.to - range.from != size || view.state.sliceDoc(from, to) != replaced || + // Unfortunately, there's no way to make multiple + // changes in the same node work without aborting + // composition, so cursors in the composition range are + // ignored. + compositionRange && range.to >= compositionRange.from && range.from <= compositionRange.to) + return { range }; + let rangeChanges = startState.changes({ from, to, insert: change.insert }), selOff = range.to - sel.to; + return { + changes: rangeChanges, + range: !mainSel ? range.map(rangeChanges) : + EditorSelection.range(Math.max(0, mainSel.anchor + selOff), Math.max(0, mainSel.head + selOff)) + }; + }); + } + else { + tr = { + changes, + selection: mainSel && startState.selection.replaceRange(mainSel) + }; + } + } + let userEvent = "input.type"; + if (view.composing) { + userEvent += ".compose"; + if (view.inputState.compositionFirstChange) { + userEvent += ".start"; + view.inputState.compositionFirstChange = false; + } + } + view.dispatch(tr, { scrollIntoView: true, userEvent }); + return true; + } + else if (newSel && !newSel.main.eq(sel)) { + let scrollIntoView = false, userEvent = "select"; + if (view.inputState.lastSelectionTime > Date.now() - 50) { + if (view.inputState.lastSelectionOrigin == "select") + scrollIntoView = true; + userEvent = view.inputState.lastSelectionOrigin; + } + view.dispatch({ selection: newSel, scrollIntoView, userEvent }); + return true; + } + else { + return false; + } + } + function findDiff(a, b, preferredPos, preferredSide) { + let minLen = Math.min(a.length, b.length); + let from = 0; + while (from < minLen && a.charCodeAt(from) == b.charCodeAt(from)) + from++; + if (from == minLen && a.length == b.length) + return null; + let toA = a.length, toB = b.length; + while (toA > 0 && toB > 0 && a.charCodeAt(toA - 1) == b.charCodeAt(toB - 1)) { + toA--; + toB--; + } + if (preferredSide == "end") { + let adjust = Math.max(0, from - Math.min(toA, toB)); + preferredPos -= toA + adjust - from; + } + if (toA < from && a.length < b.length) { + let move = preferredPos <= from && preferredPos >= toA ? from - preferredPos : 0; + from -= move; + toB = from + (toB - toA); + toA = from; + } + else if (toB < from) { + let move = preferredPos <= from && preferredPos >= toB ? from - preferredPos : 0; + from -= move; + toA = from + (toA - toB); + toB = from; + } + return { from, toA, toB }; + } + function selectionPoints(view) { + let result = []; + if (view.root.activeElement != view.contentDOM) + return result; + let { anchorNode, anchorOffset, focusNode, focusOffset } = view.observer.selectionRange; + if (anchorNode) { + result.push(new DOMPoint(anchorNode, anchorOffset)); + if (focusNode != anchorNode || focusOffset != anchorOffset) + result.push(new DOMPoint(focusNode, focusOffset)); + } + return result; + } + function selectionFromPoints(points, base) { + if (points.length == 0) + return null; + let anchor = points[0].pos, head = points.length == 2 ? points[1].pos : anchor; + return anchor > -1 && head > -1 ? EditorSelection.single(anchor + base, head + base) : null; + } + + // The editor's update state machine looks something like this: + // + // Idle → Updating ⇆ Idle (unchecked) → Measuring → Idle + // ↑ ↓ + // Updating (measure) + // + // The difference between 'Idle' and 'Idle (unchecked)' lies in + // whether a layout check has been scheduled. A regular update through + // the `update` method updates the DOM in a write-only fashion, and + // relies on a check (scheduled with `requestAnimationFrame`) to make + // sure everything is where it should be and the viewport covers the + // visible code. That check continues to measure and then optionally + // update until it reaches a coherent state. + /** + An editor view represents the editor's user interface. It holds + the editable DOM surface, and possibly other elements such as the + line number gutter. It handles events and dispatches state + transactions for editing actions. + */ + class EditorView { + /** + Construct a new view. You'll want to either provide a `parent` + option, or put `view.dom` into your document after creating a + view, so that the user can see the editor. + */ + constructor(config = {}) { + this.plugins = []; + this.pluginMap = new Map; + this.editorAttrs = {}; + this.contentAttrs = {}; + this.bidiCache = []; + this.destroyed = false; + /** + @internal + */ + this.updateState = 2 /* UpdateState.Updating */; + /** + @internal + */ + this.measureScheduled = -1; + /** + @internal + */ + 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.style.cssText = "position: absolute; top: -10000px"; + this.announceDOM.setAttribute("aria-live", "polite"); + this.dom = document.createElement("div"); + this.dom.appendChild(this.announceDOM); + this.dom.appendChild(this.scrollDOM); + this._dispatch = config.dispatch || ((tr) => this.update([tr])); + this.dispatch = this.dispatch.bind(this); + this._root = (config.root || getRoot(config.parent) || document); + this.viewState = new ViewState(config.state || EditorState.create(config)); + this.plugins = this.state.facet(viewPlugin).map(spec => new PluginInstance(spec)); + for (let plugin of this.plugins) + plugin.update(this); + this.observer = new DOMObserver(this, (from, to, typeOver) => { + return applyDOMChange(this, from, to, typeOver); + }, event => { + this.inputState.runScrollHandlers(this, event); + if (this.observer.intersecting) + this.measure(); + }); + this.inputState = new InputState(this); + this.inputState.ensureHandlers(this, this.plugins); + this.docView = new DocView(this); + this.mountStyles(); + this.updateAttrs(); + this.updateState = 0 /* UpdateState.Idle */; + this.requestMeasure(); + if (config.parent) + config.parent.appendChild(this.dom); + } + /** + The current editor state. + */ + get state() { return this.viewState.state; } + /** + To be able to display large documents without consuming too much + memory or overloading the browser, CodeMirror only draws the + code that is visible (plus a margin around it) to the DOM. This + property tells you the extent of the current drawn viewport, in + document positions. + */ + get viewport() { return this.viewState.viewport; } + /** + When there are, for example, large collapsed ranges in the + viewport, its size can be a lot bigger than the actual visible + content. Thus, if you are doing something like styling the + content in the viewport, it is preferable to only do so for + these ranges, which are the subset of the viewport that is + actually drawn. + */ + get visibleRanges() { return this.viewState.visibleRanges; } + /** + Returns false when the editor is entirely scrolled out of view + or otherwise hidden. + */ + get inView() { return this.viewState.inView; } + /** + Indicates whether the user is currently composing text via + [IME](https://en.wikipedia.org/wiki/Input_method), and at least + one change has been made in the current composition. + */ + get composing() { return this.inputState.composing > 0; } + /** + Indicates whether the user is currently in composing state. Note + that on some platforms, like Android, this will be the case a + lot, since just putting the cursor on a word starts a + composition there. + */ + get compositionStarted() { return this.inputState.composing >= 0; } + /** + The document or shadow root that the view lives in. + */ + get root() { return this._root; } + /** + @internal + */ + get win() { return this.dom.ownerDocument.defaultView || window; } + dispatch(...input) { + this._dispatch(input.length == 1 && input[0] instanceof Transaction ? input[0] + : this.state.update(...input)); + } + /** + Update the view for the given array of transactions. This will + update the visible document and selection to match the state + produced by the transactions, and notify view plugins of the + change. You should usually call + [`dispatch`](https://codemirror.net/6/docs/ref/#view.EditorView.dispatch) instead, which uses this + as a primitive. + */ + update(transactions) { + if (this.updateState != 0 /* UpdateState.Idle */) + throw new Error("Calls to EditorView.update are not allowed while an update is in progress"); + let redrawn = false, attrsChanged = false, update; + let state = this.state; + for (let tr of transactions) { + if (tr.startState != state) + throw new RangeError("Trying to update state with a transaction that doesn't start from the previous state."); + state = tr.state; + } + if (this.destroyed) { + this.viewState.state = state; + return; + } + this.observer.clear(); + // When the phrases change, redraw the editor + if (state.facet(EditorState.phrases) != this.state.facet(EditorState.phrases)) + return this.setState(state); + update = ViewUpdate.create(this, state, transactions); + let scrollTarget = this.viewState.scrollTarget; + try { + this.updateState = 2 /* UpdateState.Updating */; + for (let tr of transactions) { + if (scrollTarget) + scrollTarget = scrollTarget.map(tr.changes); + if (tr.scrollIntoView) { + let { main } = tr.state.selection; + scrollTarget = new ScrollTarget(main.empty ? main : EditorSelection.cursor(main.head, main.head > main.anchor ? -1 : 1)); + } + for (let e of tr.effects) + if (e.is(scrollIntoView$1)) + scrollTarget = e.value; + } + this.viewState.update(update, scrollTarget); + this.bidiCache = CachedOrder.update(this.bidiCache, update.changes); + if (!update.empty) { + this.updatePlugins(update); + this.inputState.update(update); + } + redrawn = this.docView.update(update); + if (this.state.facet(styleModule) != this.styleModules) + this.mountStyles(); + attrsChanged = this.updateAttrs(); + this.showAnnouncements(transactions); + this.docView.updateSelection(redrawn, transactions.some(tr => tr.isUserEvent("select.pointer"))); + } + finally { + this.updateState = 0 /* UpdateState.Idle */; + } + if (update.startState.facet(theme) != update.state.facet(theme)) + this.viewState.mustMeasureContent = true; + if (redrawn || attrsChanged || scrollTarget || this.viewState.mustEnforceCursorAssoc || this.viewState.mustMeasureContent) + this.requestMeasure(); + if (!update.empty) + for (let listener of this.state.facet(updateListener)) + listener(update); + } + /** + Reset the view to the given state. (This will cause the entire + document to be redrawn and all view plugins to be reinitialized, + so you should probably only use it when the new state isn't + derived from the old state. Otherwise, use + [`dispatch`](https://codemirror.net/6/docs/ref/#view.EditorView.dispatch) instead.) + */ + setState(newState) { + if (this.updateState != 0 /* UpdateState.Idle */) + throw new Error("Calls to EditorView.setState are not allowed while an update is in progress"); + if (this.destroyed) { + this.viewState.state = newState; + return; + } + this.updateState = 2 /* UpdateState.Updating */; + let hadFocus = this.hasFocus; + try { + for (let plugin of this.plugins) + plugin.destroy(this); + this.viewState = new ViewState(newState); + this.plugins = newState.facet(viewPlugin).map(spec => new PluginInstance(spec)); + this.pluginMap.clear(); + for (let plugin of this.plugins) + plugin.update(this); + this.docView = new DocView(this); + this.inputState.ensureHandlers(this, this.plugins); + this.mountStyles(); + this.updateAttrs(); + this.bidiCache = []; + } + finally { + this.updateState = 0 /* UpdateState.Idle */; + } + if (hadFocus) + this.focus(); + this.requestMeasure(); + } + updatePlugins(update) { + let prevSpecs = update.startState.facet(viewPlugin), specs = update.state.facet(viewPlugin); + if (prevSpecs != specs) { + let newPlugins = []; + for (let spec of specs) { + let found = prevSpecs.indexOf(spec); + if (found < 0) { + newPlugins.push(new PluginInstance(spec)); + } + else { + let plugin = this.plugins[found]; + plugin.mustUpdate = update; + newPlugins.push(plugin); + } + } + for (let plugin of this.plugins) + if (plugin.mustUpdate != update) + plugin.destroy(this); + this.plugins = newPlugins; + this.pluginMap.clear(); + this.inputState.ensureHandlers(this, this.plugins); + } + else { + for (let p of this.plugins) + p.mustUpdate = update; + } + for (let i = 0; i < this.plugins.length; i++) + this.plugins[i].update(this); + } + /** + @internal + */ + measure(flush = true) { + if (this.destroyed) + return; + if (this.measureScheduled > -1) + cancelAnimationFrame(this.measureScheduled); + this.measureScheduled = 0; // Prevent requestMeasure calls from scheduling another animation frame + if (flush) + this.observer.forceFlush(); + let updated = null; + let { scrollHeight, scrollTop, clientHeight } = this.scrollDOM; + let refHeight = scrollTop > scrollHeight - clientHeight - 4 ? scrollHeight : scrollTop; + try { + for (let i = 0;; i++) { + this.updateState = 1 /* UpdateState.Measuring */; + let oldViewport = this.viewport; + let refBlock = this.viewState.lineBlockAtHeight(refHeight); + let changed = this.viewState.measure(this); + if (!changed && !this.measureRequests.length && this.viewState.scrollTarget == null) + break; + if (i > 5) { + console.warn(this.measureRequests.length + ? "Measure loop restarted more than 5 times" + : "Viewport failed to stabilize"); + break; + } + let measuring = []; + // Only run measure requests in this cycle when the viewport didn't change + if (!(changed & 4 /* UpdateFlag.Viewport */)) + [this.measureRequests, measuring] = [measuring, this.measureRequests]; + let measured = measuring.map(m => { + try { + return m.read(this); + } + catch (e) { + logException(this.state, e); + return BadMeasure; + } + }); + let update = ViewUpdate.create(this, this.state, []), redrawn = false, scrolled = false; + update.flags |= changed; + if (!updated) + updated = update; + else + updated.flags |= changed; + this.updateState = 2 /* UpdateState.Updating */; + if (!update.empty) { + this.updatePlugins(update); + this.inputState.update(update); + this.updateAttrs(); + redrawn = this.docView.update(update); + } + for (let i = 0; i < measuring.length; i++) + if (measured[i] != BadMeasure) { + try { + let m = measuring[i]; + if (m.write) + m.write(measured[i], this); + } + catch (e) { + logException(this.state, e); + } + } + if (this.viewState.scrollTarget) { + this.docView.scrollIntoView(this.viewState.scrollTarget); + this.viewState.scrollTarget = null; + scrolled = true; + } + else { + let diff = this.viewState.lineBlockAt(refBlock.from).top - refBlock.top; + if (diff > 1 || diff < -1) { + this.scrollDOM.scrollTop += diff; + scrolled = true; + } + } + if (redrawn) + this.docView.updateSelection(true); + if (this.viewport.from == oldViewport.from && this.viewport.to == oldViewport.to && + !scrolled && this.measureRequests.length == 0) + break; + } + } + finally { + this.updateState = 0 /* UpdateState.Idle */; + this.measureScheduled = -1; + } + if (updated && !updated.empty) + for (let listener of this.state.facet(updateListener)) + listener(updated); + } + /** + Get the CSS classes for the currently active editor themes. + */ + get themeClasses() { + return baseThemeID + " " + + (this.state.facet(darkTheme) ? baseDarkID : baseLightID) + " " + + this.state.facet(theme); + } + updateAttrs() { + let editorAttrs = attrsFromFacet(this, editorAttributes, { + class: "cm-editor" + (this.hasFocus ? " cm-focused " : " ") + this.themeClasses + }); + let contentAttrs = { + spellcheck: "false", + autocorrect: "off", + autocapitalize: "off", + translate: "no", + contenteditable: !this.state.facet(editable) ? "false" : "true", + class: "cm-content", + style: `${browser.tabSize}: ${this.state.tabSize}`, + role: "textbox", + "aria-multiline": "true" + }; + if (this.state.readOnly) + contentAttrs["aria-readonly"] = "true"; + attrsFromFacet(this, contentAttributes, contentAttrs); + let changed = this.observer.ignore(() => { + let changedContent = updateAttrs(this.contentDOM, this.contentAttrs, contentAttrs); + let changedEditor = updateAttrs(this.dom, this.editorAttrs, editorAttrs); + return changedContent || changedEditor; + }); + this.editorAttrs = editorAttrs; + this.contentAttrs = contentAttrs; + return changed; + } + showAnnouncements(trs) { + let first = true; + for (let tr of trs) + for (let effect of tr.effects) + if (effect.is(EditorView.announce)) { + if (first) + this.announceDOM.textContent = ""; + first = false; + let div = this.announceDOM.appendChild(document.createElement("div")); + div.textContent = effect.value; + } + } + mountStyles() { + this.styleModules = this.state.facet(styleModule); + StyleModule.mount(this.root, this.styleModules.concat(baseTheme$1$3).reverse()); + } + readMeasured() { + if (this.updateState == 2 /* UpdateState.Updating */) + throw new Error("Reading the editor layout isn't allowed during an update"); + if (this.updateState == 0 /* UpdateState.Idle */ && this.measureScheduled > -1) + this.measure(false); + } + /** + Schedule a layout measurement, optionally providing callbacks to + do custom DOM measuring followed by a DOM write phase. Using + this is preferable reading DOM layout directly from, for + example, an event handler, because it'll make sure measuring and + drawing done by other components is synchronized, avoiding + unnecessary DOM layout computations. + */ + requestMeasure(request) { + if (this.measureScheduled < 0) + this.measureScheduled = this.win.requestAnimationFrame(() => this.measure()); + if (request) { + if (request.key != null) + for (let i = 0; i < this.measureRequests.length; i++) { + if (this.measureRequests[i].key === request.key) { + this.measureRequests[i] = request; + return; + } + } + this.measureRequests.push(request); + } + } + /** + Get the value of a specific plugin, if present. Note that + plugins that crash can be dropped from a view, so even when you + know you registered a given plugin, it is recommended to check + the return value of this method. + */ + plugin(plugin) { + let known = this.pluginMap.get(plugin); + if (known === undefined || known && known.spec != plugin) + this.pluginMap.set(plugin, known = this.plugins.find(p => p.spec == plugin) || null); + return known && known.update(this).value; + } + /** + The top position of the document, in screen coordinates. This + may be negative when the editor is scrolled down. Points + directly to the top of the first line, not above the padding. + */ + get documentTop() { + return this.contentDOM.getBoundingClientRect().top + this.viewState.paddingTop; + } + /** + Reports the padding above and below the document. + */ + get documentPadding() { + return { top: this.viewState.paddingTop, bottom: this.viewState.paddingBottom }; + } + /** + Find the text line or block widget at the given vertical + position (which is interpreted as relative to the [top of the + document](https://codemirror.net/6/docs/ref/#view.EditorView.documentTop)). + */ + elementAtHeight(height) { + this.readMeasured(); + return this.viewState.elementAtHeight(height); + } + /** + Find the line block (see + [`lineBlockAt`](https://codemirror.net/6/docs/ref/#view.EditorView.lineBlockAt) at the given + height, again interpreted relative to the [top of the + document](https://codemirror.net/6/docs/ref/#view.EditorView.documentTop). + */ + lineBlockAtHeight(height) { + this.readMeasured(); + return this.viewState.lineBlockAtHeight(height); + } + /** + Get the extent and vertical position of all [line + blocks](https://codemirror.net/6/docs/ref/#view.EditorView.lineBlockAt) in the viewport. Positions + are relative to the [top of the + document](https://codemirror.net/6/docs/ref/#view.EditorView.documentTop); + */ + get viewportLineBlocks() { + return this.viewState.viewportLines; + } + /** + Find the line block around the given document position. A line + block is a range delimited on both sides by either a + non-[hidden](https://codemirror.net/6/docs/ref/#view.Decoration^replace) line breaks, or the + start/end of the document. It will usually just hold a line of + text, but may be broken into multiple textblocks by block + widgets. + */ + lineBlockAt(pos) { + return this.viewState.lineBlockAt(pos); + } + /** + The editor's total content height. + */ + get contentHeight() { + return this.viewState.contentHeight; + } + /** + Move a cursor position by [grapheme + cluster](https://codemirror.net/6/docs/ref/#state.findClusterBreak). `forward` determines whether + the motion is away from the line start, or towards it. In + bidirectional text, the line is traversed in visual order, using + the editor's [text direction](https://codemirror.net/6/docs/ref/#view.EditorView.textDirection). + When the start position was the last one on the line, the + returned position will be across the line break. If there is no + further line, the original position is returned. + + By default, this method moves over a single cluster. The + optional `by` argument can be used to move across more. It will + be called with the first cluster as argument, and should return + a predicate that determines, for each subsequent cluster, + whether it should also be moved over. + */ + moveByChar(start, forward, by) { + return skipAtoms(this, start, moveByChar(this, start, forward, by)); + } + /** + Move a cursor position across the next group of either + [letters](https://codemirror.net/6/docs/ref/#state.EditorState.charCategorizer) or non-letter + non-whitespace characters. + */ + moveByGroup(start, forward) { + return skipAtoms(this, start, moveByChar(this, start, forward, initial => byGroup(this, start.head, initial))); + } + /** + Move to the next line boundary in the given direction. If + `includeWrap` is true, line wrapping is on, and there is a + further wrap point on the current line, the wrap point will be + returned. Otherwise this function will return the start or end + of the line. + */ + moveToLineBoundary(start, forward, includeWrap = true) { + return moveToLineBoundary(this, start, forward, includeWrap); + } + /** + Move a cursor position vertically. When `distance` isn't given, + it defaults to moving to the next line (including wrapped + lines). Otherwise, `distance` should provide a positive distance + in pixels. + + When `start` has a + [`goalColumn`](https://codemirror.net/6/docs/ref/#state.SelectionRange.goalColumn), the vertical + motion will use that as a target horizontal position. Otherwise, + the cursor's own horizontal position is used. The returned + cursor will have its goal column set to whichever column was + used. + */ + moveVertically(start, forward, distance) { + return skipAtoms(this, start, moveVertically(this, start, forward, distance)); + } + /** + Find the DOM parent node and offset (child offset if `node` is + an element, character offset when it is a text node) at the + given document position. + + Note that for positions that aren't currently in + `visibleRanges`, the resulting DOM position isn't necessarily + meaningful (it may just point before or after a placeholder + element). + */ + domAtPos(pos) { + return this.docView.domAtPos(pos); + } + /** + Find the document position at the given DOM node. Can be useful + for associating positions with DOM events. Will raise an error + when `node` isn't part of the editor content. + */ + posAtDOM(node, offset = 0) { + return this.docView.posFromDOM(node, offset); + } + posAtCoords(coords, precise = true) { + this.readMeasured(); + return posAtCoords(this, coords, precise); + } + /** + Get the screen coordinates at the given document position. + `side` determines whether the coordinates are based on the + element before (-1) or after (1) the position (if no element is + available on the given side, the method will transparently use + another strategy to get reasonable coordinates). + */ + coordsAtPos(pos, side = 1) { + this.readMeasured(); + let rect = this.docView.coordsAt(pos, side); + if (!rect || rect.left == rect.right) + return rect; + let line = this.state.doc.lineAt(pos), order = this.bidiSpans(line); + let span = order[BidiSpan.find(order, pos - line.from, -1, side)]; + return flattenRect(rect, (span.dir == Direction.LTR) == (side > 0)); + } + /** + The default width of a character in the editor. May not + accurately reflect the width of all characters (given variable + width fonts or styling of invididual ranges). + */ + get defaultCharacterWidth() { return this.viewState.heightOracle.charWidth; } + /** + The default height of a line in the editor. May not be accurate + for all lines. + */ + get defaultLineHeight() { return this.viewState.heightOracle.lineHeight; } + /** + The text direction + ([`direction`](https://developer.mozilla.org/en-US/docs/Web/CSS/direction) + CSS property) of the editor's content element. + */ + get textDirection() { return this.viewState.defaultTextDirection; } + /** + Find the text direction of the block at the given position, as + assigned by CSS. If + [`perLineTextDirection`](https://codemirror.net/6/docs/ref/#view.EditorView^perLineTextDirection) + isn't enabled, or the given position is outside of the viewport, + this will always return the same as + [`textDirection`](https://codemirror.net/6/docs/ref/#view.EditorView.textDirection). Note that + this may trigger a DOM layout. + */ + textDirectionAt(pos) { + let perLine = this.state.facet(perLineTextDirection); + if (!perLine || pos < this.viewport.from || pos > this.viewport.to) + return this.textDirection; + this.readMeasured(); + return this.docView.textDirectionAt(pos); + } + /** + Whether this editor [wraps lines](https://codemirror.net/6/docs/ref/#view.EditorView.lineWrapping) + (as determined by the + [`white-space`](https://developer.mozilla.org/en-US/docs/Web/CSS/white-space) + CSS property of its content element). + */ + get lineWrapping() { return this.viewState.heightOracle.lineWrapping; } + /** + Returns the bidirectional text structure of the given line + (which should be in the current document) as an array of span + objects. The order of these spans matches the [text + direction](https://codemirror.net/6/docs/ref/#view.EditorView.textDirection)—if that is + left-to-right, the leftmost spans come first, otherwise the + rightmost spans come first. + */ + bidiSpans(line) { + if (line.length > MaxBidiLine) + return trivialOrder(line.length); + let dir = this.textDirectionAt(line.from); + for (let entry of this.bidiCache) + if (entry.from == line.from && entry.dir == dir) + return entry.order; + let order = computeOrder(line.text, dir); + this.bidiCache.push(new CachedOrder(line.from, line.to, dir, order)); + return order; + } + /** + Check whether the editor has focus. + */ + get hasFocus() { + var _a; + // Safari return false for hasFocus when the context menu is open + // or closing, which leads us to ignore selection changes from the + // context menu because it looks like the editor isn't focused. + // This kludges around that. + return (this.dom.ownerDocument.hasFocus() || browser.safari && ((_a = this.inputState) === null || _a === void 0 ? void 0 : _a.lastContextMenu) > Date.now() - 3e4) && + this.root.activeElement == this.contentDOM; + } + /** + Put focus on the editor. + */ + focus() { + this.observer.ignore(() => { + focusPreventScroll(this.contentDOM); + this.docView.updateSelection(); + }); + } + /** + Update the [root](https://codemirror.net/6/docs/ref/##view.EditorViewConfig.root) in which the editor lives. This is only + necessary when moving the editor's existing DOM to a new window or shadow root. + */ + setRoot(root) { + if (this._root != root) { + this._root = root; + this.observer.setWindow((root.nodeType == 9 ? root : root.ownerDocument).defaultView || window); + this.mountStyles(); + } + } + /** + Clean up this editor view, removing its element from the + document, unregistering event handlers, and notifying + plugins. The view instance can no longer be used after + calling this. + */ + destroy() { + for (let plugin of this.plugins) + plugin.destroy(this); + this.plugins = []; + this.inputState.destroy(); + this.dom.remove(); + this.observer.destroy(); + if (this.measureScheduled > -1) + cancelAnimationFrame(this.measureScheduled); + this.destroyed = true; + } + /** + Returns an effect that can be + [added](https://codemirror.net/6/docs/ref/#state.TransactionSpec.effects) to a transaction to + cause it to scroll the given position or range into view. + */ + static scrollIntoView(pos, options = {}) { + return scrollIntoView$1.of(new ScrollTarget(typeof pos == "number" ? EditorSelection.cursor(pos) : pos, options.y, options.x, options.yMargin, options.xMargin)); + } + /** + Returns an extension that can be used to add DOM event handlers. + The value should be an object mapping event names to handler + functions. For any given event, such functions are ordered by + extension precedence, and the first handler to return true will + be assumed to have handled that event, and no other handlers or + built-in behavior will be activated for it. These are registered + on the [content element](https://codemirror.net/6/docs/ref/#view.EditorView.contentDOM), except + for `scroll` handlers, which will be called any time the + editor's [scroll element](https://codemirror.net/6/docs/ref/#view.EditorView.scrollDOM) or one of + its parent nodes is scrolled. + */ + static domEventHandlers(handlers) { + return ViewPlugin.define(() => ({}), { eventHandlers: handlers }); + } + /** + Create a theme extension. The first argument can be a + [`style-mod`](https://github.com/marijnh/style-mod#documentation) + style spec providing the styles for the theme. These will be + prefixed with a generated class for the style. + + Because the selectors will be prefixed with a scope class, rule + that directly match the editor's [wrapper + element](https://codemirror.net/6/docs/ref/#view.EditorView.dom)—to which the scope class will be + added—need to be explicitly differentiated by adding an `&` to + the selector for that element—for example + `&.cm-focused`. + + When `dark` is set to true, the theme will be marked as dark, + which will cause the `&dark` rules from [base + themes](https://codemirror.net/6/docs/ref/#view.EditorView^baseTheme) to be used (as opposed to + `&light` when a light theme is active). + */ + static theme(spec, options) { + let prefix = StyleModule.newName(); + let result = [theme.of(prefix), styleModule.of(buildTheme(`.${prefix}`, spec))]; + if (options && options.dark) + result.push(darkTheme.of(true)); + return result; + } + /** + Create an extension that adds styles to the base theme. Like + with [`theme`](https://codemirror.net/6/docs/ref/#view.EditorView^theme), use `&` to indicate the + place of the editor wrapper element when directly targeting + that. You can also use `&dark` or `&light` instead to only + target editors with a dark or light theme. + */ + static baseTheme(spec) { + return Prec.lowest(styleModule.of(buildTheme("." + baseThemeID, spec, lightDarkIDs))); + } + /** + Retrieve an editor view instance from the view's DOM + representation. + */ + static findFromDOM(dom) { + var _a; + let content = dom.querySelector(".cm-content"); + let cView = content && ContentView.get(content) || ContentView.get(dom); + return ((_a = cView === null || cView === void 0 ? void 0 : cView.rootView) === null || _a === void 0 ? void 0 : _a.view) || null; + } + } + /** + Facet to add a [style + module](https://github.com/marijnh/style-mod#documentation) to + an editor view. The view will ensure that the module is + mounted in its [document + root](https://codemirror.net/6/docs/ref/#view.EditorView.constructor^config.root). + */ + EditorView.styleModule = styleModule; + /** + An input handler can override the way changes to the editable + DOM content are handled. Handlers are passed the document + positions between which the change was found, and the new + content. When one returns true, no further input handlers are + called and the default behavior is prevented. + */ + EditorView.inputHandler = inputHandler$1; + /** + By default, the editor assumes all its content has the same + [text direction](https://codemirror.net/6/docs/ref/#view.Direction). Configure this with a `true` + value to make it read the text direction of every (rendered) + line separately. + */ + EditorView.perLineTextDirection = perLineTextDirection; + /** + Allows you to provide a function that should be called when the + library catches an exception from an extension (mostly from view + plugins, but may be used by other extensions to route exceptions + from user-code-provided callbacks). This is mostly useful for + debugging and logging. See [`logException`](https://codemirror.net/6/docs/ref/#view.logException). + */ + EditorView.exceptionSink = exceptionSink; + /** + A facet that can be used to register a function to be called + every time the view updates. + */ + EditorView.updateListener = updateListener; + /** + Facet that controls whether the editor content DOM is editable. + When its highest-precedence value is `false`, the element will + not have its `contenteditable` attribute set. (Note that this + doesn't affect API calls that change the editor content, even + when those are bound to keys or buttons. See the + [`readOnly`](https://codemirror.net/6/docs/ref/#state.EditorState.readOnly) facet for that.) + */ + EditorView.editable = editable; + /** + Allows you to influence the way mouse selection happens. The + functions in this facet will be called for a `mousedown` event + on the editor, and can return an object that overrides the way a + selection is computed from that mouse click or drag. + */ + EditorView.mouseSelectionStyle = mouseSelectionStyle; + /** + Facet used to configure whether a given selection drag event + should move or copy the selection. The given predicate will be + called with the `mousedown` event, and can return `true` when + the drag should move the content. + */ + EditorView.dragMovesSelection = dragMovesSelection$1; + /** + Facet used to configure whether a given selecting click adds a + new range to the existing selection or replaces it entirely. The + default behavior is to check `event.metaKey` on macOS, and + `event.ctrlKey` elsewhere. + */ + EditorView.clickAddsSelectionRange = clickAddsSelectionRange; + /** + A facet that determines which [decorations](https://codemirror.net/6/docs/ref/#view.Decoration) + are shown in the view. Decorations can be provided in two + ways—directly, or via a function that takes an editor view. + + Only decoration sets provided directly are allowed to influence + the editor's vertical layout structure. The ones provided as + functions are called _after_ the new viewport has been computed, + and thus **must not** introduce block widgets or replacing + decorations that cover line breaks. + + If you want decorated ranges to behave like atomic units for + cursor motion and deletion purposes, also provide the range set + containing the decorations to + [`EditorView.atomicRanges`](https://codemirror.net/6/docs/ref/#view.EditorView^atomicRanges). + */ + EditorView.decorations = decorations; + /** + Used to provide ranges that should be treated as atoms as far as + cursor motion is concerned. This causes methods like + [`moveByChar`](https://codemirror.net/6/docs/ref/#view.EditorView.moveByChar) and + [`moveVertically`](https://codemirror.net/6/docs/ref/#view.EditorView.moveVertically) (and the + commands built on top of them) to skip across such regions when + a selection endpoint would enter them. This does _not_ prevent + direct programmatic [selection + updates](https://codemirror.net/6/docs/ref/#state.TransactionSpec.selection) from moving into such + regions. + */ + EditorView.atomicRanges = atomicRanges; + /** + Facet that allows extensions to provide additional scroll + margins (space around the sides of the scrolling element that + should be considered invisible). This can be useful when the + plugin introduces elements that cover part of that element (for + example a horizontally fixed gutter). + */ + EditorView.scrollMargins = scrollMargins; + /** + This facet records whether a dark theme is active. The extension + returned by [`theme`](https://codemirror.net/6/docs/ref/#view.EditorView^theme) automatically + includes an instance of this when the `dark` option is set to + true. + */ + EditorView.darkTheme = darkTheme; + /** + Facet that provides additional DOM attributes for the editor's + editable DOM element. + */ + EditorView.contentAttributes = contentAttributes; + /** + Facet that provides DOM attributes for the editor's outer + element. + */ + EditorView.editorAttributes = editorAttributes; + /** + An extension that enables line wrapping in the editor (by + setting CSS `white-space` to `pre-wrap` in the content). + */ + EditorView.lineWrapping = /*@__PURE__*/EditorView.contentAttributes.of({ "class": "cm-lineWrapping" }); + /** + State effect used to include screen reader announcements in a + transaction. These will be added to the DOM in a visually hidden + element with `aria-live="polite"` set, and should be used to + describe effects that are visually obvious but may not be + noticed by screen reader users (such as moving to the next + search match). + */ + EditorView.announce = /*@__PURE__*/StateEffect.define(); + // Maximum line length for which we compute accurate bidi info + const MaxBidiLine = 4096; + const BadMeasure = {}; + class CachedOrder { + constructor(from, to, dir, order) { + this.from = from; + this.to = to; + this.dir = dir; + this.order = order; + } + static update(cache, changes) { + if (changes.empty) + return cache; + let result = [], lastDir = cache.length ? cache[cache.length - 1].dir : Direction.LTR; + for (let i = Math.max(0, cache.length - 10); i < cache.length; i++) { + let entry = cache[i]; + if (entry.dir == lastDir && !changes.touchesRange(entry.from, entry.to)) + result.push(new CachedOrder(changes.mapPos(entry.from, 1), changes.mapPos(entry.to, -1), entry.dir, entry.order)); + } + return result; + } + } + function attrsFromFacet(view, facet, base) { + for (let sources = view.state.facet(facet), i = sources.length - 1; i >= 0; i--) { + let source = sources[i], value = typeof source == "function" ? source(view) : source; + if (value) + combineAttrs(value, base); + } + return base; + } + + const currentPlatform = browser.mac ? "mac" : browser.windows ? "win" : browser.linux ? "linux" : "key"; + function normalizeKeyName(name, platform) { + const parts = name.split(/-(?!$)/); + let result = parts[parts.length - 1]; + if (result == "Space") + result = " "; + let alt, ctrl, shift, meta; + for (let i = 0; i < parts.length - 1; ++i) { + const mod = parts[i]; + if (/^(cmd|meta|m)$/i.test(mod)) + meta = 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 if (/^mod$/i.test(mod)) { + if (platform == "mac") + meta = true; + else + ctrl = true; + } + else + throw new Error("Unrecognized modifier name: " + mod); + } + if (alt) + result = "Alt-" + result; + if (ctrl) + result = "Ctrl-" + result; + if (meta) + result = "Meta-" + result; + if (shift) + result = "Shift-" + result; + return result; + } + function modifiers(name, event, shift) { + if (event.altKey) + name = "Alt-" + name; + if (event.ctrlKey) + name = "Ctrl-" + name; + if (event.metaKey) + name = "Meta-" + name; + if (shift !== false && event.shiftKey) + name = "Shift-" + name; + return name; + } + const handleKeyEvents = /*@__PURE__*/Prec.default(/*@__PURE__*/EditorView.domEventHandlers({ + keydown(event, view) { + return runHandlers(getKeymap(view.state), event, view, "editor"); + } + })); + /** + Facet used for registering keymaps. + + You can add multiple keymaps to an editor. Their priorities + determine their precedence (the ones specified early or with high + priority get checked first). When a handler has returned `true` + for a given key, no further handlers are called. + */ + const keymap = /*@__PURE__*/Facet.define({ enables: handleKeyEvents }); + const Keymaps = /*@__PURE__*/new WeakMap(); + // This is hidden behind an indirection, rather than directly computed + // by the facet, to keep internal types out of the facet's type. + function getKeymap(state) { + let bindings = state.facet(keymap); + let map = Keymaps.get(bindings); + if (!map) + Keymaps.set(bindings, map = buildKeymap(bindings.reduce((a, b) => a.concat(b), []))); + return map; + } + /** + Run the key handlers registered for a given scope. The event + object should be a `"keydown"` event. Returns true if any of the + handlers handled it. + */ + function runScopeHandlers(view, event, scope) { + return runHandlers(getKeymap(view.state), event, view, scope); + } + let storedPrefix = null; + const PrefixTimeout = 4000; + function buildKeymap(bindings, platform = currentPlatform) { + let bound = Object.create(null); + let isPrefix = Object.create(null); + let checkPrefix = (name, is) => { + let current = isPrefix[name]; + if (current == null) + isPrefix[name] = is; + else if (current != is) + throw new Error("Key binding " + name + " is used both as a regular binding and as a multi-stroke prefix"); + }; + let add = (scope, key, command, preventDefault) => { + var _a, _b; + let scopeObj = bound[scope] || (bound[scope] = Object.create(null)); + let parts = key.split(/ (?!$)/).map(k => normalizeKeyName(k, platform)); + for (let i = 1; i < parts.length; i++) { + let prefix = parts.slice(0, i).join(" "); + checkPrefix(prefix, true); + if (!scopeObj[prefix]) + scopeObj[prefix] = { + preventDefault: true, + run: [(view) => { + let ourObj = storedPrefix = { view, prefix, scope }; + setTimeout(() => { if (storedPrefix == ourObj) + storedPrefix = null; }, PrefixTimeout); + return true; + }] + }; + } + let full = parts.join(" "); + checkPrefix(full, false); + let binding = scopeObj[full] || (scopeObj[full] = { preventDefault: false, run: ((_b = (_a = scopeObj._any) === null || _a === void 0 ? void 0 : _a.run) === null || _b === void 0 ? void 0 : _b.slice()) || [] }); + if (command) + binding.run.push(command); + if (preventDefault) + binding.preventDefault = true; + }; + for (let b of bindings) { + let scopes = b.scope ? b.scope.split(" ") : ["editor"]; + if (b.any) + for (let scope of scopes) { + let scopeObj = bound[scope] || (bound[scope] = Object.create(null)); + if (!scopeObj._any) + scopeObj._any = { preventDefault: false, run: [] }; + for (let key in scopeObj) + scopeObj[key].run.push(b.any); + } + let name = b[platform] || b.key; + if (!name) + continue; + for (let scope of scopes) { + add(scope, name, b.run, b.preventDefault); + if (b.shift) + add(scope, "Shift-" + name, b.shift, b.preventDefault); + } + } + return bound; + } + function runHandlers(map, event, view, scope) { + let name = keyName(event); + let charCode = codePointAt(name, 0), isChar = codePointSize(charCode) == name.length && name != " "; + let prefix = "", fallthrough = false; + if (storedPrefix && storedPrefix.view == view && storedPrefix.scope == scope) { + prefix = storedPrefix.prefix + " "; + if (fallthrough = modifierCodes.indexOf(event.keyCode) < 0) + storedPrefix = null; + } + let ran = new Set; + let runFor = (binding) => { + if (binding) { + for (let cmd of binding.run) + if (!ran.has(cmd)) { + ran.add(cmd); + if (cmd(view, event)) + return true; + } + if (binding.preventDefault) + fallthrough = true; + } + return false; + }; + let scopeObj = map[scope], baseName, shiftName; + if (scopeObj) { + if (runFor(scopeObj[prefix + modifiers(name, event, !isChar)])) + return true; + if (isChar && (event.shiftKey || event.altKey || event.metaKey || charCode > 127) && + (baseName = base[event.keyCode]) && baseName != name) { + if (runFor(scopeObj[prefix + modifiers(baseName, event, true)])) + return true; + else if (event.shiftKey && (shiftName = shift[event.keyCode]) != name && shiftName != baseName && + runFor(scopeObj[prefix + modifiers(shiftName, event, false)])) + return true; + } + else if (isChar && event.shiftKey) { + if (runFor(scopeObj[prefix + modifiers(name, event, true)])) + return true; + } + if (runFor(scopeObj._any)) + return true; + } + return fallthrough; + } + + const CanHidePrimary = !browser.ios; // FIXME test IE + const selectionConfig = /*@__PURE__*/Facet.define({ + combine(configs) { + return combineConfig(configs, { + cursorBlinkRate: 1200, + drawRangeCursor: true + }, { + cursorBlinkRate: (a, b) => Math.min(a, b), + drawRangeCursor: (a, b) => a || b + }); + } + }); + /** + Returns an extension that hides the browser's native selection and + cursor, replacing the selection with a background behind the text + (with the `cm-selectionBackground` class), and the + cursors with elements overlaid over the code (using + `cm-cursor-primary` and `cm-cursor-secondary`). + + This allows the editor to display secondary selection ranges, and + tends to produce a type of selection more in line with that users + expect in a text editor (the native selection styling will often + leave gaps between lines and won't fill the horizontal space after + a line when the selection continues past it). + + It does have a performance cost, in that it requires an extra DOM + layout cycle for many updates (the selection is drawn based on DOM + layout information that's only available after laying out the + content). + */ + function drawSelection(config = {}) { + return [ + selectionConfig.of(config), + drawSelectionPlugin, + hideNativeSelection + ]; + } + class Piece { + constructor(left, top, width, height, className) { + this.left = left; + this.top = top; + this.width = width; + this.height = height; + this.className = className; + } + draw() { + let elt = document.createElement("div"); + elt.className = this.className; + this.adjust(elt); + return elt; + } + adjust(elt) { + elt.style.left = this.left + "px"; + elt.style.top = this.top + "px"; + if (this.width >= 0) + elt.style.width = this.width + "px"; + elt.style.height = this.height + "px"; + } + eq(p) { + return this.left == p.left && this.top == p.top && this.width == p.width && this.height == p.height && + this.className == p.className; + } + } + const drawSelectionPlugin = /*@__PURE__*/ViewPlugin.fromClass(class { + constructor(view) { + this.view = view; + this.rangePieces = []; + this.cursors = []; + this.measureReq = { read: this.readPos.bind(this), write: this.drawSel.bind(this) }; + this.selectionLayer = view.scrollDOM.appendChild(document.createElement("div")); + this.selectionLayer.className = "cm-selectionLayer"; + this.selectionLayer.setAttribute("aria-hidden", "true"); + this.cursorLayer = view.scrollDOM.appendChild(document.createElement("div")); + this.cursorLayer.className = "cm-cursorLayer"; + this.cursorLayer.setAttribute("aria-hidden", "true"); + view.requestMeasure(this.measureReq); + this.setBlinkRate(); + } + setBlinkRate() { + this.cursorLayer.style.animationDuration = this.view.state.facet(selectionConfig).cursorBlinkRate + "ms"; + } + update(update) { + let confChanged = update.startState.facet(selectionConfig) != update.state.facet(selectionConfig); + if (confChanged || update.selectionSet || update.geometryChanged || update.viewportChanged) + this.view.requestMeasure(this.measureReq); + if (update.transactions.some(tr => tr.scrollIntoView)) + this.cursorLayer.style.animationName = this.cursorLayer.style.animationName == "cm-blink" ? "cm-blink2" : "cm-blink"; + if (confChanged) + this.setBlinkRate(); + } + readPos() { + let { state } = this.view, conf = state.facet(selectionConfig); + let rangePieces = state.selection.ranges.map(r => r.empty ? [] : measureRange(this.view, r)).reduce((a, b) => a.concat(b)); + let cursors = []; + for (let r of state.selection.ranges) { + let prim = r == state.selection.main; + if (r.empty ? !prim || CanHidePrimary : conf.drawRangeCursor) { + let piece = measureCursor(this.view, r, prim); + if (piece) + cursors.push(piece); + } + } + return { rangePieces, cursors }; + } + drawSel({ rangePieces, cursors }) { + if (rangePieces.length != this.rangePieces.length || rangePieces.some((p, i) => !p.eq(this.rangePieces[i]))) { + this.selectionLayer.textContent = ""; + for (let p of rangePieces) + this.selectionLayer.appendChild(p.draw()); + this.rangePieces = rangePieces; + } + if (cursors.length != this.cursors.length || cursors.some((c, i) => !c.eq(this.cursors[i]))) { + let oldCursors = this.cursorLayer.children; + if (oldCursors.length !== cursors.length) { + this.cursorLayer.textContent = ""; + for (const c of cursors) + this.cursorLayer.appendChild(c.draw()); + } + else { + cursors.forEach((c, idx) => c.adjust(oldCursors[idx])); + } + this.cursors = cursors; + } + } + destroy() { + this.selectionLayer.remove(); + this.cursorLayer.remove(); + } + }); + const themeSpec = { + ".cm-line": { + "& ::selection": { backgroundColor: "transparent !important" }, + "&::selection": { backgroundColor: "transparent !important" } + } + }; + if (CanHidePrimary) + themeSpec[".cm-line"].caretColor = "transparent !important"; + const hideNativeSelection = /*@__PURE__*/Prec.highest(/*@__PURE__*/EditorView.theme(themeSpec)); + function getBase(view) { + let rect = view.scrollDOM.getBoundingClientRect(); + let left = view.textDirection == Direction.LTR ? rect.left : rect.right - view.scrollDOM.clientWidth; + return { left: left - view.scrollDOM.scrollLeft, top: rect.top - view.scrollDOM.scrollTop }; + } + function wrappedLine(view, pos, inside) { + let range = EditorSelection.cursor(pos); + return { from: Math.max(inside.from, view.moveToLineBoundary(range, false, true).from), + to: Math.min(inside.to, view.moveToLineBoundary(range, true, true).from), + type: BlockType.Text }; + } + function blockAt(view, pos) { + let line = view.lineBlockAt(pos); + if (Array.isArray(line.type)) + for (let l of line.type) { + if (l.to > pos || l.to == pos && (l.to == line.to || l.type == BlockType.Text)) + return l; + } + return line; + } + function measureRange(view, range) { + if (range.to <= view.viewport.from || range.from >= view.viewport.to) + return []; + let from = Math.max(range.from, view.viewport.from), to = Math.min(range.to, view.viewport.to); + let ltr = view.textDirection == Direction.LTR; + let content = view.contentDOM, contentRect = content.getBoundingClientRect(), base = getBase(view); + let lineStyle = window.getComputedStyle(content.firstChild); + let leftSide = contentRect.left + parseInt(lineStyle.paddingLeft) + Math.min(0, parseInt(lineStyle.textIndent)); + let rightSide = contentRect.right - parseInt(lineStyle.paddingRight); + let startBlock = blockAt(view, from), endBlock = blockAt(view, to); + let visualStart = startBlock.type == BlockType.Text ? startBlock : null; + let visualEnd = endBlock.type == BlockType.Text ? endBlock : null; + if (view.lineWrapping) { + if (visualStart) + visualStart = wrappedLine(view, from, visualStart); + if (visualEnd) + visualEnd = wrappedLine(view, to, visualEnd); + } + if (visualStart && visualEnd && visualStart.from == visualEnd.from) { + return pieces(drawForLine(range.from, range.to, visualStart)); + } + else { + let top = visualStart ? drawForLine(range.from, null, visualStart) : drawForWidget(startBlock, false); + let bottom = visualEnd ? drawForLine(null, range.to, visualEnd) : drawForWidget(endBlock, true); + let between = []; + if ((visualStart || startBlock).to < (visualEnd || endBlock).from - 1) + between.push(piece(leftSide, top.bottom, rightSide, bottom.top)); + else if (top.bottom < bottom.top && view.elementAtHeight((top.bottom + bottom.top) / 2).type == BlockType.Text) + top.bottom = bottom.top = (top.bottom + bottom.top) / 2; + return pieces(top).concat(between).concat(pieces(bottom)); + } + function piece(left, top, right, bottom) { + return new Piece(left - base.left, top - base.top - 0.01 /* C.Epsilon */, right - left, bottom - top + 0.01 /* C.Epsilon */, "cm-selectionBackground"); + } + function pieces({ top, bottom, horizontal }) { + let pieces = []; + for (let i = 0; i < horizontal.length; i += 2) + pieces.push(piece(horizontal[i], top, horizontal[i + 1], bottom)); + return pieces; + } + // Gets passed from/to in line-local positions + function drawForLine(from, to, line) { + let top = 1e9, bottom = -1e9, horizontal = []; + function addSpan(from, fromOpen, to, toOpen, dir) { + // Passing 2/-2 is a kludge to force the view to return + // coordinates on the proper side of block widgets, since + // normalizing the side there, though appropriate for most + // coordsAtPos queries, would break selection drawing. + let fromCoords = view.coordsAtPos(from, (from == line.to ? -2 : 2)); + let toCoords = view.coordsAtPos(to, (to == line.from ? 2 : -2)); + top = Math.min(fromCoords.top, toCoords.top, top); + bottom = Math.max(fromCoords.bottom, toCoords.bottom, bottom); + if (dir == Direction.LTR) + horizontal.push(ltr && fromOpen ? leftSide : fromCoords.left, ltr && toOpen ? rightSide : toCoords.right); + else + horizontal.push(!ltr && toOpen ? leftSide : toCoords.left, !ltr && fromOpen ? rightSide : fromCoords.right); + } + let start = from !== null && from !== void 0 ? from : line.from, end = to !== null && to !== void 0 ? to : line.to; + // Split the range by visible range and document line + for (let r of view.visibleRanges) + if (r.to > start && r.from < end) { + for (let pos = Math.max(r.from, start), endPos = Math.min(r.to, end);;) { + let docLine = view.state.doc.lineAt(pos); + for (let span of view.bidiSpans(docLine)) { + let spanFrom = span.from + docLine.from, spanTo = span.to + docLine.from; + if (spanFrom >= endPos) + break; + if (spanTo > pos) + addSpan(Math.max(spanFrom, pos), from == null && spanFrom <= start, Math.min(spanTo, endPos), to == null && spanTo >= end, span.dir); + } + pos = docLine.to + 1; + if (pos >= endPos) + break; + } + } + if (horizontal.length == 0) + addSpan(start, from == null, end, to == null, view.textDirection); + return { top, bottom, horizontal }; + } + function drawForWidget(block, top) { + let y = contentRect.top + (top ? block.top : block.bottom); + return { top: y, bottom: y, horizontal: [] }; + } + } + function measureCursor(view, cursor, primary) { + let pos = view.coordsAtPos(cursor.head, cursor.assoc || 1); + if (!pos) + return null; + let base = getBase(view); + return new Piece(pos.left - base.left, pos.top - base.top, -1, pos.bottom - pos.top, primary ? "cm-cursor cm-cursor-primary" : "cm-cursor cm-cursor-secondary"); + } + + const setDropCursorPos = /*@__PURE__*/StateEffect.define({ + map(pos, mapping) { return pos == null ? null : mapping.mapPos(pos); } + }); + const dropCursorPos = /*@__PURE__*/StateField.define({ + create() { return null; }, + update(pos, tr) { + if (pos != null) + pos = tr.changes.mapPos(pos); + return tr.effects.reduce((pos, e) => e.is(setDropCursorPos) ? e.value : pos, pos); + } + }); + const drawDropCursor = /*@__PURE__*/ViewPlugin.fromClass(class { + constructor(view) { + this.view = view; + this.cursor = null; + this.measureReq = { read: this.readPos.bind(this), write: this.drawCursor.bind(this) }; + } + update(update) { + var _a; + let cursorPos = update.state.field(dropCursorPos); + if (cursorPos == null) { + if (this.cursor != null) { + (_a = this.cursor) === null || _a === void 0 ? void 0 : _a.remove(); + this.cursor = null; + } + } + else { + if (!this.cursor) { + this.cursor = this.view.scrollDOM.appendChild(document.createElement("div")); + this.cursor.className = "cm-dropCursor"; + } + if (update.startState.field(dropCursorPos) != cursorPos || update.docChanged || update.geometryChanged) + this.view.requestMeasure(this.measureReq); + } + } + readPos() { + let pos = this.view.state.field(dropCursorPos); + let rect = pos != null && this.view.coordsAtPos(pos); + if (!rect) + return null; + let outer = this.view.scrollDOM.getBoundingClientRect(); + return { + left: rect.left - outer.left + this.view.scrollDOM.scrollLeft, + top: rect.top - outer.top + this.view.scrollDOM.scrollTop, + height: rect.bottom - rect.top + }; + } + drawCursor(pos) { + if (this.cursor) { + if (pos) { + this.cursor.style.left = pos.left + "px"; + this.cursor.style.top = pos.top + "px"; + this.cursor.style.height = pos.height + "px"; + } + else { + this.cursor.style.left = "-100000px"; + } + } + } + destroy() { + if (this.cursor) + this.cursor.remove(); + } + setDropPos(pos) { + if (this.view.state.field(dropCursorPos) != pos) + this.view.dispatch({ effects: setDropCursorPos.of(pos) }); + } + }, { + eventHandlers: { + dragover(event) { + this.setDropPos(this.view.posAtCoords({ x: event.clientX, y: event.clientY })); + }, + dragleave(event) { + if (event.target == this.view.contentDOM || !this.view.contentDOM.contains(event.relatedTarget)) + this.setDropPos(null); + }, + dragend() { + this.setDropPos(null); + }, + drop() { + this.setDropPos(null); + } + } + }); + /** + Draws a cursor at the current drop position when something is + dragged over the editor. + */ + function dropCursor() { + return [dropCursorPos, drawDropCursor]; + } + + function iterMatches(doc, re, from, to, f) { + re.lastIndex = 0; + for (let cursor = doc.iterRange(from, to), pos = from, m; !cursor.next().done; pos += cursor.value.length) { + if (!cursor.lineBreak) + while (m = re.exec(cursor.value)) + f(pos + m.index, m); + } + } + function matchRanges(view, maxLength) { + let visible = view.visibleRanges; + if (visible.length == 1 && visible[0].from == view.viewport.from && + visible[0].to == view.viewport.to) + return visible; + let result = []; + for (let { from, to } of visible) { + from = Math.max(view.state.doc.lineAt(from).from, from - maxLength); + to = Math.min(view.state.doc.lineAt(to).to, to + maxLength); + if (result.length && result[result.length - 1].to >= from) + result[result.length - 1].to = to; + else + result.push({ from, to }); + } + return result; + } + /** + Helper class used to make it easier to maintain decorations on + visible code that matches a given regular expression. To be used + in a [view plugin](https://codemirror.net/6/docs/ref/#view.ViewPlugin). Instances of this object + represent a matching configuration. + */ + class MatchDecorator { + /** + Create a decorator. + */ + constructor(config) { + const { regexp, decoration, decorate, boundary, maxLength = 1000 } = config; + if (!regexp.global) + throw new RangeError("The regular expression given to MatchDecorator should have its 'g' flag set"); + this.regexp = regexp; + if (decorate) { + this.addMatch = (match, view, from, add) => decorate(add, from, from + match[0].length, match, view); + } + else if (typeof decoration == "function") { + this.addMatch = (match, view, from, add) => { + let deco = decoration(match, view, from); + if (deco) + add(from, from + match[0].length, deco); + }; + } + else if (decoration) { + this.addMatch = (match, _view, from, add) => add(from, from + match[0].length, decoration); + } + else { + throw new RangeError("Either 'decorate' or 'decoration' should be provided to MatchDecorator"); + } + this.boundary = boundary; + this.maxLength = maxLength; + } + /** + Compute the full set of decorations for matches in the given + view's viewport. You'll want to call this when initializing your + plugin. + */ + createDeco(view) { + let build = new RangeSetBuilder(), add = build.add.bind(build); + for (let { from, to } of matchRanges(view, this.maxLength)) + iterMatches(view.state.doc, this.regexp, from, to, (from, m) => this.addMatch(m, view, from, add)); + return build.finish(); + } + /** + Update a set of decorations for a view update. `deco` _must_ be + the set of decorations produced by _this_ `MatchDecorator` for + the view state before the update. + */ + updateDeco(update, deco) { + let changeFrom = 1e9, changeTo = -1; + if (update.docChanged) + update.changes.iterChanges((_f, _t, from, to) => { + if (to > update.view.viewport.from && from < update.view.viewport.to) { + changeFrom = Math.min(from, changeFrom); + changeTo = Math.max(to, changeTo); + } + }); + if (update.viewportChanged || changeTo - changeFrom > 1000) + return this.createDeco(update.view); + if (changeTo > -1) + return this.updateRange(update.view, deco.map(update.changes), changeFrom, changeTo); + return deco; + } + updateRange(view, deco, updateFrom, updateTo) { + for (let r of view.visibleRanges) { + let from = Math.max(r.from, updateFrom), to = Math.min(r.to, updateTo); + if (to > from) { + let fromLine = view.state.doc.lineAt(from), toLine = fromLine.to < to ? view.state.doc.lineAt(to) : fromLine; + let start = Math.max(r.from, fromLine.from), end = Math.min(r.to, toLine.to); + if (this.boundary) { + for (; from > fromLine.from; from--) + if (this.boundary.test(fromLine.text[from - 1 - fromLine.from])) { + start = from; + break; + } + for (; to < toLine.to; to++) + if (this.boundary.test(toLine.text[to - toLine.from])) { + end = to; + break; + } + } + let ranges = [], m; + let add = (from, to, deco) => ranges.push(deco.range(from, to)); + if (fromLine == toLine) { + this.regexp.lastIndex = start - fromLine.from; + while ((m = this.regexp.exec(fromLine.text)) && m.index < end - fromLine.from) + this.addMatch(m, view, m.index + fromLine.from, add); + } + else { + iterMatches(view.state.doc, this.regexp, start, end, (from, m) => this.addMatch(m, view, from, add)); + } + deco = deco.update({ filterFrom: start, filterTo: end, filter: (from, to) => from < start || to > end, add: ranges }); + } + } + return deco; + } + } + + const UnicodeRegexpSupport = /x/.unicode != null ? "gu" : "g"; + const Specials = /*@__PURE__*/new RegExp("[\u0000-\u0008\u000a-\u001f\u007f-\u009f\u00ad\u061c\u200b\u200e\u200f\u2028\u2029\u202d\u202e\u2066\u2067\u2069\ufeff\ufff9-\ufffc]", UnicodeRegexpSupport); + const Names = { + 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 _supportsTabSize = null; + function supportsTabSize() { + var _a; + if (_supportsTabSize == null && typeof document != "undefined" && document.body) { + let styles = document.body.style; + _supportsTabSize = ((_a = styles.tabSize) !== null && _a !== void 0 ? _a : styles.MozTabSize) != null; + } + return _supportsTabSize || false; + } + const specialCharConfig = /*@__PURE__*/Facet.define({ + combine(configs) { + let config = combineConfig(configs, { + render: null, + specialChars: Specials, + addSpecialChars: null + }); + if (config.replaceTabs = !supportsTabSize()) + config.specialChars = new RegExp("\t|" + config.specialChars.source, UnicodeRegexpSupport); + if (config.addSpecialChars) + config.specialChars = new RegExp(config.specialChars.source + "|" + config.addSpecialChars.source, UnicodeRegexpSupport); + return config; + } + }); + /** + Returns an extension that installs highlighting of special + characters. + */ + function highlightSpecialChars( + /** + Configuration options. + */ + config = {}) { + return [specialCharConfig.of(config), specialCharPlugin()]; + } + let _plugin = null; + function specialCharPlugin() { + return _plugin || (_plugin = ViewPlugin.fromClass(class { + constructor(view) { + this.view = view; + this.decorations = Decoration.none; + this.decorationCache = Object.create(null); + this.decorator = this.makeDecorator(view.state.facet(specialCharConfig)); + this.decorations = this.decorator.createDeco(view); + } + makeDecorator(conf) { + return new MatchDecorator({ + regexp: conf.specialChars, + decoration: (m, view, pos) => { + let { doc } = view.state; + let code = codePointAt(m[0], 0); + if (code == 9) { + let line = doc.lineAt(pos); + let size = view.state.tabSize, col = countColumn(line.text, size, pos - line.from); + return Decoration.replace({ widget: new TabWidget((size - (col % size)) * this.view.defaultCharacterWidth) }); + } + return this.decorationCache[code] || + (this.decorationCache[code] = Decoration.replace({ widget: new SpecialCharWidget(conf, code) })); + }, + boundary: conf.replaceTabs ? undefined : /[^]/ + }); + } + update(update) { + let conf = update.state.facet(specialCharConfig); + if (update.startState.facet(specialCharConfig) != conf) { + this.decorator = this.makeDecorator(conf); + this.decorations = this.decorator.createDeco(update.view); + } + else { + this.decorations = this.decorator.updateDeco(update, this.decorations); + } + } + }, { + decorations: v => v.decorations + })); + } + const DefaultPlaceholder = "\u2022"; + // Assigns placeholder characters from the Control Pictures block to + // ASCII control characters + function placeholder$1(code) { + if (code >= 32) + return DefaultPlaceholder; + if (code == 10) + return "\u2424"; + return String.fromCharCode(9216 + code); + } + class SpecialCharWidget extends WidgetType { + constructor(options, code) { + super(); + this.options = options; + this.code = code; + } + eq(other) { return other.code == this.code; } + toDOM(view) { + let ph = placeholder$1(this.code); + let desc = view.state.phrase("Control character") + " " + (Names[this.code] || "0x" + this.code.toString(16)); + let custom = this.options.render && this.options.render(this.code, desc, ph); + if (custom) + return custom; + let span = document.createElement("span"); + span.textContent = ph; + span.title = desc; + span.setAttribute("aria-label", desc); + span.className = "cm-specialChar"; + return span; + } + ignoreEvent() { return false; } + } + class TabWidget extends WidgetType { + constructor(width) { + super(); + this.width = width; + } + eq(other) { return other.width == this.width; } + toDOM() { + let span = document.createElement("span"); + span.textContent = "\t"; + span.className = "cm-tab"; + span.style.width = this.width + "px"; + return span; + } + ignoreEvent() { return false; } + } + + /** + Mark lines that have a cursor on them with the `"cm-activeLine"` + DOM class. + */ + function highlightActiveLine() { + return activeLineHighlighter; + } + const lineDeco = /*@__PURE__*/Decoration.line({ class: "cm-activeLine" }); + const activeLineHighlighter = /*@__PURE__*/ViewPlugin.fromClass(class { + constructor(view) { + this.decorations = this.getDeco(view); + } + update(update) { + if (update.docChanged || update.selectionSet) + this.decorations = this.getDeco(update.view); + } + getDeco(view) { + let lastLineStart = -1, deco = []; + for (let r of view.state.selection.ranges) { + let line = view.lineBlockAt(r.head); + if (line.from > lastLineStart) { + deco.push(lineDeco.range(line.from)); + lastLineStart = line.from; + } + } + return Decoration.set(deco); + } + }, { + decorations: v => v.decorations + }); + + // Don't compute precise column positions for line offsets above this + // (since it could get expensive). Assume offset==column for them. + const MaxOff = 2000; + function rectangleFor(state, a, b) { + let startLine = Math.min(a.line, b.line), endLine = Math.max(a.line, b.line); + let ranges = []; + if (a.off > MaxOff || b.off > MaxOff || a.col < 0 || b.col < 0) { + let startOff = Math.min(a.off, b.off), endOff = Math.max(a.off, b.off); + for (let i = startLine; i <= endLine; i++) { + let line = state.doc.line(i); + if (line.length <= endOff) + ranges.push(EditorSelection.range(line.from + startOff, line.to + endOff)); + } + } + else { + let startCol = Math.min(a.col, b.col), endCol = Math.max(a.col, b.col); + for (let i = startLine; i <= endLine; i++) { + let line = state.doc.line(i); + let start = findColumn(line.text, startCol, state.tabSize, true); + if (start > -1) { + let end = findColumn(line.text, endCol, state.tabSize); + ranges.push(EditorSelection.range(line.from + start, line.from + end)); + } + } + } + return ranges; + } + function absoluteColumn(view, x) { + let ref = view.coordsAtPos(view.viewport.from); + return ref ? Math.round(Math.abs((ref.left - x) / view.defaultCharacterWidth)) : -1; + } + function getPos(view, event) { + let offset = view.posAtCoords({ x: event.clientX, y: event.clientY }, false); + let line = view.state.doc.lineAt(offset), off = offset - line.from; + let col = off > MaxOff ? -1 + : off == line.length ? absoluteColumn(view, event.clientX) + : countColumn(line.text, view.state.tabSize, offset - line.from); + return { line: line.number, col, off }; + } + function rectangleSelectionStyle(view, event) { + let start = getPos(view, event), startSel = view.state.selection; + if (!start) + return null; + return { + update(update) { + if (update.docChanged) { + let newStart = update.changes.mapPos(update.startState.doc.line(start.line).from); + let newLine = update.state.doc.lineAt(newStart); + start = { line: newLine.number, col: start.col, off: Math.min(start.off, newLine.length) }; + startSel = startSel.map(update.changes); + } + }, + get(event, _extend, multiple) { + let cur = getPos(view, event); + if (!cur) + return startSel; + let ranges = rectangleFor(view.state, start, cur); + if (!ranges.length) + return startSel; + if (multiple) + return EditorSelection.create(ranges.concat(startSel.ranges)); + else + return EditorSelection.create(ranges); + } + }; + } + /** + Create an extension that enables rectangular selections. By + default, it will react to left mouse drag with the Alt key held + down. When such a selection occurs, the text within the rectangle + that was dragged over will be selected, as one selection + [range](https://codemirror.net/6/docs/ref/#state.SelectionRange) per line. + */ + function rectangularSelection(options) { + let filter = (options === null || options === void 0 ? void 0 : options.eventFilter) || (e => e.altKey && e.button == 0); + return EditorView.mouseSelectionStyle.of((view, event) => filter(event) ? rectangleSelectionStyle(view, event) : null); + } + const keys = { + Alt: [18, e => e.altKey], + Control: [17, e => e.ctrlKey], + Shift: [16, e => e.shiftKey], + Meta: [91, e => e.metaKey] + }; + const showCrosshair = { style: "cursor: crosshair" }; + /** + Returns an extension that turns the pointer cursor into a + crosshair when a given modifier key, defaulting to Alt, is held + down. Can serve as a visual hint that rectangular selection is + going to happen when paired with + [`rectangularSelection`](https://codemirror.net/6/docs/ref/#view.rectangularSelection). + */ + function crosshairCursor(options = {}) { + let [code, getter] = keys[options.key || "Alt"]; + let plugin = ViewPlugin.fromClass(class { + constructor(view) { + this.view = view; + this.isDown = false; + } + set(isDown) { + if (this.isDown != isDown) { + this.isDown = isDown; + this.view.update([]); + } + } + }, { + eventHandlers: { + keydown(e) { + this.set(e.keyCode == code || getter(e)); + }, + keyup(e) { + if (e.keyCode == code || !getter(e)) + this.set(false); + } + } + }); + return [ + plugin, + EditorView.contentAttributes.of(view => { var _a; return ((_a = view.plugin(plugin)) === null || _a === void 0 ? void 0 : _a.isDown) ? showCrosshair : null; }) + ]; + } + + const Outside = "-10000px"; + class TooltipViewManager { + constructor(view, facet, createTooltipView) { + this.facet = facet; + this.createTooltipView = createTooltipView; + this.input = view.state.facet(facet); + this.tooltips = this.input.filter(t => t); + this.tooltipViews = this.tooltips.map(createTooltipView); + } + update(update) { + let input = update.state.facet(this.facet); + let tooltips = input.filter(x => x); + if (input === this.input) { + for (let t of this.tooltipViews) + if (t.update) + t.update(update); + return false; + } + let tooltipViews = []; + for (let i = 0; i < tooltips.length; i++) { + let tip = tooltips[i], known = -1; + if (!tip) + continue; + for (let i = 0; i < this.tooltips.length; i++) { + let other = this.tooltips[i]; + if (other && other.create == tip.create) + known = i; + } + if (known < 0) { + tooltipViews[i] = this.createTooltipView(tip); + } + else { + let tooltipView = tooltipViews[i] = this.tooltipViews[known]; + if (tooltipView.update) + tooltipView.update(update); + } + } + for (let t of this.tooltipViews) + if (tooltipViews.indexOf(t) < 0) + t.dom.remove(); + this.input = input; + this.tooltips = tooltips; + this.tooltipViews = tooltipViews; + return true; + } + } + function windowSpace(view) { + let { win } = view; + return { top: 0, left: 0, bottom: win.innerHeight, right: win.innerWidth }; + } + const tooltipConfig = /*@__PURE__*/Facet.define({ + combine: values => { + var _a, _b, _c; + return ({ + position: browser.ios ? "absolute" : ((_a = values.find(conf => conf.position)) === null || _a === void 0 ? void 0 : _a.position) || "fixed", + parent: ((_b = values.find(conf => conf.parent)) === null || _b === void 0 ? void 0 : _b.parent) || null, + tooltipSpace: ((_c = values.find(conf => conf.tooltipSpace)) === null || _c === void 0 ? void 0 : _c.tooltipSpace) || windowSpace, + }); + } + }); + const tooltipPlugin = /*@__PURE__*/ViewPlugin.fromClass(class { + constructor(view) { + this.view = view; + this.inView = true; + this.lastTransaction = 0; + this.measureTimeout = -1; + let config = view.state.facet(tooltipConfig); + this.position = config.position; + this.parent = config.parent; + this.classes = view.themeClasses; + this.createContainer(); + this.measureReq = { read: this.readMeasure.bind(this), write: this.writeMeasure.bind(this), key: this }; + this.manager = new TooltipViewManager(view, showTooltip, t => this.createTooltip(t)); + this.intersectionObserver = typeof IntersectionObserver == "function" ? new IntersectionObserver(entries => { + if (Date.now() > this.lastTransaction - 50 && + entries.length > 0 && entries[entries.length - 1].intersectionRatio < 1) + this.measureSoon(); + }, { threshold: [1] }) : null; + this.observeIntersection(); + view.win.addEventListener("resize", this.measureSoon = this.measureSoon.bind(this)); + this.maybeMeasure(); + } + createContainer() { + if (this.parent) { + this.container = document.createElement("div"); + this.container.style.position = "relative"; + this.container.className = this.view.themeClasses; + this.parent.appendChild(this.container); + } + else { + this.container = this.view.dom; + } + } + observeIntersection() { + if (this.intersectionObserver) { + this.intersectionObserver.disconnect(); + for (let tooltip of this.manager.tooltipViews) + this.intersectionObserver.observe(tooltip.dom); + } + } + measureSoon() { + if (this.measureTimeout < 0) + this.measureTimeout = setTimeout(() => { + this.measureTimeout = -1; + this.maybeMeasure(); + }, 50); + } + update(update) { + if (update.transactions.length) + this.lastTransaction = Date.now(); + let updated = this.manager.update(update); + if (updated) + this.observeIntersection(); + let shouldMeasure = updated || update.geometryChanged; + let newConfig = update.state.facet(tooltipConfig); + if (newConfig.position != this.position) { + this.position = newConfig.position; + for (let t of this.manager.tooltipViews) + t.dom.style.position = this.position; + shouldMeasure = true; + } + if (newConfig.parent != this.parent) { + if (this.parent) + this.container.remove(); + this.parent = newConfig.parent; + this.createContainer(); + for (let t of this.manager.tooltipViews) + this.container.appendChild(t.dom); + shouldMeasure = true; + } + else if (this.parent && this.view.themeClasses != this.classes) { + this.classes = this.container.className = this.view.themeClasses; + } + if (shouldMeasure) + this.maybeMeasure(); + } + createTooltip(tooltip) { + let tooltipView = tooltip.create(this.view); + tooltipView.dom.classList.add("cm-tooltip"); + if (tooltip.arrow && !tooltipView.dom.querySelector(".cm-tooltip > .cm-tooltip-arrow")) { + let arrow = document.createElement("div"); + arrow.className = "cm-tooltip-arrow"; + tooltipView.dom.appendChild(arrow); + } + tooltipView.dom.style.position = this.position; + tooltipView.dom.style.top = Outside; + this.container.appendChild(tooltipView.dom); + if (tooltipView.mount) + tooltipView.mount(this.view); + return tooltipView; + } + destroy() { + var _a; + this.view.win.removeEventListener("resize", this.measureSoon); + for (let { dom } of this.manager.tooltipViews) + dom.remove(); + (_a = this.intersectionObserver) === null || _a === void 0 ? void 0 : _a.disconnect(); + clearTimeout(this.measureTimeout); + } + readMeasure() { + let editor = this.view.dom.getBoundingClientRect(); + return { + editor, + parent: this.parent ? this.container.getBoundingClientRect() : editor, + pos: this.manager.tooltips.map((t, i) => { + let tv = this.manager.tooltipViews[i]; + return tv.getCoords ? tv.getCoords(t.pos) : this.view.coordsAtPos(t.pos); + }), + size: this.manager.tooltipViews.map(({ dom }) => dom.getBoundingClientRect()), + space: this.view.state.facet(tooltipConfig).tooltipSpace(this.view), + }; + } + writeMeasure(measured) { + let { editor, space } = measured; + let others = []; + for (let i = 0; i < this.manager.tooltips.length; i++) { + let tooltip = this.manager.tooltips[i], tView = this.manager.tooltipViews[i], { dom } = tView; + let pos = measured.pos[i], size = measured.size[i]; + // Hide tooltips that are outside of the editor. + if (!pos || pos.bottom <= Math.max(editor.top, space.top) || + pos.top >= Math.min(editor.bottom, space.bottom) || + pos.right < Math.max(editor.left, space.left) - .1 || + pos.left > Math.min(editor.right, space.right) + .1) { + dom.style.top = Outside; + continue; + } + let arrow = tooltip.arrow ? tView.dom.querySelector(".cm-tooltip-arrow") : null; + let arrowHeight = arrow ? 7 /* Arrow.Size */ : 0; + let width = size.right - size.left, height = size.bottom - size.top; + let offset = tView.offset || noOffset, ltr = this.view.textDirection == Direction.LTR; + let left = size.width > space.right - space.left ? (ltr ? space.left : space.right - size.width) + : ltr ? Math.min(pos.left - (arrow ? 14 /* Arrow.Offset */ : 0) + offset.x, space.right - width) + : Math.max(space.left, pos.left - width + (arrow ? 14 /* Arrow.Offset */ : 0) - offset.x); + let above = !!tooltip.above; + if (!tooltip.strictSide && (above + ? pos.top - (size.bottom - size.top) - offset.y < space.top + : pos.bottom + (size.bottom - size.top) + offset.y > space.bottom) && + above == (space.bottom - pos.bottom > pos.top - space.top)) + above = !above; + let top = above ? pos.top - height - arrowHeight - offset.y : pos.bottom + arrowHeight + offset.y; + let right = left + width; + if (tView.overlap !== true) + for (let r of others) + if (r.left < right && r.right > left && r.top < top + height && r.bottom > top) + top = above ? r.top - height - 2 - arrowHeight : r.bottom + arrowHeight + 2; + if (this.position == "absolute") { + dom.style.top = (top - measured.parent.top) + "px"; + dom.style.left = (left - measured.parent.left) + "px"; + } + else { + dom.style.top = top + "px"; + dom.style.left = left + "px"; + } + if (arrow) + arrow.style.left = `${pos.left + (ltr ? offset.x : -offset.x) - (left + 14 /* Arrow.Offset */ - 7 /* Arrow.Size */)}px`; + if (tView.overlap !== true) + others.push({ left, top, right, bottom: top + height }); + dom.classList.toggle("cm-tooltip-above", above); + dom.classList.toggle("cm-tooltip-below", !above); + if (tView.positioned) + tView.positioned(); + } + } + maybeMeasure() { + if (this.manager.tooltips.length) { + if (this.view.inView) + this.view.requestMeasure(this.measureReq); + if (this.inView != this.view.inView) { + this.inView = this.view.inView; + if (!this.inView) + for (let tv of this.manager.tooltipViews) + tv.dom.style.top = Outside; + } + } + } + }, { + eventHandlers: { + scroll() { this.maybeMeasure(); } + } + }); + const baseTheme$4 = /*@__PURE__*/EditorView.baseTheme({ + ".cm-tooltip": { + zIndex: 100 + }, + "&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: `${7 /* Arrow.Size */}px`, + width: `${7 /* Arrow.Size */ * 2}px`, + position: "absolute", + zIndex: -1, + overflow: "hidden", + "&:before, &:after": { + content: "''", + position: "absolute", + width: 0, + height: 0, + borderLeft: `${7 /* Arrow.Size */}px solid transparent`, + borderRight: `${7 /* Arrow.Size */}px solid transparent`, + }, + ".cm-tooltip-above &": { + bottom: `-${7 /* Arrow.Size */}px`, + "&:before": { + borderTop: `${7 /* Arrow.Size */}px solid #bbb`, + }, + "&:after": { + borderTop: `${7 /* Arrow.Size */}px solid #f5f5f5`, + bottom: "1px" + } + }, + ".cm-tooltip-below &": { + top: `-${7 /* Arrow.Size */}px`, + "&:before": { + borderBottom: `${7 /* Arrow.Size */}px solid #bbb`, + }, + "&:after": { + borderBottom: `${7 /* Arrow.Size */}px solid #f5f5f5`, + top: "1px" + } + }, + }, + "&dark .cm-tooltip .cm-tooltip-arrow": { + "&:before": { + borderTopColor: "#333338", + borderBottomColor: "#333338" + }, + "&:after": { + borderTopColor: "transparent", + borderBottomColor: "transparent" + } + } + }); + const noOffset = { x: 0, y: 0 }; + /** + Facet to which an extension can add a value to show a tooltip. + */ + const showTooltip = /*@__PURE__*/Facet.define({ + enables: [tooltipPlugin, baseTheme$4] + }); + const showHoverTooltip = /*@__PURE__*/Facet.define(); + class HoverTooltipHost { + constructor(view) { + this.view = view; + this.mounted = false; + this.dom = document.createElement("div"); + this.dom.classList.add("cm-tooltip-hover"); + this.manager = new TooltipViewManager(view, showHoverTooltip, t => this.createHostedView(t)); + } + // Needs to be static so that host tooltip instances always match + static create(view) { + return new HoverTooltipHost(view); + } + createHostedView(tooltip) { + let hostedView = tooltip.create(this.view); + hostedView.dom.classList.add("cm-tooltip-section"); + this.dom.appendChild(hostedView.dom); + if (this.mounted && hostedView.mount) + hostedView.mount(this.view); + return hostedView; + } + mount(view) { + for (let hostedView of this.manager.tooltipViews) { + if (hostedView.mount) + hostedView.mount(view); + } + this.mounted = true; + } + positioned() { + for (let hostedView of this.manager.tooltipViews) { + if (hostedView.positioned) + hostedView.positioned(); + } + } + update(update) { + this.manager.update(update); + } + } + const showHoverTooltipHost = /*@__PURE__*/showTooltip.compute([showHoverTooltip], state => { + let tooltips = state.facet(showHoverTooltip).filter(t => t); + if (tooltips.length === 0) + return null; + return { + pos: Math.min(...tooltips.map(t => t.pos)), + end: Math.max(...tooltips.filter(t => t.end != null).map(t => t.end)), + create: HoverTooltipHost.create, + above: tooltips[0].above, + arrow: tooltips.some(t => t.arrow), + }; + }); + class HoverPlugin { + constructor(view, source, field, setHover, hoverTime) { + this.view = view; + this.source = source; + this.field = field; + this.setHover = setHover; + this.hoverTime = hoverTime; + this.hoverTimeout = -1; + this.restartTimeout = -1; + this.pending = null; + this.lastMove = { x: 0, y: 0, target: view.dom, time: 0 }; + this.checkHover = this.checkHover.bind(this); + view.dom.addEventListener("mouseleave", this.mouseleave = this.mouseleave.bind(this)); + view.dom.addEventListener("mousemove", this.mousemove = this.mousemove.bind(this)); + } + update() { + if (this.pending) { + this.pending = null; + clearTimeout(this.restartTimeout); + this.restartTimeout = setTimeout(() => this.startHover(), 20); + } + } + get active() { + return this.view.state.field(this.field); + } + checkHover() { + this.hoverTimeout = -1; + if (this.active) + return; + let hovered = Date.now() - this.lastMove.time; + if (hovered < this.hoverTime) + this.hoverTimeout = setTimeout(this.checkHover, this.hoverTime - hovered); + else + this.startHover(); + } + startHover() { + clearTimeout(this.restartTimeout); + let { lastMove } = this; + let pos = this.view.contentDOM.contains(lastMove.target) ? this.view.posAtCoords(lastMove) : null; + if (pos == null) + return; + let posCoords = this.view.coordsAtPos(pos); + if (posCoords == null || lastMove.y < posCoords.top || lastMove.y > posCoords.bottom || + lastMove.x < posCoords.left - this.view.defaultCharacterWidth || + lastMove.x > posCoords.right + this.view.defaultCharacterWidth) + return; + let bidi = this.view.bidiSpans(this.view.state.doc.lineAt(pos)).find(s => s.from <= pos && s.to >= pos); + let rtl = bidi && bidi.dir == Direction.RTL ? -1 : 1; + let open = this.source(this.view, pos, (lastMove.x < posCoords.left ? -rtl : rtl)); + if (open === null || open === void 0 ? void 0 : open.then) { + let pending = this.pending = { pos }; + open.then(result => { + if (this.pending == pending) { + this.pending = null; + if (result) + this.view.dispatch({ effects: this.setHover.of(result) }); + } + }, e => logException(this.view.state, e, "hover tooltip")); + } + else if (open) { + this.view.dispatch({ effects: this.setHover.of(open) }); + } + } + mousemove(event) { + var _a; + this.lastMove = { x: event.clientX, y: event.clientY, target: event.target, time: Date.now() }; + if (this.hoverTimeout < 0) + this.hoverTimeout = setTimeout(this.checkHover, this.hoverTime); + let tooltip = this.active; + if (tooltip && !isInTooltip(this.lastMove.target) || this.pending) { + let { pos } = tooltip || this.pending, end = (_a = tooltip === null || tooltip === void 0 ? void 0 : tooltip.end) !== null && _a !== void 0 ? _a : pos; + if ((pos == end ? this.view.posAtCoords(this.lastMove) != pos + : !isOverRange(this.view, pos, end, event.clientX, event.clientY, 6 /* Hover.MaxDist */))) { + this.view.dispatch({ effects: this.setHover.of(null) }); + this.pending = null; + } + } + } + mouseleave() { + clearTimeout(this.hoverTimeout); + this.hoverTimeout = -1; + if (this.active) + this.view.dispatch({ effects: this.setHover.of(null) }); + } + destroy() { + clearTimeout(this.hoverTimeout); + this.view.dom.removeEventListener("mouseleave", this.mouseleave); + this.view.dom.removeEventListener("mousemove", this.mousemove); + } + } + function isInTooltip(elt) { + for (let cur = elt; cur; cur = cur.parentNode) + if (cur.nodeType == 1 && cur.classList.contains("cm-tooltip")) + return true; + return false; + } + function isOverRange(view, from, to, x, y, margin) { + let range = document.createRange(); + let fromDOM = view.domAtPos(from), toDOM = view.domAtPos(to); + range.setEnd(toDOM.node, toDOM.offset); + range.setStart(fromDOM.node, fromDOM.offset); + let rects = range.getClientRects(); + range.detach(); + for (let i = 0; i < rects.length; i++) { + let rect = rects[i]; + let dist = Math.max(rect.top - y, y - rect.bottom, rect.left - x, x - rect.right); + if (dist <= margin) + return true; + } + return false; + } + /** + Set up a hover tooltip, which shows up when the pointer hovers + over ranges of text. The callback is called when the mouse hovers + over the document text. It should, if there is a tooltip + associated with position `pos`, return the tooltip description + (either directly or in a promise). The `side` argument indicates + on which side of the position the pointer is—it will be -1 if the + pointer is before the position, 1 if after the position. + + Note that all hover tooltips are hosted within a single tooltip + container element. This allows multiple tooltips over the same + range to be "merged" together without overlapping. + */ + function hoverTooltip(source, options = {}) { + let setHover = StateEffect.define(); + let hoverState = StateField.define({ + create() { return null; }, + update(value, tr) { + if (value && (options.hideOnChange && (tr.docChanged || tr.selection) || + options.hideOn && options.hideOn(tr, value))) + return null; + if (value && tr.docChanged) { + let newPos = tr.changes.mapPos(value.pos, -1, MapMode.TrackDel); + if (newPos == null) + return null; + let copy = Object.assign(Object.create(null), value); + copy.pos = newPos; + if (value.end != null) + copy.end = tr.changes.mapPos(value.end); + value = copy; + } + for (let effect of tr.effects) { + if (effect.is(setHover)) + value = effect.value; + if (effect.is(closeHoverTooltipEffect)) + value = null; + } + return value; + }, + provide: f => showHoverTooltip.from(f) + }); + return [ + hoverState, + ViewPlugin.define(view => new HoverPlugin(view, source, hoverState, setHover, options.hoverTime || 300 /* Hover.Time */)), + showHoverTooltipHost + ]; + } + /** + Get the active tooltip view for a given tooltip, if available. + */ + function getTooltip(view, tooltip) { + let plugin = view.plugin(tooltipPlugin); + if (!plugin) + return null; + let found = plugin.manager.tooltips.indexOf(tooltip); + return found < 0 ? null : plugin.manager.tooltipViews[found]; + } + const closeHoverTooltipEffect = /*@__PURE__*/StateEffect.define(); + + const panelConfig = /*@__PURE__*/Facet.define({ + combine(configs) { + let topContainer, bottomContainer; + for (let c of configs) { + topContainer = topContainer || c.topContainer; + bottomContainer = bottomContainer || c.bottomContainer; + } + return { topContainer, bottomContainer }; + } + }); + /** + Get the active panel created by the given constructor, if any. + This can be useful when you need access to your panels' DOM + structure. + */ + function getPanel(view, panel) { + let plugin = view.plugin(panelPlugin); + let index = plugin ? plugin.specs.indexOf(panel) : -1; + return index > -1 ? plugin.panels[index] : null; + } + const panelPlugin = /*@__PURE__*/ViewPlugin.fromClass(class { + constructor(view) { + this.input = view.state.facet(showPanel); + this.specs = this.input.filter(s => s); + this.panels = this.specs.map(spec => spec(view)); + let conf = view.state.facet(panelConfig); + this.top = new PanelGroup(view, true, conf.topContainer); + this.bottom = new PanelGroup(view, false, conf.bottomContainer); + this.top.sync(this.panels.filter(p => p.top)); + this.bottom.sync(this.panels.filter(p => !p.top)); + for (let p of this.panels) { + p.dom.classList.add("cm-panel"); + if (p.mount) + p.mount(); + } + } + update(update) { + let conf = update.state.facet(panelConfig); + if (this.top.container != conf.topContainer) { + this.top.sync([]); + this.top = new PanelGroup(update.view, true, conf.topContainer); + } + if (this.bottom.container != conf.bottomContainer) { + this.bottom.sync([]); + this.bottom = new PanelGroup(update.view, false, conf.bottomContainer); + } + this.top.syncClasses(); + this.bottom.syncClasses(); + let input = update.state.facet(showPanel); + if (input != this.input) { + let specs = input.filter(x => x); + let panels = [], top = [], bottom = [], mount = []; + for (let spec of specs) { + let known = this.specs.indexOf(spec), panel; + if (known < 0) { + panel = spec(update.view); + mount.push(panel); + } + else { + panel = this.panels[known]; + if (panel.update) + panel.update(update); + } + panels.push(panel); + (panel.top ? top : bottom).push(panel); + } + this.specs = specs; + this.panels = panels; + this.top.sync(top); + this.bottom.sync(bottom); + for (let p of mount) { + p.dom.classList.add("cm-panel"); + if (p.mount) + p.mount(); + } + } + else { + for (let p of this.panels) + if (p.update) + p.update(update); + } + } + destroy() { + this.top.sync([]); + this.bottom.sync([]); + } + }, { + provide: plugin => EditorView.scrollMargins.of(view => { + let value = view.plugin(plugin); + return value && { top: value.top.scrollMargin(), bottom: value.bottom.scrollMargin() }; + }) + }); + class PanelGroup { + constructor(view, top, container) { + this.view = view; + this.top = top; + this.container = container; + this.dom = undefined; + this.classes = ""; + this.panels = []; + this.syncClasses(); + } + sync(panels) { + for (let p of this.panels) + if (p.destroy && panels.indexOf(p) < 0) + p.destroy(); + this.panels = panels; + this.syncDOM(); + } + syncDOM() { + if (this.panels.length == 0) { + if (this.dom) { + this.dom.remove(); + this.dom = undefined; + } + return; + } + 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 parent = this.container || this.view.dom; + parent.insertBefore(this.dom, this.top ? parent.firstChild : null); + } + let curDOM = this.dom.firstChild; + for (let panel of this.panels) { + if (panel.dom.parentNode == this.dom) { + while (curDOM != panel.dom) + curDOM = rm(curDOM); + curDOM = curDOM.nextSibling; + } + else { + this.dom.insertBefore(panel.dom, curDOM); + } + } + while (curDOM) + curDOM = rm(curDOM); + } + 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) + return; + for (let cls of this.classes.split(" ")) + if (cls) + this.container.classList.remove(cls); + for (let cls of (this.classes = this.view.themeClasses).split(" ")) + if (cls) + this.container.classList.add(cls); + } + } + function rm(node) { + let next = node.nextSibling; + node.remove(); + return next; + } + /** + Opening a panel is done by providing a constructor function for + the panel through this facet. (The panel is closed again when its + constructor is no longer provided.) Values of `null` are ignored. + */ + const showPanel = /*@__PURE__*/Facet.define({ + enables: panelPlugin + }); + + /** + A gutter marker represents a bit of information attached to a line + in a specific gutter. Your own custom markers have to extend this + class. + */ + class GutterMarker extends RangeValue { + /** + @internal + */ + compare(other) { + return this == other || this.constructor == other.constructor && this.eq(other); + } + /** + Compare this marker to another marker of the same type. + */ + eq(other) { return false; } + /** + Called if the marker has a `toDOM` method and its representation + was removed from a gutter. + */ + destroy(dom) { } + } + GutterMarker.prototype.elementClass = ""; + GutterMarker.prototype.toDOM = undefined; + GutterMarker.prototype.mapMode = MapMode.TrackBefore; + GutterMarker.prototype.startSide = GutterMarker.prototype.endSide = -1; + GutterMarker.prototype.point = true; + /** + Facet used to add a class to all gutter elements for a given line. + Markers given to this facet should _only_ define an + [`elementclass`](https://codemirror.net/6/docs/ref/#view.GutterMarker.elementClass), not a + [`toDOM`](https://codemirror.net/6/docs/ref/#view.GutterMarker.toDOM) (or the marker will appear + in all gutters for the line). + */ + const gutterLineClass = /*@__PURE__*/Facet.define(); + const defaults$1 = { + class: "", + renderEmptyElements: false, + elementStyle: "", + markers: () => RangeSet.empty, + lineMarker: () => null, + lineMarkerChange: null, + initialSpacer: null, + updateSpacer: null, + domEventHandlers: {} + }; + const activeGutters = /*@__PURE__*/Facet.define(); + /** + Define an editor gutter. The order in which the gutters appear is + determined by their extension priority. + */ + function gutter(config) { + return [gutters(), activeGutters.of(Object.assign(Object.assign({}, defaults$1), config))]; + } + const unfixGutters = /*@__PURE__*/Facet.define({ + combine: values => values.some(x => x) + }); + /** + The gutter-drawing plugin is automatically enabled when you add a + gutter, but you can use this function to explicitly configure it. + + Unless `fixed` is explicitly set to `false`, the gutters are + fixed, meaning they don't scroll along with the content + horizontally (except on Internet Explorer, which doesn't support + CSS [`position: + sticky`](https://developer.mozilla.org/en-US/docs/Web/CSS/position#sticky)). + */ + function gutters(config) { + let result = [ + gutterView, + ]; + if (config && config.fixed === false) + result.push(unfixGutters.of(true)); + return result; + } + const gutterView = /*@__PURE__*/ViewPlugin.fromClass(class { + constructor(view) { + this.view = view; + this.prevViewport = view.viewport; + this.dom = document.createElement("div"); + this.dom.className = "cm-gutters"; + this.dom.setAttribute("aria-hidden", "true"); + this.dom.style.minHeight = this.view.contentHeight + "px"; + this.gutters = view.state.facet(activeGutters).map(conf => new SingleGutterView(view, conf)); + for (let gutter of this.gutters) + this.dom.appendChild(gutter.dom); + this.fixed = !view.state.facet(unfixGutters); + if (this.fixed) { + // FIXME IE11 fallback, which doesn't support position: sticky, + // by using position: relative + event handlers that realign the + // gutter (or just force fixed=false on IE11?) + this.dom.style.position = "sticky"; + } + this.syncGutters(false); + view.scrollDOM.insertBefore(this.dom, view.contentDOM); + } + update(update) { + if (this.updateGutters(update)) { + // Detach during sync when the viewport changed significantly + // (such as during scrolling), since for large updates that is + // faster. + let vpA = this.prevViewport, vpB = update.view.viewport; + let vpOverlap = Math.min(vpA.to, vpB.to) - Math.max(vpA.from, vpB.from); + this.syncGutters(vpOverlap < (vpB.to - vpB.from) * 0.8); + } + if (update.geometryChanged) + this.dom.style.minHeight = this.view.contentHeight + "px"; + if (this.view.state.facet(unfixGutters) != !this.fixed) { + this.fixed = !this.fixed; + this.dom.style.position = this.fixed ? "sticky" : ""; + } + this.prevViewport = update.view.viewport; + } + syncGutters(detach) { + let after = this.dom.nextSibling; + if (detach) + this.dom.remove(); + let lineClasses = RangeSet.iter(this.view.state.facet(gutterLineClass), this.view.viewport.from); + let classSet = []; + let contexts = this.gutters.map(gutter => new UpdateContext(gutter, this.view.viewport, -this.view.documentPadding.top)); + for (let line of this.view.viewportLineBlocks) { + let text; + if (Array.isArray(line.type)) { + for (let b of line.type) + if (b.type == BlockType.Text) { + text = b; + break; + } + } + else { + text = line.type == BlockType.Text ? line : undefined; + } + if (!text) + continue; + if (classSet.length) + classSet = []; + advanceCursor(lineClasses, classSet, line.from); + for (let cx of contexts) + cx.line(this.view, text, classSet); + } + for (let cx of contexts) + cx.finish(); + if (detach) + this.view.scrollDOM.insertBefore(this.dom, after); + } + updateGutters(update) { + let prev = update.startState.facet(activeGutters), cur = update.state.facet(activeGutters); + let change = update.docChanged || update.heightChanged || update.viewportChanged || + !RangeSet.eq(update.startState.facet(gutterLineClass), update.state.facet(gutterLineClass), update.view.viewport.from, update.view.viewport.to); + if (prev == cur) { + for (let gutter of this.gutters) + if (gutter.update(update)) + change = true; + } + else { + change = true; + let gutters = []; + for (let conf of cur) { + let known = prev.indexOf(conf); + if (known < 0) { + gutters.push(new SingleGutterView(this.view, conf)); + } + else { + this.gutters[known].update(update); + gutters.push(this.gutters[known]); + } + } + for (let g of this.gutters) { + g.dom.remove(); + if (gutters.indexOf(g) < 0) + g.destroy(); + } + for (let g of gutters) + this.dom.appendChild(g.dom); + this.gutters = gutters; + } + return change; + } + destroy() { + for (let view of this.gutters) + view.destroy(); + this.dom.remove(); + } + }, { + provide: plugin => EditorView.scrollMargins.of(view => { + let value = view.plugin(plugin); + if (!value || value.gutters.length == 0 || !value.fixed) + return null; + return view.textDirection == Direction.LTR ? { left: value.dom.offsetWidth } : { right: value.dom.offsetWidth }; + }) + }); + function asArray(val) { return (Array.isArray(val) ? val : [val]); } + function advanceCursor(cursor, collect, pos) { + while (cursor.value && cursor.from <= pos) { + if (cursor.from == pos) + collect.push(cursor.value); + cursor.next(); + } + } + class UpdateContext { + constructor(gutter, viewport, height) { + this.gutter = gutter; + this.height = height; + this.localMarkers = []; + this.i = 0; + this.cursor = RangeSet.iter(gutter.markers, viewport.from); + } + line(view, line, extraMarkers) { + if (this.localMarkers.length) + this.localMarkers = []; + advanceCursor(this.cursor, this.localMarkers, line.from); + let localMarkers = extraMarkers.length ? this.localMarkers.concat(extraMarkers) : this.localMarkers; + let forLine = this.gutter.config.lineMarker(view, line, localMarkers); + if (forLine) + localMarkers.unshift(forLine); + let gutter = this.gutter; + if (localMarkers.length == 0 && !gutter.config.renderEmptyElements) + return; + let above = line.top - this.height; + if (this.i == gutter.elements.length) { + let newElt = new GutterElement(view, line.height, above, localMarkers); + gutter.elements.push(newElt); + gutter.dom.appendChild(newElt.dom); + } + else { + gutter.elements[this.i].update(view, line.height, above, localMarkers); + } + this.height = line.bottom; + this.i++; + } + finish() { + let gutter = this.gutter; + while (gutter.elements.length > this.i) { + let last = gutter.elements.pop(); + gutter.dom.removeChild(last.dom); + last.destroy(); + } + } + } + class SingleGutterView { + constructor(view, config) { + this.view = view; + this.config = config; + this.elements = []; + this.spacer = null; + this.dom = document.createElement("div"); + this.dom.className = "cm-gutter" + (this.config.class ? " " + this.config.class : ""); + for (let prop in config.domEventHandlers) { + this.dom.addEventListener(prop, (event) => { + let line = view.lineBlockAtHeight(event.clientY - view.documentTop); + if (config.domEventHandlers[prop](view, line, event)) + event.preventDefault(); + }); + } + this.markers = asArray(config.markers(view)); + if (config.initialSpacer) { + this.spacer = new GutterElement(view, 0, 0, [config.initialSpacer(view)]); + this.dom.appendChild(this.spacer.dom); + this.spacer.dom.style.cssText += "visibility: hidden; pointer-events: none"; + } + } + update(update) { + let prevMarkers = this.markers; + this.markers = asArray(this.config.markers(update.view)); + if (this.spacer && this.config.updateSpacer) { + let updated = this.config.updateSpacer(this.spacer.markers[0], update); + if (updated != this.spacer.markers[0]) + this.spacer.update(update.view, 0, 0, [updated]); + } + let vp = update.view.viewport; + return !RangeSet.eq(this.markers, prevMarkers, vp.from, vp.to) || + (this.config.lineMarkerChange ? this.config.lineMarkerChange(update) : false); + } + destroy() { + for (let elt of this.elements) + elt.destroy(); + } + } + class GutterElement { + constructor(view, height, above, markers) { + this.height = -1; + this.above = 0; + this.markers = []; + this.dom = document.createElement("div"); + this.dom.className = "cm-gutterElement"; + this.update(view, height, above, markers); + } + update(view, height, above, markers) { + if (this.height != height) + this.dom.style.height = (this.height = height) + "px"; + if (this.above != above) + this.dom.style.marginTop = (this.above = above) ? above + "px" : ""; + if (!sameMarkers(this.markers, markers)) + this.setMarkers(view, markers); + } + setMarkers(view, markers) { + let cls = "cm-gutterElement", domPos = this.dom.firstChild; + for (let iNew = 0, iOld = 0;;) { + let skipTo = iOld, marker = iNew < markers.length ? markers[iNew++] : null, matched = false; + if (marker) { + let c = marker.elementClass; + if (c) + cls += " " + c; + for (let i = iOld; i < this.markers.length; i++) + if (this.markers[i].compare(marker)) { + skipTo = i; + matched = true; + break; + } + } + else { + skipTo = this.markers.length; + } + while (iOld < skipTo) { + let next = this.markers[iOld++]; + if (next.toDOM) { + next.destroy(domPos); + let after = domPos.nextSibling; + domPos.remove(); + domPos = after; + } + } + if (!marker) + break; + if (marker.toDOM) { + if (matched) + domPos = domPos.nextSibling; + else + this.dom.insertBefore(marker.toDOM(view), domPos); + } + if (matched) + iOld++; + } + this.dom.className = cls; + this.markers = markers; + } + destroy() { + this.setMarkers(null, []); // First argument not used unless creating markers + } + } + function sameMarkers(a, b) { + if (a.length != b.length) + return false; + for (let i = 0; i < a.length; i++) + if (!a[i].compare(b[i])) + return false; + return true; + } + /** + Facet used to provide markers to the line number gutter. + */ + const lineNumberMarkers = /*@__PURE__*/Facet.define(); + const lineNumberConfig = /*@__PURE__*/Facet.define({ + combine(values) { + return combineConfig(values, { formatNumber: String, domEventHandlers: {} }, { + domEventHandlers(a, b) { + let result = Object.assign({}, a); + for (let event in b) { + let exists = result[event], add = b[event]; + result[event] = exists ? (view, line, event) => exists(view, line, event) || add(view, line, event) : add; + } + return result; + } + }); + } + }); + class NumberMarker extends GutterMarker { + constructor(number) { + super(); + this.number = number; + } + eq(other) { return this.number == other.number; } + toDOM() { return document.createTextNode(this.number); } + } + function formatNumber(view, number) { + return view.state.facet(lineNumberConfig).formatNumber(number, view.state); + } + const lineNumberGutter = /*@__PURE__*/activeGutters.compute([lineNumberConfig], state => ({ + class: "cm-lineNumbers", + renderEmptyElements: false, + markers(view) { return view.state.facet(lineNumberMarkers); }, + lineMarker(view, line, others) { + if (others.some(m => m.toDOM)) + return null; + return new NumberMarker(formatNumber(view, view.state.doc.lineAt(line.from).number)); + }, + lineMarkerChange: update => update.startState.facet(lineNumberConfig) != update.state.facet(lineNumberConfig), + initialSpacer(view) { + return new NumberMarker(formatNumber(view, maxLineNumber(view.state.doc.lines))); + }, + updateSpacer(spacer, update) { + let max = formatNumber(update.view, maxLineNumber(update.view.state.doc.lines)); + return max == spacer.number ? spacer : new NumberMarker(max); + }, + domEventHandlers: state.facet(lineNumberConfig).domEventHandlers + })); + /** + Create a line number gutter extension. + */ + function lineNumbers(config = {}) { + return [ + lineNumberConfig.of(config), + gutters(), + lineNumberGutter + ]; + } + function maxLineNumber(lines) { + let last = 9; + while (last < lines) + last = last * 10 + 9; + return last; + } + const activeLineGutterMarker = /*@__PURE__*/new class extends GutterMarker { + constructor() { + super(...arguments); + this.elementClass = "cm-activeLineGutter"; + } + }; + const activeLineGutterHighlighter = /*@__PURE__*/gutterLineClass.compute(["selection"], state => { + let marks = [], last = -1; + for (let range of state.selection.ranges) { + let linePos = state.doc.lineAt(range.head).from; + if (linePos > last) { + last = linePos; + marks.push(activeLineGutterMarker.range(linePos)); + } + } + return RangeSet.of(marks); + }); + /** + Returns an extension that adds a `cm-activeLineGutter` class to + all gutter elements on the [active + line](https://codemirror.net/6/docs/ref/#view.highlightActiveLine). + */ + function highlightActiveLineGutter() { + return activeLineGutterHighlighter; + } + + // FIXME profile adding a per-Tree TreeNode cache, validating it by + // parent pointer + /// The default maximum length of a `TreeBuffer` node. + const DefaultBufferLength = 1024; + let nextPropID = 0; + class Range { + constructor(from, to) { + this.from = from; + this.to = to; + } + } + /// Each [node type](#common.NodeType) or [individual tree](#common.Tree) + /// can have metadata associated with it in props. Instances of this + /// class represent prop names. + class NodeProp { + /// Create a new node prop type. + constructor(config = {}) { + this.id = nextPropID++; + this.perNode = !!config.perNode; + this.deserialize = config.deserialize || (() => { + throw new Error("This node type doesn't define a deserialize function"); + }); + } + /// This is meant to be used with + /// [`NodeSet.extend`](#common.NodeSet.extend) or + /// [`LRParser.configure`](#lr.ParserConfig.props) to compute + /// prop values for each node type in the set. Takes a [match + /// object](#common.NodeType^match) or function that returns undefined + /// if the node type doesn't get this prop, and the prop's value if + /// it does. + add(match) { + if (this.perNode) + throw new RangeError("Can't add per-node props to node types"); + if (typeof match != "function") + match = NodeType.match(match); + return (type) => { + let result = match(type); + return result === undefined ? null : [this, result]; + }; + } + } + /// Prop that is used to describe matching delimiters. For opening + /// delimiters, this holds an array of node names (written as a + /// space-separated string when declaring this prop in a grammar) + /// for the node types of closing delimiters that match it. + NodeProp.closedBy = new NodeProp({ deserialize: str => str.split(" ") }); + /// The inverse of [`closedBy`](#common.NodeProp^closedBy). This is + /// attached to closing delimiters, holding an array of node names + /// of types of matching opening delimiters. + NodeProp.openedBy = new NodeProp({ deserialize: str => str.split(" ") }); + /// Used to assign node types to groups (for example, all node + /// types that represent an expression could be tagged with an + /// `"Expression"` group). + NodeProp.group = new NodeProp({ deserialize: str => str.split(" ") }); + /// The hash of the [context](#lr.ContextTracker.constructor) + /// that the node was parsed in, if any. Used to limit reuse of + /// contextual nodes. + NodeProp.contextHash = new NodeProp({ perNode: true }); + /// The distance beyond the end of the node that the tokenizer + /// looked ahead for any of the tokens inside the node. (The LR + /// parser only stores this when it is larger than 25, for + /// efficiency reasons.) + NodeProp.lookAhead = new NodeProp({ perNode: true }); + /// This per-node prop is used to replace a given node, or part of a + /// node, with another tree. This is useful to include trees from + /// different languages in mixed-language parsers. + NodeProp.mounted = new NodeProp({ perNode: true }); + const noProps = Object.create(null); + /// Each node in a syntax tree has a node type associated with it. + class NodeType { + /// @internal + constructor( + /// The name of the node type. Not necessarily unique, but if the + /// grammar was written properly, different node types with the + /// same name within a node set should play the same semantic + /// role. + name, + /// @internal + props, + /// The id of this node in its set. Corresponds to the term ids + /// used in the parser. + id, + /// @internal + flags = 0) { + this.name = name; + this.props = props; + this.id = id; + this.flags = flags; + } + /// Define a node type. + static define(spec) { + let props = spec.props && spec.props.length ? Object.create(null) : noProps; + let flags = (spec.top ? 1 /* Top */ : 0) | (spec.skipped ? 2 /* Skipped */ : 0) | + (spec.error ? 4 /* Error */ : 0) | (spec.name == null ? 8 /* Anonymous */ : 0); + let type = new NodeType(spec.name || "", props, spec.id, flags); + if (spec.props) + for (let src of spec.props) { + if (!Array.isArray(src)) + src = src(type); + if (src) { + if (src[0].perNode) + throw new RangeError("Can't store a per-node prop on a node type"); + props[src[0].id] = src[1]; + } + } + return type; + } + /// Retrieves a node prop for this type. Will return `undefined` if + /// the prop isn't present on this node. + prop(prop) { return this.props[prop.id]; } + /// True when this is the top node of a grammar. + get isTop() { return (this.flags & 1 /* Top */) > 0; } + /// True when this node is produced by a skip rule. + get isSkipped() { return (this.flags & 2 /* Skipped */) > 0; } + /// Indicates whether this is an error node. + get isError() { return (this.flags & 4 /* Error */) > 0; } + /// When true, this node type doesn't correspond to a user-declared + /// named node, for example because it is used to cache repetition. + get isAnonymous() { return (this.flags & 8 /* Anonymous */) > 0; } + /// Returns true when this node's name or one of its + /// [groups](#common.NodeProp^group) matches the given string. + is(name) { + if (typeof name == 'string') { + if (this.name == name) + return true; + let group = this.prop(NodeProp.group); + return group ? group.indexOf(name) > -1 : false; + } + return this.id == name; + } + /// Create a function from node types to arbitrary values by + /// specifying an object whose property names are node or + /// [group](#common.NodeProp^group) names. Often useful with + /// [`NodeProp.add`](#common.NodeProp.add). You can put multiple + /// names, separated by spaces, in a single property name to map + /// multiple node names to a single value. + static match(map) { + let direct = Object.create(null); + for (let prop in map) + for (let name of prop.split(" ")) + direct[name] = map[prop]; + return (node) => { + for (let groups = node.prop(NodeProp.group), i = -1; i < (groups ? groups.length : 0); i++) { + let found = direct[i < 0 ? node.name : groups[i]]; + if (found) + return found; + } + }; + } + } + /// An empty dummy node type to use when no actual type is available. + NodeType.none = new NodeType("", Object.create(null), 0, 8 /* Anonymous */); + /// A node set holds a collection of node types. It is used to + /// compactly represent trees by storing their type ids, rather than a + /// full pointer to the type object, in a numeric array. Each parser + /// [has](#lr.LRParser.nodeSet) a node set, and [tree + /// buffers](#common.TreeBuffer) can only store collections of nodes + /// from the same set. A set can have a maximum of 2**16 (65536) node + /// types in it, so that the ids fit into 16-bit typed array slots. + class NodeSet { + /// Create a set with the given types. The `id` property of each + /// type should correspond to its position within the array. + constructor( + /// The node types in this set, by id. + types) { + this.types = types; + for (let i = 0; i < types.length; i++) + if (types[i].id != i) + throw new RangeError("Node type ids should correspond to array positions when creating a node set"); + } + /// Create a copy of this set with some node properties added. The + /// arguments to this method can be created with + /// [`NodeProp.add`](#common.NodeProp.add). + extend(...props) { + let newTypes = []; + for (let type of this.types) { + let newProps = null; + for (let source of props) { + let add = source(type); + if (add) { + if (!newProps) + newProps = Object.assign({}, type.props); + newProps[add[0].id] = add[1]; + } + } + newTypes.push(newProps ? new NodeType(type.name, newProps, type.id, type.flags) : type); + } + return new NodeSet(newTypes); + } + } + const CachedNode = new WeakMap(), CachedInnerNode = new WeakMap(); + /// Options that control iteration. Can be combined with the `|` + /// operator to enable multiple ones. + var IterMode; + (function (IterMode) { + /// When enabled, iteration will only visit [`Tree`](#common.Tree) + /// objects, not nodes packed into + /// [`TreeBuffer`](#common.TreeBuffer)s. + IterMode[IterMode["ExcludeBuffers"] = 1] = "ExcludeBuffers"; + /// Enable this to make iteration include anonymous nodes (such as + /// the nodes that wrap repeated grammar constructs into a balanced + /// tree). + IterMode[IterMode["IncludeAnonymous"] = 2] = "IncludeAnonymous"; + /// By default, regular [mounted](#common.NodeProp^mounted) nodes + /// replace their base node in iteration. Enable this to ignore them + /// instead. + IterMode[IterMode["IgnoreMounts"] = 4] = "IgnoreMounts"; + /// This option only applies in + /// [`enter`](#common.SyntaxNode.enter)-style methods. It tells the + /// library to not enter mounted overlays if one covers the given + /// position. + IterMode[IterMode["IgnoreOverlays"] = 8] = "IgnoreOverlays"; + })(IterMode || (IterMode = {})); + /// A piece of syntax tree. There are two ways to approach these + /// trees: the way they are actually stored in memory, and the + /// convenient way. + /// + /// Syntax trees are stored as a tree of `Tree` and `TreeBuffer` + /// objects. By packing detail information into `TreeBuffer` leaf + /// nodes, the representation is made a lot more memory-efficient. + /// + /// However, when you want to actually work with tree nodes, this + /// representation is very awkward, so most client code will want to + /// use the [`TreeCursor`](#common.TreeCursor) or + /// [`SyntaxNode`](#common.SyntaxNode) interface instead, which provides + /// a view on some part of this data structure, and can be used to + /// move around to adjacent nodes. + class Tree { + /// Construct a new tree. See also [`Tree.build`](#common.Tree^build). + constructor( + /// The type of the top node. + type, + /// This node's child nodes. + children, + /// The positions (offsets relative to the start of this tree) of + /// the children. + positions, + /// The total length of this tree + length, + /// Per-node [node props](#common.NodeProp) to associate with this node. + props) { + this.type = type; + this.children = children; + this.positions = positions; + this.length = length; + /// @internal + this.props = null; + if (props && props.length) { + this.props = Object.create(null); + for (let [prop, value] of props) + this.props[typeof prop == "number" ? prop : prop.id] = value; + } + } + /// @internal + toString() { + let mounted = this.prop(NodeProp.mounted); + if (mounted && !mounted.overlay) + return mounted.tree.toString(); + let children = ""; + for (let ch of this.children) { + let str = ch.toString(); + if (str) { + if (children) + children += ","; + children += str; + } + } + return !this.type.name ? children : + (/\W/.test(this.type.name) && !this.type.isError ? JSON.stringify(this.type.name) : this.type.name) + + (children.length ? "(" + children + ")" : ""); + } + /// Get a [tree cursor](#common.TreeCursor) positioned at the top of + /// the tree. Mode can be used to [control](#common.IterMode) which + /// nodes the cursor visits. + cursor(mode = 0) { + return new TreeCursor(this.topNode, mode); + } + /// Get a [tree cursor](#common.TreeCursor) pointing into this tree + /// at the given position and side (see + /// [`moveTo`](#common.TreeCursor.moveTo). + cursorAt(pos, side = 0, mode = 0) { + let scope = CachedNode.get(this) || this.topNode; + let cursor = new TreeCursor(scope); + cursor.moveTo(pos, side); + CachedNode.set(this, cursor._tree); + return cursor; + } + /// Get a [syntax node](#common.SyntaxNode) object for the top of the + /// tree. + get topNode() { + return new TreeNode(this, 0, 0, null); + } + /// Get the [syntax node](#common.SyntaxNode) at the given position. + /// If `side` is -1, this will move into nodes that end at the + /// position. If 1, it'll move into nodes that start at the + /// position. With 0, it'll only enter nodes that cover the position + /// from both sides. + /// + /// Note that this will not enter + /// [overlays](#common.MountedTree.overlay), and you often want + /// [`resolveInner`](#common.Tree.resolveInner) instead. + resolve(pos, side = 0) { + let node = resolveNode(CachedNode.get(this) || this.topNode, pos, side, false); + CachedNode.set(this, node); + return node; + } + /// Like [`resolve`](#common.Tree.resolve), but will enter + /// [overlaid](#common.MountedTree.overlay) nodes, producing a syntax node + /// pointing into the innermost overlaid tree at the given position + /// (with parent links going through all parent structure, including + /// the host trees). + resolveInner(pos, side = 0) { + let node = resolveNode(CachedInnerNode.get(this) || this.topNode, pos, side, true); + CachedInnerNode.set(this, node); + return node; + } + /// Iterate over the tree and its children, calling `enter` for any + /// node that touches the `from`/`to` region (if given) before + /// running over such a node's children, and `leave` (if given) when + /// leaving the node. When `enter` returns `false`, that node will + /// not have its children iterated over (or `leave` called). + iterate(spec) { + let { enter, leave, from = 0, to = this.length } = spec; + for (let c = this.cursor((spec.mode || 0) | IterMode.IncludeAnonymous);;) { + let entered = false; + if (c.from <= to && c.to >= from && (c.type.isAnonymous || enter(c) !== false)) { + if (c.firstChild()) + continue; + entered = true; + } + for (;;) { + if (entered && leave && !c.type.isAnonymous) + leave(c); + if (c.nextSibling()) + break; + if (!c.parent()) + return; + entered = true; + } + } + } + /// Get the value of the given [node prop](#common.NodeProp) for this + /// node. Works with both per-node and per-type props. + prop(prop) { + return !prop.perNode ? this.type.prop(prop) : this.props ? this.props[prop.id] : undefined; + } + /// Returns the node's [per-node props](#common.NodeProp.perNode) in a + /// format that can be passed to the [`Tree`](#common.Tree) + /// constructor. + get propValues() { + let result = []; + if (this.props) + for (let id in this.props) + result.push([+id, this.props[id]]); + return result; + } + /// Balance the direct children of this tree, producing a copy of + /// which may have children grouped into subtrees with type + /// [`NodeType.none`](#common.NodeType^none). + balance(config = {}) { + return this.children.length <= 8 /* BranchFactor */ ? this : + balanceRange(NodeType.none, this.children, this.positions, 0, this.children.length, 0, this.length, (children, positions, length) => new Tree(this.type, children, positions, length, this.propValues), config.makeTree || ((children, positions, length) => new Tree(NodeType.none, children, positions, length))); + } + /// Build a tree from a postfix-ordered buffer of node information, + /// or a cursor over such a buffer. + static build(data) { return buildTree(data); } + } + /// The empty tree + Tree.empty = new Tree(NodeType.none, [], [], 0); + class FlatBufferCursor { + constructor(buffer, index) { + this.buffer = buffer; + this.index = index; + } + 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 FlatBufferCursor(this.buffer, this.index); } + } + /// Tree buffers contain (type, start, end, endIndex) quads for each + /// node. In such a buffer, nodes are stored in prefix order (parents + /// before children, with the endIndex of the parent indicating which + /// children belong to it). + class TreeBuffer { + /// Create a tree buffer. + constructor( + /// The buffer's content. + buffer, + /// The total length of the group of nodes in the buffer. + length, + /// The node set used in this buffer. + set) { + this.buffer = buffer; + this.length = length; + this.set = set; + } + /// @internal + get type() { return NodeType.none; } + /// @internal + toString() { + let result = []; + for (let index = 0; index < this.buffer.length;) { + result.push(this.childString(index)); + index = this.buffer[index + 3]; + } + return result.join(","); + } + /// @internal + childString(index) { + let id = this.buffer[index], endIndex = this.buffer[index + 3]; + let type = this.set.types[id], result = type.name; + if (/\W/.test(result) && !type.isError) + result = JSON.stringify(result); + index += 4; + if (endIndex == index) + return result; + let children = []; + while (index < endIndex) { + children.push(this.childString(index)); + index = this.buffer[index + 3]; + } + return result + "(" + children.join(",") + ")"; + } + /// @internal + findChild(startIndex, endIndex, dir, pos, side) { + let { buffer } = this, pick = -1; + for (let i = startIndex; i != endIndex; i = buffer[i + 3]) { + if (checkSide(side, pos, buffer[i + 1], buffer[i + 2])) { + pick = i; + if (dir > 0) + break; + } + } + return pick; + } + /// @internal + slice(startI, endI, from, to) { + let b = this.buffer; + let copy = new Uint16Array(endI - startI); + for (let i = startI, j = 0; i < endI;) { + copy[j++] = b[i++]; + copy[j++] = b[i++] - from; + copy[j++] = b[i++] - from; + copy[j++] = b[i++] - startI; + } + return new TreeBuffer(copy, to - from, this.set); + } + } + function checkSide(side, pos, from, to) { + switch (side) { + case -2 /* Before */: return from < pos; + case -1 /* AtOrBefore */: return to >= pos && from < pos; + case 0 /* Around */: return from < pos && to > pos; + case 1 /* AtOrAfter */: return from <= pos && to > pos; + case 2 /* After */: return to > pos; + case 4 /* DontCare */: return true; + } + } + function enterUnfinishedNodesBefore(node, pos) { + let scan = node.childBefore(pos); + while (scan) { + let last = scan.lastChild; + if (!last || last.to != scan.to) + break; + if (last.type.isError && last.from == last.to) { + node = scan; + scan = last.prevSibling; + } + else { + scan = last; + } + } + return node; + } + function resolveNode(node, pos, side, overlays) { + var _a; + // Move up to a node that actually holds the position, if possible + while (node.from == node.to || + (side < 1 ? node.from >= pos : node.from > pos) || + (side > -1 ? node.to <= pos : node.to < pos)) { + let parent = !overlays && node instanceof TreeNode && node.index < 0 ? null : node.parent; + if (!parent) + return node; + node = parent; + } + let mode = overlays ? 0 : IterMode.IgnoreOverlays; + // Must go up out of overlays when those do not overlap with pos + if (overlays) + for (let scan = node, parent = scan.parent; parent; scan = parent, parent = scan.parent) { + if (scan instanceof TreeNode && scan.index < 0 && ((_a = parent.enter(pos, side, mode)) === null || _a === void 0 ? void 0 : _a.from) != scan.from) + node = parent; + } + for (;;) { + let inner = node.enter(pos, side, mode); + if (!inner) + return node; + node = inner; + } + } + class TreeNode { + constructor(_tree, from, + // Index in parent node, set to -1 if the node is not a direct child of _parent.node (overlay) + index, _parent) { + this._tree = _tree; + this.from = from; + this.index = index; + this._parent = _parent; + } + get type() { return this._tree.type; } + get name() { return this._tree.type.name; } + get to() { return this.from + this._tree.length; } + nextChild(i, dir, pos, side, mode = 0) { + for (let parent = this;;) { + for (let { children, positions } = parent._tree, e = dir > 0 ? children.length : -1; i != e; i += dir) { + let next = children[i], start = positions[i] + parent.from; + if (!checkSide(side, pos, start, start + next.length)) + continue; + if (next instanceof TreeBuffer) { + if (mode & IterMode.ExcludeBuffers) + continue; + let index = next.findChild(0, next.buffer.length, dir, pos - start, side); + if (index > -1) + return new BufferNode(new BufferContext(parent, next, i, start), null, index); + } + else if ((mode & IterMode.IncludeAnonymous) || (!next.type.isAnonymous || hasChild(next))) { + let mounted; + if (!(mode & IterMode.IgnoreMounts) && + next.props && (mounted = next.prop(NodeProp.mounted)) && !mounted.overlay) + return new TreeNode(mounted.tree, start, i, parent); + let inner = new TreeNode(next, start, i, parent); + return (mode & IterMode.IncludeAnonymous) || !inner.type.isAnonymous ? inner + : inner.nextChild(dir < 0 ? next.children.length - 1 : 0, dir, pos, side); + } + } + if ((mode & IterMode.IncludeAnonymous) || !parent.type.isAnonymous) + return null; + if (parent.index >= 0) + i = parent.index + dir; + else + i = dir < 0 ? -1 : parent._parent._tree.children.length; + parent = parent._parent; + if (!parent) + return null; + } + } + get firstChild() { return this.nextChild(0, 1, 0, 4 /* DontCare */); } + get lastChild() { return this.nextChild(this._tree.children.length - 1, -1, 0, 4 /* DontCare */); } + childAfter(pos) { return this.nextChild(0, 1, pos, 2 /* After */); } + childBefore(pos) { return this.nextChild(this._tree.children.length - 1, -1, pos, -2 /* Before */); } + enter(pos, side, mode = 0) { + let mounted; + if (!(mode & IterMode.IgnoreOverlays) && (mounted = this._tree.prop(NodeProp.mounted)) && mounted.overlay) { + let rPos = pos - this.from; + for (let { from, to } of mounted.overlay) { + if ((side > 0 ? from <= rPos : from < rPos) && + (side < 0 ? to >= rPos : to > rPos)) + return new TreeNode(mounted.tree, mounted.overlay[0].from + this.from, -1, this); + } + } + return this.nextChild(0, 1, pos, side, mode); + } + nextSignificantParent() { + let val = this; + while (val.type.isAnonymous && val._parent) + val = val._parent; + return val; + } + 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 /* DontCare */) : null; + } + get prevSibling() { + return this._parent && this.index >= 0 ? this._parent.nextChild(this.index - 1, -1, 0, 4 /* DontCare */) : null; + } + cursor(mode = 0) { return new TreeCursor(this, mode); } + get tree() { return this._tree; } + toTree() { return this._tree; } + resolve(pos, side = 0) { + return resolveNode(this, pos, side, false); + } + resolveInner(pos, side = 0) { + return resolveNode(this, pos, side, true); + } + enterUnfinishedNodesBefore(pos) { return enterUnfinishedNodesBefore(this, pos); } + getChild(type, before = null, after = null) { + let r = getChildren(this, type, before, after); + return r.length ? r[0] : null; + } + getChildren(type, before = null, after = null) { + return getChildren(this, type, before, after); + } + /// @internal + toString() { return this._tree.toString(); } + get node() { return this; } + matchContext(context) { return matchNodeContext(this, context); } + } + function getChildren(node, type, before, after) { + let cur = node.cursor(), result = []; + if (!cur.firstChild()) + return result; + if (before != null) + while (!cur.type.is(before)) + if (!cur.nextSibling()) + return result; + for (;;) { + if (after != null && cur.type.is(after)) + return result; + if (cur.type.is(type)) + result.push(cur.node); + if (!cur.nextSibling()) + return after == null ? result : []; + } + } + function matchNodeContext(node, context, i = context.length - 1) { + for (let p = node.parent; i >= 0; p = p.parent) { + if (!p) + return false; + if (!p.type.isAnonymous) { + if (context[i] && context[i] != p.name) + return false; + i--; + } + } + return true; + } + class BufferContext { + constructor(parent, buffer, index, start) { + this.parent = parent; + this.buffer = buffer; + this.index = index; + this.start = start; + } + } + class BufferNode { + constructor(context, _parent, index) { + this.context = context; + this._parent = _parent; + this.index = index; + this.type = context.buffer.set.types[context.buffer.buffer[index]]; + } + 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]; } + child(dir, pos, side) { + let { buffer } = this.context; + let index = buffer.findChild(this.index + 4, buffer.buffer[this.index + 3], dir, pos - this.context.start, side); + return index < 0 ? null : new BufferNode(this.context, this, index); + } + get firstChild() { return this.child(1, 0, 4 /* DontCare */); } + get lastChild() { return this.child(-1, 0, 4 /* DontCare */); } + childAfter(pos) { return this.child(1, pos, 2 /* After */); } + childBefore(pos) { return this.child(-1, pos, -2 /* Before */); } + enter(pos, side, mode = 0) { + if (mode & IterMode.ExcludeBuffers) + return null; + let { buffer } = this.context; + let index = buffer.findChild(this.index + 4, buffer.buffer[this.index + 3], side > 0 ? 1 : -1, pos - this.context.start, side); + return index < 0 ? null : new BufferNode(this.context, this, index); + } + get parent() { + return this._parent || this.context.parent.nextSignificantParent(); + } + externalSibling(dir) { + return this._parent ? null : this.context.parent.nextChild(this.context.index + dir, dir, 0, 4 /* DontCare */); + } + get nextSibling() { + let { buffer } = this.context; + let after = buffer.buffer[this.index + 3]; + if (after < (this._parent ? buffer.buffer[this._parent.index + 3] : buffer.buffer.length)) + return new BufferNode(this.context, this._parent, after); + return this.externalSibling(1); + } + get prevSibling() { + let { buffer } = this.context; + let parentStart = this._parent ? this._parent.index + 4 : 0; + if (this.index == parentStart) + return this.externalSibling(-1); + return new BufferNode(this.context, this._parent, buffer.findChild(parentStart, this.index, -1, 0, 4 /* DontCare */)); + } + cursor(mode = 0) { return new TreeCursor(this, mode); } + get tree() { return null; } + toTree() { + let children = [], positions = []; + let { buffer } = this.context; + let startI = this.index + 4, endI = buffer.buffer[this.index + 3]; + if (endI > startI) { + let from = buffer.buffer[this.index + 1], to = buffer.buffer[this.index + 2]; + children.push(buffer.slice(startI, endI, from, to)); + positions.push(0); + } + return new Tree(this.type, children, positions, this.to - this.from); + } + resolve(pos, side = 0) { + return resolveNode(this, pos, side, false); + } + resolveInner(pos, side = 0) { + return resolveNode(this, pos, side, true); + } + enterUnfinishedNodesBefore(pos) { return enterUnfinishedNodesBefore(this, pos); } + /// @internal + toString() { return this.context.buffer.childString(this.index); } + getChild(type, before = null, after = null) { + let r = getChildren(this, type, before, after); + return r.length ? r[0] : null; + } + getChildren(type, before = null, after = null) { + return getChildren(this, type, before, after); + } + get node() { return this; } + matchContext(context) { return matchNodeContext(this, context); } + } + /// A tree cursor object focuses on a given node in a syntax tree, and + /// allows you to move to adjacent nodes. + class TreeCursor { + /// @internal + constructor(node, + /// @internal + mode = 0) { + this.mode = mode; + /// @internal + this.buffer = null; + this.stack = []; + /// @internal + this.index = 0; + this.bufferNode = null; + if (node instanceof TreeNode) { + this.yieldNode(node); + } + else { + this._tree = node.context.parent; + this.buffer = node.context; + for (let n = node._parent; n; n = n._parent) + this.stack.unshift(n.index); + this.bufferNode = node; + this.yieldBuf(node.index); + } + } + /// Shorthand for `.type.name`. + get name() { return this.type.name; } + yieldNode(node) { + if (!node) + return false; + this._tree = node; + this.type = node.type; + this.from = node.from; + this.to = node.to; + return true; + } + yieldBuf(index, type) { + this.index = index; + let { start, buffer } = this.buffer; + this.type = type || buffer.set.types[buffer.buffer[index]]; + this.from = start + buffer.buffer[index + 1]; + this.to = start + buffer.buffer[index + 2]; + return true; + } + yield(node) { + if (!node) + return false; + if (node instanceof TreeNode) { + this.buffer = null; + return this.yieldNode(node); + } + this.buffer = node.context; + return this.yieldBuf(node.index, node.type); + } + /// @internal + toString() { + return this.buffer ? this.buffer.buffer.childString(this.index) : this._tree.toString(); + } + /// @internal + enterChild(dir, pos, side) { + if (!this.buffer) + return this.yield(this._tree.nextChild(dir < 0 ? this._tree._tree.children.length - 1 : 0, dir, pos, side, this.mode)); + let { buffer } = this.buffer; + let index = buffer.findChild(this.index + 4, buffer.buffer[this.index + 3], dir, pos - this.buffer.start, side); + if (index < 0) + return false; + this.stack.push(this.index); + return this.yieldBuf(index); + } + /// Move the cursor to this node's first child. When this returns + /// false, the node has no child, and the cursor has not been moved. + firstChild() { return this.enterChild(1, 0, 4 /* DontCare */); } + /// Move the cursor to this node's last child. + lastChild() { return this.enterChild(-1, 0, 4 /* DontCare */); } + /// Move the cursor to the first child that ends after `pos`. + childAfter(pos) { return this.enterChild(1, pos, 2 /* After */); } + /// Move to the last child that starts before `pos`. + childBefore(pos) { return this.enterChild(-1, pos, -2 /* Before */); } + /// Move the cursor to the child around `pos`. If side is -1 the + /// child may end at that position, when 1 it may start there. This + /// will also enter [overlaid](#common.MountedTree.overlay) + /// [mounted](#common.NodeProp^mounted) trees unless `overlays` is + /// set to false. + enter(pos, side, mode = this.mode) { + if (!this.buffer) + return this.yield(this._tree.enter(pos, side, mode)); + return mode & IterMode.ExcludeBuffers ? false : this.enterChild(1, pos, side); + } + /// Move to the node's parent node, if this isn't the top node. + parent() { + if (!this.buffer) + return this.yieldNode((this.mode & IterMode.IncludeAnonymous) ? this._tree._parent : this._tree.parent); + if (this.stack.length) + return this.yieldBuf(this.stack.pop()); + let parent = (this.mode & IterMode.IncludeAnonymous) ? this.buffer.parent : this.buffer.parent.nextSignificantParent(); + this.buffer = null; + return this.yieldNode(parent); + } + /// @internal + sibling(dir) { + if (!this.buffer) + return !this._tree._parent ? false + : this.yield(this._tree.index < 0 ? null + : this._tree._parent.nextChild(this._tree.index + dir, dir, 0, 4 /* DontCare */, this.mode)); + let { buffer } = this.buffer, d = this.stack.length - 1; + if (dir < 0) { + let parentStart = d < 0 ? 0 : this.stack[d] + 4; + if (this.index != parentStart) + return this.yieldBuf(buffer.findChild(parentStart, this.index, -1, 0, 4 /* DontCare */)); + } + else { + let after = buffer.buffer[this.index + 3]; + if (after < (d < 0 ? buffer.buffer.length : buffer.buffer[this.stack[d] + 3])) + return this.yieldBuf(after); + } + return d < 0 ? this.yield(this.buffer.parent.nextChild(this.buffer.index + dir, dir, 0, 4 /* DontCare */, this.mode)) : false; + } + /// Move to this node's next sibling, if any. + nextSibling() { return this.sibling(1); } + /// Move to this node's previous sibling, if any. + prevSibling() { return this.sibling(-1); } + atLastNode(dir) { + let index, parent, { buffer } = this; + if (buffer) { + if (dir > 0) { + if (this.index < buffer.buffer.buffer.length) + return false; + } + else { + for (let i = 0; i < this.index; i++) + if (buffer.buffer.buffer[i + 3] < this.index) + return false; + } + ({ index, parent } = buffer); + } + else { + ({ index, _parent: parent } = this._tree); + } + for (; parent; { index, _parent: parent } = parent) { + if (index > -1) + for (let i = index + dir, e = dir < 0 ? -1 : parent._tree.children.length; i != e; i += dir) { + let child = parent._tree.children[i]; + if ((this.mode & IterMode.IncludeAnonymous) || + child instanceof TreeBuffer || + !child.type.isAnonymous || + hasChild(child)) + return false; + } + } + return true; + } + move(dir, enter) { + if (enter && this.enterChild(dir, 0, 4 /* DontCare */)) + return true; + for (;;) { + if (this.sibling(dir)) + return true; + if (this.atLastNode(dir) || !this.parent()) + return false; + } + } + /// Move to the next node in a + /// [pre-order](https://en.wikipedia.org/wiki/Tree_traversal#Pre-order_(NLR)) + /// traversal, going from a node to its first child or, if the + /// current node is empty or `enter` is false, its next sibling or + /// the next sibling of the first parent node that has one. + next(enter = true) { return this.move(1, enter); } + /// Move to the next node in a last-to-first pre-order traveral. A + /// node is followed by its last child or, if it has none, its + /// previous sibling or the previous sibling of the first parent + /// node that has one. + prev(enter = true) { return this.move(-1, enter); } + /// Move the cursor to the innermost node that covers `pos`. If + /// `side` is -1, it will enter nodes that end at `pos`. If it is 1, + /// it will enter nodes that start at `pos`. + moveTo(pos, side = 0) { + // Move up to a node that actually holds the position, if possible + while (this.from == this.to || + (side < 1 ? this.from >= pos : this.from > pos) || + (side > -1 ? this.to <= pos : this.to < pos)) + if (!this.parent()) + break; + // Then scan down into child nodes as far as possible + while (this.enterChild(1, pos, side)) { } + return this; + } + /// Get a [syntax node](#common.SyntaxNode) at the cursor's current + /// position. + get node() { + if (!this.buffer) + return this._tree; + let cache = this.bufferNode, result = null, depth = 0; + if (cache && cache.context == this.buffer) { + scan: for (let index = this.index, d = this.stack.length; d >= 0;) { + for (let c = cache; c; c = c._parent) + if (c.index == index) { + if (index == this.index) + return c; + result = c; + depth = d + 1; + break scan; + } + index = this.stack[--d]; + } + } + for (let i = depth; i < this.stack.length; i++) + result = new BufferNode(this.buffer, result, this.stack[i]); + return this.bufferNode = new BufferNode(this.buffer, result, this.index); + } + /// Get the [tree](#common.Tree) that represents the current node, if + /// any. Will return null when the node is in a [tree + /// buffer](#common.TreeBuffer). + get tree() { + return this.buffer ? null : this._tree._tree; + } + /// Iterate over the current node and all its descendants, calling + /// `enter` when entering a node and `leave`, if given, when leaving + /// one. When `enter` returns `false`, any children of that node are + /// skipped, and `leave` isn't called for it. + iterate(enter, leave) { + for (let depth = 0;;) { + let mustLeave = false; + if (this.type.isAnonymous || enter(this) !== false) { + if (this.firstChild()) { + depth++; + continue; + } + if (!this.type.isAnonymous) + mustLeave = true; + } + for (;;) { + if (mustLeave && leave) + leave(this); + mustLeave = this.type.isAnonymous; + if (this.nextSibling()) + break; + if (!depth) + return; + this.parent(); + depth--; + mustLeave = true; + } + } + } + /// Test whether the current node matches a given context—a sequence + /// of direct parent node names. Empty strings in the context array + /// are treated as wildcards. + matchContext(context) { + if (!this.buffer) + return matchNodeContext(this.node, context); + let { buffer } = this.buffer, { types } = buffer.set; + for (let i = context.length - 1, d = this.stack.length - 1; i >= 0; d--) { + if (d < 0) + return matchNodeContext(this.node, context, i); + let type = types[buffer.buffer[this.stack[d]]]; + if (!type.isAnonymous) { + if (context[i] && context[i] != type.name) + return false; + i--; + } + } + return true; + } + } + function hasChild(tree) { + return tree.children.some(ch => ch instanceof TreeBuffer || !ch.type.isAnonymous || hasChild(ch)); + } + function buildTree(data) { + var _a; + let { buffer, nodeSet, maxBufferLength = DefaultBufferLength, reused = [], minRepeatType = nodeSet.types.length } = data; + let cursor = Array.isArray(buffer) ? new FlatBufferCursor(buffer, buffer.length) : buffer; + let types = nodeSet.types; + let contextHash = 0, lookAhead = 0; + function takeNode(parentStart, minPos, children, positions, inRepeat) { + let { id, start, end, size } = cursor; + let lookAheadAtStart = lookAhead; + while (size < 0) { + cursor.next(); + if (size == -1 /* Reuse */) { + let node = reused[id]; + children.push(node); + positions.push(start - parentStart); + return; + } + else if (size == -3 /* ContextChange */) { // Context change + contextHash = id; + return; + } + else if (size == -4 /* LookAhead */) { + lookAhead = id; + return; + } + else { + throw new RangeError(`Unrecognized record size: ${size}`); + } + } + let type = types[id], node, buffer; + let startPos = start - parentStart; + if (end - start <= maxBufferLength && (buffer = findBufferSize(cursor.pos - minPos, inRepeat))) { + // Small enough for a buffer, and no reused nodes inside + let data = new Uint16Array(buffer.size - buffer.skip); + let endPos = cursor.pos - buffer.size, index = data.length; + while (cursor.pos > endPos) + index = copyToBuffer(buffer.start, data, index); + node = new TreeBuffer(data, end - buffer.start, nodeSet); + startPos = buffer.start - parentStart; + } + else { // Make it a node + let endPos = cursor.pos - size; + cursor.next(); + let localChildren = [], localPositions = []; + let localInRepeat = id >= minRepeatType ? id : -1; + let lastGroup = 0, lastEnd = end; + while (cursor.pos > endPos) { + if (localInRepeat >= 0 && cursor.id == localInRepeat && cursor.size >= 0) { + if (cursor.end <= lastEnd - maxBufferLength) { + makeRepeatLeaf(localChildren, localPositions, start, lastGroup, cursor.end, lastEnd, localInRepeat, lookAheadAtStart); + lastGroup = localChildren.length; + lastEnd = cursor.end; + } + cursor.next(); + } + else { + takeNode(start, endPos, localChildren, localPositions, localInRepeat); + } + } + if (localInRepeat >= 0 && lastGroup > 0 && lastGroup < localChildren.length) + makeRepeatLeaf(localChildren, localPositions, start, lastGroup, start, lastEnd, localInRepeat, lookAheadAtStart); + localChildren.reverse(); + localPositions.reverse(); + if (localInRepeat > -1 && lastGroup > 0) { + let make = makeBalanced(type); + node = balanceRange(type, localChildren, localPositions, 0, localChildren.length, 0, end - start, make, make); + } + else { + node = makeTree(type, localChildren, localPositions, end - start, lookAheadAtStart - end); + } + } + children.push(node); + positions.push(startPos); + } + function makeBalanced(type) { + return (children, positions, length) => { + let lookAhead = 0, lastI = children.length - 1, last, lookAheadProp; + if (lastI >= 0 && (last = children[lastI]) instanceof Tree) { + if (!lastI && last.type == type && last.length == length) + return last; + if (lookAheadProp = last.prop(NodeProp.lookAhead)) + lookAhead = positions[lastI] + last.length + lookAheadProp; + } + return makeTree(type, children, positions, length, lookAhead); + }; + } + function makeRepeatLeaf(children, positions, base, i, from, to, type, lookAhead) { + let localChildren = [], localPositions = []; + while (children.length > i) { + localChildren.push(children.pop()); + localPositions.push(positions.pop() + base - from); + } + children.push(makeTree(nodeSet.types[type], localChildren, localPositions, to - from, lookAhead - to)); + positions.push(from - base); + } + function makeTree(type, children, positions, length, lookAhead = 0, props) { + if (contextHash) { + let pair = [NodeProp.contextHash, contextHash]; + props = props ? [pair].concat(props) : [pair]; + } + if (lookAhead > 25) { + let pair = [NodeProp.lookAhead, lookAhead]; + props = props ? [pair].concat(props) : [pair]; + } + return new Tree(type, children, positions, length, props); + } + function findBufferSize(maxSize, inRepeat) { + // Scan through the buffer to find previous siblings that fit + // together in a TreeBuffer, and don't contain any reused nodes + // (which can't be stored in a buffer). + // If `inRepeat` is > -1, ignore node boundaries of that type for + // nesting, but make sure the end falls either at the start + // (`maxSize`) or before such a node. + let fork = cursor.fork(); + let size = 0, start = 0, skip = 0, minStart = fork.end - maxBufferLength; + let result = { size: 0, start: 0, skip: 0 }; + scan: for (let minPos = fork.pos - maxSize; fork.pos > minPos;) { + let nodeSize = fork.size; + // Pretend nested repeat nodes of the same type don't exist + if (fork.id == inRepeat && nodeSize >= 0) { + // Except that we store the current state as a valid return + // value. + result.size = size; + result.start = start; + result.skip = skip; + skip += 4; + size += 4; + fork.next(); + continue; + } + let startPos = fork.pos - nodeSize; + if (nodeSize < 0 || startPos < minPos || fork.start < minStart) + break; + let localSkipped = fork.id >= minRepeatType ? 4 : 0; + let nodeStart = fork.start; + fork.next(); + while (fork.pos > startPos) { + if (fork.size < 0) { + if (fork.size == -3 /* ContextChange */) + localSkipped += 4; + else + break scan; + } + else if (fork.id >= minRepeatType) { + localSkipped += 4; + } + fork.next(); + } + start = nodeStart; + size += nodeSize; + skip += localSkipped; + } + if (inRepeat < 0 || size == maxSize) { + result.size = size; + result.start = start; + result.skip = skip; + } + return result.size > 4 ? result : undefined; + } + function copyToBuffer(bufferStart, buffer, index) { + let { id, start, end, size } = cursor; + cursor.next(); + if (size >= 0 && id < minRepeatType) { + let startIndex = index; + if (size > 4) { + let endPos = cursor.pos - (size - 4); + while (cursor.pos > endPos) + index = copyToBuffer(bufferStart, buffer, index); + } + buffer[--index] = startIndex; + buffer[--index] = end - bufferStart; + buffer[--index] = start - bufferStart; + buffer[--index] = id; + } + else if (size == -3 /* ContextChange */) { + contextHash = id; + } + else if (size == -4 /* LookAhead */) { + lookAhead = id; + } + return index; + } + let children = [], positions = []; + while (cursor.pos > 0) + takeNode(data.start || 0, data.bufferStart || 0, children, positions, -1); + let length = (_a = data.length) !== null && _a !== void 0 ? _a : (children.length ? positions[0] + children[0].length : 0); + return new Tree(types[data.topID], children.reverse(), positions.reverse(), length); + } + const nodeSizeCache = new WeakMap; + function nodeSize(balanceType, node) { + if (!balanceType.isAnonymous || node instanceof TreeBuffer || node.type != balanceType) + return 1; + let size = nodeSizeCache.get(node); + if (size == null) { + size = 1; + for (let child of node.children) { + if (child.type != balanceType || !(child instanceof Tree)) { + size = 1; + break; + } + size += nodeSize(balanceType, child); + } + nodeSizeCache.set(node, size); + } + return size; + } + function balanceRange( + // The type the balanced tree's inner nodes. + balanceType, + // The direct children and their positions + children, positions, + // The index range in children/positions to use + from, to, + // The start position of the nodes, relative to their parent. + start, + // Length of the outer node + length, + // Function to build the top node of the balanced tree + mkTop, + // Function to build internal nodes for the balanced tree + mkTree) { + let total = 0; + for (let i = from; i < to; i++) + total += nodeSize(balanceType, children[i]); + let maxChild = Math.ceil((total * 1.5) / 8 /* BranchFactor */); + let localChildren = [], localPositions = []; + function divide(children, positions, from, to, offset) { + for (let i = from; i < to;) { + let groupFrom = i, groupStart = positions[i], groupSize = nodeSize(balanceType, children[i]); + i++; + for (; i < to; i++) { + let nextSize = nodeSize(balanceType, children[i]); + if (groupSize + nextSize >= maxChild) + break; + groupSize += nextSize; + } + if (i == groupFrom + 1) { + if (groupSize > maxChild) { + let only = children[groupFrom]; // Only trees can have a size > 1 + divide(only.children, only.positions, 0, only.children.length, positions[groupFrom] + offset); + continue; + } + localChildren.push(children[groupFrom]); + } + else { + let length = positions[i - 1] + children[i - 1].length - groupStart; + localChildren.push(balanceRange(balanceType, children, positions, groupFrom, i, groupStart, length, null, mkTree)); + } + localPositions.push(groupStart + offset - start); + } + } + divide(children, positions, from, to, 0); + return (mkTop || mkTree)(localChildren, localPositions, length); + } + + /// Tree fragments are used during [incremental + /// parsing](#common.Parser.startParse) to track parts of old trees + /// that can be reused in a new parse. An array of fragments is used + /// to track regions of an old tree whose nodes might be reused in new + /// parses. Use the static + /// [`applyChanges`](#common.TreeFragment^applyChanges) method to + /// update fragments for document changes. + class TreeFragment { + /// Construct a tree fragment. You'll usually want to use + /// [`addTree`](#common.TreeFragment^addTree) and + /// [`applyChanges`](#common.TreeFragment^applyChanges) instead of + /// calling this directly. + constructor( + /// The start of the unchanged range pointed to by this fragment. + /// This refers to an offset in the _updated_ document (as opposed + /// to the original tree). + from, + /// The end of the unchanged range. + to, + /// The tree that this fragment is based on. + tree, + /// The offset between the fragment's tree and the document that + /// this fragment can be used against. Add this when going from + /// document to tree positions, subtract it to go from tree to + /// document positions. + offset, openStart = false, openEnd = false) { + this.from = from; + this.to = to; + this.tree = tree; + this.offset = offset; + this.open = (openStart ? 1 /* Start */ : 0) | (openEnd ? 2 /* End */ : 0); + } + /// Whether the start of the fragment represents the start of a + /// parse, or the end of a change. (In the second case, it may not + /// be safe to reuse some nodes at the start, depending on the + /// parsing algorithm.) + get openStart() { return (this.open & 1 /* Start */) > 0; } + /// Whether the end of the fragment represents the end of a + /// full-document parse, or the start of a change. + get openEnd() { return (this.open & 2 /* End */) > 0; } + /// Create a set of fragments from a freshly parsed tree, or update + /// an existing set of fragments by replacing the ones that overlap + /// with a tree with content from the new tree. When `partial` is + /// true, the parse is treated as incomplete, and the resulting + /// fragment has [`openEnd`](#common.TreeFragment.openEnd) set to + /// true. + static addTree(tree, fragments = [], partial = false) { + let result = [new TreeFragment(0, tree.length, tree, 0, false, partial)]; + for (let f of fragments) + if (f.to > tree.length) + result.push(f); + return result; + } + /// Apply a set of edits to an array of fragments, removing or + /// splitting fragments as necessary to remove edited ranges, and + /// adjusting offsets for fragments that moved. + static applyChanges(fragments, changes, minGap = 128) { + if (!changes.length) + return fragments; + let result = []; + let fI = 1, nextF = fragments.length ? fragments[0] : null; + for (let cI = 0, pos = 0, off = 0;; cI++) { + let nextC = cI < changes.length ? changes[cI] : null; + let nextPos = nextC ? nextC.fromA : 1e9; + if (nextPos - pos >= minGap) + while (nextF && nextF.from < nextPos) { + let cut = nextF; + if (pos >= cut.from || nextPos <= cut.to || off) { + let fFrom = Math.max(cut.from, pos) - off, fTo = Math.min(cut.to, nextPos) - off; + cut = fFrom >= fTo ? null : new TreeFragment(fFrom, fTo, cut.tree, cut.offset + off, cI > 0, !!nextC); + } + if (cut) + result.push(cut); + if (nextF.to > nextPos) + break; + nextF = fI < fragments.length ? fragments[fI++] : null; + } + if (!nextC) + break; + pos = nextC.toA; + off = nextC.toA - nextC.toB; + } + return result; + } + } + /// A superclass that parsers should extend. + class Parser { + /// Start a parse, returning a [partial parse](#common.PartialParse) + /// object. [`fragments`](#common.TreeFragment) can be passed in to + /// make the parse incremental. + /// + /// By default, the entire input is parsed. You can pass `ranges`, + /// which should be a sorted array of non-empty, non-overlapping + /// ranges, to parse only those ranges. The tree returned in that + /// case will start at `ranges[0].from`. + startParse(input, fragments, ranges) { + if (typeof input == "string") + input = new StringInput(input); + ranges = !ranges ? [new Range(0, input.length)] : ranges.length ? ranges.map(r => new Range(r.from, r.to)) : [new Range(0, 0)]; + return this.createParse(input, fragments || [], ranges); + } + /// Run a full parse, returning the resulting tree. + parse(input, fragments, ranges) { + let parse = this.startParse(input, fragments, ranges); + for (;;) { + let done = parse.advance(); + if (done) + return done; + } + } + } + class StringInput { + constructor(string) { + this.string = string; + } + get length() { return this.string.length; } + chunk(from) { return this.string.slice(from); } + get lineChunks() { return false; } + read(from, to) { return this.string.slice(from, to); } + } + new NodeProp({ perNode: true }); + + let nextTagID = 0; + /// Highlighting tags are markers that denote a highlighting category. + /// They are [associated](#highlight.styleTags) with parts of a syntax + /// tree by a language mode, and then mapped to an actual CSS style by + /// a [highlighter](#highlight.Highlighter). + /// + /// Because syntax tree node types and highlight styles have to be + /// able to talk the same language, CodeMirror uses a mostly _closed_ + /// [vocabulary](#highlight.tags) of syntax tags (as opposed to + /// traditional open string-based systems, which make it hard for + /// highlighting themes to cover all the tokens produced by the + /// various languages). + /// + /// It _is_ possible to [define](#highlight.Tag^define) your own + /// highlighting tags for system-internal use (where you control both + /// the language package and the highlighter), but such tags will not + /// be picked up by regular highlighters (though you can derive them + /// from standard tags to allow highlighters to fall back to those). + class Tag { + /// @internal + constructor( + /// The set of this tag and all its parent tags, starting with + /// this one itself and sorted in order of decreasing specificity. + set, + /// The base unmodified tag that this one is based on, if it's + /// modified @internal + base, + /// The modifiers applied to this.base @internal + modified) { + this.set = set; + this.base = base; + this.modified = modified; + /// @internal + this.id = nextTagID++; + } + /// Define a new tag. If `parent` is given, the tag is treated as a + /// sub-tag of that parent, and + /// [highlighters](#highlight.tagHighlighter) that don't mention + /// this tag will try to fall back to the parent tag (or grandparent + /// tag, etc). + static define(parent) { + if (parent === null || parent === void 0 ? void 0 : parent.base) + throw new Error("Can not derive from a modified tag"); + let tag = new Tag([], null, []); + tag.set.push(tag); + if (parent) + for (let t of parent.set) + tag.set.push(t); + return tag; + } + /// Define a tag _modifier_, which is a function that, given a tag, + /// will return a tag that is a subtag of the original. Applying the + /// same modifier to a twice tag will return the same value (`m1(t1) + /// == m1(t1)`) and applying multiple modifiers will, regardless or + /// order, produce the same tag (`m1(m2(t1)) == m2(m1(t1))`). + /// + /// When multiple modifiers are applied to a given base tag, each + /// smaller set of modifiers is registered as a parent, so that for + /// example `m1(m2(m3(t1)))` is a subtype of `m1(m2(t1))`, + /// `m1(m3(t1)`, and so on. + static defineModifier() { + let mod = new Modifier; + return (tag) => { + if (tag.modified.indexOf(mod) > -1) + return tag; + return Modifier.get(tag.base || tag, tag.modified.concat(mod).sort((a, b) => a.id - b.id)); + }; + } + } + let nextModifierID = 0; + class Modifier { + constructor() { + this.instances = []; + this.id = nextModifierID++; + } + static get(base, mods) { + if (!mods.length) + return base; + let exists = mods[0].instances.find(t => t.base == base && sameArray(mods, t.modified)); + if (exists) + return exists; + let set = [], tag = new Tag(set, base, mods); + for (let m of mods) + m.instances.push(tag); + let configs = permute(mods); + for (let parent of base.set) + for (let config of configs) + set.push(Modifier.get(parent, config)); + return tag; + } + } + function sameArray(a, b) { + return a.length == b.length && a.every((x, i) => x == b[i]); + } + function permute(array) { + let result = [array]; + for (let i = 0; i < array.length; i++) { + for (let a of permute(array.slice(0, i).concat(array.slice(i + 1)))) + result.push(a); + } + return result; + } + /// This function is used to add a set of tags to a language syntax + /// via [`NodeSet.extend`](#common.NodeSet.extend) or + /// [`LRParser.configure`](#lr.LRParser.configure). + /// + /// The argument object maps node selectors to [highlighting + /// tags](#highlight.Tag) or arrays of tags. + /// + /// Node selectors may hold one or more (space-separated) node paths. + /// Such a path can be a [node name](#common.NodeType.name), or + /// multiple node names (or `*` wildcards) separated by slash + /// characters, as in `"Block/Declaration/VariableName"`. Such a path + /// matches the final node but only if its direct parent nodes are the + /// other nodes mentioned. A `*` in such a path matches any parent, + /// but only a single level—wildcards that match multiple parents + /// aren't supported, both for efficiency reasons and because Lezer + /// trees make it rather hard to reason about what they would match.) + /// + /// A path can be ended with `/...` to indicate that the tag assigned + /// to the node should also apply to all child nodes, even if they + /// match their own style (by default, only the innermost style is + /// used). + /// + /// When a path ends in `!`, as in `Attribute!`, no further matching + /// happens for the node's child nodes, and the entire node gets the + /// given style. + /// + /// In this notation, node names that contain `/`, `!`, `*`, or `...` + /// must be quoted as JSON strings. + /// + /// For example: + /// + /// ```javascript + /// parser.withProps( + /// styleTags({ + /// // Style Number and BigNumber nodes + /// "Number BigNumber": tags.number, + /// // Style Escape nodes whose parent is String + /// "String/Escape": tags.escape, + /// // Style anything inside Attributes nodes + /// "Attributes!": tags.meta, + /// // Add a style to all content inside Italic nodes + /// "Italic/...": tags.emphasis, + /// // Style InvalidString nodes as both `string` and `invalid` + /// "InvalidString": [tags.string, tags.invalid], + /// // Style the node named "/" as punctuation + /// '"/"': tags.punctuation + /// }) + /// ) + /// ``` + function styleTags(spec) { + let byName = Object.create(null); + for (let prop in spec) { + let tags = spec[prop]; + if (!Array.isArray(tags)) + tags = [tags]; + for (let part of prop.split(" ")) + if (part) { + let pieces = [], mode = 2 /* Normal */, rest = part; + for (let pos = 0;;) { + if (rest == "..." && pos > 0 && pos + 3 == part.length) { + mode = 1 /* Inherit */; + break; + } + let m = /^"(?:[^"\\]|\\.)*?"|[^\/!]+/.exec(rest); + if (!m) + throw new RangeError("Invalid path: " + part); + pieces.push(m[0] == "*" ? "" : m[0][0] == '"' ? JSON.parse(m[0]) : m[0]); + pos += m[0].length; + if (pos == part.length) + break; + let next = part[pos++]; + if (pos == part.length && next == "!") { + mode = 0 /* Opaque */; + break; + } + if (next != "/") + throw new RangeError("Invalid path: " + part); + rest = part.slice(pos); + } + let last = pieces.length - 1, inner = pieces[last]; + if (!inner) + throw new RangeError("Invalid path: " + part); + let rule = new Rule(tags, mode, last > 0 ? pieces.slice(0, last) : null); + byName[inner] = rule.sort(byName[inner]); + } + } + return ruleNodeProp.add(byName); + } + const ruleNodeProp = new NodeProp(); + class Rule { + constructor(tags, mode, context, next) { + this.tags = tags; + this.mode = mode; + this.context = context; + this.next = next; + } + get opaque() { return this.mode == 0 /* Opaque */; } + get inherit() { return this.mode == 1 /* Inherit */; } + sort(other) { + if (!other || other.depth < this.depth) { + this.next = other; + return this; + } + other.next = this.sort(other.next); + return other; + } + get depth() { return this.context ? this.context.length : 0; } + } + Rule.empty = new Rule([], 2 /* Normal */, null); + /// Define a [highlighter](#highlight.Highlighter) from an array of + /// tag/class pairs. Classes associated with more specific tags will + /// take precedence. + function tagHighlighter(tags, options) { + let map = Object.create(null); + for (let style of tags) { + if (!Array.isArray(style.tag)) + map[style.tag.id] = style.class; + else + for (let tag of style.tag) + map[tag.id] = style.class; + } + let { scope, all = null } = options || {}; + return { + style: (tags) => { + let cls = all; + for (let tag of tags) { + for (let sub of tag.set) { + let tagClass = map[sub.id]; + if (tagClass) { + cls = cls ? cls + " " + tagClass : tagClass; + break; + } + } + } + return cls; + }, + scope + }; + } + function highlightTags(highlighters, tags) { + let result = null; + for (let highlighter of highlighters) { + let value = highlighter.style(tags); + if (value) + result = result ? result + " " + value : value; + } + return result; + } + /// Highlight the given [tree](#common.Tree) with the given + /// [highlighter](#highlight.Highlighter). + function highlightTree(tree, highlighter, + /// Assign styling to a region of the text. Will be called, in order + /// of position, for any ranges where more than zero classes apply. + /// `classes` is a space separated string of CSS classes. + putStyle, + /// The start of the range to highlight. + from = 0, + /// The end of the range. + to = tree.length) { + let builder = new HighlightBuilder(from, Array.isArray(highlighter) ? highlighter : [highlighter], putStyle); + builder.highlightRange(tree.cursor(), from, to, "", builder.highlighters); + builder.flush(to); + } + class HighlightBuilder { + constructor(at, highlighters, span) { + this.at = at; + this.highlighters = highlighters; + this.span = span; + this.class = ""; + } + startSpan(at, cls) { + if (cls != this.class) { + this.flush(at); + if (at > this.at) + this.at = at; + this.class = cls; + } + } + flush(to) { + if (to > this.at && this.class) + this.span(this.at, to, this.class); + } + highlightRange(cursor, from, to, inheritedClass, highlighters) { + let { type, from: start, to: end } = cursor; + if (start >= to || end <= from) + return; + if (type.isTop) + highlighters = this.highlighters.filter(h => !h.scope || h.scope(type)); + let cls = inheritedClass; + let rule = getStyleTags(cursor) || Rule.empty; + let tagCls = highlightTags(highlighters, rule.tags); + if (tagCls) { + if (cls) + cls += " "; + cls += tagCls; + if (rule.mode == 1 /* Inherit */) + inheritedClass += (inheritedClass ? " " : "") + tagCls; + } + this.startSpan(cursor.from, cls); + if (rule.opaque) + return; + let mounted = cursor.tree && cursor.tree.prop(NodeProp.mounted); + if (mounted && mounted.overlay) { + let inner = cursor.node.enter(mounted.overlay[0].from + start, 1); + let innerHighlighters = this.highlighters.filter(h => !h.scope || h.scope(mounted.tree.type)); + let hasChild = cursor.firstChild(); + for (let i = 0, pos = start;; i++) { + let next = i < mounted.overlay.length ? mounted.overlay[i] : null; + let nextPos = next ? next.from + start : end; + let rangeFrom = Math.max(from, pos), rangeTo = Math.min(to, nextPos); + if (rangeFrom < rangeTo && hasChild) { + while (cursor.from < rangeTo) { + this.highlightRange(cursor, rangeFrom, rangeTo, inheritedClass, highlighters); + this.startSpan(Math.min(to, cursor.to), cls); + if (cursor.to >= nextPos || !cursor.nextSibling()) + break; + } + } + if (!next || nextPos > to) + break; + pos = next.to + start; + if (pos > from) { + this.highlightRange(inner.cursor(), Math.max(from, next.from + start), Math.min(to, pos), inheritedClass, innerHighlighters); + this.startSpan(pos, cls); + } + } + if (hasChild) + cursor.parent(); + } + else if (cursor.firstChild()) { + do { + if (cursor.to <= from) + continue; + if (cursor.from >= to) + break; + this.highlightRange(cursor, from, to, inheritedClass, highlighters); + this.startSpan(Math.min(to, cursor.to), cls); + } while (cursor.nextSibling()); + cursor.parent(); + } + } + } + /// Match a syntax node's [highlight rules](#highlight.styleTags). If + /// there's a match, return its set of tags, and whether it is + /// opaque (uses a `!`) or applies to all child nodes (`/...`). + function getStyleTags(node) { + let rule = node.type.prop(ruleNodeProp); + while (rule && rule.context && !node.matchContext(rule.context)) + rule = rule.next; + return rule || null; + } + const t = Tag.define; + const comment = t(), name = t(), typeName = t(name), propertyName = t(name), literal = t(), string = t(literal), number = t(literal), content = t(), heading = t(content), keyword = t(), operator = t(), punctuation = t(), bracket = t(punctuation), meta = t(); + /// The default set of highlighting [tags](#highlight.Tag). + /// + /// This collection is heavily biased towards programming languages, + /// and necessarily incomplete. A full ontology of syntactic + /// constructs would fill a stack of books, and be impractical to + /// write themes for. So try to make do with this set. If all else + /// fails, [open an + /// issue](https://github.com/codemirror/codemirror.next) to propose a + /// new tag, or [define](#highlight.Tag^define) a local custom tag for + /// your use case. + /// + /// Note that it is not obligatory to always attach the most specific + /// tag possible to an element—if your grammar can't easily + /// distinguish a certain type of element (such as a local variable), + /// it is okay to style it as its more general variant (a variable). + /// + /// For tags that extend some parent tag, the documentation links to + /// the parent. + const tags = { + /// A comment. + comment, + /// A line [comment](#highlight.tags.comment). + lineComment: t(comment), + /// A block [comment](#highlight.tags.comment). + blockComment: t(comment), + /// A documentation [comment](#highlight.tags.comment). + docComment: t(comment), + /// Any kind of identifier. + name, + /// The [name](#highlight.tags.name) of a variable. + variableName: t(name), + /// A type [name](#highlight.tags.name). + typeName: typeName, + /// A tag name (subtag of [`typeName`](#highlight.tags.typeName)). + tagName: t(typeName), + /// A property or field [name](#highlight.tags.name). + propertyName: propertyName, + /// An attribute name (subtag of [`propertyName`](#highlight.tags.propertyName)). + attributeName: t(propertyName), + /// The [name](#highlight.tags.name) of a class. + className: t(name), + /// A label [name](#highlight.tags.name). + labelName: t(name), + /// A namespace [name](#highlight.tags.name). + namespace: t(name), + /// The [name](#highlight.tags.name) of a macro. + macroName: t(name), + /// A literal value. + literal, + /// A string [literal](#highlight.tags.literal). + string, + /// A documentation [string](#highlight.tags.string). + docString: t(string), + /// A character literal (subtag of [string](#highlight.tags.string)). + character: t(string), + /// An attribute value (subtag of [string](#highlight.tags.string)). + attributeValue: t(string), + /// A number [literal](#highlight.tags.literal). + number, + /// An integer [number](#highlight.tags.number) literal. + integer: t(number), + /// A floating-point [number](#highlight.tags.number) literal. + float: t(number), + /// A boolean [literal](#highlight.tags.literal). + bool: t(literal), + /// Regular expression [literal](#highlight.tags.literal). + regexp: t(literal), + /// An escape [literal](#highlight.tags.literal), for example a + /// backslash escape in a string. + escape: t(literal), + /// A color [literal](#highlight.tags.literal). + color: t(literal), + /// A URL [literal](#highlight.tags.literal). + url: t(literal), + /// A language keyword. + keyword, + /// The [keyword](#highlight.tags.keyword) for the self or this + /// object. + self: t(keyword), + /// The [keyword](#highlight.tags.keyword) for null. + null: t(keyword), + /// A [keyword](#highlight.tags.keyword) denoting some atomic value. + atom: t(keyword), + /// A [keyword](#highlight.tags.keyword) that represents a unit. + unit: t(keyword), + /// A modifier [keyword](#highlight.tags.keyword). + modifier: t(keyword), + /// A [keyword](#highlight.tags.keyword) that acts as an operator. + operatorKeyword: t(keyword), + /// A control-flow related [keyword](#highlight.tags.keyword). + controlKeyword: t(keyword), + /// A [keyword](#highlight.tags.keyword) that defines something. + definitionKeyword: t(keyword), + /// A [keyword](#highlight.tags.keyword) related to defining or + /// interfacing with modules. + moduleKeyword: t(keyword), + /// An operator. + operator, + /// An [operator](#highlight.tags.operator) that dereferences something. + derefOperator: t(operator), + /// Arithmetic-related [operator](#highlight.tags.operator). + arithmeticOperator: t(operator), + /// Logical [operator](#highlight.tags.operator). + logicOperator: t(operator), + /// Bit [operator](#highlight.tags.operator). + bitwiseOperator: t(operator), + /// Comparison [operator](#highlight.tags.operator). + compareOperator: t(operator), + /// [Operator](#highlight.tags.operator) that updates its operand. + updateOperator: t(operator), + /// [Operator](#highlight.tags.operator) that defines something. + definitionOperator: t(operator), + /// Type-related [operator](#highlight.tags.operator). + typeOperator: t(operator), + /// Control-flow [operator](#highlight.tags.operator). + controlOperator: t(operator), + /// Program or markup punctuation. + punctuation, + /// [Punctuation](#highlight.tags.punctuation) that separates + /// things. + separator: t(punctuation), + /// Bracket-style [punctuation](#highlight.tags.punctuation). + bracket, + /// Angle [brackets](#highlight.tags.bracket) (usually `<` and `>` + /// tokens). + angleBracket: t(bracket), + /// Square [brackets](#highlight.tags.bracket) (usually `[` and `]` + /// tokens). + squareBracket: t(bracket), + /// Parentheses (usually `(` and `)` tokens). Subtag of + /// [bracket](#highlight.tags.bracket). + paren: t(bracket), + /// Braces (usually `{` and `}` tokens). Subtag of + /// [bracket](#highlight.tags.bracket). + brace: t(bracket), + /// Content, for example plain text in XML or markup documents. + content, + /// [Content](#highlight.tags.content) that represents a heading. + heading, + /// A level 1 [heading](#highlight.tags.heading). + heading1: t(heading), + /// A level 2 [heading](#highlight.tags.heading). + heading2: t(heading), + /// A level 3 [heading](#highlight.tags.heading). + heading3: t(heading), + /// A level 4 [heading](#highlight.tags.heading). + heading4: t(heading), + /// A level 5 [heading](#highlight.tags.heading). + heading5: t(heading), + /// A level 6 [heading](#highlight.tags.heading). + heading6: t(heading), + /// A prose separator (such as a horizontal rule). + contentSeparator: t(content), + /// [Content](#highlight.tags.content) that represents a list. + list: t(content), + /// [Content](#highlight.tags.content) that represents a quote. + quote: t(content), + /// [Content](#highlight.tags.content) that is emphasized. + emphasis: t(content), + /// [Content](#highlight.tags.content) that is styled strong. + strong: t(content), + /// [Content](#highlight.tags.content) that is part of a link. + link: t(content), + /// [Content](#highlight.tags.content) that is styled as code or + /// monospace. + monospace: t(content), + /// [Content](#highlight.tags.content) that has a strike-through + /// style. + strikethrough: t(content), + /// Inserted text in a change-tracking format. + inserted: t(), + /// Deleted text. + deleted: t(), + /// Changed text. + changed: t(), + /// An invalid or unsyntactic element. + invalid: t(), + /// Metadata or meta-instruction. + meta, + /// [Metadata](#highlight.tags.meta) that applies to the entire + /// document. + documentMeta: t(meta), + /// [Metadata](#highlight.tags.meta) that annotates or adds + /// attributes to a given syntactic element. + annotation: t(meta), + /// Processing instruction or preprocessor directive. Subtag of + /// [meta](#highlight.tags.meta). + processingInstruction: t(meta), + /// [Modifier](#highlight.Tag^defineModifier) that indicates that a + /// given element is being defined. Expected to be used with the + /// various [name](#highlight.tags.name) tags. + definition: Tag.defineModifier(), + /// [Modifier](#highlight.Tag^defineModifier) that indicates that + /// something is constant. Mostly expected to be used with + /// [variable names](#highlight.tags.variableName). + constant: Tag.defineModifier(), + /// [Modifier](#highlight.Tag^defineModifier) used to indicate that + /// a [variable](#highlight.tags.variableName) or [property + /// name](#highlight.tags.propertyName) is being called or defined + /// as a function. + function: Tag.defineModifier(), + /// [Modifier](#highlight.Tag^defineModifier) that can be applied to + /// [names](#highlight.tags.name) to indicate that they belong to + /// the language's standard environment. + standard: Tag.defineModifier(), + /// [Modifier](#highlight.Tag^defineModifier) that indicates a given + /// [names](#highlight.tags.name) is local to some scope. + local: Tag.defineModifier(), + /// A generic variant [modifier](#highlight.Tag^defineModifier) that + /// can be used to tag language-specific alternative variants of + /// some common tag. It is recommended for themes to define special + /// forms of at least the [string](#highlight.tags.string) and + /// [variable name](#highlight.tags.variableName) tags, since those + /// come up a lot. + special: Tag.defineModifier() + }; + /// This is a highlighter that adds stable, predictable classes to + /// tokens, for styling with external CSS. + /// + /// The following tags are mapped to their name prefixed with `"tok-"` + /// (for example `"tok-comment"`): + /// + /// * [`link`](#highlight.tags.link) + /// * [`heading`](#highlight.tags.heading) + /// * [`emphasis`](#highlight.tags.emphasis) + /// * [`strong`](#highlight.tags.strong) + /// * [`keyword`](#highlight.tags.keyword) + /// * [`atom`](#highlight.tags.atom) + /// * [`bool`](#highlight.tags.bool) + /// * [`url`](#highlight.tags.url) + /// * [`labelName`](#highlight.tags.labelName) + /// * [`inserted`](#highlight.tags.inserted) + /// * [`deleted`](#highlight.tags.deleted) + /// * [`literal`](#highlight.tags.literal) + /// * [`string`](#highlight.tags.string) + /// * [`number`](#highlight.tags.number) + /// * [`variableName`](#highlight.tags.variableName) + /// * [`typeName`](#highlight.tags.typeName) + /// * [`namespace`](#highlight.tags.namespace) + /// * [`className`](#highlight.tags.className) + /// * [`macroName`](#highlight.tags.macroName) + /// * [`propertyName`](#highlight.tags.propertyName) + /// * [`operator`](#highlight.tags.operator) + /// * [`comment`](#highlight.tags.comment) + /// * [`meta`](#highlight.tags.meta) + /// * [`punctuation`](#highlight.tags.punctuation) + /// * [`invalid`](#highlight.tags.invalid) + /// + /// In addition, these mappings are provided: + /// + /// * [`regexp`](#highlight.tags.regexp), + /// [`escape`](#highlight.tags.escape), and + /// [`special`](#highlight.tags.special)[`(string)`](#highlight.tags.string) + /// are mapped to `"tok-string2"` + /// * [`special`](#highlight.tags.special)[`(variableName)`](#highlight.tags.variableName) + /// to `"tok-variableName2"` + /// * [`local`](#highlight.tags.local)[`(variableName)`](#highlight.tags.variableName) + /// to `"tok-variableName tok-local"` + /// * [`definition`](#highlight.tags.definition)[`(variableName)`](#highlight.tags.variableName) + /// to `"tok-variableName tok-definition"` + /// * [`definition`](#highlight.tags.definition)[`(propertyName)`](#highlight.tags.propertyName) + /// to `"tok-propertyName tok-definition"` + tagHighlighter([ + { tag: tags.link, class: "tok-link" }, + { tag: tags.heading, class: "tok-heading" }, + { tag: tags.emphasis, class: "tok-emphasis" }, + { tag: tags.strong, class: "tok-strong" }, + { tag: tags.keyword, class: "tok-keyword" }, + { tag: tags.atom, class: "tok-atom" }, + { tag: tags.bool, class: "tok-bool" }, + { tag: tags.url, class: "tok-url" }, + { tag: tags.labelName, class: "tok-labelName" }, + { tag: tags.inserted, class: "tok-inserted" }, + { tag: tags.deleted, class: "tok-deleted" }, + { tag: tags.literal, class: "tok-literal" }, + { tag: tags.string, class: "tok-string" }, + { tag: tags.number, class: "tok-number" }, + { tag: [tags.regexp, tags.escape, tags.special(tags.string)], class: "tok-string2" }, + { tag: tags.variableName, class: "tok-variableName" }, + { tag: tags.local(tags.variableName), class: "tok-variableName tok-local" }, + { tag: tags.definition(tags.variableName), class: "tok-variableName tok-definition" }, + { tag: tags.special(tags.variableName), class: "tok-variableName2" }, + { tag: tags.definition(tags.propertyName), class: "tok-propertyName tok-definition" }, + { tag: tags.typeName, class: "tok-typeName" }, + { tag: tags.namespace, class: "tok-namespace" }, + { tag: tags.className, class: "tok-className" }, + { tag: tags.macroName, class: "tok-macroName" }, + { tag: tags.propertyName, class: "tok-propertyName" }, + { tag: tags.operator, class: "tok-operator" }, + { tag: tags.comment, class: "tok-comment" }, + { tag: tags.meta, class: "tok-meta" }, + { tag: tags.invalid, class: "tok-invalid" }, + { tag: tags.punctuation, class: "tok-punctuation" } + ]); + + var _a; + /** + Node prop stored in a parser's top syntax node to provide the + facet that stores language-specific data for that language. + */ + const languageDataProp = /*@__PURE__*/new NodeProp(); + /** + Helper function to define a facet (to be added to the top syntax + node(s) for a language via + [`languageDataProp`](https://codemirror.net/6/docs/ref/#language.languageDataProp)), that will be + used to associate language data with the language. You + probably only need this when subclassing + [`Language`](https://codemirror.net/6/docs/ref/#language.Language). + */ + function defineLanguageFacet(baseData) { + return Facet.define({ + combine: baseData ? values => values.concat(baseData) : undefined + }); + } + /** + A language object manages parsing and per-language + [metadata](https://codemirror.net/6/docs/ref/#state.EditorState.languageDataAt). Parse data is + managed as a [Lezer](https://lezer.codemirror.net) tree. The class + can be used directly, via the [`LRLanguage`](https://codemirror.net/6/docs/ref/#language.LRLanguage) + subclass for [Lezer](https://lezer.codemirror.net/) LR parsers, or + via the [`StreamLanguage`](https://codemirror.net/6/docs/ref/#language.StreamLanguage) subclass + for stream parsers. + */ + class Language { + /** + Construct a language object. If you need to invoke this + directly, first define a data facet with + [`defineLanguageFacet`](https://codemirror.net/6/docs/ref/#language.defineLanguageFacet), and then + configure your parser to [attach](https://codemirror.net/6/docs/ref/#language.languageDataProp) it + to the language's outer syntax node. + */ + constructor( + /** + The [language data](https://codemirror.net/6/docs/ref/#state.EditorState.languageDataAt) facet + used for this language. + */ + data, parser, extraExtensions = []) { + this.data = data; + // Kludge to define EditorState.tree as a debugging helper, + // without the EditorState package actually knowing about + // languages and lezer trees. + if (!EditorState.prototype.hasOwnProperty("tree")) + Object.defineProperty(EditorState.prototype, "tree", { get() { return syntaxTree(this); } }); + this.parser = parser; + this.extension = [ + language.of(this), + EditorState.languageData.of((state, pos, side) => state.facet(languageDataFacetAt(state, pos, side))) + ].concat(extraExtensions); + } + /** + Query whether this language is active at the given position. + */ + isActiveAt(state, pos, side = -1) { + return languageDataFacetAt(state, pos, side) == this.data; + } + /** + Find the document regions that were parsed using this language. + The returned regions will _include_ any nested languages rooted + in this language, when those exist. + */ + findRegions(state) { + let lang = state.facet(language); + if ((lang === null || lang === void 0 ? void 0 : lang.data) == this.data) + return [{ from: 0, to: state.doc.length }]; + if (!lang || !lang.allowsNesting) + return []; + let result = []; + let explore = (tree, from) => { + if (tree.prop(languageDataProp) == this.data) { + result.push({ from, to: from + tree.length }); + return; + } + let mount = tree.prop(NodeProp.mounted); + if (mount) { + if (mount.tree.prop(languageDataProp) == this.data) { + if (mount.overlay) + for (let r of mount.overlay) + result.push({ from: r.from + from, to: r.to + from }); + else + result.push({ from: from, to: from + tree.length }); + return; + } + else if (mount.overlay) { + let size = result.length; + explore(mount.tree, mount.overlay[0].from + from); + if (result.length > size) + return; + } + } + for (let i = 0; i < tree.children.length; i++) { + let ch = tree.children[i]; + if (ch instanceof Tree) + explore(ch, tree.positions[i] + from); + } + }; + explore(syntaxTree(state), 0); + return result; + } + /** + Indicates whether this language allows nested languages. The + default implementation returns true. + */ + get allowsNesting() { return true; } + } + /** + @internal + */ + Language.setState = /*@__PURE__*/StateEffect.define(); + function languageDataFacetAt(state, pos, side) { + let topLang = state.facet(language); + if (!topLang) + return null; + let facet = topLang.data; + if (topLang.allowsNesting) { + for (let node = syntaxTree(state).topNode; node; node = node.enter(pos, side, IterMode.ExcludeBuffers)) + facet = node.type.prop(languageDataProp) || facet; + } + return facet; + } + /** + A subclass of [`Language`](https://codemirror.net/6/docs/ref/#language.Language) for use with Lezer + [LR parsers](https://lezer.codemirror.net/docs/ref#lr.LRParser) + parsers. + */ + class LRLanguage extends Language { + constructor(data, parser) { + super(data, parser); + this.parser = parser; + } + /** + Define a language from a parser. + */ + static define(spec) { + let data = defineLanguageFacet(spec.languageData); + return new LRLanguage(data, spec.parser.configure({ + props: [languageDataProp.add(type => type.isTop ? data : undefined)] + })); + } + /** + Create a new instance of this language with a reconfigured + version of its parser. + */ + configure(options) { + return new LRLanguage(this.data, this.parser.configure(options)); + } + get allowsNesting() { return this.parser.hasWrappers(); } + } + /** + Get the syntax tree for a state, which is the current (possibly + incomplete) parse tree of the active + [language](https://codemirror.net/6/docs/ref/#language.Language), or the empty tree if there is no + language available. + */ + function syntaxTree(state) { + let field = state.field(Language.state, false); + return field ? field.tree : Tree.empty; + } + // Lezer-style Input object for a Text document. + class DocInput { + constructor(doc, length = doc.length) { + this.doc = doc; + this.length = length; + this.cursorPos = 0; + this.string = ""; + this.cursor = doc.iter(); + } + syncTo(pos) { + this.string = this.cursor.next(pos - this.cursorPos).value; + this.cursorPos = pos + this.string.length; + return this.cursorPos - this.string.length; + } + chunk(pos) { + this.syncTo(pos); + return this.string; + } + get lineChunks() { return true; } + read(from, to) { + let stringStart = this.cursorPos - this.string.length; + if (from < stringStart || to >= this.cursorPos) + return this.doc.sliceString(from, to); + else + return this.string.slice(from - stringStart, to - stringStart); + } + } + let currentContext = null; + /** + A parse context provided to parsers working on the editor content. + */ + class ParseContext { + constructor(parser, + /** + The current editor state. + */ + state, + /** + Tree fragments that can be reused by incremental re-parses. + */ + fragments = [], + /** + @internal + */ + tree, + /** + @internal + */ + treeLen, + /** + The current editor viewport (or some overapproximation + thereof). Intended to be used for opportunistically avoiding + work (in which case + [`skipUntilInView`](https://codemirror.net/6/docs/ref/#language.ParseContext.skipUntilInView) + should be called to make sure the parser is restarted when the + skipped region becomes visible). + */ + viewport, + /** + @internal + */ + skipped, + /** + This is where skipping parsers can register a promise that, + when resolved, will schedule a new parse. It is cleared when + the parse worker picks up the promise. @internal + */ + scheduleOn) { + this.parser = parser; + this.state = state; + this.fragments = fragments; + this.tree = tree; + this.treeLen = treeLen; + this.viewport = viewport; + this.skipped = skipped; + this.scheduleOn = scheduleOn; + this.parse = null; + /** + @internal + */ + this.tempSkipped = []; + } + /** + @internal + */ + static create(parser, state, viewport) { + return new ParseContext(parser, state, [], Tree.empty, 0, viewport, [], null); + } + startParse() { + return this.parser.startParse(new DocInput(this.state.doc), this.fragments); + } + /** + @internal + */ + work(until, upto) { + if (upto != null && upto >= this.state.doc.length) + upto = undefined; + if (this.tree != Tree.empty && this.isDone(upto !== null && upto !== void 0 ? upto : this.state.doc.length)) { + this.takeTree(); + return true; + } + return this.withContext(() => { + var _a; + if (typeof until == "number") { + let endTime = Date.now() + until; + until = () => Date.now() > endTime; + } + if (!this.parse) + this.parse = this.startParse(); + if (upto != null && (this.parse.stoppedAt == null || this.parse.stoppedAt > upto) && + upto < this.state.doc.length) + this.parse.stopAt(upto); + for (;;) { + let done = this.parse.advance(); + if (done) { + this.fragments = this.withoutTempSkipped(TreeFragment.addTree(done, this.fragments, this.parse.stoppedAt != null)); + this.treeLen = (_a = this.parse.stoppedAt) !== null && _a !== void 0 ? _a : this.state.doc.length; + this.tree = done; + this.parse = null; + if (this.treeLen < (upto !== null && upto !== void 0 ? upto : this.state.doc.length)) + this.parse = this.startParse(); + else + return true; + } + if (until()) + return false; + } + }); + } + /** + @internal + */ + takeTree() { + let pos, tree; + if (this.parse && (pos = this.parse.parsedPos) >= this.treeLen) { + if (this.parse.stoppedAt == null || this.parse.stoppedAt > pos) + this.parse.stopAt(pos); + this.withContext(() => { while (!(tree = this.parse.advance())) { } }); + this.treeLen = pos; + this.tree = tree; + this.fragments = this.withoutTempSkipped(TreeFragment.addTree(this.tree, this.fragments, true)); + this.parse = null; + } + } + withContext(f) { + let prev = currentContext; + currentContext = this; + try { + return f(); + } + finally { + currentContext = prev; + } + } + withoutTempSkipped(fragments) { + for (let r; r = this.tempSkipped.pop();) + fragments = cutFragments(fragments, r.from, r.to); + return fragments; + } + /** + @internal + */ + changes(changes, newState) { + let { fragments, tree, treeLen, viewport, skipped } = this; + this.takeTree(); + if (!changes.empty) { + let ranges = []; + changes.iterChangedRanges((fromA, toA, fromB, toB) => ranges.push({ fromA, toA, fromB, toB })); + fragments = TreeFragment.applyChanges(fragments, ranges); + tree = Tree.empty; + treeLen = 0; + viewport = { from: changes.mapPos(viewport.from, -1), to: changes.mapPos(viewport.to, 1) }; + if (this.skipped.length) { + skipped = []; + for (let r of this.skipped) { + let from = changes.mapPos(r.from, 1), to = changes.mapPos(r.to, -1); + if (from < to) + skipped.push({ from, to }); + } + } + } + return new ParseContext(this.parser, newState, fragments, tree, treeLen, viewport, skipped, this.scheduleOn); + } + /** + @internal + */ + updateViewport(viewport) { + if (this.viewport.from == viewport.from && this.viewport.to == viewport.to) + return false; + this.viewport = viewport; + let startLen = this.skipped.length; + for (let i = 0; i < this.skipped.length; i++) { + let { from, to } = this.skipped[i]; + if (from < viewport.to && to > viewport.from) { + this.fragments = cutFragments(this.fragments, from, to); + this.skipped.splice(i--, 1); + } + } + if (this.skipped.length >= startLen) + return false; + this.reset(); + return true; + } + /** + @internal + */ + reset() { + if (this.parse) { + this.takeTree(); + this.parse = null; + } + } + /** + Notify the parse scheduler that the given region was skipped + because it wasn't in view, and the parse should be restarted + when it comes into view. + */ + skipUntilInView(from, to) { + this.skipped.push({ from, to }); + } + /** + Returns a parser intended to be used as placeholder when + asynchronously loading a nested parser. It'll skip its input and + mark it as not-really-parsed, so that the next update will parse + it again. + + When `until` is given, a reparse will be scheduled when that + promise resolves. + */ + static getSkippingParser(until) { + return new class extends Parser { + createParse(input, fragments, ranges) { + let from = ranges[0].from, to = ranges[ranges.length - 1].to; + let parser = { + parsedPos: from, + advance() { + let cx = currentContext; + if (cx) { + for (let r of ranges) + cx.tempSkipped.push(r); + if (until) + cx.scheduleOn = cx.scheduleOn ? Promise.all([cx.scheduleOn, until]) : until; + } + this.parsedPos = to; + return new Tree(NodeType.none, [], [], to - from); + }, + stoppedAt: null, + stopAt() { } + }; + return parser; + } + }; + } + /** + @internal + */ + isDone(upto) { + upto = Math.min(upto, this.state.doc.length); + let frags = this.fragments; + return this.treeLen >= upto && frags.length && frags[0].from == 0 && frags[0].to >= upto; + } + /** + Get the context for the current parse, or `null` if no editor + parse is in progress. + */ + static get() { return currentContext; } + } + function cutFragments(fragments, from, to) { + return TreeFragment.applyChanges(fragments, [{ fromA: from, toA: to, fromB: from, toB: to }]); + } + class LanguageState { + constructor( + // A mutable parse state that is used to preserve work done during + // the lifetime of a state when moving to the next state. + context) { + this.context = context; + this.tree = context.tree; + } + apply(tr) { + if (!tr.docChanged && this.tree == this.context.tree) + return this; + let newCx = this.context.changes(tr.changes, tr.state); + // If the previous parse wasn't done, go forward only up to its + // end position or the end of the viewport, to avoid slowing down + // state updates with parse work beyond the viewport. + let upto = this.context.treeLen == tr.startState.doc.length ? undefined + : Math.max(tr.changes.mapPos(this.context.treeLen), newCx.viewport.to); + if (!newCx.work(20 /* Apply */, upto)) + newCx.takeTree(); + return new LanguageState(newCx); + } + static init(state) { + let vpTo = Math.min(3000 /* InitViewport */, state.doc.length); + let parseState = ParseContext.create(state.facet(language).parser, state, { from: 0, to: vpTo }); + if (!parseState.work(20 /* Apply */, vpTo)) + parseState.takeTree(); + return new LanguageState(parseState); + } + } + Language.state = /*@__PURE__*/StateField.define({ + create: LanguageState.init, + update(value, tr) { + for (let e of tr.effects) + if (e.is(Language.setState)) + return e.value; + if (tr.startState.facet(language) != tr.state.facet(language)) + return LanguageState.init(tr.state); + return value.apply(tr); + } + }); + let requestIdle = (callback) => { + let timeout = setTimeout(() => callback(), 500 /* MaxPause */); + return () => clearTimeout(timeout); + }; + if (typeof requestIdleCallback != "undefined") + requestIdle = (callback) => { + let idle = -1, timeout = setTimeout(() => { + idle = requestIdleCallback(callback, { timeout: 500 /* MaxPause */ - 100 /* MinPause */ }); + }, 100 /* MinPause */); + return () => idle < 0 ? clearTimeout(timeout) : cancelIdleCallback(idle); + }; + const isInputPending = typeof navigator != "undefined" && ((_a = navigator.scheduling) === null || _a === void 0 ? void 0 : _a.isInputPending) + ? () => navigator.scheduling.isInputPending() : null; + const parseWorker = /*@__PURE__*/ViewPlugin.fromClass(class ParseWorker { + constructor(view) { + this.view = view; + this.working = null; + this.workScheduled = 0; + // End of the current time chunk + this.chunkEnd = -1; + // Milliseconds of budget left for this chunk + this.chunkBudget = -1; + this.work = this.work.bind(this); + this.scheduleWork(); + } + update(update) { + let cx = this.view.state.field(Language.state).context; + if (cx.updateViewport(update.view.viewport) || this.view.viewport.to > cx.treeLen) + this.scheduleWork(); + if (update.docChanged) { + if (this.view.hasFocus) + this.chunkBudget += 50 /* ChangeBonus */; + this.scheduleWork(); + } + this.checkAsyncSchedule(cx); + } + scheduleWork() { + if (this.working) + return; + let { state } = this.view, field = state.field(Language.state); + if (field.tree != field.context.tree || !field.context.isDone(state.doc.length)) + this.working = requestIdle(this.work); + } + work(deadline) { + this.working = null; + let now = Date.now(); + if (this.chunkEnd < now && (this.chunkEnd < 0 || this.view.hasFocus)) { // Start a new chunk + this.chunkEnd = now + 30000 /* ChunkTime */; + this.chunkBudget = 3000 /* ChunkBudget */; + } + if (this.chunkBudget <= 0) + return; // No more budget + let { state, viewport: { to: vpTo } } = this.view, field = state.field(Language.state); + if (field.tree == field.context.tree && field.context.isDone(vpTo + 100000 /* MaxParseAhead */)) + return; + let endTime = Date.now() + Math.min(this.chunkBudget, 100 /* Slice */, deadline && !isInputPending ? Math.max(25 /* MinSlice */, deadline.timeRemaining() - 5) : 1e9); + let viewportFirst = field.context.treeLen < vpTo && state.doc.length > vpTo + 1000; + let done = field.context.work(() => { + return isInputPending && isInputPending() || Date.now() > endTime; + }, vpTo + (viewportFirst ? 0 : 100000 /* MaxParseAhead */)); + this.chunkBudget -= Date.now() - now; + if (done || this.chunkBudget <= 0) { + field.context.takeTree(); + this.view.dispatch({ effects: Language.setState.of(new LanguageState(field.context)) }); + } + if (this.chunkBudget > 0 && !(done && !viewportFirst)) + this.scheduleWork(); + this.checkAsyncSchedule(field.context); + } + checkAsyncSchedule(cx) { + if (cx.scheduleOn) { + this.workScheduled++; + cx.scheduleOn + .then(() => this.scheduleWork()) + .catch(err => logException(this.view.state, err)) + .then(() => this.workScheduled--); + cx.scheduleOn = null; + } + } + destroy() { + if (this.working) + this.working(); + } + isWorking() { + return !!(this.working || this.workScheduled > 0); + } + }, { + eventHandlers: { focus() { this.scheduleWork(); } } + }); + /** + The facet used to associate a language with an editor state. Used + by `Language` object's `extension` property (so you don't need to + manually wrap your languages in this). Can be used to access the + current language on a state. + */ + const language = /*@__PURE__*/Facet.define({ + combine(languages) { return languages.length ? languages[0] : null; }, + enables: [Language.state, parseWorker] + }); + /** + This class bundles a [language](https://codemirror.net/6/docs/ref/#language.Language) with an + optional set of supporting extensions. Language packages are + encouraged to export a function that optionally takes a + configuration object and returns a `LanguageSupport` instance, as + the main way for client code to use the package. + */ + class LanguageSupport { + /** + Create a language support object. + */ + constructor( + /** + The language object. + */ + language, + /** + An optional set of supporting extensions. When nesting a + language in another language, the outer language is encouraged + to include the supporting extensions for its inner languages + in its own set of support extensions. + */ + support = []) { + this.language = language; + this.support = support; + this.extension = [language, support]; + } + } + + /** + Facet that defines a way to provide a function that computes the + appropriate indentation depth at the start of a given line, or + `null` to indicate no appropriate indentation could be determined. + */ + const indentService = /*@__PURE__*/Facet.define(); + /** + Facet for overriding the unit by which indentation happens. + Should be a string consisting either entirely of spaces or + entirely of tabs. When not set, this defaults to 2 spaces. + */ + const indentUnit = /*@__PURE__*/Facet.define({ + combine: values => { + if (!values.length) + return " "; + if (!/^(?: +|\t+)$/.test(values[0])) + throw new Error("Invalid indent unit: " + JSON.stringify(values[0])); + return values[0]; + } + }); + /** + Return the _column width_ of an indent unit in the state. + Determined by the [`indentUnit`](https://codemirror.net/6/docs/ref/#language.indentUnit) + facet, and [`tabSize`](https://codemirror.net/6/docs/ref/#state.EditorState^tabSize) when that + contains tabs. + */ + function getIndentUnit(state) { + let unit = state.facet(indentUnit); + return unit.charCodeAt(0) == 9 ? state.tabSize * unit.length : unit.length; + } + /** + Create an indentation string that covers columns 0 to `cols`. + Will use tabs for as much of the columns as possible when the + [`indentUnit`](https://codemirror.net/6/docs/ref/#language.indentUnit) facet contains + tabs. + */ + function indentString(state, cols) { + let result = "", ts = state.tabSize; + if (state.facet(indentUnit).charCodeAt(0) == 9) + while (cols >= ts) { + result += "\t"; + cols -= ts; + } + for (let i = 0; i < cols; i++) + result += " "; + return result; + } + /** + Get the indentation at the given position. Will first consult any + [indent services](https://codemirror.net/6/docs/ref/#language.indentService) that are registered, + and if none of those return an indentation, this will check the + syntax tree for the [indent node prop](https://codemirror.net/6/docs/ref/#language.indentNodeProp) + and use that if found. Returns a number when an indentation could + be determined, and null otherwise. + */ + function getIndentation(context, pos) { + if (context instanceof EditorState) + context = new IndentContext(context); + for (let service of context.state.facet(indentService)) { + let result = service(context, pos); + if (result != null) + return result; + } + let tree = syntaxTree(context.state); + return tree ? syntaxIndentation(context, tree, pos) : null; + } + /** + Indentation contexts are used when calling [indentation + services](https://codemirror.net/6/docs/ref/#language.indentService). They provide helper utilities + useful in indentation logic, and can selectively override the + indentation reported for some lines. + */ + class IndentContext { + /** + Create an indent context. + */ + constructor( + /** + The editor state. + */ + state, + /** + @internal + */ + options = {}) { + this.state = state; + this.options = options; + this.unit = getIndentUnit(state); + } + /** + Get a description of the line at the given position, taking + [simulated line + breaks](https://codemirror.net/6/docs/ref/#language.IndentContext.constructor^options.simulateBreak) + into account. If there is such a break at `pos`, the `bias` + argument determines whether the part of the line line before or + after the break is used. + */ + lineAt(pos, bias = 1) { + let line = this.state.doc.lineAt(pos); + let { simulateBreak, simulateDoubleBreak } = this.options; + if (simulateBreak != null && simulateBreak >= line.from && simulateBreak <= line.to) { + if (simulateDoubleBreak && simulateBreak == pos) + return { text: "", from: pos }; + else if (bias < 0 ? simulateBreak < pos : simulateBreak <= pos) + return { text: line.text.slice(simulateBreak - line.from), from: simulateBreak }; + else + return { text: line.text.slice(0, simulateBreak - line.from), from: line.from }; + } + return line; + } + /** + Get the text directly after `pos`, either the entire line + or the next 100 characters, whichever is shorter. + */ + textAfterPos(pos, bias = 1) { + if (this.options.simulateDoubleBreak && pos == this.options.simulateBreak) + return ""; + let { text, from } = this.lineAt(pos, bias); + return text.slice(pos - from, Math.min(text.length, pos + 100 - from)); + } + /** + Find the column for the given position. + */ + column(pos, bias = 1) { + let { text, from } = this.lineAt(pos, bias); + let result = this.countColumn(text, pos - from); + let override = this.options.overrideIndentation ? this.options.overrideIndentation(from) : -1; + if (override > -1) + result += override - this.countColumn(text, text.search(/\S|$/)); + return result; + } + /** + Find the column position (taking tabs into account) of the given + position in the given string. + */ + countColumn(line, pos = line.length) { + return countColumn(line, this.state.tabSize, pos); + } + /** + Find the indentation column of the line at the given point. + */ + lineIndent(pos, bias = 1) { + let { text, from } = this.lineAt(pos, bias); + let override = this.options.overrideIndentation; + if (override) { + let overriden = override(from); + if (overriden > -1) + return overriden; + } + return this.countColumn(text, text.search(/\S|$/)); + } + /** + Returns the [simulated line + break](https://codemirror.net/6/docs/ref/#language.IndentContext.constructor^options.simulateBreak) + for this context, if any. + */ + get simulatedBreak() { + return this.options.simulateBreak || null; + } + } + /** + A syntax tree node prop used to associate indentation strategies + with node types. Such a strategy is a function from an indentation + context to a column number or null, where null indicates that no + definitive indentation can be determined. + */ + const indentNodeProp = /*@__PURE__*/new NodeProp(); + // Compute the indentation for a given position from the syntax tree. + function syntaxIndentation(cx, ast, pos) { + return indentFrom(ast.resolveInner(pos).enterUnfinishedNodesBefore(pos), pos, cx); + } + function ignoreClosed(cx) { + return cx.pos == cx.options.simulateBreak && cx.options.simulateDoubleBreak; + } + function indentStrategy(tree) { + let strategy = tree.type.prop(indentNodeProp); + if (strategy) + return strategy; + let first = tree.firstChild, close; + if (first && (close = first.type.prop(NodeProp.closedBy))) { + let last = tree.lastChild, closed = last && close.indexOf(last.name) > -1; + return cx => delimitedStrategy(cx, true, 1, undefined, closed && !ignoreClosed(cx) ? last.from : undefined); + } + return tree.parent == null ? topIndent$1 : null; + } + function indentFrom(node, pos, base) { + for (; node; node = node.parent) { + let strategy = indentStrategy(node); + if (strategy) + return strategy(TreeIndentContext.create(base, pos, node)); + } + return null; + } + function topIndent$1() { return 0; } + /** + Objects of this type provide context information and helper + methods to indentation functions registered on syntax nodes. + */ + class TreeIndentContext extends IndentContext { + constructor(base, + /** + The position at which indentation is being computed. + */ + pos, + /** + The syntax tree node to which the indentation strategy + applies. + */ + node) { + super(base.state, base.options); + this.base = base; + this.pos = pos; + this.node = node; + } + /** + @internal + */ + static create(base, pos, node) { + return new TreeIndentContext(base, pos, node); + } + /** + Get the text directly after `this.pos`, either the entire line + or the next 100 characters, whichever is shorter. + */ + get textAfter() { + return this.textAfterPos(this.pos); + } + /** + Get the indentation at the reference line for `this.node`, which + is the line on which it starts, unless there is a node that is + _not_ a parent of this node covering the start of that line. If + so, the line at the start of that node is tried, again skipping + on if it is covered by another such node. + */ + get baseIndent() { + let line = this.state.doc.lineAt(this.node.from); + // Skip line starts that are covered by a sibling (or cousin, etc) + for (;;) { + let atBreak = this.node.resolve(line.from); + while (atBreak.parent && atBreak.parent.from == atBreak.from) + atBreak = atBreak.parent; + if (isParent(atBreak, this.node)) + break; + line = this.state.doc.lineAt(atBreak.from); + } + return this.lineIndent(line.from); + } + /** + Continue looking for indentations in the node's parent nodes, + and return the result of that. + */ + continue() { + let parent = this.node.parent; + return parent ? indentFrom(parent, this.pos, this.base) : 0; + } + } + function isParent(parent, of) { + for (let cur = of; cur; cur = cur.parent) + if (parent == cur) + return true; + return false; + } + // Check whether a delimited node is aligned (meaning there are + // non-skipped nodes on the same line as the opening delimiter). And + // if so, return the opening token. + function bracketedAligned(context) { + let tree = context.node; + let openToken = tree.childAfter(tree.from), last = tree.lastChild; + if (!openToken) + return null; + let sim = context.options.simulateBreak; + let openLine = context.state.doc.lineAt(openToken.from); + let lineEnd = sim == null || sim <= openLine.from ? openLine.to : Math.min(openLine.to, sim); + for (let pos = openToken.to;;) { + let next = tree.childAfter(pos); + if (!next || next == last) + return null; + if (!next.type.isSkipped) + return next.from < lineEnd ? openToken : null; + pos = next.to; + } + } + /** + An indentation strategy for delimited (usually bracketed) nodes. + Will, by default, indent one unit more than the parent's base + indent unless the line starts with a closing token. When `align` + is true and there are non-skipped nodes on the node's opening + line, the content of the node will be aligned with the end of the + opening node, like this: + + foo(bar, + baz) + */ + function delimitedIndent({ closing, align = true, units = 1 }) { + return (context) => delimitedStrategy(context, align, units, closing); + } + function delimitedStrategy(context, align, units, closing, closedAt) { + let after = context.textAfter, space = after.match(/^\s*/)[0].length; + let closed = closing && after.slice(space, space + closing.length) == closing || closedAt == context.pos + space; + let aligned = align ? bracketedAligned(context) : null; + if (aligned) + return closed ? context.column(aligned.from) : context.column(aligned.to); + return context.baseIndent + (closed ? 0 : context.unit * units); + } + const DontIndentBeyond = 200; + /** + Enables reindentation on input. When a language defines an + `indentOnInput` field in its [language + data](https://codemirror.net/6/docs/ref/#state.EditorState.languageDataAt), which must hold a regular + expression, the line at the cursor will be reindented whenever new + text is typed and the input from the start of the line up to the + cursor matches that regexp. + + To avoid unneccesary reindents, it is recommended to start the + regexp with `^` (usually followed by `\s*`), and end it with `$`. + For example, `/^\s*\}$/` will reindent when a closing brace is + added at the start of a line. + */ + function indentOnInput() { + return EditorState.transactionFilter.of(tr => { + if (!tr.docChanged || !tr.isUserEvent("input.type") && !tr.isUserEvent("input.complete")) + return tr; + let rules = tr.startState.languageDataAt("indentOnInput", tr.startState.selection.main.head); + if (!rules.length) + return tr; + let doc = tr.newDoc, { head } = tr.newSelection.main, line = doc.lineAt(head); + if (head > line.from + DontIndentBeyond) + return tr; + let lineStart = doc.sliceString(line.from, head); + if (!rules.some(r => r.test(lineStart))) + return tr; + let { state } = tr, last = -1, changes = []; + for (let { head } of state.selection.ranges) { + let line = state.doc.lineAt(head); + if (line.from == last) + continue; + last = line.from; + let indent = getIndentation(state, line.from); + if (indent == null) + continue; + let cur = /^\s*/.exec(line.text)[0]; + let norm = indentString(state, indent); + if (cur != norm) + changes.push({ from: line.from, to: line.from + cur.length, insert: norm }); + } + return changes.length ? [tr, { changes, sequential: true }] : tr; + }); + } + + /** + A facet that registers a code folding service. When called with + the extent of a line, such a function should return a foldable + range that starts on that line (but continues beyond it), if one + can be found. + */ + const foldService = /*@__PURE__*/Facet.define(); + /** + This node prop is used to associate folding information with + syntax node types. Given a syntax node, it should check whether + that tree is foldable and return the range that can be collapsed + when it is. + */ + const foldNodeProp = /*@__PURE__*/new NodeProp(); + /** + [Fold](https://codemirror.net/6/docs/ref/#language.foldNodeProp) function that folds everything but + the first and the last child of a syntax node. Useful for nodes + that start and end with delimiters. + */ + function foldInside(node) { + let first = node.firstChild, last = node.lastChild; + return first && first.to < last.from ? { from: first.to, to: last.type.isError ? node.to : last.from } : null; + } + function syntaxFolding(state, start, end) { + let tree = syntaxTree(state); + if (tree.length < end) + return null; + let inner = tree.resolveInner(end); + let found = null; + for (let cur = inner; cur; cur = cur.parent) { + if (cur.to <= end || cur.from > end) + continue; + if (found && cur.from < start) + break; + let prop = cur.type.prop(foldNodeProp); + if (prop && (cur.to < tree.length - 50 || tree.length == state.doc.length || !isUnfinished(cur))) { + let value = prop(cur, state); + if (value && value.from <= end && value.from >= start && value.to > end) + found = value; + } + } + return found; + } + function isUnfinished(node) { + let ch = node.lastChild; + return ch && ch.to == node.to && ch.type.isError; + } + /** + Check whether the given line is foldable. First asks any fold + services registered through + [`foldService`](https://codemirror.net/6/docs/ref/#language.foldService), and if none of them return + a result, tries to query the [fold node + prop](https://codemirror.net/6/docs/ref/#language.foldNodeProp) of syntax nodes that cover the end + of the line. + */ + function foldable(state, lineStart, lineEnd) { + for (let service of state.facet(foldService)) { + let result = service(state, lineStart, lineEnd); + if (result) + return result; + } + return syntaxFolding(state, lineStart, lineEnd); + } + function mapRange(range, mapping) { + let from = mapping.mapPos(range.from, 1), to = mapping.mapPos(range.to, -1); + return from >= to ? undefined : { from, to }; + } + /** + State effect that can be attached to a transaction to fold the + given range. (You probably only need this in exceptional + circumstances—usually you'll just want to let + [`foldCode`](https://codemirror.net/6/docs/ref/#language.foldCode) and the [fold + gutter](https://codemirror.net/6/docs/ref/#language.foldGutter) create the transactions.) + */ + const foldEffect = /*@__PURE__*/StateEffect.define({ map: mapRange }); + /** + State effect that unfolds the given range (if it was folded). + */ + const unfoldEffect = /*@__PURE__*/StateEffect.define({ map: mapRange }); + function selectedLines(view) { + let lines = []; + for (let { head } of view.state.selection.ranges) { + if (lines.some(l => l.from <= head && l.to >= head)) + continue; + lines.push(view.lineBlockAt(head)); + } + return lines; + } + /** + The state field that stores the folded ranges (as a [decoration + set](https://codemirror.net/6/docs/ref/#view.DecorationSet)). Can be passed to + [`EditorState.toJSON`](https://codemirror.net/6/docs/ref/#state.EditorState.toJSON) and + [`fromJSON`](https://codemirror.net/6/docs/ref/#state.EditorState^fromJSON) to serialize the fold + state. + */ + const foldState = /*@__PURE__*/StateField.define({ + create() { + return Decoration.none; + }, + update(folded, tr) { + folded = folded.map(tr.changes); + for (let e of tr.effects) { + if (e.is(foldEffect) && !foldExists(folded, e.value.from, e.value.to)) + folded = folded.update({ add: [foldWidget.range(e.value.from, e.value.to)] }); + else if (e.is(unfoldEffect)) + folded = folded.update({ filter: (from, to) => e.value.from != from || e.value.to != to, + filterFrom: e.value.from, filterTo: e.value.to }); + } + // Clear folded ranges that cover the selection head + if (tr.selection) { + let onSelection = false, { head } = tr.selection.main; + folded.between(head, head, (a, b) => { if (a < head && b > head) + onSelection = true; }); + if (onSelection) + folded = folded.update({ + filterFrom: head, + filterTo: head, + filter: (a, b) => b <= head || a >= head + }); + } + return folded; + }, + provide: f => EditorView.decorations.from(f), + toJSON(folded, state) { + let ranges = []; + folded.between(0, state.doc.length, (from, to) => { ranges.push(from, to); }); + return ranges; + }, + fromJSON(value) { + if (!Array.isArray(value) || value.length % 2) + throw new RangeError("Invalid JSON for fold state"); + let ranges = []; + for (let i = 0; i < value.length;) { + let from = value[i++], to = value[i++]; + if (typeof from != "number" || typeof to != "number") + throw new RangeError("Invalid JSON for fold state"); + ranges.push(foldWidget.range(from, to)); + } + return Decoration.set(ranges, true); + } + }); + function findFold(state, from, to) { + var _a; + let found = null; + (_a = state.field(foldState, false)) === null || _a === void 0 ? void 0 : _a.between(from, to, (from, to) => { + if (!found || found.from > from) + found = { from, to }; + }); + return found; + } + function foldExists(folded, from, to) { + let found = false; + folded.between(from, from, (a, b) => { if (a == from && b == to) + found = true; }); + return found; + } + function maybeEnable(state, other) { + return state.field(foldState, false) ? other : other.concat(StateEffect.appendConfig.of(codeFolding())); + } + /** + Fold the lines that are selected, if possible. + */ + const foldCode = view => { + for (let line of selectedLines(view)) { + let range = foldable(view.state, line.from, line.to); + if (range) { + view.dispatch({ effects: maybeEnable(view.state, [foldEffect.of(range), announceFold(view, range)]) }); + return true; + } + } + return false; + }; + /** + Unfold folded ranges on selected lines. + */ + const unfoldCode = view => { + if (!view.state.field(foldState, false)) + return false; + let effects = []; + for (let line of selectedLines(view)) { + let folded = findFold(view.state, line.from, line.to); + if (folded) + effects.push(unfoldEffect.of(folded), announceFold(view, folded, false)); + } + if (effects.length) + view.dispatch({ effects }); + return effects.length > 0; + }; + function announceFold(view, range, fold = true) { + let lineFrom = view.state.doc.lineAt(range.from).number, lineTo = view.state.doc.lineAt(range.to).number; + return EditorView.announce.of(`${view.state.phrase(fold ? "Folded lines" : "Unfolded lines")} ${lineFrom} ${view.state.phrase("to")} ${lineTo}.`); + } + /** + Fold all top-level foldable ranges. Note that, in most cases, + folding information will depend on the [syntax + tree](https://codemirror.net/6/docs/ref/#language.syntaxTree), and folding everything may not work + reliably when the document hasn't been fully parsed (either + because the editor state was only just initialized, or because the + document is so big that the parser decided not to parse it + entirely). + */ + const foldAll = view => { + let { state } = view, effects = []; + for (let pos = 0; pos < state.doc.length;) { + let line = view.lineBlockAt(pos), range = foldable(state, line.from, line.to); + if (range) + effects.push(foldEffect.of(range)); + pos = (range ? view.lineBlockAt(range.to) : line).to + 1; + } + if (effects.length) + view.dispatch({ effects: maybeEnable(view.state, effects) }); + return !!effects.length; + }; + /** + Unfold all folded code. + */ + const unfoldAll = view => { + let field = view.state.field(foldState, false); + if (!field || !field.size) + return false; + let effects = []; + field.between(0, view.state.doc.length, (from, to) => { effects.push(unfoldEffect.of({ from, to })); }); + view.dispatch({ effects }); + return true; + }; + /** + Default fold-related key bindings. + + - Ctrl-Shift-[ (Cmd-Alt-[ on macOS): [`foldCode`](https://codemirror.net/6/docs/ref/#language.foldCode). + - Ctrl-Shift-] (Cmd-Alt-] on macOS): [`unfoldCode`](https://codemirror.net/6/docs/ref/#language.unfoldCode). + - Ctrl-Alt-[: [`foldAll`](https://codemirror.net/6/docs/ref/#language.foldAll). + - Ctrl-Alt-]: [`unfoldAll`](https://codemirror.net/6/docs/ref/#language.unfoldAll). + */ + const foldKeymap = [ + { key: "Ctrl-Shift-[", mac: "Cmd-Alt-[", run: foldCode }, + { key: "Ctrl-Shift-]", mac: "Cmd-Alt-]", run: unfoldCode }, + { key: "Ctrl-Alt-[", run: foldAll }, + { key: "Ctrl-Alt-]", run: unfoldAll } + ]; + const defaultConfig = { + placeholderDOM: null, + placeholderText: "…" + }; + const foldConfig = /*@__PURE__*/Facet.define({ + combine(values) { return combineConfig(values, defaultConfig); } + }); + /** + Create an extension that configures code folding. + */ + function codeFolding(config) { + let result = [foldState, baseTheme$1$2]; + if (config) + result.push(foldConfig.of(config)); + return result; + } + const foldWidget = /*@__PURE__*/Decoration.replace({ widget: /*@__PURE__*/new class extends WidgetType { + toDOM(view) { + let { state } = view, conf = state.facet(foldConfig); + let onclick = (event) => { + let line = view.lineBlockAt(view.posAtDOM(event.target)); + let folded = findFold(view.state, line.from, line.to); + if (folded) + view.dispatch({ effects: unfoldEffect.of(folded) }); + event.preventDefault(); + }; + if (conf.placeholderDOM) + return conf.placeholderDOM(view, onclick); + let element = document.createElement("span"); + element.textContent = conf.placeholderText; + element.setAttribute("aria-label", state.phrase("folded code")); + element.title = state.phrase("unfold"); + element.className = "cm-foldPlaceholder"; + element.onclick = onclick; + return element; + } + } }); + const foldGutterDefaults = { + openText: "⌄", + closedText: "›", + markerDOM: null, + domEventHandlers: {}, + foldingChanged: () => false + }; + class FoldMarker extends GutterMarker { + constructor(config, open) { + super(); + this.config = config; + this.open = open; + } + eq(other) { return this.config == other.config && this.open == other.open; } + toDOM(view) { + if (this.config.markerDOM) + return this.config.markerDOM(this.open); + let span = document.createElement("span"); + span.textContent = this.open ? this.config.openText : this.config.closedText; + span.title = view.state.phrase(this.open ? "Fold line" : "Unfold line"); + return span; + } + } + /** + Create an extension that registers a fold gutter, which shows a + fold status indicator before foldable lines (which can be clicked + to fold or unfold the line). + */ + function foldGutter(config = {}) { + let fullConfig = Object.assign(Object.assign({}, foldGutterDefaults), config); + let canFold = new FoldMarker(fullConfig, true), canUnfold = new FoldMarker(fullConfig, false); + let markers = ViewPlugin.fromClass(class { + constructor(view) { + this.from = view.viewport.from; + this.markers = this.buildMarkers(view); + } + update(update) { + if (update.docChanged || update.viewportChanged || + update.startState.facet(language) != update.state.facet(language) || + update.startState.field(foldState, false) != update.state.field(foldState, false) || + syntaxTree(update.startState) != syntaxTree(update.state) || + fullConfig.foldingChanged(update)) + this.markers = this.buildMarkers(update.view); + } + buildMarkers(view) { + let builder = new RangeSetBuilder(); + for (let line of view.viewportLineBlocks) { + let mark = findFold(view.state, line.from, line.to) ? canUnfold + : foldable(view.state, line.from, line.to) ? canFold : null; + if (mark) + builder.add(line.from, line.from, mark); + } + return builder.finish(); + } + }); + let { domEventHandlers } = fullConfig; + return [ + markers, + gutter({ + class: "cm-foldGutter", + markers(view) { var _a; return ((_a = view.plugin(markers)) === null || _a === void 0 ? void 0 : _a.markers) || RangeSet.empty; }, + initialSpacer() { + return new FoldMarker(fullConfig, false); + }, + domEventHandlers: Object.assign(Object.assign({}, domEventHandlers), { click: (view, line, event) => { + if (domEventHandlers.click && domEventHandlers.click(view, line, event)) + return true; + let folded = findFold(view.state, line.from, line.to); + if (folded) { + view.dispatch({ effects: unfoldEffect.of(folded) }); + return true; + } + let range = foldable(view.state, line.from, line.to); + if (range) { + view.dispatch({ effects: foldEffect.of(range) }); + return true; + } + return false; + } }) + }), + codeFolding() + ]; + } + const baseTheme$1$2 = /*@__PURE__*/EditorView.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" + } + }); + + /** + A highlight style associates CSS styles with higlighting + [tags](https://lezer.codemirror.net/docs/ref#highlight.Tag). + */ + class HighlightStyle { + constructor(spec, options) { + let modSpec; + function def(spec) { + let cls = StyleModule.newName(); + (modSpec || (modSpec = Object.create(null)))["." + cls] = spec; + return cls; + } + const all = typeof options.all == "string" ? options.all : options.all ? def(options.all) : undefined; + const scopeOpt = options.scope; + this.scope = scopeOpt instanceof Language ? (type) => type.prop(languageDataProp) == scopeOpt.data + : scopeOpt ? (type) => type == scopeOpt : undefined; + this.style = tagHighlighter(spec.map(style => ({ + tag: style.tag, + class: style.class || def(Object.assign({}, style, { tag: null })) + })), { + all, + }).style; + this.module = modSpec ? new StyleModule(modSpec) : null; + this.themeType = options.themeType; + } + /** + Create a highlighter style that associates the given styles to + the given tags. The specs must be objects that hold a style tag + or array of tags in their `tag` property, and either a single + `class` property providing a static CSS class (for highlighter + that rely on external styling), or a + [`style-mod`](https://github.com/marijnh/style-mod#documentation)-style + set of CSS properties (which define the styling for those tags). + + The CSS rules created for a highlighter will be emitted in the + order of the spec's properties. That means that for elements that + have multiple tags associated with them, styles defined further + down in the list will have a higher CSS precedence than styles + defined earlier. + */ + static define(specs, options) { + return new HighlightStyle(specs, options || {}); + } + } + const highlighterFacet = /*@__PURE__*/Facet.define(); + const fallbackHighlighter = /*@__PURE__*/Facet.define({ + combine(values) { return values.length ? [values[0]] : null; } + }); + function getHighlighters(state) { + let main = state.facet(highlighterFacet); + return main.length ? main : state.facet(fallbackHighlighter); + } + /** + Wrap a highlighter in an editor extension that uses it to apply + syntax highlighting to the editor content. + + When multiple (non-fallback) styles are provided, the styling + applied is the union of the classes they emit. + */ + function syntaxHighlighting(highlighter, options) { + let ext = [treeHighlighter], themeType; + if (highlighter instanceof HighlightStyle) { + if (highlighter.module) + ext.push(EditorView.styleModule.of(highlighter.module)); + themeType = highlighter.themeType; + } + if (options === null || options === void 0 ? void 0 : options.fallback) + ext.push(fallbackHighlighter.of(highlighter)); + else if (themeType) + ext.push(highlighterFacet.computeN([EditorView.darkTheme], state => { + return state.facet(EditorView.darkTheme) == (themeType == "dark") ? [highlighter] : []; + })); + else + ext.push(highlighterFacet.of(highlighter)); + return ext; + } + class TreeHighlighter { + constructor(view) { + this.markCache = Object.create(null); + this.tree = syntaxTree(view.state); + this.decorations = this.buildDeco(view, getHighlighters(view.state)); + } + update(update) { + let tree = syntaxTree(update.state), highlighters = getHighlighters(update.state); + let styleChange = highlighters != getHighlighters(update.startState); + if (tree.length < update.view.viewport.to && !styleChange && tree.type == this.tree.type) { + this.decorations = this.decorations.map(update.changes); + } + else if (tree != this.tree || update.viewportChanged || styleChange) { + this.tree = tree; + this.decorations = this.buildDeco(update.view, highlighters); + } + } + buildDeco(view, highlighters) { + if (!highlighters || !this.tree.length) + return Decoration.none; + let builder = new RangeSetBuilder(); + for (let { from, to } of view.visibleRanges) { + highlightTree(this.tree, highlighters, (from, to, style) => { + builder.add(from, to, this.markCache[style] || (this.markCache[style] = Decoration.mark({ class: style }))); + }, from, to); + } + return builder.finish(); + } + } + const treeHighlighter = /*@__PURE__*/Prec.high(/*@__PURE__*/ViewPlugin.fromClass(TreeHighlighter, { + decorations: v => v.decorations + })); + /** + A default highlight style (works well with light themes). + */ + const defaultHighlightStyle = /*@__PURE__*/HighlightStyle.define([ + { tag: tags.meta, + color: "#7a757a" }, + { tag: tags.link, + textDecoration: "underline" }, + { tag: tags.heading, + textDecoration: "underline", + fontWeight: "bold" }, + { tag: tags.emphasis, + fontStyle: "italic" }, + { tag: tags.strong, + fontWeight: "bold" }, + { tag: tags.strikethrough, + textDecoration: "line-through" }, + { tag: tags.keyword, + color: "#708" }, + { tag: [tags.atom, tags.bool, tags.url, tags.contentSeparator, tags.labelName], + color: "#219" }, + { tag: [tags.literal, tags.inserted], + color: "#164" }, + { tag: [tags.string, tags.deleted], + color: "#a11" }, + { tag: [tags.regexp, tags.escape, /*@__PURE__*/tags.special(tags.string)], + color: "#e40" }, + { tag: /*@__PURE__*/tags.definition(tags.variableName), + color: "#00f" }, + { tag: /*@__PURE__*/tags.local(tags.variableName), + color: "#30a" }, + { tag: [tags.typeName, tags.namespace], + color: "#085" }, + { tag: tags.className, + color: "#167" }, + { tag: [/*@__PURE__*/tags.special(tags.variableName), tags.macroName], + color: "#256" }, + { tag: /*@__PURE__*/tags.definition(tags.propertyName), + color: "#00c" }, + { tag: tags.comment, + color: "#940" }, + { tag: tags.invalid, + color: "#f00" } + ]); + + const baseTheme$3 = /*@__PURE__*/EditorView.baseTheme({ + "&.cm-focused .cm-matchingBracket": { backgroundColor: "#328c8252" }, + "&.cm-focused .cm-nonmatchingBracket": { backgroundColor: "#bb555544" } + }); + const DefaultScanDist = 10000, DefaultBrackets = "()[]{}"; + const bracketMatchingConfig = /*@__PURE__*/Facet.define({ + combine(configs) { + return combineConfig(configs, { + afterCursor: true, + brackets: DefaultBrackets, + maxScanDistance: DefaultScanDist, + renderMatch: defaultRenderMatch + }); + } + }); + const matchingMark = /*@__PURE__*/Decoration.mark({ class: "cm-matchingBracket" }), nonmatchingMark = /*@__PURE__*/Decoration.mark({ class: "cm-nonmatchingBracket" }); + function defaultRenderMatch(match) { + let decorations = []; + let mark = match.matched ? matchingMark : nonmatchingMark; + decorations.push(mark.range(match.start.from, match.start.to)); + if (match.end) + decorations.push(mark.range(match.end.from, match.end.to)); + return decorations; + } + const bracketMatchingState = /*@__PURE__*/StateField.define({ + create() { return Decoration.none; }, + update(deco, tr) { + if (!tr.docChanged && !tr.selection) + return deco; + let decorations = []; + let config = tr.state.facet(bracketMatchingConfig); + for (let range of tr.state.selection.ranges) { + if (!range.empty) + continue; + let match = matchBrackets(tr.state, range.head, -1, config) + || (range.head > 0 && matchBrackets(tr.state, range.head - 1, 1, config)) + || (config.afterCursor && + (matchBrackets(tr.state, range.head, 1, config) || + (range.head < tr.state.doc.length && matchBrackets(tr.state, range.head + 1, -1, config)))); + if (match) + decorations = decorations.concat(config.renderMatch(match, tr.state)); + } + return Decoration.set(decorations, true); + }, + provide: f => EditorView.decorations.from(f) + }); + const bracketMatchingUnique = [ + bracketMatchingState, + baseTheme$3 + ]; + /** + Create an extension that enables bracket matching. Whenever the + cursor is next to a bracket, that bracket and the one it matches + are highlighted. Or, when no matching bracket is found, another + highlighting style is used to indicate this. + */ + function bracketMatching(config = {}) { + return [bracketMatchingConfig.of(config), bracketMatchingUnique]; + } + function matchingNodes(node, dir, brackets) { + let byProp = node.prop(dir < 0 ? NodeProp.openedBy : NodeProp.closedBy); + if (byProp) + return byProp; + if (node.name.length == 1) { + let index = brackets.indexOf(node.name); + if (index > -1 && index % 2 == (dir < 0 ? 1 : 0)) + return [brackets[index + dir]]; + } + return null; + } + /** + Find the matching bracket for the token at `pos`, scanning + direction `dir`. Only the `brackets` and `maxScanDistance` + properties are used from `config`, if given. Returns null if no + bracket was found at `pos`, or a match result otherwise. + */ + function matchBrackets(state, pos, dir, config = {}) { + let maxScanDistance = config.maxScanDistance || DefaultScanDist, brackets = config.brackets || DefaultBrackets; + let tree = syntaxTree(state), node = tree.resolveInner(pos, dir); + for (let cur = node; cur; cur = cur.parent) { + let matches = matchingNodes(cur.type, dir, brackets); + if (matches && cur.from < cur.to) + return matchMarkedBrackets(state, pos, dir, cur, matches, brackets); + } + return matchPlainBrackets(state, pos, dir, tree, node.type, maxScanDistance, brackets); + } + function matchMarkedBrackets(_state, _pos, dir, token, matching, brackets) { + let parent = token.parent, firstToken = { from: token.from, to: token.to }; + let depth = 0, cursor = parent === null || parent === void 0 ? void 0 : parent.cursor(); + if (cursor && (dir < 0 ? cursor.childBefore(token.from) : cursor.childAfter(token.to))) + do { + if (dir < 0 ? cursor.to <= token.from : cursor.from >= token.to) { + if (depth == 0 && matching.indexOf(cursor.type.name) > -1 && cursor.from < cursor.to) { + return { start: firstToken, end: { from: cursor.from, to: cursor.to }, matched: true }; + } + else if (matchingNodes(cursor.type, dir, brackets)) { + depth++; + } + else if (matchingNodes(cursor.type, -dir, brackets)) { + if (depth == 0) + return { + start: firstToken, + end: cursor.from == cursor.to ? undefined : { from: cursor.from, to: cursor.to }, + matched: false + }; + depth--; + } + } + } while (dir < 0 ? cursor.prevSibling() : cursor.nextSibling()); + return { start: firstToken, matched: false }; + } + function matchPlainBrackets(state, pos, dir, tree, tokenType, maxScanDistance, brackets) { + let startCh = dir < 0 ? state.sliceDoc(pos - 1, pos) : state.sliceDoc(pos, pos + 1); + let bracket = brackets.indexOf(startCh); + if (bracket < 0 || (bracket % 2 == 0) != (dir > 0)) + return null; + let startToken = { from: dir < 0 ? pos - 1 : pos, to: dir > 0 ? pos + 1 : pos }; + let iter = state.doc.iterRange(pos, dir > 0 ? state.doc.length : 0), depth = 0; + for (let distance = 0; !(iter.next()).done && distance <= maxScanDistance;) { + let text = iter.value; + if (dir < 0) + distance += text.length; + let basePos = pos + distance * dir; + for (let pos = dir > 0 ? 0 : text.length - 1, end = dir > 0 ? text.length : -1; pos != end; pos += dir) { + let found = brackets.indexOf(text[pos]); + if (found < 0 || tree.resolveInner(basePos + pos, 1).type != tokenType) + continue; + if ((found % 2 == 0) == (dir > 0)) { + depth++; + } + else if (depth == 1) { // Closing + return { start: startToken, end: { from: basePos + pos, to: basePos + pos + 1 }, matched: (found >> 1) == (bracket >> 1) }; + } + else { + depth--; + } + } + if (dir > 0) + distance += text.length; + } + return iter.done ? { start: startToken, matched: false } : null; + } + const noTokens = /*@__PURE__*/Object.create(null); + const typeArray = [NodeType.none]; + const warned = []; + const defaultTable = /*@__PURE__*/Object.create(null); + for (let [legacyName, name] 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"] + ]) + defaultTable[legacyName] = /*@__PURE__*/createTokenType(noTokens, name); + function warnForPart(part, msg) { + if (warned.indexOf(part) > -1) + return; + warned.push(part); + console.warn(msg); + } + function createTokenType(extra, tagStr) { + let tag = null; + for (let part of tagStr.split(".")) { + let value = (extra[part] || tags[part]); + if (!value) { + warnForPart(part, `Unknown highlighting tag ${part}`); + } + else if (typeof value == "function") { + if (!tag) + warnForPart(part, `Modifier ${part} used at start of tag`); + else + tag = value(tag); + } + else { + if (tag) + warnForPart(part, `Tag ${part} used as modifier`); + else + tag = value; + } + } + if (!tag) + return 0; + let name = tagStr.replace(/ /g, "_"), type = NodeType.define({ + id: typeArray.length, + name, + props: [styleTags({ [name]: tag })] + }); + typeArray.push(type); + return type.id; + } + + /** + Comment or uncomment the current selection. Will use line comments + if available, otherwise falling back to block comments. + */ + const toggleComment = target => { + let config = getConfig(target.state); + return config.line ? toggleLineComment(target) : config.block ? toggleBlockCommentByLine(target) : false; + }; + function command(f, option) { + return ({ state, dispatch }) => { + if (state.readOnly) + return false; + let tr = f(option, state); + if (!tr) + return false; + dispatch(state.update(tr)); + return true; + }; + } + /** + Comment or uncomment the current selection using line comments. + The line comment syntax is taken from the + [`commentTokens`](https://codemirror.net/6/docs/ref/#commands.CommentTokens) [language + data](https://codemirror.net/6/docs/ref/#state.EditorState.languageDataAt). + */ + const toggleLineComment = /*@__PURE__*/command(changeLineComment, 0 /* CommentOption.Toggle */); + /** + Comment or uncomment the current selection using block comments. + The block comment syntax is taken from the + [`commentTokens`](https://codemirror.net/6/docs/ref/#commands.CommentTokens) [language + data](https://codemirror.net/6/docs/ref/#state.EditorState.languageDataAt). + */ + const toggleBlockComment = /*@__PURE__*/command(changeBlockComment, 0 /* CommentOption.Toggle */); + /** + Comment or uncomment the lines around the current selection using + block comments. + */ + const toggleBlockCommentByLine = /*@__PURE__*/command((o, s) => changeBlockComment(o, s, selectedLineRanges(s)), 0 /* CommentOption.Toggle */); + function getConfig(state, pos = state.selection.main.head) { + let data = state.languageDataAt("commentTokens", pos); + return data.length ? data[0] : {}; + } + const SearchMargin = 50; + /** + Determines if the given range is block-commented in the given + state. + */ + function findBlockComment(state, { open, close }, from, to) { + let textBefore = state.sliceDoc(from - SearchMargin, from); + let textAfter = state.sliceDoc(to, to + SearchMargin); + let spaceBefore = /\s*$/.exec(textBefore)[0].length, spaceAfter = /^\s*/.exec(textAfter)[0].length; + let beforeOff = textBefore.length - spaceBefore; + if (textBefore.slice(beforeOff - open.length, beforeOff) == open && + textAfter.slice(spaceAfter, spaceAfter + close.length) == close) { + return { open: { pos: from - spaceBefore, margin: spaceBefore && 1 }, + close: { pos: to + spaceAfter, margin: spaceAfter && 1 } }; + } + let startText, endText; + if (to - from <= 2 * SearchMargin) { + startText = endText = state.sliceDoc(from, to); + } + else { + startText = state.sliceDoc(from, from + SearchMargin); + endText = state.sliceDoc(to - SearchMargin, to); + } + let startSpace = /^\s*/.exec(startText)[0].length, endSpace = /\s*$/.exec(endText)[0].length; + let endOff = endText.length - endSpace - close.length; + if (startText.slice(startSpace, startSpace + open.length) == open && + endText.slice(endOff, endOff + close.length) == close) { + return { open: { pos: from + startSpace + open.length, + margin: /\s/.test(startText.charAt(startSpace + open.length)) ? 1 : 0 }, + close: { pos: to - endSpace - close.length, + margin: /\s/.test(endText.charAt(endOff - 1)) ? 1 : 0 } }; + } + return null; + } + function selectedLineRanges(state) { + let ranges = []; + for (let r of state.selection.ranges) { + let fromLine = state.doc.lineAt(r.from); + let toLine = r.to <= fromLine.to ? fromLine : state.doc.lineAt(r.to); + let last = ranges.length - 1; + if (last >= 0 && ranges[last].to > fromLine.from) + ranges[last].to = toLine.to; + else + ranges.push({ from: fromLine.from, to: toLine.to }); + } + return ranges; + } + // Performs toggle, comment and uncomment of block comments in + // languages that support them. + function changeBlockComment(option, state, ranges = state.selection.ranges) { + let tokens = ranges.map(r => getConfig(state, r.from).block); + if (!tokens.every(c => c)) + return null; + let comments = ranges.map((r, i) => findBlockComment(state, tokens[i], r.from, r.to)); + if (option != 2 /* CommentOption.Uncomment */ && !comments.every(c => c)) { + return { changes: state.changes(ranges.map((range, i) => { + if (comments[i]) + return []; + return [{ from: range.from, insert: tokens[i].open + " " }, { from: range.to, insert: " " + tokens[i].close }]; + })) }; + } + else if (option != 1 /* CommentOption.Comment */ && comments.some(c => c)) { + let changes = []; + for (let i = 0, comment; i < comments.length; i++) + if (comment = comments[i]) { + let token = tokens[i], { open, close } = comment; + changes.push({ from: open.pos - token.open.length, to: open.pos + open.margin }, { from: close.pos - close.margin, to: close.pos + token.close.length }); + } + return { changes }; + } + return null; + } + // Performs toggle, comment and uncomment of line comments. + function changeLineComment(option, state, ranges = state.selection.ranges) { + let lines = []; + let prevLine = -1; + for (let { from, to } of ranges) { + let startI = lines.length, minIndent = 1e9; + for (let pos = from; pos <= to;) { + let line = state.doc.lineAt(pos); + if (line.from > prevLine && (from == to || to > line.from)) { + prevLine = line.from; + let token = getConfig(state, pos).line; + if (!token) + continue; + let indent = /^\s*/.exec(line.text)[0].length; + let empty = indent == line.length; + let comment = line.text.slice(indent, indent + token.length) == token ? indent : -1; + if (indent < line.text.length && indent < minIndent) + minIndent = indent; + lines.push({ line, comment, token, indent, empty, single: false }); + } + pos = line.to + 1; + } + if (minIndent < 1e9) + for (let i = startI; i < lines.length; i++) + if (lines[i].indent < lines[i].line.text.length) + lines[i].indent = minIndent; + if (lines.length == startI + 1) + lines[startI].single = true; + } + if (option != 2 /* CommentOption.Uncomment */ && lines.some(l => l.comment < 0 && (!l.empty || l.single))) { + let changes = []; + for (let { line, token, indent, empty, single } of lines) + if (single || !empty) + changes.push({ from: line.from + indent, insert: token + " " }); + let changeSet = state.changes(changes); + return { changes: changeSet, selection: state.selection.map(changeSet, 1) }; + } + else if (option != 1 /* CommentOption.Comment */ && lines.some(l => l.comment >= 0)) { + let changes = []; + for (let { line, comment, token } of lines) + if (comment >= 0) { + let from = line.from + comment, to = from + token.length; + if (line.text[to - line.from] == " ") + to++; + changes.push({ from, to }); + } + return { changes }; + } + return null; + } + + const fromHistory = /*@__PURE__*/Annotation.define(); + /** + Transaction annotation that will prevent that transaction from + being combined with other transactions in the undo history. Given + `"before"`, it'll prevent merging with previous transactions. With + `"after"`, subsequent transactions won't be combined with this + one. With `"full"`, the transaction is isolated on both sides. + */ + const isolateHistory = /*@__PURE__*/Annotation.define(); + /** + This facet provides a way to register functions that, given a + transaction, provide a set of effects that the history should + store when inverting the transaction. This can be used to + integrate some kinds of effects in the history, so that they can + be undone (and redone again). + */ + const invertedEffects = /*@__PURE__*/Facet.define(); + const historyConfig = /*@__PURE__*/Facet.define({ + combine(configs) { + return combineConfig(configs, { + minDepth: 100, + newGroupDelay: 500 + }, { minDepth: Math.max, newGroupDelay: Math.min }); + } + }); + function changeEnd(changes) { + let end = 0; + changes.iterChangedRanges((_, to) => end = to); + return end; + } + const historyField_ = /*@__PURE__*/StateField.define({ + create() { + return HistoryState.empty; + }, + update(state, tr) { + let config = tr.state.facet(historyConfig); + let fromHist = tr.annotation(fromHistory); + if (fromHist) { + let selection = tr.docChanged ? EditorSelection.single(changeEnd(tr.changes)) : undefined; + let item = HistEvent.fromTransaction(tr, selection), from = fromHist.side; + let other = from == 0 /* BranchName.Done */ ? state.undone : state.done; + if (item) + other = updateBranch(other, other.length, config.minDepth, item); + else + other = addSelection(other, tr.startState.selection); + return new HistoryState(from == 0 /* BranchName.Done */ ? fromHist.rest : other, from == 0 /* BranchName.Done */ ? other : fromHist.rest); + } + let isolate = tr.annotation(isolateHistory); + if (isolate == "full" || isolate == "before") + state = state.isolate(); + if (tr.annotation(Transaction.addToHistory) === false) + return !tr.changes.empty ? state.addMapping(tr.changes.desc) : state; + let event = HistEvent.fromTransaction(tr); + let time = tr.annotation(Transaction.time), userEvent = tr.annotation(Transaction.userEvent); + if (event) + state = state.addChanges(event, time, userEvent, config.newGroupDelay, config.minDepth); + else if (tr.selection) + state = state.addSelection(tr.startState.selection, time, userEvent, config.newGroupDelay); + if (isolate == "full" || isolate == "after") + state = state.isolate(); + return state; + }, + toJSON(value) { + return { done: value.done.map(e => e.toJSON()), undone: value.undone.map(e => e.toJSON()) }; + }, + fromJSON(json) { + return new HistoryState(json.done.map(HistEvent.fromJSON), json.undone.map(HistEvent.fromJSON)); + } + }); + /** + Create a history extension with the given configuration. + */ + function history(config = {}) { + return [ + historyField_, + historyConfig.of(config), + EditorView.domEventHandlers({ + beforeinput(e, view) { + let command = e.inputType == "historyUndo" ? undo : e.inputType == "historyRedo" ? redo : null; + if (!command) + return false; + e.preventDefault(); + return command(view); + } + }) + ]; + } + function cmd(side, selection) { + return function ({ state, dispatch }) { + if (!selection && state.readOnly) + return false; + let historyState = state.field(historyField_, false); + if (!historyState) + return false; + let tr = historyState.pop(side, state, selection); + if (!tr) + return false; + dispatch(tr); + return true; + }; + } + /** + Undo a single group of history events. Returns false if no group + was available. + */ + const undo = /*@__PURE__*/cmd(0 /* BranchName.Done */, false); + /** + Redo a group of history events. Returns false if no group was + available. + */ + const redo = /*@__PURE__*/cmd(1 /* BranchName.Undone */, false); + /** + Undo a change or selection change. + */ + const undoSelection = /*@__PURE__*/cmd(0 /* BranchName.Done */, true); + /** + Redo a change or selection change. + */ + const redoSelection = /*@__PURE__*/cmd(1 /* BranchName.Undone */, true); + // History events store groups of changes or effects that need to be + // undone/redone together. + class HistEvent { + constructor( + // The changes in this event. Normal events hold at least one + // change or effect. But it may be necessary to store selection + // events before the first change, in which case a special type of + // instance is created which doesn't hold any changes, with + // changes == startSelection == undefined + changes, + // The effects associated with this event + effects, + // Accumulated mapping (from addToHistory==false) that should be + // applied to events below this one. + mapped, + // The selection before this event + startSelection, + // Stores selection changes after this event, to be used for + // selection undo/redo. + selectionsAfter) { + this.changes = changes; + this.effects = effects; + this.mapped = mapped; + this.startSelection = startSelection; + this.selectionsAfter = selectionsAfter; + } + setSelAfter(after) { + return new HistEvent(this.changes, this.effects, this.mapped, this.startSelection, after); + } + toJSON() { + var _a, _b, _c; + return { + changes: (_a = this.changes) === null || _a === void 0 ? void 0 : _a.toJSON(), + mapped: (_b = this.mapped) === null || _b === void 0 ? void 0 : _b.toJSON(), + startSelection: (_c = this.startSelection) === null || _c === void 0 ? void 0 : _c.toJSON(), + selectionsAfter: this.selectionsAfter.map(s => s.toJSON()) + }; + } + static fromJSON(json) { + return new HistEvent(json.changes && ChangeSet.fromJSON(json.changes), [], json.mapped && ChangeDesc.fromJSON(json.mapped), json.startSelection && EditorSelection.fromJSON(json.startSelection), json.selectionsAfter.map(EditorSelection.fromJSON)); + } + // This does not check `addToHistory` and such, it assumes the + // transaction needs to be converted to an item. Returns null when + // there are no changes or effects in the transaction. + static fromTransaction(tr, selection) { + let effects = none$1; + for (let invert of tr.startState.facet(invertedEffects)) { + let result = invert(tr); + if (result.length) + effects = effects.concat(result); + } + if (!effects.length && tr.changes.empty) + return null; + return new HistEvent(tr.changes.invert(tr.startState.doc), effects, undefined, selection || tr.startState.selection, none$1); + } + static selection(selections) { + return new HistEvent(undefined, none$1, undefined, undefined, selections); + } + } + function updateBranch(branch, to, maxLen, newEvent) { + let start = to + 1 > maxLen + 20 ? to - maxLen - 1 : 0; + let newBranch = branch.slice(start, to); + newBranch.push(newEvent); + return newBranch; + } + function isAdjacent(a, b) { + let ranges = [], isAdjacent = false; + a.iterChangedRanges((f, t) => ranges.push(f, t)); + b.iterChangedRanges((_f, _t, f, t) => { + for (let i = 0; i < ranges.length;) { + let from = ranges[i++], to = ranges[i++]; + if (t >= from && f <= to) + isAdjacent = true; + } + }); + return isAdjacent; + } + function eqSelectionShape(a, b) { + return a.ranges.length == b.ranges.length && + a.ranges.filter((r, i) => r.empty != b.ranges[i].empty).length === 0; + } + function conc(a, b) { + return !a.length ? b : !b.length ? a : a.concat(b); + } + const none$1 = []; + const MaxSelectionsPerEvent = 200; + function addSelection(branch, selection) { + if (!branch.length) { + return [HistEvent.selection([selection])]; + } + else { + let lastEvent = branch[branch.length - 1]; + let sels = lastEvent.selectionsAfter.slice(Math.max(0, lastEvent.selectionsAfter.length - MaxSelectionsPerEvent)); + if (sels.length && sels[sels.length - 1].eq(selection)) + return branch; + sels.push(selection); + return updateBranch(branch, branch.length - 1, 1e9, lastEvent.setSelAfter(sels)); + } + } + // Assumes the top item has one or more selectionAfter values + function popSelection(branch) { + let last = branch[branch.length - 1]; + let newBranch = branch.slice(); + newBranch[branch.length - 1] = last.setSelAfter(last.selectionsAfter.slice(0, last.selectionsAfter.length - 1)); + return newBranch; + } + // Add a mapping to the top event in the given branch. If this maps + // away all the changes and effects in that item, drop it and + // propagate the mapping to the next item. + function addMappingToBranch(branch, mapping) { + if (!branch.length) + return branch; + let length = branch.length, selections = none$1; + while (length) { + let event = mapEvent(branch[length - 1], mapping, selections); + if (event.changes && !event.changes.empty || event.effects.length) { // Event survived mapping + let result = branch.slice(0, length); + result[length - 1] = event; + return result; + } + else { // Drop this event, since there's no changes or effects left + mapping = event.mapped; + length--; + selections = event.selectionsAfter; + } + } + return selections.length ? [HistEvent.selection(selections)] : none$1; + } + function mapEvent(event, mapping, extraSelections) { + let selections = conc(event.selectionsAfter.length ? event.selectionsAfter.map(s => s.map(mapping)) : none$1, extraSelections); + // Change-less events don't store mappings (they are always the last event in a branch) + if (!event.changes) + return HistEvent.selection(selections); + let mappedChanges = event.changes.map(mapping), before = mapping.mapDesc(event.changes, true); + let fullMapping = event.mapped ? event.mapped.composeDesc(before) : before; + return new HistEvent(mappedChanges, StateEffect.mapEffects(event.effects, mapping), fullMapping, event.startSelection.map(before), selections); + } + const joinableUserEvent = /^(input\.type|delete)($|\.)/; + class HistoryState { + constructor(done, undone, prevTime = 0, prevUserEvent = undefined) { + this.done = done; + this.undone = undone; + this.prevTime = prevTime; + this.prevUserEvent = prevUserEvent; + } + isolate() { + return this.prevTime ? new HistoryState(this.done, this.undone) : this; + } + addChanges(event, time, userEvent, newGroupDelay, maxLen) { + let done = this.done, lastEvent = done[done.length - 1]; + if (lastEvent && lastEvent.changes && !lastEvent.changes.empty && event.changes && + (!userEvent || joinableUserEvent.test(userEvent)) && + ((!lastEvent.selectionsAfter.length && + time - this.prevTime < newGroupDelay && + isAdjacent(lastEvent.changes, event.changes)) || + // For compose (but not compose.start) events, always join with previous event + userEvent == "input.type.compose")) { + done = updateBranch(done, done.length - 1, maxLen, new HistEvent(event.changes.compose(lastEvent.changes), conc(event.effects, lastEvent.effects), lastEvent.mapped, lastEvent.startSelection, none$1)); + } + else { + done = updateBranch(done, done.length, maxLen, event); + } + return new HistoryState(done, none$1, time, userEvent); + } + addSelection(selection, time, userEvent, newGroupDelay) { + let last = this.done.length ? this.done[this.done.length - 1].selectionsAfter : none$1; + if (last.length > 0 && + time - this.prevTime < newGroupDelay && + userEvent == this.prevUserEvent && userEvent && /^select($|\.)/.test(userEvent) && + eqSelectionShape(last[last.length - 1], selection)) + return this; + return new HistoryState(addSelection(this.done, selection), this.undone, time, userEvent); + } + addMapping(mapping) { + return new HistoryState(addMappingToBranch(this.done, mapping), addMappingToBranch(this.undone, mapping), this.prevTime, this.prevUserEvent); + } + pop(side, state, selection) { + let branch = side == 0 /* BranchName.Done */ ? this.done : this.undone; + if (branch.length == 0) + return null; + let event = branch[branch.length - 1]; + if (selection && event.selectionsAfter.length) { + return state.update({ + selection: event.selectionsAfter[event.selectionsAfter.length - 1], + annotations: fromHistory.of({ side, rest: popSelection(branch) }), + userEvent: side == 0 /* BranchName.Done */ ? "select.undo" : "select.redo", + scrollIntoView: true + }); + } + else if (!event.changes) { + return null; + } + else { + let rest = branch.length == 1 ? none$1 : branch.slice(0, branch.length - 1); + if (event.mapped) + rest = addMappingToBranch(rest, event.mapped); + return state.update({ + changes: event.changes, + selection: event.startSelection, + effects: event.effects, + annotations: fromHistory.of({ side, rest }), + filter: false, + userEvent: side == 0 /* BranchName.Done */ ? "undo" : "redo", + scrollIntoView: true + }); + } + } + } + HistoryState.empty = /*@__PURE__*/new HistoryState(none$1, none$1); + /** + Default key bindings for the undo history. + + - Mod-z: [`undo`](https://codemirror.net/6/docs/ref/#commands.undo). + - Mod-y (Mod-Shift-z on macOS) + Ctrl-Shift-z on Linux: [`redo`](https://codemirror.net/6/docs/ref/#commands.redo). + - Mod-u: [`undoSelection`](https://codemirror.net/6/docs/ref/#commands.undoSelection). + - Alt-u (Mod-Shift-u on macOS): [`redoSelection`](https://codemirror.net/6/docs/ref/#commands.redoSelection). + */ + const historyKeymap = [ + { key: "Mod-z", run: undo, preventDefault: true }, + { key: "Mod-y", mac: "Mod-Shift-z", run: redo, preventDefault: true }, + { linux: "Ctrl-Shift-z", run: redo, preventDefault: true }, + { key: "Mod-u", run: undoSelection, preventDefault: true }, + { key: "Alt-u", mac: "Mod-Shift-u", run: redoSelection, preventDefault: true } + ]; + + function updateSel(sel, by) { + return EditorSelection.create(sel.ranges.map(by), sel.mainIndex); + } + function setSel(state, selection) { + return state.update({ selection, scrollIntoView: true, userEvent: "select" }); + } + function moveSel({ state, dispatch }, how) { + let selection = updateSel(state.selection, how); + if (selection.eq(state.selection)) + return false; + dispatch(setSel(state, selection)); + return true; + } + function rangeEnd(range, forward) { + return EditorSelection.cursor(forward ? range.to : range.from); + } + function cursorByChar(view, forward) { + return moveSel(view, range => range.empty ? view.moveByChar(range, forward) : rangeEnd(range, forward)); + } + function ltrAtCursor(view) { + return view.textDirectionAt(view.state.selection.main.head) == Direction.LTR; + } + /** + Move the selection one character to the left (which is backward in + left-to-right text, forward in right-to-left text). + */ + const cursorCharLeft = view => cursorByChar(view, !ltrAtCursor(view)); + /** + Move the selection one character to the right. + */ + const cursorCharRight = view => cursorByChar(view, ltrAtCursor(view)); + function cursorByGroup(view, forward) { + return moveSel(view, range => range.empty ? view.moveByGroup(range, forward) : rangeEnd(range, forward)); + } + /** + Move the selection to the left across one group of word or + non-word (but also non-space) characters. + */ + const cursorGroupLeft = view => cursorByGroup(view, !ltrAtCursor(view)); + /** + Move the selection one group to the right. + */ + const cursorGroupRight = view => cursorByGroup(view, ltrAtCursor(view)); + function interestingNode(state, node, bracketProp) { + if (node.type.prop(bracketProp)) + return true; + let len = node.to - node.from; + return len && (len > 2 || /[^\s,.;:]/.test(state.sliceDoc(node.from, node.to))) || node.firstChild; + } + function moveBySyntax(state, start, forward) { + let pos = syntaxTree(state).resolveInner(start.head); + let bracketProp = forward ? NodeProp.closedBy : NodeProp.openedBy; + // Scan forward through child nodes to see if there's an interesting + // node ahead. + for (let at = start.head;;) { + let next = forward ? pos.childAfter(at) : pos.childBefore(at); + if (!next) + break; + if (interestingNode(state, next, bracketProp)) + pos = next; + else + at = forward ? next.to : next.from; + } + let bracket = pos.type.prop(bracketProp), match, newPos; + if (bracket && (match = forward ? matchBrackets(state, pos.from, 1) : matchBrackets(state, pos.to, -1)) && match.matched) + newPos = forward ? match.end.to : match.end.from; + else + newPos = forward ? pos.to : pos.from; + return EditorSelection.cursor(newPos, forward ? -1 : 1); + } + /** + Move the cursor over the next syntactic element to the left. + */ + const cursorSyntaxLeft = view => moveSel(view, range => moveBySyntax(view.state, range, !ltrAtCursor(view))); + /** + Move the cursor over the next syntactic element to the right. + */ + const cursorSyntaxRight = view => moveSel(view, range => moveBySyntax(view.state, range, ltrAtCursor(view))); + function cursorByLine(view, forward) { + return moveSel(view, range => { + if (!range.empty) + return rangeEnd(range, forward); + let moved = view.moveVertically(range, forward); + return moved.head != range.head ? moved : view.moveToLineBoundary(range, forward); + }); + } + /** + Move the selection one line up. + */ + const cursorLineUp = view => cursorByLine(view, false); + /** + Move the selection one line down. + */ + const cursorLineDown = view => cursorByLine(view, true); + function pageHeight(view) { + return Math.max(view.defaultLineHeight, Math.min(view.dom.clientHeight, innerHeight) - 5); + } + function cursorByPage(view, forward) { + let { state } = view, selection = updateSel(state.selection, range => { + return range.empty ? view.moveVertically(range, forward, pageHeight(view)) : rangeEnd(range, forward); + }); + if (selection.eq(state.selection)) + return false; + let startPos = view.coordsAtPos(state.selection.main.head); + let scrollRect = view.scrollDOM.getBoundingClientRect(); + let effect; + if (startPos && startPos.top > scrollRect.top && startPos.bottom < scrollRect.bottom && + startPos.top - scrollRect.top <= view.scrollDOM.scrollHeight - view.scrollDOM.scrollTop - view.scrollDOM.clientHeight) + effect = EditorView.scrollIntoView(selection.main.head, { y: "start", yMargin: startPos.top - scrollRect.top }); + view.dispatch(setSel(state, selection), { effects: effect }); + return true; + } + /** + Move the selection one page up. + */ + const cursorPageUp = view => cursorByPage(view, false); + /** + Move the selection one page down. + */ + const cursorPageDown = view => cursorByPage(view, true); + function moveByLineBoundary(view, start, forward) { + let line = view.lineBlockAt(start.head), moved = view.moveToLineBoundary(start, forward); + if (moved.head == start.head && moved.head != (forward ? line.to : line.from)) + moved = view.moveToLineBoundary(start, forward, false); + if (!forward && moved.head == line.from && line.length) { + let space = /^\s*/.exec(view.state.sliceDoc(line.from, Math.min(line.from + 100, line.to)))[0].length; + if (space && start.head != line.from + space) + moved = EditorSelection.cursor(line.from + space); + } + return moved; + } + /** + Move the selection to the next line wrap point, or to the end of + the line if there isn't one left on this line. + */ + const cursorLineBoundaryForward = view => moveSel(view, range => moveByLineBoundary(view, range, true)); + /** + Move the selection to previous line wrap point, or failing that to + the start of the line. If the line is indented, and the cursor + isn't already at the end of the indentation, this will move to the + end of the indentation instead of the start of the line. + */ + const cursorLineBoundaryBackward = view => moveSel(view, range => moveByLineBoundary(view, range, false)); + /** + Move the selection one line wrap point to the left. + */ + const cursorLineBoundaryLeft = view => moveSel(view, range => moveByLineBoundary(view, range, !ltrAtCursor(view))); + /** + Move the selection one line wrap point to the right. + */ + const cursorLineBoundaryRight = view => moveSel(view, range => moveByLineBoundary(view, range, ltrAtCursor(view))); + /** + Move the selection to the start of the line. + */ + const cursorLineStart = view => moveSel(view, range => EditorSelection.cursor(view.lineBlockAt(range.head).from, 1)); + /** + Move the selection to the end of the line. + */ + const cursorLineEnd = view => moveSel(view, range => EditorSelection.cursor(view.lineBlockAt(range.head).to, -1)); + function toMatchingBracket(state, dispatch, extend) { + let found = false, selection = updateSel(state.selection, range => { + let matching = matchBrackets(state, range.head, -1) + || matchBrackets(state, range.head, 1) + || (range.head > 0 && matchBrackets(state, range.head - 1, 1)) + || (range.head < state.doc.length && matchBrackets(state, range.head + 1, -1)); + if (!matching || !matching.end) + return range; + found = true; + let head = matching.start.from == range.head ? matching.end.to : matching.end.from; + return extend ? EditorSelection.range(range.anchor, head) : EditorSelection.cursor(head); + }); + if (!found) + return false; + dispatch(setSel(state, selection)); + return true; + } + /** + Move the selection to the bracket matching the one it is currently + on, if any. + */ + const cursorMatchingBracket = ({ state, dispatch }) => toMatchingBracket(state, dispatch, false); + function extendSel(view, how) { + let selection = updateSel(view.state.selection, range => { + let head = how(range); + return EditorSelection.range(range.anchor, head.head, head.goalColumn); + }); + if (selection.eq(view.state.selection)) + return false; + view.dispatch(setSel(view.state, selection)); + return true; + } + function selectByChar(view, forward) { + return extendSel(view, range => view.moveByChar(range, forward)); + } + /** + Move the selection head one character to the left, while leaving + the anchor in place. + */ + const selectCharLeft = view => selectByChar(view, !ltrAtCursor(view)); + /** + Move the selection head one character to the right. + */ + const selectCharRight = view => selectByChar(view, ltrAtCursor(view)); + function selectByGroup(view, forward) { + return extendSel(view, range => view.moveByGroup(range, forward)); + } + /** + Move the selection head one [group](https://codemirror.net/6/docs/ref/#commands.cursorGroupLeft) to + the left. + */ + const selectGroupLeft = view => selectByGroup(view, !ltrAtCursor(view)); + /** + Move the selection head one group to the right. + */ + const selectGroupRight = view => selectByGroup(view, ltrAtCursor(view)); + /** + Move the selection head over the next syntactic element to the left. + */ + const selectSyntaxLeft = view => extendSel(view, range => moveBySyntax(view.state, range, !ltrAtCursor(view))); + /** + Move the selection head over the next syntactic element to the right. + */ + const selectSyntaxRight = view => extendSel(view, range => moveBySyntax(view.state, range, ltrAtCursor(view))); + function selectByLine(view, forward) { + return extendSel(view, range => view.moveVertically(range, forward)); + } + /** + Move the selection head one line up. + */ + const selectLineUp = view => selectByLine(view, false); + /** + Move the selection head one line down. + */ + const selectLineDown = view => selectByLine(view, true); + function selectByPage(view, forward) { + return extendSel(view, range => view.moveVertically(range, forward, pageHeight(view))); + } + /** + Move the selection head one page up. + */ + const selectPageUp = view => selectByPage(view, false); + /** + Move the selection head one page down. + */ + const selectPageDown = view => selectByPage(view, true); + /** + Move the selection head to the next line boundary. + */ + const selectLineBoundaryForward = view => extendSel(view, range => moveByLineBoundary(view, range, true)); + /** + Move the selection head to the previous line boundary. + */ + const selectLineBoundaryBackward = view => extendSel(view, range => moveByLineBoundary(view, range, false)); + /** + Move the selection head one line boundary to the left. + */ + const selectLineBoundaryLeft = view => extendSel(view, range => moveByLineBoundary(view, range, !ltrAtCursor(view))); + /** + Move the selection head one line boundary to the right. + */ + const selectLineBoundaryRight = view => extendSel(view, range => moveByLineBoundary(view, range, ltrAtCursor(view))); + /** + Move the selection head to the start of the line. + */ + const selectLineStart = view => extendSel(view, range => EditorSelection.cursor(view.lineBlockAt(range.head).from)); + /** + Move the selection head to the end of the line. + */ + const selectLineEnd = view => extendSel(view, range => EditorSelection.cursor(view.lineBlockAt(range.head).to)); + /** + Move the selection to the start of the document. + */ + const cursorDocStart = ({ state, dispatch }) => { + dispatch(setSel(state, { anchor: 0 })); + return true; + }; + /** + Move the selection to the end of the document. + */ + const cursorDocEnd = ({ state, dispatch }) => { + dispatch(setSel(state, { anchor: state.doc.length })); + return true; + }; + /** + Move the selection head to the start of the document. + */ + const selectDocStart = ({ state, dispatch }) => { + dispatch(setSel(state, { anchor: state.selection.main.anchor, head: 0 })); + return true; + }; + /** + Move the selection head to the end of the document. + */ + const selectDocEnd = ({ state, dispatch }) => { + dispatch(setSel(state, { anchor: state.selection.main.anchor, head: state.doc.length })); + return true; + }; + /** + Select the entire document. + */ + const selectAll = ({ state, dispatch }) => { + dispatch(state.update({ selection: { anchor: 0, head: state.doc.length }, userEvent: "select" })); + return true; + }; + /** + Expand the selection to cover entire lines. + */ + const selectLine = ({ state, dispatch }) => { + let ranges = selectedLineBlocks(state).map(({ from, to }) => EditorSelection.range(from, Math.min(to + 1, state.doc.length))); + dispatch(state.update({ selection: EditorSelection.create(ranges), userEvent: "select" })); + return true; + }; + /** + Select the next syntactic construct that is larger than the + selection. Note that this will only work insofar as the language + [provider](https://codemirror.net/6/docs/ref/#language.language) you use builds up a full + syntax tree. + */ + const selectParentSyntax = ({ state, dispatch }) => { + let selection = updateSel(state.selection, range => { + var _a; + let context = syntaxTree(state).resolveInner(range.head, 1); + while (!((context.from < range.from && context.to >= range.to) || + (context.to > range.to && context.from <= range.from) || + !((_a = context.parent) === null || _a === void 0 ? void 0 : _a.parent))) + context = context.parent; + return EditorSelection.range(context.to, context.from); + }); + dispatch(setSel(state, selection)); + return true; + }; + /** + Simplify the current selection. When multiple ranges are selected, + reduce it to its main range. Otherwise, if the selection is + non-empty, convert it to a cursor selection. + */ + const simplifySelection = ({ state, dispatch }) => { + let cur = state.selection, selection = null; + if (cur.ranges.length > 1) + selection = EditorSelection.create([cur.main]); + else if (!cur.main.empty) + selection = EditorSelection.create([EditorSelection.cursor(cur.main.head)]); + if (!selection) + return false; + dispatch(setSel(state, selection)); + return true; + }; + function deleteBy(target, by) { + if (target.state.readOnly) + return false; + let event = "delete.selection", { state } = target; + let changes = state.changeByRange(range => { + let { from, to } = range; + if (from == to) { + let towards = by(from); + if (towards < from) { + event = "delete.backward"; + towards = skipAtomic(target, towards, false); + } + else if (towards > from) { + event = "delete.forward"; + towards = skipAtomic(target, towards, true); + } + from = Math.min(from, towards); + to = Math.max(to, towards); + } + else { + from = skipAtomic(target, from, false); + to = skipAtomic(target, from, true); + } + return from == to ? { range } : { changes: { from, to }, range: EditorSelection.cursor(from) }; + }); + if (changes.changes.empty) + return false; + target.dispatch(state.update(changes, { + scrollIntoView: true, + userEvent: event, + effects: event == "delete.selection" ? EditorView.announce.of(state.phrase("Selection deleted")) : undefined + })); + return true; + } + function skipAtomic(target, pos, forward) { + if (target instanceof EditorView) + for (let ranges of target.state.facet(EditorView.atomicRanges).map(f => f(target))) + ranges.between(pos, pos, (from, to) => { + if (from < pos && to > pos) + pos = forward ? to : from; + }); + return pos; + } + const deleteByChar = (target, forward) => deleteBy(target, pos => { + let { state } = target, line = state.doc.lineAt(pos), before, targetPos; + if (!forward && pos > line.from && pos < line.from + 200 && + !/[^ \t]/.test(before = line.text.slice(0, pos - line.from))) { + if (before[before.length - 1] == "\t") + return pos - 1; + let col = countColumn(before, state.tabSize), drop = col % getIndentUnit(state) || getIndentUnit(state); + for (let i = 0; i < drop && before[before.length - 1 - i] == " "; i++) + pos--; + targetPos = pos; + } + else { + targetPos = findClusterBreak(line.text, pos - line.from, forward, forward) + line.from; + if (targetPos == pos && line.number != (forward ? state.doc.lines : 1)) + targetPos += forward ? 1 : -1; + } + return targetPos; + }); + /** + Delete the selection, or, for cursor selections, the character + before the cursor. + */ + const deleteCharBackward = view => deleteByChar(view, false); + /** + Delete the selection or the character after the cursor. + */ + const deleteCharForward = view => deleteByChar(view, true); + const deleteByGroup = (target, forward) => deleteBy(target, start => { + let pos = start, { state } = target, line = state.doc.lineAt(pos); + let categorize = state.charCategorizer(pos); + for (let cat = null;;) { + if (pos == (forward ? line.to : line.from)) { + if (pos == start && line.number != (forward ? state.doc.lines : 1)) + pos += forward ? 1 : -1; + break; + } + let next = findClusterBreak(line.text, pos - line.from, forward) + line.from; + let nextChar = line.text.slice(Math.min(pos, next) - line.from, Math.max(pos, next) - line.from); + let nextCat = categorize(nextChar); + if (cat != null && nextCat != cat) + break; + if (nextChar != " " || pos != start) + cat = nextCat; + pos = next; + } + return pos; + }); + /** + Delete the selection or backward until the end of the next + [group](https://codemirror.net/6/docs/ref/#view.EditorView.moveByGroup), only skipping groups of + whitespace when they consist of a single space. + */ + const deleteGroupBackward = target => deleteByGroup(target, false); + /** + Delete the selection or forward until the end of the next group. + */ + const deleteGroupForward = target => deleteByGroup(target, true); + /** + Delete the selection, or, if it is a cursor selection, delete to + the end of the line. If the cursor is directly at the end of the + line, delete the line break after it. + */ + const deleteToLineEnd = view => deleteBy(view, pos => { + let lineEnd = view.lineBlockAt(pos).to; + return pos < lineEnd ? lineEnd : Math.min(view.state.doc.length, pos + 1); + }); + /** + Delete the selection, or, if it is a cursor selection, delete to + the start of the line. If the cursor is directly at the start of the + line, delete the line break before it. + */ + const deleteToLineStart = view => deleteBy(view, pos => { + let lineStart = view.lineBlockAt(pos).from; + return pos > lineStart ? lineStart : Math.max(0, pos - 1); + }); + /** + Replace each selection range with a line break, leaving the cursor + on the line before the break. + */ + const splitLine = ({ state, dispatch }) => { + if (state.readOnly) + return false; + let changes = state.changeByRange(range => { + return { changes: { from: range.from, to: range.to, insert: Text.of(["", ""]) }, + range: EditorSelection.cursor(range.from) }; + }); + dispatch(state.update(changes, { scrollIntoView: true, userEvent: "input" })); + return true; + }; + /** + Flip the characters before and after the cursor(s). + */ + const transposeChars = ({ state, dispatch }) => { + if (state.readOnly) + return false; + let changes = state.changeByRange(range => { + if (!range.empty || range.from == 0 || range.from == state.doc.length) + return { range }; + let pos = range.from, line = state.doc.lineAt(pos); + let from = pos == line.from ? pos - 1 : findClusterBreak(line.text, pos - line.from, false) + line.from; + let to = pos == line.to ? pos + 1 : findClusterBreak(line.text, pos - line.from, true) + line.from; + return { changes: { from, to, insert: state.doc.slice(pos, to).append(state.doc.slice(from, pos)) }, + range: EditorSelection.cursor(to) }; + }); + if (changes.changes.empty) + return false; + dispatch(state.update(changes, { scrollIntoView: true, userEvent: "move.character" })); + return true; + }; + function selectedLineBlocks(state) { + let blocks = [], upto = -1; + for (let range of state.selection.ranges) { + let startLine = state.doc.lineAt(range.from), endLine = state.doc.lineAt(range.to); + if (!range.empty && range.to == endLine.from) + endLine = state.doc.lineAt(range.to - 1); + if (upto >= startLine.number) { + let prev = blocks[blocks.length - 1]; + prev.to = endLine.to; + prev.ranges.push(range); + } + else { + blocks.push({ from: startLine.from, to: endLine.to, ranges: [range] }); + } + upto = endLine.number + 1; + } + return blocks; + } + function moveLine(state, dispatch, forward) { + if (state.readOnly) + return false; + let changes = [], ranges = []; + for (let block of selectedLineBlocks(state)) { + if (forward ? block.to == state.doc.length : block.from == 0) + continue; + let nextLine = state.doc.lineAt(forward ? block.to + 1 : block.from - 1); + let size = nextLine.length + 1; + if (forward) { + changes.push({ from: block.to, to: nextLine.to }, { from: block.from, insert: nextLine.text + state.lineBreak }); + for (let r of block.ranges) + ranges.push(EditorSelection.range(Math.min(state.doc.length, r.anchor + size), Math.min(state.doc.length, r.head + size))); + } + else { + changes.push({ from: nextLine.from, to: block.from }, { from: block.to, insert: state.lineBreak + nextLine.text }); + for (let r of block.ranges) + ranges.push(EditorSelection.range(r.anchor - size, r.head - size)); + } + } + if (!changes.length) + return false; + dispatch(state.update({ + changes, + scrollIntoView: true, + selection: EditorSelection.create(ranges, state.selection.mainIndex), + userEvent: "move.line" + })); + return true; + } + /** + Move the selected lines up one line. + */ + const moveLineUp = ({ state, dispatch }) => moveLine(state, dispatch, false); + /** + Move the selected lines down one line. + */ + const moveLineDown = ({ state, dispatch }) => moveLine(state, dispatch, true); + function copyLine(state, dispatch, forward) { + if (state.readOnly) + return false; + let changes = []; + for (let block of selectedLineBlocks(state)) { + if (forward) + changes.push({ from: block.from, insert: state.doc.slice(block.from, block.to) + state.lineBreak }); + else + changes.push({ from: block.to, insert: state.lineBreak + state.doc.slice(block.from, block.to) }); + } + dispatch(state.update({ changes, scrollIntoView: true, userEvent: "input.copyline" })); + return true; + } + /** + Create a copy of the selected lines. Keep the selection in the top copy. + */ + const copyLineUp = ({ state, dispatch }) => copyLine(state, dispatch, false); + /** + Create a copy of the selected lines. Keep the selection in the bottom copy. + */ + const copyLineDown = ({ state, dispatch }) => copyLine(state, dispatch, true); + /** + Delete selected lines. + */ + const deleteLine = view => { + if (view.state.readOnly) + return false; + let { state } = view, changes = state.changes(selectedLineBlocks(state).map(({ from, to }) => { + if (from > 0) + from--; + else if (to < state.doc.length) + to++; + return { from, to }; + })); + let selection = updateSel(state.selection, range => view.moveVertically(range, true)).map(changes); + view.dispatch({ changes, selection, scrollIntoView: true, userEvent: "delete.line" }); + return true; + }; + function isBetweenBrackets(state, pos) { + if (/\(\)|\[\]|\{\}/.test(state.sliceDoc(pos - 1, pos + 1))) + return { from: pos, to: pos }; + let context = syntaxTree(state).resolveInner(pos); + let before = context.childBefore(pos), after = context.childAfter(pos), closedBy; + if (before && after && before.to <= pos && after.from >= pos && + (closedBy = before.type.prop(NodeProp.closedBy)) && closedBy.indexOf(after.name) > -1 && + state.doc.lineAt(before.to).from == state.doc.lineAt(after.from).from) + return { from: before.to, to: after.from }; + return null; + } + /** + Replace the selection with a newline and indent the newly created + line(s). If the current line consists only of whitespace, this + will also delete that whitespace. When the cursor is between + matching brackets, an additional newline will be inserted after + the cursor. + */ + const insertNewlineAndIndent = /*@__PURE__*/newlineAndIndent(false); + /** + Create a blank, indented line below the current line. + */ + const insertBlankLine = /*@__PURE__*/newlineAndIndent(true); + function newlineAndIndent(atEof) { + return ({ state, dispatch }) => { + if (state.readOnly) + return false; + let changes = state.changeByRange(range => { + let { from, to } = range, line = state.doc.lineAt(from); + let explode = !atEof && from == to && isBetweenBrackets(state, from); + if (atEof) + from = to = (to <= line.to ? line : state.doc.lineAt(to)).to; + let cx = new IndentContext(state, { simulateBreak: from, simulateDoubleBreak: !!explode }); + let indent = getIndentation(cx, from); + if (indent == null) + indent = /^\s*/.exec(state.doc.lineAt(from).text)[0].length; + while (to < line.to && /\s/.test(line.text[to - line.from])) + to++; + if (explode) + ({ from, to } = explode); + else if (from > line.from && from < line.from + 100 && !/\S/.test(line.text.slice(0, from))) + from = line.from; + let insert = ["", indentString(state, indent)]; + if (explode) + insert.push(indentString(state, cx.lineIndent(line.from, -1))); + return { changes: { from, to, insert: Text.of(insert) }, + range: EditorSelection.cursor(from + 1 + insert[1].length) }; + }); + dispatch(state.update(changes, { scrollIntoView: true, userEvent: "input" })); + return true; + }; + } + function changeBySelectedLine(state, f) { + let atLine = -1; + return state.changeByRange(range => { + let changes = []; + for (let pos = range.from; pos <= range.to;) { + let line = state.doc.lineAt(pos); + if (line.number > atLine && (range.empty || range.to > line.from)) { + f(line, changes, range); + atLine = line.number; + } + pos = line.to + 1; + } + let changeSet = state.changes(changes); + return { changes, + range: EditorSelection.range(changeSet.mapPos(range.anchor, 1), changeSet.mapPos(range.head, 1)) }; + }); + } + /** + Auto-indent the selected lines. This uses the [indentation service + facet](https://codemirror.net/6/docs/ref/#language.indentService) as source for auto-indent + information. + */ + const indentSelection = ({ state, dispatch }) => { + if (state.readOnly) + return false; + let updated = Object.create(null); + let context = new IndentContext(state, { overrideIndentation: start => { + let found = updated[start]; + return found == null ? -1 : found; + } }); + let changes = changeBySelectedLine(state, (line, changes, range) => { + let indent = getIndentation(context, line.from); + if (indent == null) + return; + if (!/\S/.test(line.text)) + indent = 0; + let cur = /^\s*/.exec(line.text)[0]; + let norm = indentString(state, indent); + if (cur != norm || range.from < line.from + cur.length) { + updated[line.from] = indent; + changes.push({ from: line.from, to: line.from + cur.length, insert: norm }); + } + }); + if (!changes.changes.empty) + dispatch(state.update(changes, { userEvent: "indent" })); + return true; + }; + /** + Add a [unit](https://codemirror.net/6/docs/ref/#language.indentUnit) of indentation to all selected + lines. + */ + const indentMore = ({ state, dispatch }) => { + if (state.readOnly) + return false; + dispatch(state.update(changeBySelectedLine(state, (line, changes) => { + changes.push({ from: line.from, insert: state.facet(indentUnit) }); + }), { userEvent: "input.indent" })); + return true; + }; + /** + Remove a [unit](https://codemirror.net/6/docs/ref/#language.indentUnit) of indentation from all + selected lines. + */ + const indentLess = ({ state, dispatch }) => { + if (state.readOnly) + return false; + dispatch(state.update(changeBySelectedLine(state, (line, changes) => { + let space = /^\s*/.exec(line.text)[0]; + if (!space) + return; + let col = countColumn(space, state.tabSize), keep = 0; + let insert = indentString(state, Math.max(0, col - getIndentUnit(state))); + while (keep < space.length && keep < insert.length && space.charCodeAt(keep) == insert.charCodeAt(keep)) + keep++; + changes.push({ from: line.from + keep, to: line.from + space.length, insert: insert.slice(keep) }); + }), { userEvent: "delete.dedent" })); + return true; + }; + /** + Array of key bindings containing the Emacs-style bindings that are + available on macOS by default. + + - Ctrl-b: [`cursorCharLeft`](https://codemirror.net/6/docs/ref/#commands.cursorCharLeft) ([`selectCharLeft`](https://codemirror.net/6/docs/ref/#commands.selectCharLeft) with Shift) + - Ctrl-f: [`cursorCharRight`](https://codemirror.net/6/docs/ref/#commands.cursorCharRight) ([`selectCharRight`](https://codemirror.net/6/docs/ref/#commands.selectCharRight) with Shift) + - Ctrl-p: [`cursorLineUp`](https://codemirror.net/6/docs/ref/#commands.cursorLineUp) ([`selectLineUp`](https://codemirror.net/6/docs/ref/#commands.selectLineUp) with Shift) + - Ctrl-n: [`cursorLineDown`](https://codemirror.net/6/docs/ref/#commands.cursorLineDown) ([`selectLineDown`](https://codemirror.net/6/docs/ref/#commands.selectLineDown) with Shift) + - Ctrl-a: [`cursorLineStart`](https://codemirror.net/6/docs/ref/#commands.cursorLineStart) ([`selectLineStart`](https://codemirror.net/6/docs/ref/#commands.selectLineStart) with Shift) + - Ctrl-e: [`cursorLineEnd`](https://codemirror.net/6/docs/ref/#commands.cursorLineEnd) ([`selectLineEnd`](https://codemirror.net/6/docs/ref/#commands.selectLineEnd) with Shift) + - Ctrl-d: [`deleteCharForward`](https://codemirror.net/6/docs/ref/#commands.deleteCharForward) + - Ctrl-h: [`deleteCharBackward`](https://codemirror.net/6/docs/ref/#commands.deleteCharBackward) + - Ctrl-k: [`deleteToLineEnd`](https://codemirror.net/6/docs/ref/#commands.deleteToLineEnd) + - Ctrl-Alt-h: [`deleteGroupBackward`](https://codemirror.net/6/docs/ref/#commands.deleteGroupBackward) + - Ctrl-o: [`splitLine`](https://codemirror.net/6/docs/ref/#commands.splitLine) + - Ctrl-t: [`transposeChars`](https://codemirror.net/6/docs/ref/#commands.transposeChars) + - Ctrl-v: [`cursorPageDown`](https://codemirror.net/6/docs/ref/#commands.cursorPageDown) + - Alt-v: [`cursorPageUp`](https://codemirror.net/6/docs/ref/#commands.cursorPageUp) + */ + const emacsStyleKeymap = [ + { key: "Ctrl-b", run: cursorCharLeft, shift: selectCharLeft, preventDefault: true }, + { key: "Ctrl-f", run: cursorCharRight, shift: selectCharRight }, + { key: "Ctrl-p", run: cursorLineUp, shift: selectLineUp }, + { key: "Ctrl-n", run: cursorLineDown, shift: selectLineDown }, + { key: "Ctrl-a", run: cursorLineStart, shift: selectLineStart }, + { key: "Ctrl-e", run: cursorLineEnd, shift: selectLineEnd }, + { key: "Ctrl-d", run: deleteCharForward }, + { key: "Ctrl-h", run: deleteCharBackward }, + { key: "Ctrl-k", run: deleteToLineEnd }, + { key: "Ctrl-Alt-h", run: deleteGroupBackward }, + { key: "Ctrl-o", run: splitLine }, + { key: "Ctrl-t", run: transposeChars }, + { key: "Ctrl-v", run: cursorPageDown }, + ]; + /** + An array of key bindings closely sticking to platform-standard or + widely used bindings. (This includes the bindings from + [`emacsStyleKeymap`](https://codemirror.net/6/docs/ref/#commands.emacsStyleKeymap), with their `key` + property changed to `mac`.) + + - ArrowLeft: [`cursorCharLeft`](https://codemirror.net/6/docs/ref/#commands.cursorCharLeft) ([`selectCharLeft`](https://codemirror.net/6/docs/ref/#commands.selectCharLeft) with Shift) + - ArrowRight: [`cursorCharRight`](https://codemirror.net/6/docs/ref/#commands.cursorCharRight) ([`selectCharRight`](https://codemirror.net/6/docs/ref/#commands.selectCharRight) with Shift) + - Ctrl-ArrowLeft (Alt-ArrowLeft on macOS): [`cursorGroupLeft`](https://codemirror.net/6/docs/ref/#commands.cursorGroupLeft) ([`selectGroupLeft`](https://codemirror.net/6/docs/ref/#commands.selectGroupLeft) with Shift) + - Ctrl-ArrowRight (Alt-ArrowRight on macOS): [`cursorGroupRight`](https://codemirror.net/6/docs/ref/#commands.cursorGroupRight) ([`selectGroupRight`](https://codemirror.net/6/docs/ref/#commands.selectGroupRight) with Shift) + - Cmd-ArrowLeft (on macOS): [`cursorLineStart`](https://codemirror.net/6/docs/ref/#commands.cursorLineStart) ([`selectLineStart`](https://codemirror.net/6/docs/ref/#commands.selectLineStart) with Shift) + - Cmd-ArrowRight (on macOS): [`cursorLineEnd`](https://codemirror.net/6/docs/ref/#commands.cursorLineEnd) ([`selectLineEnd`](https://codemirror.net/6/docs/ref/#commands.selectLineEnd) with Shift) + - ArrowUp: [`cursorLineUp`](https://codemirror.net/6/docs/ref/#commands.cursorLineUp) ([`selectLineUp`](https://codemirror.net/6/docs/ref/#commands.selectLineUp) with Shift) + - ArrowDown: [`cursorLineDown`](https://codemirror.net/6/docs/ref/#commands.cursorLineDown) ([`selectLineDown`](https://codemirror.net/6/docs/ref/#commands.selectLineDown) with Shift) + - Cmd-ArrowUp (on macOS): [`cursorDocStart`](https://codemirror.net/6/docs/ref/#commands.cursorDocStart) ([`selectDocStart`](https://codemirror.net/6/docs/ref/#commands.selectDocStart) with Shift) + - Cmd-ArrowDown (on macOS): [`cursorDocEnd`](https://codemirror.net/6/docs/ref/#commands.cursorDocEnd) ([`selectDocEnd`](https://codemirror.net/6/docs/ref/#commands.selectDocEnd) with Shift) + - Ctrl-ArrowUp (on macOS): [`cursorPageUp`](https://codemirror.net/6/docs/ref/#commands.cursorPageUp) ([`selectPageUp`](https://codemirror.net/6/docs/ref/#commands.selectPageUp) with Shift) + - Ctrl-ArrowDown (on macOS): [`cursorPageDown`](https://codemirror.net/6/docs/ref/#commands.cursorPageDown) ([`selectPageDown`](https://codemirror.net/6/docs/ref/#commands.selectPageDown) with Shift) + - PageUp: [`cursorPageUp`](https://codemirror.net/6/docs/ref/#commands.cursorPageUp) ([`selectPageUp`](https://codemirror.net/6/docs/ref/#commands.selectPageUp) with Shift) + - PageDown: [`cursorPageDown`](https://codemirror.net/6/docs/ref/#commands.cursorPageDown) ([`selectPageDown`](https://codemirror.net/6/docs/ref/#commands.selectPageDown) with Shift) + - Home: [`cursorLineBoundaryBackward`](https://codemirror.net/6/docs/ref/#commands.cursorLineBoundaryBackward) ([`selectLineBoundaryBackward`](https://codemirror.net/6/docs/ref/#commands.selectLineBoundaryBackward) with Shift) + - End: [`cursorLineBoundaryForward`](https://codemirror.net/6/docs/ref/#commands.cursorLineBoundaryForward) ([`selectLineBoundaryForward`](https://codemirror.net/6/docs/ref/#commands.selectLineBoundaryForward) with Shift) + - Ctrl-Home (Cmd-Home on macOS): [`cursorDocStart`](https://codemirror.net/6/docs/ref/#commands.cursorDocStart) ([`selectDocStart`](https://codemirror.net/6/docs/ref/#commands.selectDocStart) with Shift) + - Ctrl-End (Cmd-Home on macOS): [`cursorDocEnd`](https://codemirror.net/6/docs/ref/#commands.cursorDocEnd) ([`selectDocEnd`](https://codemirror.net/6/docs/ref/#commands.selectDocEnd) with Shift) + - Enter: [`insertNewlineAndIndent`](https://codemirror.net/6/docs/ref/#commands.insertNewlineAndIndent) + - Ctrl-a (Cmd-a on macOS): [`selectAll`](https://codemirror.net/6/docs/ref/#commands.selectAll) + - Backspace: [`deleteCharBackward`](https://codemirror.net/6/docs/ref/#commands.deleteCharBackward) + - Delete: [`deleteCharForward`](https://codemirror.net/6/docs/ref/#commands.deleteCharForward) + - Ctrl-Backspace (Alt-Backspace on macOS): [`deleteGroupBackward`](https://codemirror.net/6/docs/ref/#commands.deleteGroupBackward) + - Ctrl-Delete (Alt-Delete on macOS): [`deleteGroupForward`](https://codemirror.net/6/docs/ref/#commands.deleteGroupForward) + - Cmd-Backspace (macOS): [`deleteToLineStart`](https://codemirror.net/6/docs/ref/#commands.deleteToLineStart). + - Cmd-Delete (macOS): [`deleteToLineEnd`](https://codemirror.net/6/docs/ref/#commands.deleteToLineEnd). + */ + const standardKeymap = /*@__PURE__*/[ + { key: "ArrowLeft", run: cursorCharLeft, shift: selectCharLeft, preventDefault: true }, + { key: "Mod-ArrowLeft", mac: "Alt-ArrowLeft", run: cursorGroupLeft, shift: selectGroupLeft, preventDefault: true }, + { mac: "Cmd-ArrowLeft", run: cursorLineBoundaryLeft, shift: selectLineBoundaryLeft, preventDefault: true }, + { key: "ArrowRight", run: cursorCharRight, shift: selectCharRight, preventDefault: true }, + { key: "Mod-ArrowRight", mac: "Alt-ArrowRight", run: cursorGroupRight, shift: selectGroupRight, preventDefault: true }, + { mac: "Cmd-ArrowRight", run: cursorLineBoundaryRight, shift: selectLineBoundaryRight, preventDefault: true }, + { key: "ArrowUp", run: cursorLineUp, shift: selectLineUp, preventDefault: true }, + { mac: "Cmd-ArrowUp", run: cursorDocStart, shift: selectDocStart }, + { mac: "Ctrl-ArrowUp", run: cursorPageUp, shift: selectPageUp }, + { key: "ArrowDown", run: cursorLineDown, shift: selectLineDown, preventDefault: true }, + { mac: "Cmd-ArrowDown", run: cursorDocEnd, shift: selectDocEnd }, + { mac: "Ctrl-ArrowDown", run: cursorPageDown, shift: selectPageDown }, + { key: "PageUp", run: cursorPageUp, shift: selectPageUp }, + { key: "PageDown", run: cursorPageDown, shift: selectPageDown }, + { key: "Home", run: cursorLineBoundaryBackward, shift: selectLineBoundaryBackward, preventDefault: true }, + { key: "Mod-Home", run: cursorDocStart, shift: selectDocStart }, + { key: "End", run: cursorLineBoundaryForward, shift: selectLineBoundaryForward, preventDefault: true }, + { key: "Mod-End", run: cursorDocEnd, shift: selectDocEnd }, + { key: "Enter", run: insertNewlineAndIndent }, + { key: "Mod-a", run: selectAll }, + { key: "Backspace", run: deleteCharBackward, shift: deleteCharBackward }, + { key: "Delete", run: deleteCharForward }, + { key: "Mod-Backspace", mac: "Alt-Backspace", run: deleteGroupBackward }, + { key: "Mod-Delete", mac: "Alt-Delete", run: deleteGroupForward }, + { mac: "Mod-Backspace", run: deleteToLineStart }, + { mac: "Mod-Delete", run: deleteToLineEnd } + ].concat(/*@__PURE__*/emacsStyleKeymap.map(b => ({ mac: b.key, run: b.run, shift: b.shift }))); + /** + The default keymap. Includes all bindings from + [`standardKeymap`](https://codemirror.net/6/docs/ref/#commands.standardKeymap) plus the following: + + - Alt-ArrowLeft (Ctrl-ArrowLeft on macOS): [`cursorSyntaxLeft`](https://codemirror.net/6/docs/ref/#commands.cursorSyntaxLeft) ([`selectSyntaxLeft`](https://codemirror.net/6/docs/ref/#commands.selectSyntaxLeft) with Shift) + - Alt-ArrowRight (Ctrl-ArrowRight on macOS): [`cursorSyntaxRight`](https://codemirror.net/6/docs/ref/#commands.cursorSyntaxRight) ([`selectSyntaxRight`](https://codemirror.net/6/docs/ref/#commands.selectSyntaxRight) with Shift) + - Alt-ArrowUp: [`moveLineUp`](https://codemirror.net/6/docs/ref/#commands.moveLineUp) + - Alt-ArrowDown: [`moveLineDown`](https://codemirror.net/6/docs/ref/#commands.moveLineDown) + - Shift-Alt-ArrowUp: [`copyLineUp`](https://codemirror.net/6/docs/ref/#commands.copyLineUp) + - Shift-Alt-ArrowDown: [`copyLineDown`](https://codemirror.net/6/docs/ref/#commands.copyLineDown) + - Escape: [`simplifySelection`](https://codemirror.net/6/docs/ref/#commands.simplifySelection) + - Ctrl-Enter (Comd-Enter on macOS): [`insertBlankLine`](https://codemirror.net/6/docs/ref/#commands.insertBlankLine) + - Alt-l (Ctrl-l on macOS): [`selectLine`](https://codemirror.net/6/docs/ref/#commands.selectLine) + - Ctrl-i (Cmd-i on macOS): [`selectParentSyntax`](https://codemirror.net/6/docs/ref/#commands.selectParentSyntax) + - Ctrl-[ (Cmd-[ on macOS): [`indentLess`](https://codemirror.net/6/docs/ref/#commands.indentLess) + - Ctrl-] (Cmd-] on macOS): [`indentMore`](https://codemirror.net/6/docs/ref/#commands.indentMore) + - Ctrl-Alt-\\ (Cmd-Alt-\\ on macOS): [`indentSelection`](https://codemirror.net/6/docs/ref/#commands.indentSelection) + - Shift-Ctrl-k (Shift-Cmd-k on macOS): [`deleteLine`](https://codemirror.net/6/docs/ref/#commands.deleteLine) + - Shift-Ctrl-\\ (Shift-Cmd-\\ on macOS): [`cursorMatchingBracket`](https://codemirror.net/6/docs/ref/#commands.cursorMatchingBracket) + - Ctrl-/ (Cmd-/ on macOS): [`toggleComment`](https://codemirror.net/6/docs/ref/#commands.toggleComment). + - Shift-Alt-a: [`toggleBlockComment`](https://codemirror.net/6/docs/ref/#commands.toggleBlockComment). + */ + const defaultKeymap = /*@__PURE__*/[ + { key: "Alt-ArrowLeft", mac: "Ctrl-ArrowLeft", run: cursorSyntaxLeft, shift: selectSyntaxLeft }, + { key: "Alt-ArrowRight", mac: "Ctrl-ArrowRight", run: cursorSyntaxRight, shift: selectSyntaxRight }, + { key: "Alt-ArrowUp", run: moveLineUp }, + { key: "Shift-Alt-ArrowUp", run: copyLineUp }, + { key: "Alt-ArrowDown", run: moveLineDown }, + { key: "Shift-Alt-ArrowDown", run: copyLineDown }, + { key: "Escape", run: simplifySelection }, + { key: "Mod-Enter", run: insertBlankLine }, + { key: "Alt-l", mac: "Ctrl-l", run: selectLine }, + { key: "Mod-i", run: selectParentSyntax, preventDefault: true }, + { key: "Mod-[", run: indentLess }, + { key: "Mod-]", run: indentMore }, + { key: "Mod-Alt-\\", run: indentSelection }, + { key: "Shift-Mod-k", run: deleteLine }, + { key: "Shift-Mod-\\", run: cursorMatchingBracket }, + { key: "Mod-/", run: toggleComment }, + { key: "Alt-A", run: toggleBlockComment } + ].concat(standardKeymap); + + function crelt() { + var elt = arguments[0]; + if (typeof elt == "string") elt = document.createElement(elt); + var i = 1, next = arguments[1]; + if (next && typeof next == "object" && next.nodeType == null && !Array.isArray(next)) { + for (var name in next) if (Object.prototype.hasOwnProperty.call(next, name)) { + var value = next[name]; + if (typeof value == "string") elt.setAttribute(name, value); + else if (value != null) elt[name] = value; + } + i++; } + for (; i < arguments.length; i++) add(elt, arguments[i]); + return elt + } - - var loadAll_1 = loadAll$1; - var load_1 = load$1; - - var loader$2 = { - loadAll: loadAll_1, - load: load_1 - }; - var load = loader$2.load; - - const logger$9 = getLogger('py-env'); - // Premise used to connect to the first available runtime (can be pyodide or others) - let runtime; - runtimeLoaded.subscribe(value => { - runtime = value; - }); - class PyEnv extends HTMLElement { - shadow; - wrapper; - code; - environment; - runtime; - env; - paths; - constructor() { - super(); - this.shadow = this.attachShadow({ mode: 'open' }); - this.wrapper = document.createElement('slot'); - } - connectedCallback() { - logger$9.info("The <py-env> tag is deprecated, please use <py-config> instead."); - this.code = this.innerHTML; - this.innerHTML = ''; - const env = []; - const paths = []; - this.environment = load(this.code); - if (this.environment === undefined) - return; - for (const entry of Array.isArray(this.environment) ? this.environment : []) { - if (typeof entry == 'string') { - env.push(entry); - } - else if (entry && typeof entry === 'object') { - const obj = entry; - for (const path of Array.isArray(obj.paths) ? obj.paths : []) { - if (typeof path === 'string') { - paths.push(path); - } - } - } - } - this.env = env; - this.paths = paths; - async function loadEnv() { - logger$9.info("Loading env: ", env); - await runtime.installPackage(env); - } - async function loadPaths() { - logger$9.info("Paths to load: ", paths); - for (const singleFile of paths) { - logger$9.info(` loading path: ${singleFile}`); - try { - await runtime.loadFromFile(singleFile); - } - catch (e) { - //Should we still export full error contents to console? - handleFetchError(e, singleFile); - } - } - logger$9.info("All paths loaded"); - } - addInitializer(loadEnv); - addInitializer(loadPaths); - } + function add(elt, child) { + if (typeof child == "string") { + elt.appendChild(document.createTextNode(child)); + } else if (child == null) ; else if (child.nodeType != null) { + elt.appendChild(child); + } else if (Array.isArray(child)) { + for (var i = 0; i < child.length; i++) add(elt, child[i]); + } else { + throw new RangeError("Unsupported child node: " + child) } + } - const logger$8 = getLogger('py-loader'); - class PyLoader extends BaseEvalElement { - widths; - label; - mount_name; - details; - operation; - constructor() { - super(); - } - connectedCallback() { - this.innerHTML = `<div id="pyscript_loading_splash" class="py-overlay"> + const basicNormalize = typeof String.prototype.normalize == "function" + ? x => x.normalize("NFKD") : x => x; + /** + A search cursor provides an iterator over text matches in a + document. + */ + class SearchCursor { + /** + Create a text cursor. The query is the search string, `from` to + `to` provides the region to search. + + When `normalize` is given, it will be called, on both the query + string and the content it is matched against, before comparing. + You can, for example, create a case-insensitive search by + passing `s => s.toLowerCase()`. + + Text is always normalized with + [`.normalize("NFKD")`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/normalize) + (when supported). + */ + constructor(text, query, from = 0, to = text.length, normalize, test) { + this.test = test; + /** + The current match (only holds a meaningful value after + [`next`](https://codemirror.net/6/docs/ref/#search.SearchCursor.next) has been called and when + `done` is false). + */ + this.value = { from: 0, to: 0 }; + /** + Whether the end of the iterated region has been reached. + */ + this.done = false; + this.matches = []; + this.buffer = ""; + this.bufferPos = 0; + this.iter = text.iterRange(from, to); + this.bufferStart = from; + this.normalize = normalize ? x => normalize(basicNormalize(x)) : basicNormalize; + this.query = this.normalize(query); + } + peek() { + if (this.bufferPos == this.buffer.length) { + this.bufferStart += this.buffer.length; + this.iter.next(); + if (this.iter.done) + return -1; + this.bufferPos = 0; + this.buffer = this.iter.value; + } + return codePointAt(this.buffer, this.bufferPos); + } + /** + Look for the next match. Updates the iterator's + [`value`](https://codemirror.net/6/docs/ref/#search.SearchCursor.value) and + [`done`](https://codemirror.net/6/docs/ref/#search.SearchCursor.done) properties. Should be called + at least once before using the cursor. + */ + next() { + while (this.matches.length) + this.matches.pop(); + return this.nextOverlapping(); + } + /** + The `next` method will ignore matches that partially overlap a + previous match. This method behaves like `next`, but includes + such matches. + */ + nextOverlapping() { + for (;;) { + let next = this.peek(); + if (next < 0) { + this.done = true; + return this; + } + let str = fromCodePoint(next), start = this.bufferStart + this.bufferPos; + this.bufferPos += codePointSize(next); + let norm = this.normalize(str); + for (let i = 0, pos = start;; i++) { + let code = norm.charCodeAt(i); + let match = this.match(code, pos); + if (match) { + this.value = match; + return this; + } + if (i == norm.length - 1) + break; + if (pos == start && i < str.length && str.charCodeAt(i) == code) + pos++; + } + } + } + match(code, pos) { + let match = null; + for (let i = 0; i < this.matches.length; i += 2) { + let index = this.matches[i], keep = false; + if (this.query.charCodeAt(index) == code) { + if (index == this.query.length - 1) { + match = { from: this.matches[i + 1], to: pos + 1 }; + } + else { + this.matches[i]++; + keep = true; + } + } + if (!keep) { + this.matches.splice(i, 2); + i -= 2; + } + } + if (this.query.charCodeAt(0) == code) { + if (this.query.length == 1) + match = { from: pos, to: pos + 1 }; + else + this.matches.push(1, pos); + } + if (match && this.test && !this.test(match.from, match.to, this.buffer, this.bufferPos)) + match = null; + return match; + } + } + if (typeof Symbol != "undefined") + SearchCursor.prototype[Symbol.iterator] = function () { return this; }; + + const empty = { from: -1, to: -1, match: /*@__PURE__*//.*/.exec("") }; + const baseFlags = "gm" + (/x/.unicode == null ? "" : "u"); + /** + This class is similar to [`SearchCursor`](https://codemirror.net/6/docs/ref/#search.SearchCursor) + but searches for a regular expression pattern instead of a plain + string. + */ + class RegExpCursor { + /** + Create a cursor that will search the given range in the given + document. `query` should be the raw pattern (as you'd pass it to + `new RegExp`). + */ + constructor(text, query, options, from = 0, to = text.length) { + this.text = text; + this.to = to; + this.curLine = ""; + /** + Set to `true` when the cursor has reached the end of the search + range. + */ + this.done = false; + /** + Will contain an object with the extent of the match and the + match object when [`next`](https://codemirror.net/6/docs/ref/#search.RegExpCursor.next) + sucessfully finds a match. + */ + this.value = empty; + if (/\\[sWDnr]|\n|\r|\[\^/.test(query)) + return new MultilineRegExpCursor(text, query, options, from, to); + this.re = new RegExp(query, baseFlags + ((options === null || options === void 0 ? void 0 : options.ignoreCase) ? "i" : "")); + this.test = options === null || options === void 0 ? void 0 : options.test; + this.iter = text.iter(); + let startLine = text.lineAt(from); + this.curLineStart = startLine.from; + this.matchPos = toCharEnd(text, from); + this.getLine(this.curLineStart); + } + getLine(skip) { + this.iter.next(skip); + if (this.iter.lineBreak) { + this.curLine = ""; + } + else { + this.curLine = this.iter.value; + if (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; + if (this.curLineStart > this.to) + this.curLine = ""; + else + this.getLine(0); + } + /** + Move to the next match, if there is one. + */ + next() { + for (let off = this.matchPos - this.curLineStart;;) { + this.re.lastIndex = off; + let match = this.matchPos <= this.to && this.re.exec(this.curLine); + if (match) { + let from = this.curLineStart + match.index, to = from + match[0].length; + this.matchPos = toCharEnd(this.text, to + (from == to ? 1 : 0)); + if (from == this.curLine.length) + this.nextLine(); + if ((from < to || from > this.value.to) && (!this.test || this.test(from, to, match))) { + this.value = { from, to, match }; + return this; + } + off = this.matchPos - this.curLineStart; + } + else if (this.curLineStart + this.curLine.length < this.to) { + this.nextLine(); + off = 0; + } + else { + this.done = true; + return this; + } + } + } + } + const flattened = /*@__PURE__*/new WeakMap(); + // Reusable (partially) flattened document strings + class FlattenedDoc { + constructor(from, text) { + this.from = from; + this.text = text; + } + get to() { return this.from + this.text.length; } + static get(doc, from, to) { + let cached = flattened.get(doc); + if (!cached || cached.from >= to || cached.to <= from) { + let flat = new FlattenedDoc(from, doc.sliceString(from, to)); + flattened.set(doc, flat); + return flat; + } + if (cached.from == from && cached.to == to) + return cached; + let { text, from: cachedFrom } = cached; + if (cachedFrom > from) { + text = doc.sliceString(from, cachedFrom) + text; + cachedFrom = from; + } + if (cached.to < to) + text += doc.sliceString(cached.to, to); + flattened.set(doc, new FlattenedDoc(cachedFrom, text)); + return new FlattenedDoc(from, text.slice(from - cachedFrom, to - cachedFrom)); + } + } + class MultilineRegExpCursor { + constructor(text, query, options, from, to) { + this.text = text; + this.to = to; + this.done = false; + this.value = empty; + this.matchPos = toCharEnd(text, from); + this.re = new RegExp(query, baseFlags + ((options === null || options === void 0 ? void 0 : options.ignoreCase) ? "i" : "")); + this.test = options === null || options === void 0 ? void 0 : options.test; + this.flat = FlattenedDoc.get(text, from, this.chunkEnd(from + 5000 /* Chunk.Base */)); + } + chunkEnd(pos) { + return pos >= this.to ? this.to : this.text.lineAt(pos).to; + } + next() { + for (;;) { + let off = this.re.lastIndex = this.matchPos - this.flat.from; + let match = this.re.exec(this.flat.text); + // Skip empty matches directly after the last match + if (match && !match[0] && match.index == off) { + this.re.lastIndex = off + 1; + match = this.re.exec(this.flat.text); + } + if (match) { + let from = this.flat.from + match.index, to = from + match[0].length; + // If a match goes almost to the end of a noncomplete chunk, try + // again, since it'll likely be able to match more + if ((this.flat.to >= this.to || match.index + match[0].length <= this.flat.text.length - 10) && + (!this.test || this.test(from, to, match))) { + this.value = { from, to, match }; + this.matchPos = toCharEnd(this.text, to + (from == to ? 1 : 0)); + return this; + } + } + if (this.flat.to == this.to) { + this.done = true; + return this; + } + // Grow the flattened doc + this.flat = FlattenedDoc.get(this.text, this.flat.from, this.chunkEnd(this.flat.from + this.flat.text.length * 2)); + } + } + } + if (typeof Symbol != "undefined") { + RegExpCursor.prototype[Symbol.iterator] = MultilineRegExpCursor.prototype[Symbol.iterator] = + function () { return this; }; + } + function validRegExp(source) { + try { + new RegExp(source, baseFlags); + return true; + } + catch (_a) { + return false; + } + } + function toCharEnd(text, pos) { + if (pos >= text.length) + return pos; + let line = text.lineAt(pos), next; + while (pos < line.to && (next = line.text.charCodeAt(pos - line.from)) >= 0xDC00 && next < 0xE000) + pos++; + return pos; + } + + function createLineDialog(view) { + let input = crelt("input", { class: "cm-textfield", name: "line" }); + let dom = crelt("form", { + class: "cm-gotoLine", + onkeydown: (event) => { + if (event.keyCode == 27) { // Escape + event.preventDefault(); + view.dispatch({ effects: dialogEffect.of(false) }); + view.focus(); + } + else if (event.keyCode == 13) { // Enter + event.preventDefault(); + go(); + } + }, + onsubmit: (event) => { + event.preventDefault(); + go(); + } + }, crelt("label", view.state.phrase("Go to line"), ": ", input), " ", crelt("button", { class: "cm-button", type: "submit" }, view.state.phrase("go"))); + function go() { + let match = /^([+-])?(\d+)?(:\d+)?(%)?$/.exec(input.value); + if (!match) + return; + let { state } = view, startLine = state.doc.lineAt(state.selection.main.head); + let [, sign, ln, cl, percent] = match; + let col = cl ? +cl.slice(1) : 0; + let line = ln ? +ln : startLine.number; + if (ln && percent) { + let pc = line / 100; + if (sign) + pc = pc * (sign == "-" ? -1 : 1) + (startLine.number / state.doc.lines); + line = Math.round(state.doc.lines * pc); + } + else if (ln && sign) { + line = line * (sign == "-" ? -1 : 1) + startLine.number; + } + let docLine = state.doc.line(Math.max(1, Math.min(state.doc.lines, line))); + view.dispatch({ + effects: dialogEffect.of(false), + selection: EditorSelection.cursor(docLine.from + Math.max(0, Math.min(col, docLine.length))), + scrollIntoView: true + }); + view.focus(); + } + return { dom }; + } + const dialogEffect = /*@__PURE__*/StateEffect.define(); + const dialogField = /*@__PURE__*/StateField.define({ + create() { return true; }, + update(value, tr) { + for (let e of tr.effects) + if (e.is(dialogEffect)) + value = e.value; + return value; + }, + provide: f => showPanel.from(f, val => val ? createLineDialog : null) + }); + /** + Command that shows a dialog asking the user for a line number, and + when a valid position is provided, moves the cursor to that line. + + Supports line numbers, relative line offsets prefixed with `+` or + `-`, document percentages suffixed with `%`, and an optional + column position by adding `:` and a second number after the line + number. + + The dialog can be styled with the `panel.gotoLine` theme + selector. + */ + const gotoLine = view => { + let panel = getPanel(view, createLineDialog); + if (!panel) { + let effects = [dialogEffect.of(true)]; + if (view.state.field(dialogField, false) == null) + effects.push(StateEffect.appendConfig.of([dialogField, baseTheme$1$1])); + view.dispatch({ effects }); + panel = getPanel(view, createLineDialog); + } + if (panel) + panel.dom.querySelector("input").focus(); + return true; + }; + const baseTheme$1$1 = /*@__PURE__*/EditorView.baseTheme({ + ".cm-panel.cm-gotoLine": { + padding: "2px 6px 4px", + "& label": { fontSize: "80%" } + } + }); + + const defaultHighlightOptions = { + highlightWordAroundCursor: false, + minSelectionLength: 1, + maxMatches: 100, + wholeWords: false + }; + const highlightConfig = /*@__PURE__*/Facet.define({ + combine(options) { + return combineConfig(options, defaultHighlightOptions, { + highlightWordAroundCursor: (a, b) => a || b, + minSelectionLength: Math.min, + maxMatches: Math.min + }); + } + }); + /** + This extension highlights text that matches the selection. It uses + the `"cm-selectionMatch"` class for the highlighting. When + `highlightWordAroundCursor` is enabled, the word at the cursor + itself will be highlighted with `"cm-selectionMatch-main"`. + */ + function highlightSelectionMatches(options) { + let ext = [defaultTheme, matchHighlighter]; + if (options) + ext.push(highlightConfig.of(options)); + return ext; + } + const matchDeco = /*@__PURE__*/Decoration.mark({ class: "cm-selectionMatch" }); + const mainMatchDeco = /*@__PURE__*/Decoration.mark({ class: "cm-selectionMatch cm-selectionMatch-main" }); + // Whether the characters directly outside the given positions are non-word characters + function insideWordBoundaries(check, state, from, to) { + return (from == 0 || check(state.sliceDoc(from - 1, from)) != CharCategory.Word) && + (to == state.doc.length || check(state.sliceDoc(to, to + 1)) != CharCategory.Word); + } + // Whether the characters directly at the given positions are word characters + function insideWord(check, state, from, to) { + return check(state.sliceDoc(from, from + 1)) == CharCategory.Word + && check(state.sliceDoc(to - 1, to)) == CharCategory.Word; + } + const matchHighlighter = /*@__PURE__*/ViewPlugin.fromClass(class { + constructor(view) { + this.decorations = this.getDeco(view); + } + update(update) { + if (update.selectionSet || update.docChanged || update.viewportChanged) + this.decorations = this.getDeco(update.view); + } + getDeco(view) { + let conf = view.state.facet(highlightConfig); + let { state } = view, sel = state.selection; + if (sel.ranges.length > 1) + return Decoration.none; + let range = sel.main, query, check = null; + if (range.empty) { + if (!conf.highlightWordAroundCursor) + return Decoration.none; + let word = state.wordAt(range.head); + if (!word) + return Decoration.none; + check = state.charCategorizer(range.head); + query = state.sliceDoc(word.from, word.to); + } + else { + let len = range.to - range.from; + if (len < conf.minSelectionLength || len > 200) + return Decoration.none; + if (conf.wholeWords) { + query = state.sliceDoc(range.from, range.to); // TODO: allow and include leading/trailing space? + check = state.charCategorizer(range.head); + if (!(insideWordBoundaries(check, state, range.from, range.to) + && insideWord(check, state, range.from, range.to))) + return Decoration.none; + } + else { + query = state.sliceDoc(range.from, range.to).trim(); + if (!query) + return Decoration.none; + } + } + let deco = []; + for (let part of view.visibleRanges) { + let cursor = new SearchCursor(state.doc, query, part.from, part.to); + while (!cursor.next().done) { + let { from, to } = cursor.value; + if (!check || insideWordBoundaries(check, state, from, to)) { + if (range.empty && from <= range.from && to >= range.to) + deco.push(mainMatchDeco.range(from, to)); + else if (from >= range.to || to <= range.from) + deco.push(matchDeco.range(from, to)); + if (deco.length > conf.maxMatches) + return Decoration.none; + } + } + } + return Decoration.set(deco); + } + }, { + decorations: v => v.decorations + }); + const defaultTheme = /*@__PURE__*/EditorView.baseTheme({ + ".cm-selectionMatch": { backgroundColor: "#99ff7780" }, + ".cm-searchMatch .cm-selectionMatch": { backgroundColor: "transparent" } + }); + // Select the words around the cursors. + const selectWord = ({ state, dispatch }) => { + let { selection } = state; + let newSel = EditorSelection.create(selection.ranges.map(range => state.wordAt(range.head) || EditorSelection.cursor(range.head)), selection.mainIndex); + if (newSel.eq(selection)) + return false; + dispatch(state.update({ selection: newSel })); + return true; + }; + // Find next occurrence of query relative to last cursor. Wrap around + // the document if there are no more matches. + function findNextOccurrence(state, query) { + let { main, ranges } = state.selection; + let word = state.wordAt(main.head), fullWord = word && word.from == main.from && word.to == main.to; + for (let cycled = false, cursor = new SearchCursor(state.doc, query, ranges[ranges.length - 1].to);;) { + cursor.next(); + if (cursor.done) { + if (cycled) + return null; + cursor = new SearchCursor(state.doc, query, 0, Math.max(0, ranges[ranges.length - 1].from - 1)); + cycled = true; + } + else { + if (cycled && ranges.some(r => r.from == cursor.value.from)) + continue; + if (fullWord) { + let word = state.wordAt(cursor.value.from); + if (!word || word.from != cursor.value.from || word.to != cursor.value.to) + continue; + } + return cursor.value; + } + } + } + /** + Select next occurrence of the current selection. Expand selection + to the surrounding word when the selection is empty. + */ + const selectNextOccurrence = ({ state, dispatch }) => { + let { ranges } = state.selection; + if (ranges.some(sel => sel.from === sel.to)) + return selectWord({ state, dispatch }); + let searchedText = state.sliceDoc(ranges[0].from, ranges[0].to); + if (state.selection.ranges.some(r => state.sliceDoc(r.from, r.to) != searchedText)) + return false; + let range = findNextOccurrence(state, searchedText); + if (!range) + return false; + dispatch(state.update({ + selection: state.selection.addRange(EditorSelection.range(range.from, range.to), false), + effects: EditorView.scrollIntoView(range.to) + })); + return true; + }; + + const searchConfigFacet = /*@__PURE__*/Facet.define({ + combine(configs) { + return combineConfig(configs, { + top: false, + caseSensitive: false, + literal: false, + wholeWord: false, + createPanel: view => new SearchPanel(view) + }); + } + }); + /** + A search query. Part of the editor's search state. + */ + class SearchQuery { + /** + Create a query object. + */ + constructor(config) { + this.search = config.search; + this.caseSensitive = !!config.caseSensitive; + this.literal = !!config.literal; + this.regexp = !!config.regexp; + this.replace = config.replace || ""; + this.valid = !!this.search && (!this.regexp || validRegExp(this.search)); + this.unquoted = this.literal ? this.search : this.search.replace(/\\([nrt\\])/g, (_, ch) => ch == "n" ? "\n" : ch == "r" ? "\r" : ch == "t" ? "\t" : "\\"); + this.wholeWord = !!config.wholeWord; + } + /** + Compare this query to another query. + */ + eq(other) { + return this.search == other.search && this.replace == other.replace && + this.caseSensitive == other.caseSensitive && this.regexp == other.regexp && + this.wholeWord == other.wholeWord; + } + /** + @internal + */ + create() { + return this.regexp ? new RegExpQuery(this) : new StringQuery(this); + } + /** + Get a search cursor for this query, searching through the given + range in the given state. + */ + getCursor(state, from = 0, to) { + let st = state.doc ? state : EditorState.create({ doc: state }); + if (to == null) + to = st.doc.length; + return this.regexp ? regexpCursor(this, st, from, to) : stringCursor(this, st, from, to); + } + } + class QueryType { + constructor(spec) { + this.spec = spec; + } + } + function stringCursor(spec, state, from, to) { + return new SearchCursor(state.doc, spec.unquoted, from, to, spec.caseSensitive ? undefined : x => x.toLowerCase(), spec.wholeWord ? stringWordTest(state.doc, state.charCategorizer(state.selection.main.head)) : undefined); + } + function stringWordTest(doc, categorizer) { + return (from, to, buf, bufPos) => { + if (bufPos > from || bufPos + buf.length < to) { + bufPos = Math.max(0, from - 2); + buf = doc.sliceString(bufPos, Math.min(doc.length, to + 2)); + } + return (categorizer(charBefore(buf, from - bufPos)) != CharCategory.Word || + categorizer(charAfter(buf, from - bufPos)) != CharCategory.Word) && + (categorizer(charAfter(buf, to - bufPos)) != CharCategory.Word || + categorizer(charBefore(buf, to - bufPos)) != CharCategory.Word); + }; + } + class StringQuery extends QueryType { + constructor(spec) { + super(spec); + } + nextMatch(state, curFrom, curTo) { + let cursor = stringCursor(this.spec, state, curTo, state.doc.length).nextOverlapping(); + if (cursor.done) + cursor = stringCursor(this.spec, state, 0, curFrom).nextOverlapping(); + return cursor.done ? null : cursor.value; + } + // Searching in reverse is, rather than implementing inverted search + // cursor, done by scanning chunk after chunk forward. + prevMatchInRange(state, from, to) { + for (let pos = to;;) { + let start = Math.max(from, pos - 10000 /* FindPrev.ChunkSize */ - this.spec.unquoted.length); + let cursor = stringCursor(this.spec, state, start, pos), range = null; + while (!cursor.nextOverlapping().done) + range = cursor.value; + if (range) + return range; + if (start == from) + return null; + pos -= 10000 /* FindPrev.ChunkSize */; + } + } + prevMatch(state, curFrom, curTo) { + return this.prevMatchInRange(state, 0, curFrom) || + this.prevMatchInRange(state, curTo, state.doc.length); + } + getReplacement(_result) { return this.spec.replace; } + matchAll(state, limit) { + let cursor = stringCursor(this.spec, state, 0, state.doc.length), ranges = []; + while (!cursor.next().done) { + if (ranges.length >= limit) + return null; + ranges.push(cursor.value); + } + return ranges; + } + highlight(state, from, to, add) { + let cursor = stringCursor(this.spec, state, Math.max(0, from - this.spec.unquoted.length), Math.min(to + this.spec.unquoted.length, state.doc.length)); + while (!cursor.next().done) + add(cursor.value.from, cursor.value.to); + } + } + function regexpCursor(spec, state, from, to) { + return new RegExpCursor(state.doc, spec.search, { + ignoreCase: !spec.caseSensitive, + test: spec.wholeWord ? regexpWordTest(state.charCategorizer(state.selection.main.head)) : undefined + }, from, to); + } + function charBefore(str, index) { + return str.slice(findClusterBreak(str, index, false), index); + } + function charAfter(str, index) { + return str.slice(index, findClusterBreak(str, index)); + } + function regexpWordTest(categorizer) { + return (_from, _to, match) => !match[0].length || + (categorizer(charBefore(match.input, match.index)) != CharCategory.Word || + categorizer(charAfter(match.input, match.index)) != CharCategory.Word) && + (categorizer(charAfter(match.input, match.index + match[0].length)) != CharCategory.Word || + categorizer(charBefore(match.input, match.index + match[0].length)) != CharCategory.Word); + } + class RegExpQuery extends QueryType { + nextMatch(state, curFrom, curTo) { + let cursor = regexpCursor(this.spec, state, curTo, state.doc.length).next(); + if (cursor.done) + cursor = regexpCursor(this.spec, state, 0, curFrom).next(); + return cursor.done ? null : cursor.value; + } + prevMatchInRange(state, from, to) { + for (let size = 1;; size++) { + let start = Math.max(from, to - size * 10000 /* FindPrev.ChunkSize */); + let cursor = regexpCursor(this.spec, state, start, to), range = null; + while (!cursor.next().done) + range = cursor.value; + if (range && (start == from || range.from > start + 10)) + return range; + if (start == from) + return null; + } + } + prevMatch(state, curFrom, curTo) { + return this.prevMatchInRange(state, 0, curFrom) || + this.prevMatchInRange(state, curTo, state.doc.length); + } + getReplacement(result) { + return this.spec.replace.replace(/\$([$&\d+])/g, (m, i) => i == "$" ? "$" + : i == "&" ? result.match[0] + : i != "0" && +i < result.match.length ? result.match[i] + : m); + } + matchAll(state, limit) { + let cursor = regexpCursor(this.spec, state, 0, state.doc.length), ranges = []; + while (!cursor.next().done) { + if (ranges.length >= limit) + return null; + ranges.push(cursor.value); + } + return ranges; + } + highlight(state, from, to, add) { + let cursor = regexpCursor(this.spec, state, Math.max(0, from - 250 /* RegExp.HighlightMargin */), Math.min(to + 250 /* RegExp.HighlightMargin */, state.doc.length)); + while (!cursor.next().done) + add(cursor.value.from, cursor.value.to); + } + } + /** + A state effect that updates the current search query. Note that + this only has an effect if the search state has been initialized + (by including [`search`](https://codemirror.net/6/docs/ref/#search.search) in your configuration or + by running [`openSearchPanel`](https://codemirror.net/6/docs/ref/#search.openSearchPanel) at least + once). + */ + const setSearchQuery = /*@__PURE__*/StateEffect.define(); + const togglePanel$1 = /*@__PURE__*/StateEffect.define(); + const searchState = /*@__PURE__*/StateField.define({ + create(state) { + return new SearchState(defaultQuery(state).create(), null); + }, + update(value, tr) { + for (let effect of tr.effects) { + if (effect.is(setSearchQuery)) + value = new SearchState(effect.value.create(), value.panel); + else if (effect.is(togglePanel$1)) + value = new SearchState(value.query, effect.value ? createSearchPanel : null); + } + return value; + }, + provide: f => showPanel.from(f, val => val.panel) + }); + class SearchState { + constructor(query, panel) { + this.query = query; + this.panel = panel; + } + } + const matchMark = /*@__PURE__*/Decoration.mark({ class: "cm-searchMatch" }), selectedMatchMark = /*@__PURE__*/Decoration.mark({ class: "cm-searchMatch cm-searchMatch-selected" }); + const searchHighlighter = /*@__PURE__*/ViewPlugin.fromClass(class { + constructor(view) { + this.view = view; + this.decorations = this.highlight(view.state.field(searchState)); + } + update(update) { + let state = update.state.field(searchState); + if (state != update.startState.field(searchState) || update.docChanged || update.selectionSet || update.viewportChanged) + this.decorations = this.highlight(state); + } + highlight({ query, panel }) { + if (!panel || !query.spec.valid) + return Decoration.none; + let { view } = this; + let builder = new RangeSetBuilder(); + for (let i = 0, ranges = view.visibleRanges, l = ranges.length; i < l; i++) { + let { from, to } = ranges[i]; + while (i < l - 1 && to > ranges[i + 1].from - 2 * 250 /* RegExp.HighlightMargin */) + to = ranges[++i].to; + query.highlight(view.state, from, to, (from, to) => { + let selected = view.state.selection.ranges.some(r => r.from == from && r.to == to); + builder.add(from, to, selected ? selectedMatchMark : matchMark); + }); + } + return builder.finish(); + } + }, { + decorations: v => v.decorations + }); + function searchCommand(f) { + return view => { + let state = view.state.field(searchState, false); + return state && state.query.spec.valid ? f(view, state) : openSearchPanel(view); + }; + } + /** + Open the search panel if it isn't already open, and move the + selection to the first match after the current main selection. + Will wrap around to the start of the document when it reaches the + end. + */ + const findNext = /*@__PURE__*/searchCommand((view, { query }) => { + let { to } = view.state.selection.main; + let next = query.nextMatch(view.state, to, to); + if (!next) + return false; + view.dispatch({ + selection: { anchor: next.from, head: next.to }, + scrollIntoView: true, + effects: announceMatch(view, next), + userEvent: "select.search" + }); + return true; + }); + /** + Move the selection to the previous instance of the search query, + before the current main selection. Will wrap past the start + of the document to start searching at the end again. + */ + const findPrevious = /*@__PURE__*/searchCommand((view, { query }) => { + let { state } = view, { from } = state.selection.main; + let range = query.prevMatch(state, from, from); + if (!range) + return false; + view.dispatch({ + selection: { anchor: range.from, head: range.to }, + scrollIntoView: true, + effects: announceMatch(view, range), + userEvent: "select.search" + }); + return true; + }); + /** + Select all instances of the search query. + */ + const selectMatches = /*@__PURE__*/searchCommand((view, { query }) => { + let ranges = query.matchAll(view.state, 1000); + if (!ranges || !ranges.length) + return false; + view.dispatch({ + selection: EditorSelection.create(ranges.map(r => EditorSelection.range(r.from, r.to))), + userEvent: "select.search.matches" + }); + return true; + }); + /** + Select all instances of the currently selected text. + */ + const selectSelectionMatches = ({ state, dispatch }) => { + let sel = state.selection; + if (sel.ranges.length > 1 || sel.main.empty) + return false; + let { from, to } = sel.main; + let ranges = [], main = 0; + for (let cur = new SearchCursor(state.doc, state.sliceDoc(from, to)); !cur.next().done;) { + if (ranges.length > 1000) + return false; + if (cur.value.from == from) + main = ranges.length; + ranges.push(EditorSelection.range(cur.value.from, cur.value.to)); + } + dispatch(state.update({ + selection: EditorSelection.create(ranges, main), + userEvent: "select.search.matches" + })); + return true; + }; + /** + Replace the current match of the search query. + */ + const replaceNext = /*@__PURE__*/searchCommand((view, { query }) => { + let { state } = view, { from, to } = state.selection.main; + if (state.readOnly) + return false; + let next = query.nextMatch(state, from, from); + if (!next) + return false; + let changes = [], selection, replacement; + let announce = []; + if (next.from == from && next.to == to) { + replacement = state.toText(query.getReplacement(next)); + changes.push({ from: next.from, to: next.to, insert: replacement }); + next = query.nextMatch(state, next.from, next.to); + announce.push(EditorView.announce.of(state.phrase("replaced match on line $", state.doc.lineAt(from).number) + ".")); + } + if (next) { + let off = changes.length == 0 || changes[0].from >= next.to ? 0 : next.to - next.from - replacement.length; + selection = { anchor: next.from - off, head: next.to - off }; + announce.push(announceMatch(view, next)); + } + view.dispatch({ + changes, selection, + scrollIntoView: !!selection, + effects: announce, + userEvent: "input.replace" + }); + return true; + }); + /** + Replace all instances of the search query with the given + replacement. + */ + const replaceAll = /*@__PURE__*/searchCommand((view, { query }) => { + if (view.state.readOnly) + return false; + let changes = query.matchAll(view.state, 1e9).map(match => { + let { from, to } = match; + return { from, to, insert: query.getReplacement(match) }; + }); + if (!changes.length) + return false; + let announceText = view.state.phrase("replaced $ matches", changes.length) + "."; + view.dispatch({ + changes, + effects: EditorView.announce.of(announceText), + userEvent: "input.replace.all" + }); + return true; + }); + function createSearchPanel(view) { + return view.state.facet(searchConfigFacet).createPanel(view); + } + function defaultQuery(state, fallback) { + var _a, _b, _c, _d; + let sel = state.selection.main; + let selText = sel.empty || sel.to > sel.from + 100 ? "" : state.sliceDoc(sel.from, sel.to); + if (fallback && !selText) + return fallback; + let config = state.facet(searchConfigFacet); + return new SearchQuery({ + search: ((_a = fallback === null || fallback === void 0 ? void 0 : fallback.literal) !== null && _a !== void 0 ? _a : config.literal) ? selText : selText.replace(/\n/g, "\\n"), + caseSensitive: (_b = fallback === null || fallback === void 0 ? void 0 : fallback.caseSensitive) !== null && _b !== void 0 ? _b : config.caseSensitive, + literal: (_c = fallback === null || fallback === void 0 ? void 0 : fallback.literal) !== null && _c !== void 0 ? _c : config.literal, + wholeWord: (_d = fallback === null || fallback === void 0 ? void 0 : fallback.wholeWord) !== null && _d !== void 0 ? _d : config.wholeWord + }); + } + /** + Make sure the search panel is open and focused. + */ + const openSearchPanel = view => { + let state = view.state.field(searchState, false); + if (state && state.panel) { + let panel = getPanel(view, createSearchPanel); + if (!panel) + return false; + let searchInput = panel.dom.querySelector("[main-field]"); + if (searchInput && searchInput != view.root.activeElement) { + let query = defaultQuery(view.state, state.query.spec); + if (query.valid) + view.dispatch({ effects: setSearchQuery.of(query) }); + searchInput.focus(); + searchInput.select(); + } + } + else { + view.dispatch({ effects: [ + togglePanel$1.of(true), + state ? setSearchQuery.of(defaultQuery(view.state, state.query.spec)) : StateEffect.appendConfig.of(searchExtensions) + ] }); + } + return true; + }; + /** + Close the search panel. + */ + const closeSearchPanel = view => { + let state = view.state.field(searchState, false); + if (!state || !state.panel) + return false; + let panel = getPanel(view, createSearchPanel); + if (panel && panel.dom.contains(view.root.activeElement)) + view.focus(); + view.dispatch({ effects: togglePanel$1.of(false) }); + return true; + }; + /** + Default search-related key bindings. + + - Mod-f: [`openSearchPanel`](https://codemirror.net/6/docs/ref/#search.openSearchPanel) + - F3, Mod-g: [`findNext`](https://codemirror.net/6/docs/ref/#search.findNext) + - Shift-F3, Shift-Mod-g: [`findPrevious`](https://codemirror.net/6/docs/ref/#search.findPrevious) + - Alt-g: [`gotoLine`](https://codemirror.net/6/docs/ref/#search.gotoLine) + - Mod-d: [`selectNextOccurrence`](https://codemirror.net/6/docs/ref/#search.selectNextOccurrence) + */ + const searchKeymap = [ + { key: "Mod-f", run: openSearchPanel, scope: "editor search-panel" }, + { key: "F3", run: findNext, shift: findPrevious, scope: "editor search-panel", preventDefault: true }, + { key: "Mod-g", run: findNext, shift: findPrevious, scope: "editor search-panel", preventDefault: true }, + { key: "Escape", run: closeSearchPanel, scope: "editor search-panel" }, + { key: "Mod-Shift-l", run: selectSelectionMatches }, + { key: "Alt-g", run: gotoLine }, + { key: "Mod-d", run: selectNextOccurrence, preventDefault: true }, + ]; + class SearchPanel { + constructor(view) { + this.view = view; + let query = this.query = view.state.field(searchState).query.spec; + this.commit = this.commit.bind(this); + this.searchField = crelt("input", { + value: query.search, + placeholder: phrase(view, "Find"), + "aria-label": phrase(view, "Find"), + class: "cm-textfield", + name: "search", + "main-field": "true", + onchange: this.commit, + onkeyup: this.commit + }); + this.replaceField = crelt("input", { + value: query.replace, + placeholder: phrase(view, "Replace"), + "aria-label": phrase(view, "Replace"), + class: "cm-textfield", + name: "replace", + onchange: this.commit, + onkeyup: this.commit + }); + this.caseField = crelt("input", { + type: "checkbox", + name: "case", + checked: query.caseSensitive, + onchange: this.commit + }); + this.reField = crelt("input", { + type: "checkbox", + name: "re", + checked: query.regexp, + onchange: this.commit + }); + this.wordField = crelt("input", { + type: "checkbox", + name: "word", + checked: query.wholeWord, + onchange: this.commit + }); + function button(name, onclick, content) { + return crelt("button", { class: "cm-button", name, onclick, type: "button" }, content); + } + this.dom = crelt("div", { onkeydown: (e) => this.keydown(e), class: "cm-search" }, [ + this.searchField, + button("next", () => findNext(view), [phrase(view, "next")]), + button("prev", () => findPrevious(view), [phrase(view, "previous")]), + button("select", () => selectMatches(view), [phrase(view, "all")]), + crelt("label", null, [this.caseField, phrase(view, "match case")]), + crelt("label", null, [this.reField, phrase(view, "regexp")]), + crelt("label", null, [this.wordField, phrase(view, "by word")]), + ...view.state.readOnly ? [] : [ + crelt("br"), + this.replaceField, + button("replace", () => replaceNext(view), [phrase(view, "replace")]), + button("replaceAll", () => replaceAll(view), [phrase(view, "replace all")]), + crelt("button", { + name: "close", + onclick: () => closeSearchPanel(view), + "aria-label": phrase(view, "close"), + type: "button" + }, ["×"]) + ] + ]); + } + commit() { + let query = new SearchQuery({ + search: this.searchField.value, + caseSensitive: this.caseField.checked, + regexp: this.reField.checked, + wholeWord: this.wordField.checked, + replace: this.replaceField.value, + }); + if (!query.eq(this.query)) { + this.query = query; + this.view.dispatch({ effects: setSearchQuery.of(query) }); + } + } + keydown(e) { + if (runScopeHandlers(this.view, e, "search-panel")) { + e.preventDefault(); + } + else if (e.keyCode == 13 && e.target == this.searchField) { + e.preventDefault(); + (e.shiftKey ? findPrevious : findNext)(this.view); + } + else if (e.keyCode == 13 && e.target == this.replaceField) { + e.preventDefault(); + replaceNext(this.view); + } + } + update(update) { + for (let tr of update.transactions) + for (let effect of tr.effects) { + if (effect.is(setSearchQuery) && !effect.value.eq(this.query)) + this.setQuery(effect.value); + } + } + setQuery(query) { + this.query = query; + this.searchField.value = query.search; + this.replaceField.value = query.replace; + this.caseField.checked = query.caseSensitive; + this.reField.checked = query.regexp; + this.wordField.checked = query.wholeWord; + } + mount() { + this.searchField.select(); + } + get pos() { return 80; } + get top() { return this.view.state.facet(searchConfigFacet).top; } + } + function phrase(view, phrase) { return view.state.phrase(phrase); } + const AnnounceMargin = 30; + const Break = /[\s\.,:;?!]/; + function announceMatch(view, { from, to }) { + let line = view.state.doc.lineAt(from), lineEnd = view.state.doc.lineAt(to).to; + let start = Math.max(line.from, from - AnnounceMargin), end = Math.min(lineEnd, to + AnnounceMargin); + let text = view.state.sliceDoc(start, end); + if (start != line.from) { + for (let i = 0; i < AnnounceMargin; i++) + if (!Break.test(text[i + 1]) && Break.test(text[i])) { + text = text.slice(i); + break; + } + } + if (end != lineEnd) { + for (let i = text.length - 1; i > text.length - AnnounceMargin; i--) + if (!Break.test(text[i - 1]) && Break.test(text[i])) { + text = text.slice(0, i); + break; + } + } + return EditorView.announce.of(`${view.state.phrase("current match")}. ${text} ${view.state.phrase("on line")} ${line.number}.`); + } + const baseTheme$2 = /*@__PURE__*/EditorView.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" } + }); + const searchExtensions = [ + searchState, + /*@__PURE__*/Prec.lowest(searchHighlighter), + baseTheme$2 + ]; + + /** + An instance of this is passed to completion source functions. + */ + class CompletionContext { + /** + Create a new completion context. (Mostly useful for testing + completion sources—in the editor, the extension will create + these for you.) + */ + constructor( + /** + The editor state that the completion happens in. + */ + state, + /** + The position at which the completion is happening. + */ + pos, + /** + Indicates whether completion was activated explicitly, or + implicitly by typing. The usual way to respond to this is to + only return completions when either there is part of a + completable entity before the cursor, or `explicit` is true. + */ + explicit) { + this.state = state; + this.pos = pos; + this.explicit = explicit; + /** + @internal + */ + this.abortListeners = []; + } + /** + Get the extent, content, and (if there is a token) type of the + token before `this.pos`. + */ + tokenBefore(types) { + let token = syntaxTree(this.state).resolveInner(this.pos, -1); + while (token && types.indexOf(token.name) < 0) + token = token.parent; + return token ? { from: token.from, to: this.pos, + text: this.state.sliceDoc(token.from, this.pos), + type: token.type } : null; + } + /** + Get the match of the given expression directly before the + cursor. + */ + matchBefore(expr) { + let line = this.state.doc.lineAt(this.pos); + let start = Math.max(line.from, this.pos - 250); + let str = line.text.slice(start - line.from, this.pos - line.from); + let found = str.search(ensureAnchor(expr, false)); + return found < 0 ? null : { from: start + found, to: this.pos, text: str.slice(found) }; + } + /** + Yields true when the query has been aborted. Can be useful in + asynchronous queries to avoid doing work that will be ignored. + */ + get aborted() { return this.abortListeners == null; } + /** + Allows you to register abort handlers, which will be called when + the query is + [aborted](https://codemirror.net/6/docs/ref/#autocomplete.CompletionContext.aborted). + */ + addEventListener(type, listener) { + if (type == "abort" && this.abortListeners) + this.abortListeners.push(listener); + } + } + function toSet(chars) { + let flat = Object.keys(chars).join(""); + let words = /\w/.test(flat); + if (words) + flat = flat.replace(/\w/g, ""); + return `[${words ? "\\w" : ""}${flat.replace(/[^\w\s]/g, "\\$&")}]`; + } + function prefixMatch(options) { + let first = Object.create(null), rest = Object.create(null); + for (let { label } of options) { + first[label[0]] = true; + for (let i = 1; i < label.length; i++) + rest[label[i]] = true; + } + let source = toSet(first) + toSet(rest) + "*$"; + return [new RegExp("^" + source), new RegExp(source)]; + } + /** + Given a a fixed array of options, return an autocompleter that + completes them. + */ + function completeFromList(list) { + let options = list.map(o => typeof o == "string" ? { label: o } : o); + let [validFor, match] = options.every(o => /^\w+$/.test(o.label)) ? [/\w*$/, /\w+$/] : prefixMatch(options); + return (context) => { + let token = context.matchBefore(match); + return token || context.explicit ? { from: token ? token.from : context.pos, options, validFor } : null; + }; + } + class Option { + constructor(completion, source, match) { + this.completion = completion; + this.source = source; + this.match = match; + } + } + function cur(state) { return state.selection.main.head; } + // Make sure the given regexp has a $ at its end and, if `start` is + // true, a ^ at its start. + function ensureAnchor(expr, start) { + var _a; + let { source } = expr; + let addStart = start && source[0] != "^", addEnd = source[source.length - 1] != "$"; + if (!addStart && !addEnd) + return expr; + return new RegExp(`${addStart ? "^" : ""}(?:${source})${addEnd ? "$" : ""}`, (_a = expr.flags) !== null && _a !== void 0 ? _a : (expr.ignoreCase ? "i" : "")); + } + /** + Helper function that returns a transaction spec which inserts a + completion's text in the main selection range, and any other + selection range that has the same text in front of it. + */ + function insertCompletionText(state, text, from, to) { + return Object.assign(Object.assign({}, state.changeByRange(range => { + if (range == state.selection.main) + return { + changes: { from: from, to: to, insert: text }, + range: EditorSelection.cursor(from + text.length) + }; + let len = to - from; + if (!range.empty || + len && state.sliceDoc(range.from - len, range.from) != state.sliceDoc(from, to)) + return { range }; + return { + changes: { from: range.from - len, to: range.from, insert: text }, + range: EditorSelection.cursor(range.from - len + text.length) + }; + })), { userEvent: "input.complete" }); + } + function applyCompletion(view, option) { + const apply = option.completion.apply || option.completion.label; + let result = option.source; + if (typeof apply == "string") + view.dispatch(insertCompletionText(view.state, apply, result.from, result.to)); + else + apply(view, option.completion, result.from, result.to); + } + const SourceCache = /*@__PURE__*/new WeakMap(); + function asSource(source) { + if (!Array.isArray(source)) + return source; + let known = SourceCache.get(source); + if (!known) + SourceCache.set(source, known = completeFromList(source)); + return known; + } + + // A pattern matcher for fuzzy completion matching. Create an instance + // once for a pattern, and then use that to match any number of + // completions. + class FuzzyMatcher { + constructor(pattern) { + this.pattern = pattern; + this.chars = []; + this.folded = []; + // Buffers reused by calls to `match` to track matched character + // positions. + this.any = []; + this.precise = []; + this.byWord = []; + for (let p = 0; p < pattern.length;) { + let char = codePointAt(pattern, p), size = codePointSize(char); + this.chars.push(char); + let part = pattern.slice(p, p + size), upper = part.toUpperCase(); + this.folded.push(codePointAt(upper == part ? part.toLowerCase() : upper, 0)); + p += size; + } + this.astral = pattern.length != this.chars.length; + } + // Matches a given word (completion) against the pattern (input). + // Will return null for no match, and otherwise an array that starts + // with the match score, followed by any number of `from, to` pairs + // indicating the matched parts of `word`. + // + // The score is a number that is more negative the worse the match + // is. See `Penalty` above. + match(word) { + if (this.pattern.length == 0) + return [0]; + if (word.length < this.pattern.length) + return null; + let { chars, folded, any, precise, byWord } = this; + // For single-character queries, only match when they occur right + // at the start + if (chars.length == 1) { + let first = codePointAt(word, 0); + return first == chars[0] ? [0, 0, codePointSize(first)] + : first == folded[0] ? [-200 /* Penalty.CaseFold */, 0, codePointSize(first)] : null; + } + let direct = word.indexOf(this.pattern); + if (direct == 0) + return [0, 0, this.pattern.length]; + let len = chars.length, anyTo = 0; + if (direct < 0) { + for (let i = 0, e = Math.min(word.length, 200); i < e && anyTo < len;) { + let next = codePointAt(word, i); + if (next == chars[anyTo] || next == folded[anyTo]) + any[anyTo++] = i; + i += codePointSize(next); + } + // No match, exit immediately + if (anyTo < len) + return null; + } + // This tracks the extent of the precise (non-folded, not + // necessarily adjacent) match + let preciseTo = 0; + // Tracks whether there is a match that hits only characters that + // appear to be starting words. `byWordFolded` is set to true when + // a case folded character is encountered in such a match + let byWordTo = 0, byWordFolded = false; + // If we've found a partial adjacent match, these track its state + let adjacentTo = 0, adjacentStart = -1, adjacentEnd = -1; + let hasLower = /[a-z]/.test(word), wordAdjacent = true; + // Go over the option's text, scanning for the various kinds of matches + for (let i = 0, e = Math.min(word.length, 200), prevType = 0 /* Tp.NonWord */; i < e && byWordTo < len;) { + let next = codePointAt(word, i); + if (direct < 0) { + if (preciseTo < len && next == chars[preciseTo]) + precise[preciseTo++] = i; + if (adjacentTo < len) { + if (next == chars[adjacentTo] || next == folded[adjacentTo]) { + if (adjacentTo == 0) + adjacentStart = i; + adjacentEnd = i + 1; + adjacentTo++; + } + else { + adjacentTo = 0; + } + } + } + let ch, type = next < 0xff + ? (next >= 48 && next <= 57 || next >= 97 && next <= 122 ? 2 /* Tp.Lower */ : next >= 65 && next <= 90 ? 1 /* Tp.Upper */ : 0 /* Tp.NonWord */) + : ((ch = fromCodePoint(next)) != ch.toLowerCase() ? 1 /* Tp.Upper */ : ch != ch.toUpperCase() ? 2 /* Tp.Lower */ : 0 /* Tp.NonWord */); + if (!i || type == 1 /* Tp.Upper */ && hasLower || prevType == 0 /* Tp.NonWord */ && type != 0 /* Tp.NonWord */) { + if (chars[byWordTo] == next || (folded[byWordTo] == next && (byWordFolded = true))) + byWord[byWordTo++] = i; + else if (byWord.length) + wordAdjacent = false; + } + prevType = type; + i += codePointSize(next); + } + if (byWordTo == len && byWord[0] == 0 && wordAdjacent) + return this.result(-100 /* Penalty.ByWord */ + (byWordFolded ? -200 /* Penalty.CaseFold */ : 0), byWord, word); + if (adjacentTo == len && adjacentStart == 0) + return [-200 /* Penalty.CaseFold */ - word.length, 0, adjacentEnd]; + if (direct > -1) + return [-700 /* Penalty.NotStart */ - word.length, direct, direct + this.pattern.length]; + if (adjacentTo == len) + return [-200 /* Penalty.CaseFold */ + -700 /* Penalty.NotStart */ - word.length, adjacentStart, adjacentEnd]; + if (byWordTo == len) + return this.result(-100 /* Penalty.ByWord */ + (byWordFolded ? -200 /* Penalty.CaseFold */ : 0) + -700 /* Penalty.NotStart */ + + (wordAdjacent ? 0 : -1100 /* Penalty.Gap */), byWord, word); + return chars.length == 2 ? null : this.result((any[0] ? -700 /* Penalty.NotStart */ : 0) + -200 /* Penalty.CaseFold */ + -1100 /* Penalty.Gap */, any, word); + } + result(score, positions, word) { + let result = [score - word.length], i = 1; + for (let pos of positions) { + let to = pos + (this.astral ? codePointSize(codePointAt(word, pos)) : 1); + if (i > 1 && result[i - 1] == pos) + result[i - 1] = to; + else { + result[i++] = pos; + result[i++] = to; + } + } + return result; + } + } + + const completionConfig = /*@__PURE__*/Facet.define({ + combine(configs) { + return combineConfig(configs, { + activateOnTyping: true, + selectOnOpen: true, + override: null, + closeOnBlur: true, + maxRenderedOptions: 100, + defaultKeymap: true, + optionClass: () => "", + aboveCursor: false, + icons: true, + addToOptions: [], + compareCompletions: (a, b) => a.label.localeCompare(b.label), + interactionDelay: 75 + }, { + defaultKeymap: (a, b) => a && b, + closeOnBlur: (a, b) => a && b, + icons: (a, b) => a && b, + optionClass: (a, b) => c => joinClass(a(c), b(c)), + addToOptions: (a, b) => a.concat(b) + }); + } + }); + function joinClass(a, b) { + return a ? b ? a + " " + b : a : b; + } + + function optionContent(config) { + let content = config.addToOptions.slice(); + if (config.icons) + content.push({ + render(completion) { + let icon = document.createElement("div"); + icon.classList.add("cm-completionIcon"); + if (completion.type) + icon.classList.add(...completion.type.split(/\s+/g).map(cls => "cm-completionIcon-" + cls)); + icon.setAttribute("aria-hidden", "true"); + return icon; + }, + position: 20 + }); + content.push({ + render(completion, _s, match) { + let labelElt = document.createElement("span"); + labelElt.className = "cm-completionLabel"; + let { label } = completion, off = 0; + for (let j = 1; j < match.length;) { + let from = match[j++], to = match[j++]; + if (from > off) + labelElt.appendChild(document.createTextNode(label.slice(off, from))); + let span = labelElt.appendChild(document.createElement("span")); + span.appendChild(document.createTextNode(label.slice(from, to))); + span.className = "cm-completionMatchedText"; + off = to; + } + if (off < label.length) + labelElt.appendChild(document.createTextNode(label.slice(off))); + return labelElt; + }, + position: 50 + }, { + render(completion) { + if (!completion.detail) + return null; + let detailElt = document.createElement("span"); + detailElt.className = "cm-completionDetail"; + detailElt.textContent = completion.detail; + return detailElt; + }, + position: 80 + }); + return content.sort((a, b) => a.position - b.position).map(a => a.render); + } + function rangeAroundSelected(total, selected, max) { + if (total <= max) + return { from: 0, to: total }; + if (selected < 0) + selected = 0; + if (selected <= (total >> 1)) { + let off = Math.floor(selected / max); + return { from: off * max, to: (off + 1) * max }; + } + let off = Math.floor((total - selected) / max); + return { from: total - (off + 1) * max, to: total - off * max }; + } + class CompletionTooltip { + constructor(view, stateField) { + this.view = view; + this.stateField = stateField; + this.info = null; + this.placeInfo = { + read: () => this.measureInfo(), + write: (pos) => this.positionInfo(pos), + key: this + }; + let cState = view.state.field(stateField); + let { options, selected } = cState.open; + let config = view.state.facet(completionConfig); + this.optionContent = optionContent(config); + this.optionClass = config.optionClass; + this.range = rangeAroundSelected(options.length, selected, config.maxRenderedOptions); + this.dom = document.createElement("div"); + this.dom.className = "cm-tooltip-autocomplete"; + this.dom.addEventListener("mousedown", (e) => { + for (let dom = e.target, match; dom && dom != this.dom; dom = dom.parentNode) { + if (dom.nodeName == "LI" && (match = /-(\d+)$/.exec(dom.id)) && +match[1] < options.length) { + applyCompletion(view, options[+match[1]]); + e.preventDefault(); + return; + } + } + }); + this.list = this.dom.appendChild(this.createListBox(options, cState.id, this.range)); + this.list.addEventListener("scroll", () => { + if (this.info) + this.view.requestMeasure(this.placeInfo); + }); + } + mount() { this.updateSel(); } + update(update) { + if (update.state.field(this.stateField) != update.startState.field(this.stateField)) + this.updateSel(); + } + positioned() { + if (this.info) + this.view.requestMeasure(this.placeInfo); + } + updateSel() { + let cState = this.view.state.field(this.stateField), open = cState.open; + if (open.selected > -1 && open.selected < this.range.from || open.selected >= this.range.to) { + this.range = rangeAroundSelected(open.options.length, open.selected, this.view.state.facet(completionConfig).maxRenderedOptions); + this.list.remove(); + this.list = this.dom.appendChild(this.createListBox(open.options, cState.id, this.range)); + this.list.addEventListener("scroll", () => { + if (this.info) + this.view.requestMeasure(this.placeInfo); + }); + } + if (this.updateSelectedOption(open.selected)) { + if (this.info) { + this.info.remove(); + this.info = null; + } + let { completion } = open.options[open.selected]; + let { info } = completion; + if (!info) + return; + let infoResult = typeof info === 'string' ? document.createTextNode(info) : info(completion); + if (!infoResult) + return; + if ('then' in infoResult) { + infoResult.then(node => { + if (node && this.view.state.field(this.stateField, false) == cState) + this.addInfoPane(node); + }).catch(e => logException(this.view.state, e, "completion info")); + } + else { + this.addInfoPane(infoResult); + } + } + } + addInfoPane(content) { + let dom = this.info = document.createElement("div"); + dom.className = "cm-tooltip cm-completionInfo"; + dom.appendChild(content); + this.dom.appendChild(dom); + this.view.requestMeasure(this.placeInfo); + } + updateSelectedOption(selected) { + let set = null; + for (let opt = this.list.firstChild, i = this.range.from; opt; opt = opt.nextSibling, i++) { + if (i == selected) { + if (!opt.hasAttribute("aria-selected")) { + opt.setAttribute("aria-selected", "true"); + set = opt; + } + } + else { + if (opt.hasAttribute("aria-selected")) + opt.removeAttribute("aria-selected"); + } + } + if (set) + scrollIntoView(this.list, set); + return set; + } + measureInfo() { + let sel = this.dom.querySelector("[aria-selected]"); + if (!sel || !this.info) + return null; + let win = this.dom.ownerDocument.defaultView || window; + let listRect = this.dom.getBoundingClientRect(); + let infoRect = this.info.getBoundingClientRect(); + let selRect = sel.getBoundingClientRect(); + if (selRect.top > Math.min(win.innerHeight, listRect.bottom) - 10 || selRect.bottom < Math.max(0, listRect.top) + 10) + return null; + let rtl = this.view.textDirection == Direction.RTL, left = rtl, narrow = false, maxWidth; + let top = "", bottom = ""; + let spaceLeft = listRect.left, spaceRight = win.innerWidth - listRect.right; + if (left && spaceLeft < Math.min(infoRect.width, spaceRight)) + left = false; + else if (!left && spaceRight < Math.min(infoRect.width, spaceLeft)) + left = true; + if (infoRect.width <= (left ? spaceLeft : spaceRight)) { + top = (Math.max(0, Math.min(selRect.top, win.innerHeight - infoRect.height)) - listRect.top) + "px"; + maxWidth = Math.min(400 /* Info.Width */, left ? spaceLeft : spaceRight) + "px"; + } + else { + narrow = true; + maxWidth = Math.min(400 /* Info.Width */, (rtl ? listRect.right : win.innerWidth - listRect.left) - 30 /* Info.Margin */) + "px"; + let spaceBelow = win.innerHeight - listRect.bottom; + if (spaceBelow >= infoRect.height || spaceBelow > listRect.top) // Below the completion + top = (selRect.bottom - listRect.top) + "px"; + else // Above it + bottom = (listRect.bottom - selRect.top) + "px"; + } + return { + top, bottom, maxWidth, + class: narrow ? (rtl ? "left-narrow" : "right-narrow") : left ? "left" : "right", + }; + } + positionInfo(pos) { + if (this.info) { + if (pos) { + this.info.style.top = pos.top; + this.info.style.bottom = pos.bottom; + this.info.style.maxWidth = pos.maxWidth; + this.info.className = "cm-tooltip cm-completionInfo cm-completionInfo-" + pos.class; + } + else { + this.info.style.top = "-1e6px"; + } + } + } + createListBox(options, id, range) { + const ul = document.createElement("ul"); + ul.id = id; + ul.setAttribute("role", "listbox"); + ul.setAttribute("aria-expanded", "true"); + ul.setAttribute("aria-label", this.view.state.phrase("Completions")); + for (let i = range.from; i < range.to; i++) { + let { completion, match } = options[i]; + const li = ul.appendChild(document.createElement("li")); + li.id = id + "-" + i; + li.setAttribute("role", "option"); + let cls = this.optionClass(completion); + if (cls) + li.className = cls; + for (let source of this.optionContent) { + let node = source(completion, this.view.state, match); + if (node) + li.appendChild(node); + } + } + if (range.from) + ul.classList.add("cm-completionListIncompleteTop"); + if (range.to < options.length) + ul.classList.add("cm-completionListIncompleteBottom"); + return ul; + } + } + // We allocate a new function instance every time the completion + // changes to force redrawing/repositioning of the tooltip + function completionTooltip(stateField) { + return (view) => new CompletionTooltip(view, stateField); + } + function scrollIntoView(container, element) { + let parent = container.getBoundingClientRect(); + let self = element.getBoundingClientRect(); + if (self.top < parent.top) + container.scrollTop -= parent.top - self.top; + else if (self.bottom > parent.bottom) + container.scrollTop += self.bottom - parent.bottom; + } + + // Used to pick a preferred option when two options with the same + // label occur in the result. + function score(option) { + return (option.boost || 0) * 100 + (option.apply ? 10 : 0) + (option.info ? 5 : 0) + + (option.type ? 1 : 0); + } + function sortOptions(active, state) { + let options = [], i = 0; + for (let a of active) + if (a.hasResult()) { + if (a.result.filter === false) { + let getMatch = a.result.getMatch; + for (let option of a.result.options) { + let match = [1e9 - i++]; + if (getMatch) + for (let n of getMatch(option)) + match.push(n); + options.push(new Option(option, a, match)); + } + } + else { + let matcher = new FuzzyMatcher(state.sliceDoc(a.from, a.to)), match; + for (let option of a.result.options) + if (match = matcher.match(option.label)) { + if (option.boost != null) + match[0] += option.boost; + options.push(new Option(option, a, match)); + } + } + } + let result = [], prev = null; + let compare = state.facet(completionConfig).compareCompletions; + for (let opt of options.sort((a, b) => (b.match[0] - a.match[0]) || compare(a.completion, b.completion))) { + if (!prev || prev.label != opt.completion.label || prev.detail != opt.completion.detail || + (prev.type != null && opt.completion.type != null && prev.type != opt.completion.type) || + prev.apply != opt.completion.apply) + result.push(opt); + else if (score(opt.completion) > score(prev)) + result[result.length - 1] = opt; + prev = opt.completion; + } + return result; + } + class CompletionDialog { + constructor(options, attrs, tooltip, timestamp, selected) { + this.options = options; + this.attrs = attrs; + this.tooltip = tooltip; + this.timestamp = timestamp; + this.selected = selected; + } + setSelected(selected, id) { + return selected == this.selected || selected >= this.options.length ? this + : new CompletionDialog(this.options, makeAttrs(id, selected), this.tooltip, this.timestamp, selected); + } + static build(active, state, id, prev, conf) { + let options = sortOptions(active, state); + if (!options.length) + return null; + let selected = state.facet(completionConfig).selectOnOpen ? 0 : -1; + if (prev && prev.selected != selected && prev.selected != -1) { + let selectedValue = prev.options[prev.selected].completion; + for (let i = 0; i < options.length; i++) + if (options[i].completion == selectedValue) { + selected = i; + break; + } + } + return new CompletionDialog(options, makeAttrs(id, selected), { + pos: active.reduce((a, b) => b.hasResult() ? Math.min(a, b.from) : a, 1e8), + create: completionTooltip(completionState), + above: conf.aboveCursor, + }, prev ? prev.timestamp : Date.now(), selected); + } + map(changes) { + return new CompletionDialog(this.options, this.attrs, Object.assign(Object.assign({}, this.tooltip), { pos: changes.mapPos(this.tooltip.pos) }), this.timestamp, this.selected); + } + } + class CompletionState { + constructor(active, id, open) { + this.active = active; + this.id = id; + this.open = open; + } + static start() { + return new CompletionState(none, "cm-ac-" + Math.floor(Math.random() * 2e6).toString(36), null); + } + update(tr) { + let { state } = tr, conf = state.facet(completionConfig); + let sources = conf.override || + state.languageDataAt("autocomplete", cur(state)).map(asSource); + let active = sources.map(source => { + let value = this.active.find(s => s.source == source) || + new ActiveSource(source, this.active.some(a => a.state != 0 /* State.Inactive */) ? 1 /* State.Pending */ : 0 /* State.Inactive */); + return value.update(tr, conf); + }); + if (active.length == this.active.length && active.every((a, i) => a == this.active[i])) + active = this.active; + let open = tr.selection || active.some(a => a.hasResult() && tr.changes.touchesRange(a.from, a.to)) || + !sameResults(active, this.active) ? CompletionDialog.build(active, state, this.id, this.open, conf) + : this.open && tr.docChanged ? this.open.map(tr.changes) : this.open; + if (!open && active.every(a => a.state != 1 /* State.Pending */) && active.some(a => a.hasResult())) + active = active.map(a => a.hasResult() ? new ActiveSource(a.source, 0 /* State.Inactive */) : a); + for (let effect of tr.effects) + if (effect.is(setSelectedEffect)) + open = open && open.setSelected(effect.value, this.id); + return active == this.active && open == this.open ? this : new CompletionState(active, this.id, open); + } + get tooltip() { return this.open ? this.open.tooltip : null; } + get attrs() { return this.open ? this.open.attrs : baseAttrs; } + } + function sameResults(a, b) { + if (a == b) + return true; + for (let iA = 0, iB = 0;;) { + while (iA < a.length && !a[iA].hasResult) + iA++; + while (iB < b.length && !b[iB].hasResult) + iB++; + let endA = iA == a.length, endB = iB == b.length; + if (endA || endB) + return endA == endB; + if (a[iA++].result != b[iB++].result) + return false; + } + } + const baseAttrs = { + "aria-autocomplete": "list" + }; + function makeAttrs(id, selected) { + let result = { + "aria-autocomplete": "list", + "aria-haspopup": "listbox", + "aria-controls": id + }; + if (selected > -1) + result["aria-activedescendant"] = id + "-" + selected; + return result; + } + const none = []; + function getUserEvent(tr) { + return tr.isUserEvent("input.type") ? "input" : tr.isUserEvent("delete.backward") ? "delete" : null; + } + class ActiveSource { + constructor(source, state, explicitPos = -1) { + this.source = source; + this.state = state; + this.explicitPos = explicitPos; + } + hasResult() { return false; } + update(tr, conf) { + let event = getUserEvent(tr), value = this; + if (event) + value = value.handleUserEvent(tr, event, conf); + else if (tr.docChanged) + value = value.handleChange(tr); + else if (tr.selection && value.state != 0 /* State.Inactive */) + value = new ActiveSource(value.source, 0 /* State.Inactive */); + for (let effect of tr.effects) { + if (effect.is(startCompletionEffect)) + value = new ActiveSource(value.source, 1 /* State.Pending */, effect.value ? cur(tr.state) : -1); + else if (effect.is(closeCompletionEffect)) + value = new ActiveSource(value.source, 0 /* State.Inactive */); + else if (effect.is(setActiveEffect)) + for (let active of effect.value) + if (active.source == value.source) + value = active; + } + return value; + } + handleUserEvent(tr, type, conf) { + return type == "delete" || !conf.activateOnTyping ? this.map(tr.changes) : new ActiveSource(this.source, 1 /* State.Pending */); + } + handleChange(tr) { + return tr.changes.touchesRange(cur(tr.startState)) ? new ActiveSource(this.source, 0 /* State.Inactive */) : this.map(tr.changes); + } + map(changes) { + return changes.empty || this.explicitPos < 0 ? this : new ActiveSource(this.source, this.state, changes.mapPos(this.explicitPos)); + } + } + class ActiveResult extends ActiveSource { + constructor(source, explicitPos, result, from, to) { + super(source, 2 /* State.Result */, explicitPos); + this.result = result; + this.from = from; + this.to = to; + } + hasResult() { return true; } + handleUserEvent(tr, type, conf) { + var _a; + let from = tr.changes.mapPos(this.from), to = tr.changes.mapPos(this.to, 1); + let pos = cur(tr.state); + if ((this.explicitPos < 0 ? pos <= from : pos < this.from) || + pos > to || + type == "delete" && cur(tr.startState) == this.from) + return new ActiveSource(this.source, type == "input" && conf.activateOnTyping ? 1 /* State.Pending */ : 0 /* State.Inactive */); + let explicitPos = this.explicitPos < 0 ? -1 : tr.changes.mapPos(this.explicitPos), updated; + if (checkValid(this.result.validFor, tr.state, from, to)) + return new ActiveResult(this.source, explicitPos, this.result, from, to); + if (this.result.update && + (updated = this.result.update(this.result, from, to, new CompletionContext(tr.state, pos, explicitPos >= 0)))) + return new ActiveResult(this.source, explicitPos, updated, updated.from, (_a = updated.to) !== null && _a !== void 0 ? _a : cur(tr.state)); + return new ActiveSource(this.source, 1 /* State.Pending */, explicitPos); + } + handleChange(tr) { + return tr.changes.touchesRange(this.from, this.to) ? new ActiveSource(this.source, 0 /* State.Inactive */) : this.map(tr.changes); + } + map(mapping) { + return mapping.empty ? this : + new ActiveResult(this.source, this.explicitPos < 0 ? -1 : mapping.mapPos(this.explicitPos), this.result, mapping.mapPos(this.from), mapping.mapPos(this.to, 1)); + } + } + function checkValid(validFor, state, from, to) { + if (!validFor) + return false; + let text = state.sliceDoc(from, to); + return typeof validFor == "function" ? validFor(text, from, to, state) : ensureAnchor(validFor, true).test(text); + } + const startCompletionEffect = /*@__PURE__*/StateEffect.define(); + const closeCompletionEffect = /*@__PURE__*/StateEffect.define(); + const setActiveEffect = /*@__PURE__*/StateEffect.define({ + map(sources, mapping) { return sources.map(s => s.map(mapping)); } + }); + const setSelectedEffect = /*@__PURE__*/StateEffect.define(); + const completionState = /*@__PURE__*/StateField.define({ + create() { return CompletionState.start(); }, + update(value, tr) { return value.update(tr); }, + provide: f => [ + showTooltip.from(f, val => val.tooltip), + EditorView.contentAttributes.from(f, state => state.attrs) + ] + }); + + /** + Returns a command that moves the completion selection forward or + backward by the given amount. + */ + function moveCompletionSelection(forward, by = "option") { + return (view) => { + let cState = view.state.field(completionState, false); + if (!cState || !cState.open || + Date.now() - cState.open.timestamp < view.state.facet(completionConfig).interactionDelay) + return false; + let step = 1, tooltip; + if (by == "page" && (tooltip = getTooltip(view, cState.open.tooltip))) + step = Math.max(2, Math.floor(tooltip.dom.offsetHeight / + tooltip.dom.querySelector("li").offsetHeight) - 1); + let { length } = cState.open.options; + let selected = cState.open.selected > -1 ? cState.open.selected + step * (forward ? 1 : -1) : forward ? 0 : length - 1; + if (selected < 0) + selected = by == "page" ? 0 : length - 1; + else if (selected >= length) + selected = by == "page" ? length - 1 : 0; + view.dispatch({ effects: setSelectedEffect.of(selected) }); + return true; + }; + } + /** + Accept the current completion. + */ + const acceptCompletion = (view) => { + let cState = view.state.field(completionState, false); + if (view.state.readOnly || !cState || !cState.open || cState.open.selected < 0 || + Date.now() - cState.open.timestamp < view.state.facet(completionConfig).interactionDelay) + return false; + applyCompletion(view, cState.open.options[cState.open.selected]); + return true; + }; + /** + Explicitly start autocompletion. + */ + const startCompletion = (view) => { + let cState = view.state.field(completionState, false); + if (!cState) + return false; + view.dispatch({ effects: startCompletionEffect.of(true) }); + return true; + }; + /** + Close the currently active completion. + */ + const closeCompletion = (view) => { + let cState = view.state.field(completionState, false); + if (!cState || !cState.active.some(a => a.state != 0 /* State.Inactive */)) + return false; + view.dispatch({ effects: closeCompletionEffect.of(null) }); + return true; + }; + class RunningQuery { + constructor(active, context) { + this.active = active; + this.context = context; + this.time = Date.now(); + this.updates = []; + // Note that 'undefined' means 'not done yet', whereas 'null' means + // 'query returned null'. + this.done = undefined; + } + } + const DebounceTime = 50, MaxUpdateCount = 50, MinAbortTime = 1000; + const completionPlugin = /*@__PURE__*/ViewPlugin.fromClass(class { + constructor(view) { + this.view = view; + this.debounceUpdate = -1; + this.running = []; + this.debounceAccept = -1; + this.composing = 0 /* CompositionState.None */; + for (let active of view.state.field(completionState).active) + if (active.state == 1 /* State.Pending */) + this.startQuery(active); + } + update(update) { + let cState = update.state.field(completionState); + if (!update.selectionSet && !update.docChanged && update.startState.field(completionState) == cState) + return; + let doesReset = update.transactions.some(tr => { + return (tr.selection || tr.docChanged) && !getUserEvent(tr); + }); + for (let i = 0; i < this.running.length; i++) { + let query = this.running[i]; + if (doesReset || + query.updates.length + update.transactions.length > MaxUpdateCount && Date.now() - query.time > MinAbortTime) { + for (let handler of query.context.abortListeners) { + try { + handler(); + } + catch (e) { + logException(this.view.state, e); + } + } + query.context.abortListeners = null; + this.running.splice(i--, 1); + } + else { + query.updates.push(...update.transactions); + } + } + if (this.debounceUpdate > -1) + clearTimeout(this.debounceUpdate); + this.debounceUpdate = cState.active.some(a => a.state == 1 /* State.Pending */ && !this.running.some(q => q.active.source == a.source)) + ? setTimeout(() => this.startUpdate(), DebounceTime) : -1; + if (this.composing != 0 /* CompositionState.None */) + for (let tr of update.transactions) { + if (getUserEvent(tr) == "input") + this.composing = 2 /* CompositionState.Changed */; + else if (this.composing == 2 /* CompositionState.Changed */ && tr.selection) + this.composing = 3 /* CompositionState.ChangedAndMoved */; + } + } + startUpdate() { + this.debounceUpdate = -1; + let { state } = this.view, cState = state.field(completionState); + for (let active of cState.active) { + if (active.state == 1 /* State.Pending */ && !this.running.some(r => r.active.source == active.source)) + this.startQuery(active); + } + } + startQuery(active) { + let { state } = this.view, pos = cur(state); + let context = new CompletionContext(state, pos, active.explicitPos == pos); + let pending = new RunningQuery(active, context); + this.running.push(pending); + Promise.resolve(active.source(context)).then(result => { + if (!pending.context.aborted) { + pending.done = result || null; + this.scheduleAccept(); + } + }, err => { + this.view.dispatch({ effects: closeCompletionEffect.of(null) }); + logException(this.view.state, err); + }); + } + scheduleAccept() { + if (this.running.every(q => q.done !== undefined)) + this.accept(); + else if (this.debounceAccept < 0) + this.debounceAccept = setTimeout(() => this.accept(), DebounceTime); + } + // For each finished query in this.running, try to create a result + // or, if appropriate, restart the query. + accept() { + var _a; + if (this.debounceAccept > -1) + clearTimeout(this.debounceAccept); + this.debounceAccept = -1; + let updated = []; + let conf = this.view.state.facet(completionConfig); + for (let i = 0; i < this.running.length; i++) { + let query = this.running[i]; + if (query.done === undefined) + continue; + this.running.splice(i--, 1); + if (query.done) { + let active = new ActiveResult(query.active.source, query.active.explicitPos, query.done, query.done.from, (_a = query.done.to) !== null && _a !== void 0 ? _a : cur(query.updates.length ? query.updates[0].startState : this.view.state)); + // Replay the transactions that happened since the start of + // the request and see if that preserves the result + for (let tr of query.updates) + active = active.update(tr, conf); + if (active.hasResult()) { + updated.push(active); + continue; + } + } + let current = this.view.state.field(completionState).active.find(a => a.source == query.active.source); + if (current && current.state == 1 /* State.Pending */) { + if (query.done == null) { + // Explicitly failed. Should clear the pending status if it + // hasn't been re-set in the meantime. + let active = new ActiveSource(query.active.source, 0 /* State.Inactive */); + for (let tr of query.updates) + active = active.update(tr, conf); + if (active.state != 1 /* State.Pending */) + updated.push(active); + } + else { + // Cleared by subsequent transactions. Restart. + this.startQuery(current); + } + } + } + if (updated.length) + this.view.dispatch({ effects: setActiveEffect.of(updated) }); + } + }, { + eventHandlers: { + blur() { + let state = this.view.state.field(completionState, false); + if (state && state.tooltip && this.view.state.facet(completionConfig).closeOnBlur) + this.view.dispatch({ effects: closeCompletionEffect.of(null) }); + }, + compositionstart() { + this.composing = 1 /* CompositionState.Started */; + }, + compositionend() { + if (this.composing == 3 /* CompositionState.ChangedAndMoved */) { + // Safari fires compositionend events synchronously, possibly + // from inside an update, so dispatch asynchronously to avoid reentrancy + setTimeout(() => this.view.dispatch({ effects: startCompletionEffect.of(false) }), 20); + } + this.composing = 0 /* CompositionState.None */; + } + } + }); + + const baseTheme$1 = /*@__PURE__*/EditorView.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", + listStyle: "none", + margin: 0, + padding: 0, + "& > li": { + overflowX: "hidden", + textOverflow: "ellipsis", + cursor: "pointer", + padding: "1px 3px", + lineHeight: 1.2 + }, + } + }, + "&light .cm-tooltip-autocomplete ul li[aria-selected]": { + background: "#17c", + color: "white", + }, + "&dark .cm-tooltip-autocomplete ul li[aria-selected]": { + background: "#347", + color: "white", + }, + ".cm-completionListIncompleteTop:before, .cm-completionListIncompleteBottom:after": { + content: '"···"', + opacity: 0.5, + display: "block", + textAlign: "center" + }, + ".cm-tooltip.cm-completionInfo": { + position: "absolute", + padding: "3px 9px", + width: "max-content", + maxWidth: `${400 /* Info.Width */}px`, + boxSizing: "border-box" + }, + ".cm-completionInfo.cm-completionInfo-left": { right: "100%" }, + ".cm-completionInfo.cm-completionInfo-right": { left: "100%" }, + ".cm-completionInfo.cm-completionInfo-left-narrow": { right: `${30 /* Info.Margin */}px` }, + ".cm-completionInfo.cm-completionInfo-right-narrow": { left: `${30 /* Info.Margin */}px` }, + "&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" + }, + ".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: "'🔑\uFE0E'" } // Disable emoji rendering + }, + ".cm-completionIcon-namespace": { + "&:after": { content: "'▢'" } + }, + ".cm-completionIcon-text": { + "&:after": { content: "'abc'", fontSize: "50%", verticalAlign: "middle" } + } + }); + + const defaults = { + brackets: ["(", "[", "{", "'", '"'], + before: ")]}:;>", + stringPrefixes: [] + }; + const closeBracketEffect = /*@__PURE__*/StateEffect.define({ + map(value, mapping) { + let mapped = mapping.mapPos(value, -1, MapMode.TrackAfter); + return mapped == null ? undefined : mapped; + } + }); + const skipBracketEffect = /*@__PURE__*/StateEffect.define({ + map(value, mapping) { return mapping.mapPos(value); } + }); + const closedBracket = /*@__PURE__*/new class extends RangeValue { + }; + closedBracket.startSide = 1; + closedBracket.endSide = -1; + const bracketState = /*@__PURE__*/StateField.define({ + create() { return RangeSet.empty; }, + update(value, tr) { + if (tr.selection) { + let lineStart = tr.state.doc.lineAt(tr.selection.main.head).from; + let prevLineStart = tr.startState.doc.lineAt(tr.startState.selection.main.head).from; + if (lineStart != tr.changes.mapPos(prevLineStart, -1)) + value = RangeSet.empty; + } + value = value.map(tr.changes); + for (let effect of tr.effects) { + if (effect.is(closeBracketEffect)) + value = value.update({ add: [closedBracket.range(effect.value, effect.value + 1)] }); + else if (effect.is(skipBracketEffect)) + value = value.update({ filter: from => from != effect.value }); + } + return value; + } + }); + /** + Extension to enable bracket-closing behavior. When a closeable + bracket is typed, its closing bracket is immediately inserted + after the cursor. When closing a bracket directly in front of a + closing bracket inserted by the extension, the cursor moves over + that bracket. + */ + function closeBrackets() { + return [inputHandler, bracketState]; + } + const definedClosing = "()[]{}<>"; + function closing(ch) { + for (let i = 0; i < definedClosing.length; i += 2) + if (definedClosing.charCodeAt(i) == ch) + return definedClosing.charAt(i + 1); + return fromCodePoint(ch < 128 ? ch : ch + 1); + } + function config(state, pos) { + return state.languageDataAt("closeBrackets", pos)[0] || defaults; + } + const android = typeof navigator == "object" && /*@__PURE__*//Android\b/.test(navigator.userAgent); + const inputHandler = /*@__PURE__*/EditorView.inputHandler.of((view, from, to, insert) => { + if ((android ? view.composing : view.compositionStarted) || view.state.readOnly) + return false; + let sel = view.state.selection.main; + if (insert.length > 2 || insert.length == 2 && codePointSize(codePointAt(insert, 0)) == 1 || + from != sel.from || to != sel.to) + return false; + let tr = insertBracket(view.state, insert); + if (!tr) + return false; + view.dispatch(tr); + return true; + }); + /** + Command that implements deleting a pair of matching brackets when + the cursor is between them. + */ + const deleteBracketPair = ({ state, dispatch }) => { + if (state.readOnly) + return false; + let conf = config(state, state.selection.main.head); + let tokens = conf.brackets || defaults.brackets; + let dont = null, changes = state.changeByRange(range => { + if (range.empty) { + let before = prevChar(state.doc, range.head); + for (let token of tokens) { + if (token == before && nextChar(state.doc, range.head) == closing(codePointAt(token, 0))) + return { changes: { from: range.head - token.length, to: range.head + token.length }, + range: EditorSelection.cursor(range.head - token.length) }; + } + } + return { range: dont = range }; + }); + if (!dont) + dispatch(state.update(changes, { scrollIntoView: true, userEvent: "delete.backward" })); + return !dont; + }; + /** + Close-brackets related key bindings. Binds Backspace to + [`deleteBracketPair`](https://codemirror.net/6/docs/ref/#autocomplete.deleteBracketPair). + */ + const closeBracketsKeymap = [ + { key: "Backspace", run: deleteBracketPair } + ]; + /** + Implements the extension's behavior on text insertion. If the + given string counts as a bracket in the language around the + selection, and replacing the selection with it requires custom + behavior (inserting a closing version or skipping past a + previously-closed bracket), this function returns a transaction + representing that custom behavior. (You only need this if you want + to programmatically insert brackets—the + [`closeBrackets`](https://codemirror.net/6/docs/ref/#autocomplete.closeBrackets) extension will + take care of running this for user input.) + */ + function insertBracket(state, bracket) { + let conf = config(state, state.selection.main.head); + let tokens = conf.brackets || defaults.brackets; + for (let tok of tokens) { + let closed = closing(codePointAt(tok, 0)); + if (bracket == tok) + return closed == tok ? handleSame(state, tok, tokens.indexOf(tok + tok + tok) > -1, conf) + : handleOpen(state, tok, closed, conf.before || defaults.before); + if (bracket == closed && closedBracketAt(state, state.selection.main.from)) + return handleClose(state, tok, closed); + } + return null; + } + function closedBracketAt(state, pos) { + let found = false; + state.field(bracketState).between(0, state.doc.length, from => { + if (from == pos) + found = true; + }); + return found; + } + function nextChar(doc, pos) { + let next = doc.sliceString(pos, pos + 2); + return next.slice(0, codePointSize(codePointAt(next, 0))); + } + function prevChar(doc, pos) { + let prev = doc.sliceString(pos - 2, pos); + return codePointSize(codePointAt(prev, 0)) == prev.length ? prev : prev.slice(1); + } + function handleOpen(state, open, close, closeBefore) { + let dont = null, changes = state.changeByRange(range => { + if (!range.empty) + return { changes: [{ insert: open, from: range.from }, { insert: close, from: range.to }], + effects: closeBracketEffect.of(range.to + open.length), + range: EditorSelection.range(range.anchor + open.length, range.head + open.length) }; + let next = nextChar(state.doc, range.head); + if (!next || /\s/.test(next) || closeBefore.indexOf(next) > -1) + return { changes: { insert: open + close, from: range.head }, + effects: closeBracketEffect.of(range.head + open.length), + range: EditorSelection.cursor(range.head + open.length) }; + return { range: dont = range }; + }); + return dont ? null : state.update(changes, { + scrollIntoView: true, + userEvent: "input.type" + }); + } + function handleClose(state, _open, close) { + let dont = null, moved = state.selection.ranges.map(range => { + if (range.empty && nextChar(state.doc, range.head) == close) + return EditorSelection.cursor(range.head + close.length); + return dont = range; + }); + return dont ? null : state.update({ + selection: EditorSelection.create(moved, state.selection.mainIndex), + scrollIntoView: true, + effects: state.selection.ranges.map(({ from }) => skipBracketEffect.of(from)) + }); + } + // Handles cases where the open and close token are the same, and + // possibly triple quotes (as in `"""abc"""`-style quoting). + function handleSame(state, token, allowTriple, config) { + let stringPrefixes = config.stringPrefixes || defaults.stringPrefixes; + let dont = null, changes = state.changeByRange(range => { + if (!range.empty) + return { changes: [{ insert: token, from: range.from }, { insert: token, from: range.to }], + effects: closeBracketEffect.of(range.to + token.length), + range: EditorSelection.range(range.anchor + token.length, range.head + token.length) }; + let pos = range.head, next = nextChar(state.doc, pos), start; + if (next == token) { + if (nodeStart(state, pos)) { + return { changes: { insert: token + token, from: pos }, + effects: closeBracketEffect.of(pos + token.length), + range: EditorSelection.cursor(pos + token.length) }; + } + else if (closedBracketAt(state, pos)) { + let isTriple = allowTriple && state.sliceDoc(pos, pos + token.length * 3) == token + token + token; + return { range: EditorSelection.cursor(pos + token.length * (isTriple ? 3 : 1)), + effects: skipBracketEffect.of(pos) }; + } + } + else if (allowTriple && state.sliceDoc(pos - 2 * token.length, pos) == token + token && + (start = canStartStringAt(state, pos - 2 * token.length, stringPrefixes)) > -1 && + nodeStart(state, start)) { + return { changes: { insert: token + token + token + token, from: pos }, + effects: closeBracketEffect.of(pos + token.length), + range: EditorSelection.cursor(pos + token.length) }; + } + else if (state.charCategorizer(pos)(next) != CharCategory.Word) { + if (canStartStringAt(state, pos, stringPrefixes) > -1 && !probablyInString(state, pos, token, stringPrefixes)) + return { changes: { insert: token + token, from: pos }, + effects: closeBracketEffect.of(pos + token.length), + range: EditorSelection.cursor(pos + token.length) }; + } + return { range: dont = range }; + }); + return dont ? null : state.update(changes, { + scrollIntoView: true, + userEvent: "input.type" + }); + } + function nodeStart(state, pos) { + let tree = syntaxTree(state).resolveInner(pos + 1); + return tree.parent && tree.from == pos; + } + function probablyInString(state, pos, quoteToken, prefixes) { + let node = syntaxTree(state).resolveInner(pos, -1); + let maxPrefix = prefixes.reduce((m, p) => Math.max(m, p.length), 0); + for (let i = 0; i < 5; i++) { + let start = state.sliceDoc(node.from, Math.min(node.to, node.from + quoteToken.length + maxPrefix)); + let quotePos = start.indexOf(quoteToken); + if (!quotePos || quotePos > -1 && prefixes.indexOf(start.slice(0, quotePos)) > -1) { + let first = node.firstChild; + while (first && first.from == node.from && first.to - first.from > quoteToken.length + quotePos) { + if (state.sliceDoc(first.to - quoteToken.length, first.to) == quoteToken) + return false; + first = first.firstChild; + } + return true; + } + let parent = node.to == pos && node.parent; + if (!parent) + break; + node = parent; + } + return false; + } + function canStartStringAt(state, pos, prefixes) { + let charCat = state.charCategorizer(pos); + if (charCat(state.sliceDoc(pos - 1, pos)) != CharCategory.Word) + return pos; + for (let prefix of prefixes) { + let start = pos - prefix.length; + if (state.sliceDoc(start, pos) == prefix && charCat(state.sliceDoc(start - 1, start)) != CharCategory.Word) + return start; + } + return -1; + } + + /** + Returns an extension that enables autocompletion. + */ + function autocompletion(config = {}) { + return [ + completionState, + completionConfig.of(config), + completionPlugin, + completionKeymapExt, + baseTheme$1 + ]; + } + /** + Basic keybindings for autocompletion. + + - Ctrl-Space: [`startCompletion`](https://codemirror.net/6/docs/ref/#autocomplete.startCompletion) + - Escape: [`closeCompletion`](https://codemirror.net/6/docs/ref/#autocomplete.closeCompletion) + - ArrowDown: [`moveCompletionSelection`](https://codemirror.net/6/docs/ref/#autocomplete.moveCompletionSelection)`(true)` + - ArrowUp: [`moveCompletionSelection`](https://codemirror.net/6/docs/ref/#autocomplete.moveCompletionSelection)`(false)` + - PageDown: [`moveCompletionSelection`](https://codemirror.net/6/docs/ref/#autocomplete.moveCompletionSelection)`(true, "page")` + - PageDown: [`moveCompletionSelection`](https://codemirror.net/6/docs/ref/#autocomplete.moveCompletionSelection)`(true, "page")` + - Enter: [`acceptCompletion`](https://codemirror.net/6/docs/ref/#autocomplete.acceptCompletion) + */ + const completionKeymap = [ + { key: "Ctrl-Space", run: startCompletion }, + { key: "Escape", run: closeCompletion }, + { key: "ArrowDown", run: /*@__PURE__*/moveCompletionSelection(true) }, + { key: "ArrowUp", run: /*@__PURE__*/moveCompletionSelection(false) }, + { key: "PageDown", run: /*@__PURE__*/moveCompletionSelection(true, "page") }, + { key: "PageUp", run: /*@__PURE__*/moveCompletionSelection(false, "page") }, + { key: "Enter", run: acceptCompletion } + ]; + const completionKeymapExt = /*@__PURE__*/Prec.highest(/*@__PURE__*/keymap.computeN([completionConfig], state => state.facet(completionConfig).defaultKeymap ? [completionKeymap] : [])); + + class SelectedDiagnostic { + constructor(from, to, diagnostic) { + this.from = from; + this.to = to; + this.diagnostic = diagnostic; + } + } + class LintState { + constructor(diagnostics, panel, selected) { + this.diagnostics = diagnostics; + this.panel = panel; + this.selected = selected; + } + static init(diagnostics, panel, state) { + // Filter the list of diagnostics for which to create markers + let markedDiagnostics = diagnostics; + let diagnosticFilter = state.facet(lintConfig).markerFilter; + if (diagnosticFilter) + markedDiagnostics = diagnosticFilter(markedDiagnostics); + let ranges = Decoration.set(markedDiagnostics.map((d) => { + // For zero-length ranges or ranges covering only a line break, create a widget + return d.from == d.to || (d.from == d.to - 1 && state.doc.lineAt(d.from).to == d.from) + ? Decoration.widget({ + widget: new DiagnosticWidget(d), + diagnostic: d + }).range(d.from) + : Decoration.mark({ + attributes: { class: "cm-lintRange cm-lintRange-" + d.severity }, + diagnostic: d + }).range(d.from, d.to); + }), true); + return new LintState(ranges, panel, findDiagnostic(ranges)); + } + } + function findDiagnostic(diagnostics, diagnostic = null, after = 0) { + let found = null; + diagnostics.between(after, 1e9, (from, to, { spec }) => { + if (diagnostic && spec.diagnostic != diagnostic) + return; + found = new SelectedDiagnostic(from, to, spec.diagnostic); + return false; + }); + return found; + } + function hideTooltip(tr, tooltip) { + return !!(tr.effects.some(e => e.is(setDiagnosticsEffect)) || tr.changes.touchesRange(tooltip.pos)); + } + function maybeEnableLint(state, effects) { + return state.field(lintState, false) ? effects : effects.concat(StateEffect.appendConfig.of([ + lintState, + EditorView.decorations.compute([lintState], state => { + let { selected, panel } = state.field(lintState); + return !selected || !panel || selected.from == selected.to ? Decoration.none : Decoration.set([ + activeMark.range(selected.from, selected.to) + ]); + }), + hoverTooltip(lintTooltip, { hideOn: hideTooltip }), + baseTheme + ])); + } + /** + Returns a transaction spec which updates the current set of + diagnostics, and enables the lint extension if if wasn't already + active. + */ + function setDiagnostics(state, diagnostics) { + return { + effects: maybeEnableLint(state, [setDiagnosticsEffect.of(diagnostics)]) + }; + } + /** + The state effect that updates the set of active diagnostics. Can + be useful when writing an extension that needs to track these. + */ + const setDiagnosticsEffect = /*@__PURE__*/StateEffect.define(); + const togglePanel = /*@__PURE__*/StateEffect.define(); + const movePanelSelection = /*@__PURE__*/StateEffect.define(); + const lintState = /*@__PURE__*/StateField.define({ + create() { + return new LintState(Decoration.none, null, null); + }, + update(value, tr) { + if (tr.docChanged) { + let mapped = value.diagnostics.map(tr.changes), selected = null; + if (value.selected) { + let selPos = tr.changes.mapPos(value.selected.from, 1); + selected = findDiagnostic(mapped, value.selected.diagnostic, selPos) || findDiagnostic(mapped, null, selPos); + } + value = new LintState(mapped, value.panel, selected); + } + for (let effect of tr.effects) { + if (effect.is(setDiagnosticsEffect)) { + value = LintState.init(effect.value, value.panel, tr.state); + } + else if (effect.is(togglePanel)) { + value = new LintState(value.diagnostics, effect.value ? LintPanel.open : null, value.selected); + } + else if (effect.is(movePanelSelection)) { + value = new LintState(value.diagnostics, value.panel, effect.value); + } + } + return value; + }, + provide: f => [showPanel.from(f, val => val.panel), + EditorView.decorations.from(f, s => s.diagnostics)] + }); + const activeMark = /*@__PURE__*/Decoration.mark({ class: "cm-lintRange cm-lintRange-active" }); + function lintTooltip(view, pos, side) { + let { diagnostics } = view.state.field(lintState); + let found = [], stackStart = 2e8, stackEnd = 0; + diagnostics.between(pos - (side < 0 ? 1 : 0), pos + (side > 0 ? 1 : 0), (from, to, { spec }) => { + if (pos >= from && pos <= to && + (from == to || ((pos > from || side > 0) && (pos < to || side < 0)))) { + found.push(spec.diagnostic); + stackStart = Math.min(from, stackStart); + stackEnd = Math.max(to, stackEnd); + } + }); + let diagnosticFilter = view.state.facet(lintConfig).tooltipFilter; + if (diagnosticFilter) + found = diagnosticFilter(found); + if (!found.length) + return null; + return { + pos: stackStart, + end: stackEnd, + above: view.state.doc.lineAt(stackStart).to < stackEnd, + create() { + return { dom: diagnosticsTooltip(view, found) }; + } + }; + } + function diagnosticsTooltip(view, diagnostics) { + return crelt("ul", { class: "cm-tooltip-lint" }, diagnostics.map(d => renderDiagnostic(view, d, false))); + } + /** + Command to open and focus the lint panel. + */ + const openLintPanel = (view) => { + let field = view.state.field(lintState, false); + if (!field || !field.panel) + view.dispatch({ effects: maybeEnableLint(view.state, [togglePanel.of(true)]) }); + let panel = getPanel(view, LintPanel.open); + if (panel) + panel.dom.querySelector(".cm-panel-lint ul").focus(); + return true; + }; + /** + Command to close the lint panel, when open. + */ + const closeLintPanel = (view) => { + let field = view.state.field(lintState, false); + if (!field || !field.panel) + return false; + view.dispatch({ effects: togglePanel.of(false) }); + return true; + }; + /** + Move the selection to the next diagnostic. + */ + const nextDiagnostic = (view) => { + let field = view.state.field(lintState, false); + if (!field) + return false; + let sel = view.state.selection.main, next = field.diagnostics.iter(sel.to + 1); + if (!next.value) { + next = field.diagnostics.iter(0); + if (!next.value || next.from == sel.from && next.to == sel.to) + return false; + } + view.dispatch({ selection: { anchor: next.from, head: next.to }, scrollIntoView: true }); + return true; + }; + /** + A set of default key bindings for the lint functionality. + + - Ctrl-Shift-m (Cmd-Shift-m on macOS): [`openLintPanel`](https://codemirror.net/6/docs/ref/#lint.openLintPanel) + - F8: [`nextDiagnostic`](https://codemirror.net/6/docs/ref/#lint.nextDiagnostic) + */ + const lintKeymap = [ + { key: "Mod-Shift-m", run: openLintPanel }, + { key: "F8", run: nextDiagnostic } + ]; + const lintPlugin = /*@__PURE__*/ViewPlugin.fromClass(class { + constructor(view) { + this.view = view; + this.timeout = -1; + this.set = true; + let { delay } = view.state.facet(lintConfig); + this.lintTime = Date.now() + delay; + this.run = this.run.bind(this); + this.timeout = setTimeout(this.run, delay); + } + run() { + let now = Date.now(); + if (now < this.lintTime - 10) { + setTimeout(this.run, this.lintTime - now); + } + else { + this.set = false; + let { state } = this.view, { sources } = state.facet(lintConfig); + Promise.all(sources.map(source => Promise.resolve(source(this.view)))).then(annotations => { + let all = annotations.reduce((a, b) => a.concat(b)); + if (this.view.state.doc == state.doc) + this.view.dispatch(setDiagnostics(this.view.state, all)); + }, error => { logException(this.view.state, error); }); + } + } + update(update) { + let config = update.state.facet(lintConfig); + if (update.docChanged || config != update.startState.facet(lintConfig)) { + this.lintTime = Date.now() + config.delay; + if (!this.set) { + this.set = true; + this.timeout = setTimeout(this.run, config.delay); + } + } + } + force() { + if (this.set) { + this.lintTime = Date.now(); + this.run(); + } + } + destroy() { + clearTimeout(this.timeout); + } + }); + const lintConfig = /*@__PURE__*/Facet.define({ + combine(input) { + return Object.assign({ sources: input.map(i => i.source) }, combineConfig(input.map(i => i.config), { + delay: 750, + markerFilter: null, + tooltipFilter: null + })); + }, + enables: lintPlugin + }); + function assignKeys(actions) { + let assigned = []; + if (actions) + actions: for (let { name } of actions) { + for (let i = 0; i < name.length; i++) { + let ch = name[i]; + if (/[a-zA-Z]/.test(ch) && !assigned.some(c => c.toLowerCase() == ch.toLowerCase())) { + assigned.push(ch); + continue actions; + } + } + assigned.push(""); + } + return assigned; + } + function renderDiagnostic(view, diagnostic, inPanel) { + var _a; + let keys = inPanel ? assignKeys(diagnostic.actions) : []; + return crelt("li", { class: "cm-diagnostic cm-diagnostic-" + diagnostic.severity }, crelt("span", { class: "cm-diagnosticText" }, diagnostic.renderMessage ? diagnostic.renderMessage() : diagnostic.message), (_a = diagnostic.actions) === null || _a === void 0 ? void 0 : _a.map((action, i) => { + let click = (e) => { + e.preventDefault(); + let found = findDiagnostic(view.state.field(lintState).diagnostics, diagnostic); + if (found) + action.apply(view, found.from, found.to); + }; + let { name } = action, keyIndex = keys[i] ? name.indexOf(keys[i]) : -1; + let nameElt = keyIndex < 0 ? name : [name.slice(0, keyIndex), + crelt("u", name.slice(keyIndex, keyIndex + 1)), + name.slice(keyIndex + 1)]; + return crelt("button", { + type: "button", + class: "cm-diagnosticAction", + onclick: click, + onmousedown: click, + "aria-label": ` Action: ${name}${keyIndex < 0 ? "" : ` (access key "${keys[i]})"`}.` + }, nameElt); + }), diagnostic.source && crelt("div", { class: "cm-diagnosticSource" }, diagnostic.source)); + } + class DiagnosticWidget extends WidgetType { + constructor(diagnostic) { + super(); + this.diagnostic = diagnostic; + } + eq(other) { return other.diagnostic == this.diagnostic; } + toDOM() { + return crelt("span", { class: "cm-lintPoint cm-lintPoint-" + this.diagnostic.severity }); + } + } + class PanelItem { + constructor(view, diagnostic) { + this.diagnostic = diagnostic; + this.id = "item_" + Math.floor(Math.random() * 0xffffffff).toString(16); + this.dom = renderDiagnostic(view, diagnostic, true); + this.dom.id = this.id; + this.dom.setAttribute("role", "option"); + } + } + class LintPanel { + constructor(view) { + this.view = view; + this.items = []; + let onkeydown = (event) => { + if (event.keyCode == 27) { // Escape + closeLintPanel(this.view); + this.view.focus(); + } + else if (event.keyCode == 38 || event.keyCode == 33) { // ArrowUp, PageUp + this.moveSelection((this.selectedIndex - 1 + this.items.length) % this.items.length); + } + else if (event.keyCode == 40 || event.keyCode == 34) { // ArrowDown, PageDown + this.moveSelection((this.selectedIndex + 1) % this.items.length); + } + else if (event.keyCode == 36) { // Home + this.moveSelection(0); + } + else if (event.keyCode == 35) { // End + this.moveSelection(this.items.length - 1); + } + else if (event.keyCode == 13) { // Enter + this.view.focus(); + } + else if (event.keyCode >= 65 && event.keyCode <= 90 && this.selectedIndex >= 0) { // A-Z + let { diagnostic } = this.items[this.selectedIndex], keys = assignKeys(diagnostic.actions); + for (let i = 0; i < keys.length; i++) + if (keys[i].toUpperCase().charCodeAt(0) == event.keyCode) { + let found = findDiagnostic(this.view.state.field(lintState).diagnostics, diagnostic); + if (found) + diagnostic.actions[i].apply(view, found.from, found.to); + } + } + else { + return; + } + event.preventDefault(); + }; + let onclick = (event) => { + for (let i = 0; i < this.items.length; i++) { + if (this.items[i].dom.contains(event.target)) + this.moveSelection(i); + } + }; + this.list = crelt("ul", { + tabIndex: 0, + role: "listbox", + "aria-label": this.view.state.phrase("Diagnostics"), + onkeydown, + onclick + }); + this.dom = crelt("div", { class: "cm-panel-lint" }, this.list, crelt("button", { + type: "button", + name: "close", + "aria-label": this.view.state.phrase("close"), + onclick: () => closeLintPanel(this.view) + }, "×")); + this.update(); + } + get selectedIndex() { + let selected = this.view.state.field(lintState).selected; + if (!selected) + return -1; + for (let i = 0; i < this.items.length; i++) + if (this.items[i].diagnostic == selected.diagnostic) + return i; + return -1; + } + update() { + let { diagnostics, selected } = this.view.state.field(lintState); + let i = 0, needsSync = false, newSelectedItem = null; + diagnostics.between(0, this.view.state.doc.length, (_start, _end, { spec }) => { + let found = -1, item; + for (let j = i; j < this.items.length; j++) + if (this.items[j].diagnostic == spec.diagnostic) { + found = j; + break; + } + if (found < 0) { + item = new PanelItem(this.view, spec.diagnostic); + this.items.splice(i, 0, item); + needsSync = true; + } + else { + item = this.items[found]; + if (found > i) { + this.items.splice(i, found - i); + needsSync = true; + } + } + if (selected && item.diagnostic == selected.diagnostic) { + if (!item.dom.hasAttribute("aria-selected")) { + item.dom.setAttribute("aria-selected", "true"); + newSelectedItem = item; + } + } + else if (item.dom.hasAttribute("aria-selected")) { + item.dom.removeAttribute("aria-selected"); + } + i++; + }); + while (i < this.items.length && !(this.items.length == 1 && this.items[0].diagnostic.from < 0)) { + needsSync = true; + this.items.pop(); + } + if (this.items.length == 0) { + this.items.push(new PanelItem(this.view, { + from: -1, to: -1, + severity: "info", + message: this.view.state.phrase("No diagnostics") + })); + needsSync = true; + } + if (newSelectedItem) { + this.list.setAttribute("aria-activedescendant", newSelectedItem.id); + this.view.requestMeasure({ + key: this, + read: () => ({ sel: newSelectedItem.dom.getBoundingClientRect(), panel: this.list.getBoundingClientRect() }), + write: ({ sel, panel }) => { + if (sel.top < panel.top) + this.list.scrollTop -= panel.top - sel.top; + else if (sel.bottom > panel.bottom) + this.list.scrollTop += sel.bottom - panel.bottom; + } + }); + } + else if (this.selectedIndex < 0) { + this.list.removeAttribute("aria-activedescendant"); + } + if (needsSync) + this.sync(); + } + sync() { + let domPos = this.list.firstChild; + function rm() { + let prev = domPos; + domPos = prev.nextSibling; + prev.remove(); + } + for (let item of this.items) { + if (item.dom.parentNode == this.list) { + while (domPos != item.dom) + rm(); + domPos = item.dom.nextSibling; + } + else { + this.list.insertBefore(item.dom, domPos); + } + } + while (domPos) + rm(); + } + moveSelection(selectedIndex) { + if (this.selectedIndex < 0) + return; + let field = this.view.state.field(lintState); + let selection = findDiagnostic(field.diagnostics, this.items[selectedIndex].diagnostic); + if (!selection) + return; + this.view.dispatch({ + selection: { anchor: selection.from, head: selection.to }, + scrollIntoView: true, + effects: movePanelSelection.of(selection) + }); + } + static open(view) { return new LintPanel(view); } + } + function svg(content, attrs = `viewBox="0 0 40 40"`) { + return `url('data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" ${attrs}>${encodeURIComponent(content)}</svg>')`; + } + function underline(color) { + return svg(`<path d="m0 2.5 l2 -1.5 l1 0 l2 1.5 l1 0" stroke="${color}" fill="none" stroke-width=".7"/>`, `width="6" height="3"`); + } + const baseTheme = /*@__PURE__*/EditorView.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-diagnosticAction": { + font: "inherit", + border: "none", + padding: "2px 4px", + backgroundColor: "#444", + color: "white", + borderRadius: "3px", + marginLeft: "8px" + }, + ".cm-diagnosticSource": { + fontSize: "70%", + opacity: .7 + }, + ".cm-lintRange": { + backgroundPosition: "left bottom", + backgroundRepeat: "repeat-x", + paddingBottom: "0.7px", + }, + ".cm-lintRange-error": { backgroundImage: /*@__PURE__*/underline("#d11") }, + ".cm-lintRange-warning": { backgroundImage: /*@__PURE__*/underline("orange") }, + ".cm-lintRange-info": { backgroundImage: /*@__PURE__*/underline("#999") }, + ".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-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 + } + } + }); + + // (The superfluous function calls around the list of extensions work + // around current limitations in tree-shaking software.) + /** + This is an extension value that just pulls together a number of + extensions that you might want in a basic editor. It is meant as a + convenient helper to quickly set up CodeMirror without installing + and importing a lot of separate packages. + + Specifically, it includes... + + - [the default command bindings](https://codemirror.net/6/docs/ref/#commands.defaultKeymap) + - [line numbers](https://codemirror.net/6/docs/ref/#view.lineNumbers) + - [special character highlighting](https://codemirror.net/6/docs/ref/#view.highlightSpecialChars) + - [the undo history](https://codemirror.net/6/docs/ref/#commands.history) + - [a fold gutter](https://codemirror.net/6/docs/ref/#language.foldGutter) + - [custom selection drawing](https://codemirror.net/6/docs/ref/#view.drawSelection) + - [drop cursor](https://codemirror.net/6/docs/ref/#view.dropCursor) + - [multiple selections](https://codemirror.net/6/docs/ref/#state.EditorState^allowMultipleSelections) + - [reindentation on input](https://codemirror.net/6/docs/ref/#language.indentOnInput) + - [the default highlight style](https://codemirror.net/6/docs/ref/#language.defaultHighlightStyle) (as fallback) + - [bracket matching](https://codemirror.net/6/docs/ref/#language.bracketMatching) + - [bracket closing](https://codemirror.net/6/docs/ref/#autocomplete.closeBrackets) + - [autocompletion](https://codemirror.net/6/docs/ref/#autocomplete.autocompletion) + - [rectangular selection](https://codemirror.net/6/docs/ref/#view.rectangularSelection) and [crosshair cursor](https://codemirror.net/6/docs/ref/#view.crosshairCursor) + - [active line highlighting](https://codemirror.net/6/docs/ref/#view.highlightActiveLine) + - [active line gutter highlighting](https://codemirror.net/6/docs/ref/#view.highlightActiveLineGutter) + - [selection match highlighting](https://codemirror.net/6/docs/ref/#search.highlightSelectionMatches) + - [search](https://codemirror.net/6/docs/ref/#search.searchKeymap) + - [linting](https://codemirror.net/6/docs/ref/#lint.lintKeymap) + + (You'll probably want to add some language package to your setup + too.) + + This extension does not allow customization. The idea is that, + once you decide you want to configure your editor more precisely, + you take this package's source (which is just a bunch of imports + and an array literal), copy it into your own code, and adjust it + as desired. + */ + const basicSetup = /*@__PURE__*/(() => [ + lineNumbers(), + highlightActiveLineGutter(), + highlightSpecialChars(), + history(), + foldGutter(), + drawSelection(), + dropCursor(), + EditorState.allowMultipleSelections.of(true), + indentOnInput(), + syntaxHighlighting(defaultHighlightStyle, { fallback: true }), + bracketMatching(), + closeBrackets(), + autocompletion(), + rectangularSelection(), + crosshairCursor(), + highlightActiveLine(), + highlightSelectionMatches(), + keymap.of([ + ...closeBracketsKeymap, + ...defaultKeymap, + ...searchKeymap, + ...historyKeymap, + ...foldKeymap, + ...completionKeymap, + ...lintKeymap + ]) + ])(); + + /// A parse stack. These are used internally by the parser to track + /// parsing progress. They also provide some properties and methods + /// that external code such as a tokenizer can use to get information + /// about the parse state. + class Stack { + /// @internal + constructor( + /// The parse that this stack is part of @internal + p, + /// Holds state, input pos, buffer index triplets for all but the + /// top state @internal + stack, + /// The current parse state @internal + state, + // The position at which the next reduce should take place. This + // can be less than `this.pos` when skipped expressions have been + // added to the stack (which should be moved outside of the next + // reduction) + /// @internal + reducePos, + /// The input position up to which this stack has parsed. + pos, + /// The dynamic score of the stack, including dynamic precedence + /// and error-recovery penalties + /// @internal + score, + // The output buffer. Holds (type, start, end, size) quads + // representing nodes created by the parser, where `size` is + // amount of buffer array entries covered by this node. + /// @internal + buffer, + // The base offset of the buffer. When stacks are split, the split + // instance shared the buffer history with its parent up to + // `bufferBase`, which is the absolute offset (including the + // offset of previous splits) into the buffer at which this stack + // starts writing. + /// @internal + bufferBase, + /// @internal + curContext, + /// @internal + lookAhead = 0, + // A parent stack from which this was split off, if any. This is + // set up so that it always points to a stack that has some + // additional buffer content, never to a stack with an equal + // `bufferBase`. + /// @internal + parent) { + this.p = p; + this.stack = stack; + this.state = state; + this.reducePos = reducePos; + this.pos = pos; + this.score = score; + this.buffer = buffer; + this.bufferBase = bufferBase; + this.curContext = curContext; + this.lookAhead = lookAhead; + this.parent = parent; + } + /// @internal + toString() { + return `[${this.stack.filter((_, i) => i % 3 == 0).concat(this.state)}]@${this.pos}${this.score ? "!" + this.score : ""}`; + } + // Start an empty stack + /// @internal + static start(p, state, pos = 0) { + let cx = p.parser.context; + return new Stack(p, [], state, pos, pos, 0, [], 0, cx ? new StackContext(cx, cx.start) : null, 0, null); + } + /// The stack's current [context](#lr.ContextTracker) value, if + /// any. Its type will depend on the context tracker's type + /// parameter, or it will be `null` if there is no context + /// tracker. + get context() { return this.curContext ? this.curContext.context : null; } + // Push a state onto the stack, tracking its start position as well + // as the buffer base at that point. + /// @internal + pushState(state, start) { + this.stack.push(this.state, start, this.bufferBase + this.buffer.length); + this.state = state; + } + // Apply a reduce action + /// @internal + reduce(action) { + let depth = action >> 19 /* ReduceDepthShift */, type = action & 65535 /* ValueMask */; + let { parser } = this.p; + let dPrec = parser.dynamicPrecedence(type); + if (dPrec) + this.score += dPrec; + if (depth == 0) { + this.pushState(parser.getGoto(this.state, type, true), this.reducePos); + // Zero-depth reductions are a special case—they add stuff to + // the stack without popping anything off. + if (type < parser.minRepeatTerm) + this.storeNode(type, this.reducePos, this.reducePos, 4, true); + this.reduceContext(type, this.reducePos); + return; + } + // Find the base index into `this.stack`, content after which will + // be dropped. Note that with `StayFlag` reductions we need to + // consume two extra frames (the dummy parent node for the skipped + // expression and the state that we'll be staying in, which should + // be moved to `this.state`). + let base = this.stack.length - ((depth - 1) * 3) - (action & 262144 /* StayFlag */ ? 6 : 0); + let start = this.stack[base - 2]; + let bufferBase = this.stack[base - 1], count = this.bufferBase + this.buffer.length - bufferBase; + // Store normal terms or `R -> R R` repeat reductions + if (type < parser.minRepeatTerm || (action & 131072 /* RepeatFlag */)) { + let pos = parser.stateFlag(this.state, 1 /* Skipped */) ? this.pos : this.reducePos; + this.storeNode(type, start, pos, count + 4, true); + } + if (action & 262144 /* StayFlag */) { + this.state = this.stack[base]; + } + else { + let baseStateID = this.stack[base - 3]; + this.state = parser.getGoto(baseStateID, type, true); + } + while (this.stack.length > base) + this.stack.pop(); + this.reduceContext(type, start); + } + // Shift a value into the buffer + /// @internal + storeNode(term, start, end, size = 4, isReduce = false) { + if (term == 0 /* Err */ && + (!this.stack.length || this.stack[this.stack.length - 1] < this.buffer.length + this.bufferBase)) { + // Try to omit/merge adjacent error nodes + let cur = this, top = this.buffer.length; + if (top == 0 && cur.parent) { + top = cur.bufferBase - cur.parent.bufferBase; + cur = cur.parent; + } + if (top > 0 && cur.buffer[top - 4] == 0 /* Err */ && cur.buffer[top - 1] > -1) { + if (start == end) + return; + if (cur.buffer[top - 2] >= start) { + cur.buffer[top - 2] = end; + return; + } + } + } + if (!isReduce || this.pos == end) { // Simple case, just append + this.buffer.push(term, start, end, size); + } + else { // There may be skipped nodes that have to be moved forward + let index = this.buffer.length; + if (index > 0 && this.buffer[index - 4] != 0 /* Err */) + while (index > 0 && this.buffer[index - 2] > end) { + // Move this record forward + this.buffer[index] = this.buffer[index - 4]; + this.buffer[index + 1] = this.buffer[index - 3]; + this.buffer[index + 2] = this.buffer[index - 2]; + this.buffer[index + 3] = this.buffer[index - 1]; + index -= 4; + if (size > 4) + size -= 4; + } + this.buffer[index] = term; + this.buffer[index + 1] = start; + this.buffer[index + 2] = end; + this.buffer[index + 3] = size; + } + } + // Apply a shift action + /// @internal + shift(action, next, nextEnd) { + let start = this.pos; + if (action & 131072 /* GotoFlag */) { + this.pushState(action & 65535 /* ValueMask */, this.pos); + } + else if ((action & 262144 /* StayFlag */) == 0) { // Regular shift + let nextState = action, { parser } = this.p; + if (nextEnd > this.pos || next <= parser.maxNode) { + this.pos = nextEnd; + if (!parser.stateFlag(nextState, 1 /* Skipped */)) + this.reducePos = nextEnd; + } + this.pushState(nextState, start); + this.shiftContext(next, start); + if (next <= parser.maxNode) + this.buffer.push(next, start, nextEnd, 4); + } + else { // Shift-and-stay, which means this is a skipped token + this.pos = nextEnd; + this.shiftContext(next, start); + if (next <= this.p.parser.maxNode) + this.buffer.push(next, start, nextEnd, 4); + } + } + // Apply an action + /// @internal + apply(action, next, nextEnd) { + if (action & 65536 /* ReduceFlag */) + this.reduce(action); + else + this.shift(action, next, nextEnd); + } + // Add a prebuilt (reused) node into the buffer. + /// @internal + useNode(value, next) { + let index = this.p.reused.length - 1; + if (index < 0 || this.p.reused[index] != value) { + this.p.reused.push(value); + index++; + } + let start = this.pos; + this.reducePos = this.pos = start + value.length; + this.pushState(next, start); + this.buffer.push(index, start, this.reducePos, -1 /* size == -1 means this is a reused value */); + if (this.curContext) + this.updateContext(this.curContext.tracker.reuse(this.curContext.context, value, this, this.p.stream.reset(this.pos - value.length))); + } + // Split the stack. Due to the buffer sharing and the fact + // that `this.stack` tends to stay quite shallow, this isn't very + // expensive. + /// @internal + split() { + let parent = this; + let off = parent.buffer.length; + // Because the top of the buffer (after this.pos) may be mutated + // to reorder reductions and skipped tokens, and shared buffers + // should be immutable, this copies any outstanding skipped tokens + // to the new buffer, and puts the base pointer before them. + while (off > 0 && parent.buffer[off - 2] > parent.reducePos) + off -= 4; + let buffer = parent.buffer.slice(off), base = parent.bufferBase + off; + // Make sure parent points to an actual parent with content, if there is such a parent. + while (parent && base == parent.bufferBase) + parent = parent.parent; + return new Stack(this.p, this.stack.slice(), this.state, this.reducePos, this.pos, this.score, buffer, base, this.curContext, this.lookAhead, parent); + } + // Try to recover from an error by 'deleting' (ignoring) one token. + /// @internal + recoverByDelete(next, nextEnd) { + let isNode = next <= this.p.parser.maxNode; + if (isNode) + this.storeNode(next, this.pos, nextEnd, 4); + this.storeNode(0 /* Err */, this.pos, nextEnd, isNode ? 8 : 4); + this.pos = this.reducePos = nextEnd; + this.score -= 190 /* Delete */; + } + /// Check if the given term would be able to be shifted (optionally + /// after some reductions) on this stack. This can be useful for + /// external tokenizers that want to make sure they only provide a + /// given token when it applies. + canShift(term) { + for (let sim = new SimulatedStack(this);;) { + let action = this.p.parser.stateSlot(sim.state, 4 /* DefaultReduce */) || this.p.parser.hasAction(sim.state, term); + if ((action & 65536 /* ReduceFlag */) == 0) + return true; + if (action == 0) + return false; + sim.reduce(action); + } + } + // Apply up to Recover.MaxNext recovery actions that conceptually + // inserts some missing token or rule. + /// @internal + recoverByInsert(next) { + if (this.stack.length >= 300 /* MaxInsertStackDepth */) + return []; + let nextStates = this.p.parser.nextStates(this.state); + if (nextStates.length > 4 /* MaxNext */ << 1 || this.stack.length >= 120 /* DampenInsertStackDepth */) { + let best = []; + for (let i = 0, s; i < nextStates.length; i += 2) { + if ((s = nextStates[i + 1]) != this.state && this.p.parser.hasAction(s, next)) + best.push(nextStates[i], s); + } + if (this.stack.length < 120 /* DampenInsertStackDepth */) + for (let i = 0; best.length < 4 /* MaxNext */ << 1 && i < nextStates.length; i += 2) { + let s = nextStates[i + 1]; + if (!best.some((v, i) => (i & 1) && v == s)) + best.push(nextStates[i], s); + } + nextStates = best; + } + let result = []; + for (let i = 0; i < nextStates.length && result.length < 4 /* MaxNext */; i += 2) { + let s = nextStates[i + 1]; + if (s == this.state) + continue; + let stack = this.split(); + stack.pushState(s, this.pos); + stack.storeNode(0 /* Err */, stack.pos, stack.pos, 4, true); + stack.shiftContext(nextStates[i], this.pos); + stack.score -= 200 /* Insert */; + result.push(stack); + } + return result; + } + // Force a reduce, if possible. Return false if that can't + // be done. + /// @internal + forceReduce() { + let reduce = this.p.parser.stateSlot(this.state, 5 /* ForcedReduce */); + if ((reduce & 65536 /* ReduceFlag */) == 0) + return false; + let { parser } = this.p; + if (!parser.validAction(this.state, reduce)) { + let depth = reduce >> 19 /* ReduceDepthShift */, term = reduce & 65535 /* ValueMask */; + let target = this.stack.length - depth * 3; + if (target < 0 || parser.getGoto(this.stack[target], term, false) < 0) + return false; + this.storeNode(0 /* Err */, this.reducePos, this.reducePos, 4, true); + this.score -= 100 /* Reduce */; + } + this.reducePos = this.pos; + this.reduce(reduce); + return true; + } + /// @internal + forceAll() { + while (!this.p.parser.stateFlag(this.state, 2 /* Accepting */)) { + if (!this.forceReduce()) { + this.storeNode(0 /* Err */, this.pos, this.pos, 4, true); + break; + } + } + return this; + } + /// Check whether this state has no further actions (assumed to be a direct descendant of the + /// top state, since any other states must be able to continue + /// somehow). @internal + get deadEnd() { + if (this.stack.length != 3) + return false; + let { parser } = this.p; + return parser.data[parser.stateSlot(this.state, 1 /* Actions */)] == 65535 /* End */ && + !parser.stateSlot(this.state, 4 /* DefaultReduce */); + } + /// Restart the stack (put it back in its start state). Only safe + /// when this.stack.length == 3 (state is directly below the top + /// state). @internal + restart() { + this.state = this.stack[0]; + this.stack.length = 0; + } + /// @internal + sameState(other) { + if (this.state != other.state || this.stack.length != other.stack.length) + return false; + for (let i = 0; i < this.stack.length; i += 3) + if (this.stack[i] != other.stack[i]) + return false; + return true; + } + /// Get the parser used by this stack. + get parser() { return this.p.parser; } + /// Test whether a given dialect (by numeric ID, as exported from + /// the terms file) is enabled. + dialectEnabled(dialectID) { return this.p.parser.dialect.flags[dialectID]; } + shiftContext(term, start) { + if (this.curContext) + this.updateContext(this.curContext.tracker.shift(this.curContext.context, term, this, this.p.stream.reset(start))); + } + reduceContext(term, start) { + if (this.curContext) + this.updateContext(this.curContext.tracker.reduce(this.curContext.context, term, this, this.p.stream.reset(start))); + } + /// @internal + emitContext() { + let last = this.buffer.length - 1; + if (last < 0 || this.buffer[last] != -3) + this.buffer.push(this.curContext.hash, this.reducePos, this.reducePos, -3); + } + /// @internal + emitLookAhead() { + let last = this.buffer.length - 1; + if (last < 0 || this.buffer[last] != -4) + this.buffer.push(this.lookAhead, this.reducePos, this.reducePos, -4); + } + updateContext(context) { + if (context != this.curContext.context) { + let newCx = new StackContext(this.curContext.tracker, context); + if (newCx.hash != this.curContext.hash) + this.emitContext(); + this.curContext = newCx; + } + } + /// @internal + setLookAhead(lookAhead) { + if (lookAhead > this.lookAhead) { + this.emitLookAhead(); + this.lookAhead = lookAhead; + } + } + /// @internal + close() { + if (this.curContext && this.curContext.tracker.strict) + this.emitContext(); + if (this.lookAhead > 0) + this.emitLookAhead(); + } + } + class StackContext { + constructor(tracker, context) { + this.tracker = tracker; + this.context = context; + this.hash = tracker.strict ? tracker.hash(context) : 0; + } + } + var Recover; + (function (Recover) { + Recover[Recover["Insert"] = 200] = "Insert"; + Recover[Recover["Delete"] = 190] = "Delete"; + Recover[Recover["Reduce"] = 100] = "Reduce"; + Recover[Recover["MaxNext"] = 4] = "MaxNext"; + Recover[Recover["MaxInsertStackDepth"] = 300] = "MaxInsertStackDepth"; + Recover[Recover["DampenInsertStackDepth"] = 120] = "DampenInsertStackDepth"; + })(Recover || (Recover = {})); + // Used to cheaply run some reductions to scan ahead without mutating + // an entire stack + class SimulatedStack { + constructor(start) { + this.start = start; + this.state = start.state; + this.stack = start.stack; + this.base = this.stack.length; + } + reduce(action) { + let term = action & 65535 /* ValueMask */, depth = action >> 19 /* ReduceDepthShift */; + if (depth == 0) { + if (this.stack == this.start.stack) + this.stack = this.stack.slice(); + this.stack.push(this.state, 0, 0); + this.base += 3; + } + else { + this.base -= (depth - 1) * 3; + } + let goto = this.start.p.parser.getGoto(this.stack[this.base - 3], term, true); + this.state = goto; + } + } + // This is given to `Tree.build` to build a buffer, and encapsulates + // the parent-stack-walking necessary to read the nodes. + class StackBufferCursor { + constructor(stack, pos, index) { + this.stack = stack; + this.pos = pos; + this.index = index; + this.buffer = stack.buffer; + if (this.index == 0) + this.maybeNext(); + } + static create(stack, pos = stack.bufferBase + stack.buffer.length) { + return new StackBufferCursor(stack, pos, pos - stack.bufferBase); + } + maybeNext() { + let next = this.stack.parent; + if (next != null) { + this.index = this.stack.bufferBase - next.bufferBase; + this.stack = next; + this.buffer = next.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; + if (this.index == 0) + this.maybeNext(); + } + fork() { + return new StackBufferCursor(this.stack, this.pos, this.index); + } + } + + class CachedToken { + constructor() { + this.start = -1; + this.value = -1; + this.end = -1; + this.extended = -1; + this.lookAhead = 0; + this.mask = 0; + this.context = 0; + } + } + const nullToken = new CachedToken; + /// [Tokenizers](#lr.ExternalTokenizer) interact with the input + /// through this interface. It presents the input as a stream of + /// characters, tracking lookahead and hiding the complexity of + /// [ranges](#common.Parser.parse^ranges) from tokenizer code. + class InputStream { + /// @internal + constructor( + /// @internal + input, + /// @internal + ranges) { + this.input = input; + this.ranges = ranges; + /// @internal + this.chunk = ""; + /// @internal + this.chunkOff = 0; + /// Backup chunk + this.chunk2 = ""; + this.chunk2Pos = 0; + /// The character code of the next code unit in the input, or -1 + /// when the stream is at the end of the input. + this.next = -1; + /// @internal + this.token = nullToken; + this.rangeIndex = 0; + this.pos = this.chunkPos = ranges[0].from; + this.range = ranges[0]; + this.end = ranges[ranges.length - 1].to; + this.readNext(); + } + /// @internal + resolveOffset(offset, assoc) { + let range = this.range, index = this.rangeIndex; + let pos = this.pos + offset; + while (pos < range.from) { + if (!index) + return null; + let next = this.ranges[--index]; + pos -= range.from - next.to; + range = next; + } + while (assoc < 0 ? pos > range.to : pos >= range.to) { + if (index == this.ranges.length - 1) + return null; + let next = this.ranges[++index]; + pos += next.from - range.to; + range = next; + } + return pos; + } + /// @internal + clipPos(pos) { + if (pos >= this.range.from && pos < this.range.to) + return pos; + for (let range of this.ranges) + if (range.to > pos) + return Math.max(pos, range.from); + return this.end; + } + /// Look at a code unit near the stream position. `.peek(0)` equals + /// `.next`, `.peek(-1)` gives you the previous character, and so + /// on. + /// + /// Note that looking around during tokenizing creates dependencies + /// on potentially far-away content, which may reduce the + /// effectiveness incremental parsing—when looking forward—or even + /// cause invalid reparses when looking backward more than 25 code + /// units, since the library does not track lookbehind. + peek(offset) { + let idx = this.chunkOff + offset, pos, result; + if (idx >= 0 && idx < this.chunk.length) { + pos = this.pos + offset; + result = this.chunk.charCodeAt(idx); + } + else { + let resolved = this.resolveOffset(offset, 1); + if (resolved == null) + return -1; + pos = resolved; + if (pos >= this.chunk2Pos && pos < this.chunk2Pos + this.chunk2.length) { + result = this.chunk2.charCodeAt(pos - this.chunk2Pos); + } + else { + let i = this.rangeIndex, range = this.range; + while (range.to <= pos) + range = this.ranges[++i]; + this.chunk2 = this.input.chunk(this.chunk2Pos = pos); + if (pos + this.chunk2.length > range.to) + this.chunk2 = this.chunk2.slice(0, range.to - pos); + result = this.chunk2.charCodeAt(0); + } + } + if (pos >= this.token.lookAhead) + this.token.lookAhead = pos + 1; + return result; + } + /// Accept a token. By default, the end of the token is set to the + /// current stream position, but you can pass an offset (relative to + /// the stream position) to change that. + acceptToken(token, endOffset = 0) { + let end = endOffset ? this.resolveOffset(endOffset, -1) : this.pos; + if (end == null || end < this.token.start) + throw new RangeError("Token end out of bounds"); + this.token.value = token; + this.token.end = end; + } + getChunk() { + if (this.pos >= this.chunk2Pos && this.pos < this.chunk2Pos + this.chunk2.length) { + let { chunk, chunkPos } = this; + this.chunk = this.chunk2; + this.chunkPos = this.chunk2Pos; + this.chunk2 = chunk; + this.chunk2Pos = chunkPos; + this.chunkOff = this.pos - this.chunkPos; + } + else { + this.chunk2 = this.chunk; + this.chunk2Pos = this.chunkPos; + let nextChunk = this.input.chunk(this.pos); + let end = this.pos + nextChunk.length; + this.chunk = end > this.range.to ? nextChunk.slice(0, this.range.to - this.pos) : nextChunk; + this.chunkPos = this.pos; + this.chunkOff = 0; + } + } + readNext() { + if (this.chunkOff >= this.chunk.length) { + this.getChunk(); + if (this.chunkOff == this.chunk.length) + return this.next = -1; + } + return this.next = this.chunk.charCodeAt(this.chunkOff); + } + /// Move the stream forward N (defaults to 1) code units. Returns + /// the new value of [`next`](#lr.InputStream.next). + advance(n = 1) { + this.chunkOff += n; + while (this.pos + n >= this.range.to) { + if (this.rangeIndex == this.ranges.length - 1) + return this.setDone(); + n -= this.range.to - this.pos; + this.range = this.ranges[++this.rangeIndex]; + this.pos = this.range.from; + } + this.pos += n; + if (this.pos >= this.token.lookAhead) + this.token.lookAhead = this.pos + 1; + return this.readNext(); + } + setDone() { + this.pos = this.chunkPos = this.end; + this.range = this.ranges[this.rangeIndex = this.ranges.length - 1]; + this.chunk = ""; + return this.next = -1; + } + /// @internal + reset(pos, token) { + if (token) { + this.token = token; + token.start = pos; + token.lookAhead = pos + 1; + token.value = token.extended = -1; + } + else { + this.token = nullToken; + } + if (this.pos != pos) { + this.pos = pos; + if (pos == this.end) { + this.setDone(); + return this; + } + while (pos < this.range.from) + this.range = this.ranges[--this.rangeIndex]; + while (pos >= this.range.to) + this.range = this.ranges[++this.rangeIndex]; + if (pos >= this.chunkPos && pos < this.chunkPos + this.chunk.length) { + this.chunkOff = pos - this.chunkPos; + } + else { + this.chunk = ""; + this.chunkOff = 0; + } + this.readNext(); + } + return this; + } + /// @internal + read(from, to) { + if (from >= this.chunkPos && to <= this.chunkPos + this.chunk.length) + return this.chunk.slice(from - this.chunkPos, to - this.chunkPos); + if (from >= this.chunk2Pos && to <= this.chunk2Pos + this.chunk2.length) + return this.chunk2.slice(from - this.chunk2Pos, to - this.chunk2Pos); + if (from >= this.range.from && to <= this.range.to) + return this.input.read(from, to); + let result = ""; + for (let r of this.ranges) { + if (r.from >= to) + break; + if (r.to > from) + result += this.input.read(Math.max(r.from, from), Math.min(r.to, to)); + } + return result; + } + } + /// @internal + class TokenGroup { + constructor(data, id) { + this.data = data; + this.id = id; + } + token(input, stack) { readToken(this.data, input, stack, this.id); } + } + TokenGroup.prototype.contextual = TokenGroup.prototype.fallback = TokenGroup.prototype.extend = false; + /// `@external tokens` declarations in the grammar should resolve to + /// an instance of this class. + class ExternalTokenizer { + /// Create a tokenizer. The first argument is the function that, + /// given an input stream, scans for the types of tokens it + /// recognizes at the stream's position, and calls + /// [`acceptToken`](#lr.InputStream.acceptToken) when it finds + /// one. + constructor( + /// @internal + token, options = {}) { + this.token = token; + this.contextual = !!options.contextual; + this.fallback = !!options.fallback; + this.extend = !!options.extend; + } + } + // Tokenizer data is stored a big uint16 array containing, for each + // state: + // + // - A group bitmask, indicating what token groups are reachable from + // this state, so that paths that can only lead to tokens not in + // any of the current groups can be cut off early. + // + // - The position of the end of the state's sequence of accepting + // tokens + // + // - The number of outgoing edges for the state + // + // - The accepting tokens, as (token id, group mask) pairs + // + // - The outgoing edges, as (start character, end character, state + // index) triples, with end character being exclusive + // + // This function interprets that data, running through a stream as + // long as new states with the a matching group mask can be reached, + // and updating `input.token` when it matches a token. + function readToken(data, input, stack, group) { + let state = 0, groupMask = 1 << group, { parser } = stack.p, { dialect } = parser; + scan: for (;;) { + if ((groupMask & data[state]) == 0) + break; + let accEnd = data[state + 1]; + // Check whether this state can lead to a token in the current group + // Accept tokens in this state, possibly overwriting + // lower-precedence / shorter tokens + for (let i = state + 3; i < accEnd; i += 2) + if ((data[i + 1] & groupMask) > 0) { + let term = data[i]; + if (dialect.allows(term) && + (input.token.value == -1 || input.token.value == term || parser.overrides(term, input.token.value))) { + input.acceptToken(term); + break; + } + } + let next = input.next, low = 0, high = data[state + 2]; + // Special case for EOF + if (input.next < 0 && high > low && data[accEnd + high * 3 - 3] == 65535 /* End */) { + state = data[accEnd + high * 3 - 1]; + continue scan; + } + // Do a binary search on the state's edges + for (; low < high;) { + let mid = (low + high) >> 1; + let index = accEnd + mid + (mid << 1); + let from = data[index], to = data[index + 1]; + if (next < from) + high = mid; + else if (next >= to) + low = mid + 1; + else { + state = data[index + 2]; + input.advance(); + continue scan; + } + } + break; + } + } + + // See lezer-generator/src/encode.ts for comments about the encoding + // used here + function decodeArray(input, Type = Uint16Array) { + if (typeof input != "string") + return input; + let array = null; + for (let pos = 0, out = 0; pos < input.length;) { + let value = 0; + for (;;) { + let next = input.charCodeAt(pos++), stop = false; + if (next == 126 /* BigValCode */) { + value = 65535 /* BigVal */; + break; + } + if (next >= 92 /* Gap2 */) + next--; + if (next >= 34 /* Gap1 */) + next--; + let digit = next - 32 /* Start */; + if (digit >= 46 /* Base */) { + digit -= 46 /* Base */; + stop = true; + } + value += digit; + if (stop) + break; + value *= 46 /* Base */; + } + if (array) + array[out++] = value; + else + array = new Type(value); + } + return array; + } + + // Environment variable used to control console output + const verbose = typeof process != "undefined" && process.env && /\bparse\b/.test(process.env.LOG); + let stackIDs = null; + var Safety; + (function (Safety) { + Safety[Safety["Margin"] = 25] = "Margin"; + })(Safety || (Safety = {})); + function cutAt(tree, pos, side) { + let cursor = tree.cursor(IterMode.IncludeAnonymous); + cursor.moveTo(pos); + for (;;) { + if (!(side < 0 ? cursor.childBefore(pos) : cursor.childAfter(pos))) + for (;;) { + if ((side < 0 ? cursor.to < pos : cursor.from > pos) && !cursor.type.isError) + return side < 0 ? Math.max(0, Math.min(cursor.to - 1, pos - 25 /* Margin */)) + : Math.min(tree.length, Math.max(cursor.from + 1, pos + 25 /* Margin */)); + if (side < 0 ? cursor.prevSibling() : cursor.nextSibling()) + break; + if (!cursor.parent()) + return side < 0 ? 0 : tree.length; + } + } + } + class FragmentCursor { + constructor(fragments, nodeSet) { + this.fragments = fragments; + this.nodeSet = nodeSet; + this.i = 0; + this.fragment = null; + this.safeFrom = -1; + this.safeTo = -1; + this.trees = []; + this.start = []; + this.index = []; + this.nextFragment(); + } + nextFragment() { + let fr = this.fragment = this.i == this.fragments.length ? null : this.fragments[this.i++]; + if (fr) { + this.safeFrom = fr.openStart ? cutAt(fr.tree, fr.from + fr.offset, 1) - fr.offset : fr.from; + this.safeTo = fr.openEnd ? cutAt(fr.tree, fr.to + fr.offset, -1) - fr.offset : fr.to; + while (this.trees.length) { + this.trees.pop(); + this.start.pop(); + this.index.pop(); + } + this.trees.push(fr.tree); + this.start.push(-fr.offset); + this.index.push(0); + this.nextStart = this.safeFrom; + } + else { + this.nextStart = 1e9; + } + } + // `pos` must be >= any previously given `pos` for this cursor + nodeAt(pos) { + if (pos < this.nextStart) + return null; + while (this.fragment && this.safeTo <= pos) + this.nextFragment(); + if (!this.fragment) + return null; + for (;;) { + let last = this.trees.length - 1; + if (last < 0) { // End of tree + this.nextFragment(); + return null; + } + let top = this.trees[last], index = this.index[last]; + if (index == top.children.length) { + this.trees.pop(); + this.start.pop(); + this.index.pop(); + continue; + } + let next = top.children[index]; + let start = this.start[last] + top.positions[index]; + if (start > pos) { + this.nextStart = start; + return null; + } + if (next instanceof Tree) { + if (start == pos) { + if (start < this.safeFrom) + return null; + let end = start + next.length; + if (end <= this.safeTo) { + let lookAhead = next.prop(NodeProp.lookAhead); + if (!lookAhead || end + lookAhead < this.fragment.to) + return next; + } + } + this.index[last]++; + if (start + next.length >= Math.max(this.safeFrom, pos)) { // Enter this node + this.trees.push(next); + this.start.push(start); + this.index.push(0); + } + } + else { + this.index[last]++; + this.nextStart = start + next.length; + } + } + } + } + class TokenCache { + constructor(parser, stream) { + this.stream = stream; + this.tokens = []; + this.mainToken = null; + this.actions = []; + this.tokens = parser.tokenizers.map(_ => new CachedToken); + } + getActions(stack) { + let actionIndex = 0; + let main = null; + let { parser } = stack.p, { tokenizers } = parser; + let mask = parser.stateSlot(stack.state, 3 /* TokenizerMask */); + let context = stack.curContext ? stack.curContext.hash : 0; + let lookAhead = 0; + for (let i = 0; i < tokenizers.length; i++) { + if (((1 << i) & mask) == 0) + continue; + let tokenizer = tokenizers[i], token = this.tokens[i]; + if (main && !tokenizer.fallback) + continue; + if (tokenizer.contextual || token.start != stack.pos || token.mask != mask || token.context != context) { + this.updateCachedToken(token, tokenizer, stack); + token.mask = mask; + token.context = context; + } + if (token.lookAhead > token.end + 25 /* Margin */) + lookAhead = Math.max(token.lookAhead, lookAhead); + if (token.value != 0 /* Err */) { + let startIndex = actionIndex; + if (token.extended > -1) + actionIndex = this.addActions(stack, token.extended, token.end, actionIndex); + actionIndex = this.addActions(stack, token.value, token.end, actionIndex); + if (!tokenizer.extend) { + main = token; + if (actionIndex > startIndex) + break; + } + } + } + while (this.actions.length > actionIndex) + this.actions.pop(); + if (lookAhead) + stack.setLookAhead(lookAhead); + if (!main && stack.pos == this.stream.end) { + main = new CachedToken; + main.value = stack.p.parser.eofTerm; + main.start = main.end = stack.pos; + actionIndex = this.addActions(stack, main.value, main.end, actionIndex); + } + this.mainToken = main; + return this.actions; + } + getMainToken(stack) { + if (this.mainToken) + return this.mainToken; + let main = new CachedToken, { pos, p } = stack; + main.start = pos; + main.end = Math.min(pos + 1, p.stream.end); + main.value = pos == p.stream.end ? p.parser.eofTerm : 0 /* Err */; + return main; + } + updateCachedToken(token, tokenizer, stack) { + let start = this.stream.clipPos(stack.pos); + tokenizer.token(this.stream.reset(start, token), stack); + if (token.value > -1) { + let { parser } = stack.p; + for (let i = 0; i < parser.specialized.length; i++) + if (parser.specialized[i] == token.value) { + let result = parser.specializers[i](this.stream.read(token.start, token.end), stack); + if (result >= 0 && stack.p.parser.dialect.allows(result >> 1)) { + if ((result & 1) == 0 /* Specialize */) + token.value = result >> 1; + else + token.extended = result >> 1; + break; + } + } + } + else { + token.value = 0 /* Err */; + token.end = this.stream.clipPos(start + 1); + } + } + putAction(action, token, end, index) { + // Don't add duplicate actions + for (let i = 0; i < index; i += 3) + if (this.actions[i] == action) + return index; + this.actions[index++] = action; + this.actions[index++] = token; + this.actions[index++] = end; + return index; + } + addActions(stack, token, end, index) { + let { state } = stack, { parser } = stack.p, { data } = parser; + for (let set = 0; set < 2; set++) { + for (let i = parser.stateSlot(state, set ? 2 /* Skip */ : 1 /* Actions */);; i += 3) { + if (data[i] == 65535 /* End */) { + if (data[i + 1] == 1 /* Next */) { + i = pair(data, i + 2); + } + else { + if (index == 0 && data[i + 1] == 2 /* Other */) + index = this.putAction(pair(data, i + 2), token, end, index); + break; + } + } + if (data[i] == token) + index = this.putAction(pair(data, i + 1), token, end, index); + } + } + return index; + } + } + var Rec; + (function (Rec) { + Rec[Rec["Distance"] = 5] = "Distance"; + Rec[Rec["MaxRemainingPerStep"] = 3] = "MaxRemainingPerStep"; + // When two stacks have been running independently long enough to + // add this many elements to their buffers, prune one. + Rec[Rec["MinBufferLengthPrune"] = 500] = "MinBufferLengthPrune"; + Rec[Rec["ForceReduceLimit"] = 10] = "ForceReduceLimit"; + // Once a stack reaches this depth (in .stack.length) force-reduce + // it back to CutTo to avoid creating trees that overflow the stack + // on recursive traversal. + Rec[Rec["CutDepth"] = 15000] = "CutDepth"; + Rec[Rec["CutTo"] = 9000] = "CutTo"; + })(Rec || (Rec = {})); + class Parse { + constructor(parser, input, fragments, ranges) { + this.parser = parser; + this.input = input; + this.ranges = ranges; + this.recovering = 0; + this.nextStackID = 0x2654; // ♔, ♕, ♖, ♗, ♘, ♙, ♠, ♡, ♢, ♣, ♤, ♥, ♦, ♧ + this.minStackPos = 0; + this.reused = []; + this.stoppedAt = null; + this.stream = new InputStream(input, ranges); + this.tokens = new TokenCache(parser, this.stream); + this.topTerm = parser.top[1]; + let { from } = ranges[0]; + this.stacks = [Stack.start(this, parser.top[0], from)]; + this.fragments = fragments.length && this.stream.end - from > parser.bufferLength * 4 + ? new FragmentCursor(fragments, parser.nodeSet) : null; + } + get parsedPos() { + return this.minStackPos; + } + // Move the parser forward. This will process all parse stacks at + // `this.pos` and try to advance them to a further position. If no + // stack for such a position is found, it'll start error-recovery. + // + // When the parse is finished, this will return a syntax tree. When + // not, it returns `null`. + advance() { + let stacks = this.stacks, pos = this.minStackPos; + // This will hold stacks beyond `pos`. + let newStacks = this.stacks = []; + let stopped, stoppedTokens; + // Keep advancing any stacks at `pos` until they either move + // forward or can't be advanced. Gather stacks that can't be + // advanced further in `stopped`. + for (let i = 0; i < stacks.length; i++) { + let stack = stacks[i]; + for (;;) { + this.tokens.mainToken = null; + if (stack.pos > pos) { + newStacks.push(stack); + } + else if (this.advanceStack(stack, newStacks, stacks)) { + continue; + } + else { + if (!stopped) { + stopped = []; + stoppedTokens = []; + } + stopped.push(stack); + let tok = this.tokens.getMainToken(stack); + stoppedTokens.push(tok.value, tok.end); + } + break; + } + } + if (!newStacks.length) { + let finished = stopped && findFinished(stopped); + if (finished) + return this.stackToTree(finished); + if (this.parser.strict) { + if (verbose && stopped) + console.log("Stuck with token " + (this.tokens.mainToken ? this.parser.getName(this.tokens.mainToken.value) : "none")); + throw new SyntaxError("No parse at " + pos); + } + if (!this.recovering) + this.recovering = 5 /* Distance */; + } + if (this.recovering && stopped) { + let finished = this.stoppedAt != null && stopped[0].pos > this.stoppedAt ? stopped[0] + : this.runRecovery(stopped, stoppedTokens, newStacks); + if (finished) + return this.stackToTree(finished.forceAll()); + } + if (this.recovering) { + let maxRemaining = this.recovering == 1 ? 1 : this.recovering * 3 /* MaxRemainingPerStep */; + if (newStacks.length > maxRemaining) { + newStacks.sort((a, b) => b.score - a.score); + while (newStacks.length > maxRemaining) + newStacks.pop(); + } + if (newStacks.some(s => s.reducePos > pos)) + this.recovering--; + } + else if (newStacks.length > 1) { + // Prune stacks that are in the same state, or that have been + // running without splitting for a while, to avoid getting stuck + // with multiple successful stacks running endlessly on. + outer: for (let i = 0; i < newStacks.length - 1; i++) { + let stack = newStacks[i]; + for (let j = i + 1; j < newStacks.length; j++) { + let other = newStacks[j]; + if (stack.sameState(other) || + stack.buffer.length > 500 /* MinBufferLengthPrune */ && other.buffer.length > 500 /* MinBufferLengthPrune */) { + if (((stack.score - other.score) || (stack.buffer.length - other.buffer.length)) > 0) { + newStacks.splice(j--, 1); + } + else { + newStacks.splice(i--, 1); + continue outer; + } + } + } + } + } + this.minStackPos = newStacks[0].pos; + for (let i = 1; i < newStacks.length; i++) + if (newStacks[i].pos < this.minStackPos) + this.minStackPos = newStacks[i].pos; + return null; + } + stopAt(pos) { + if (this.stoppedAt != null && this.stoppedAt < pos) + throw new RangeError("Can't move stoppedAt forward"); + this.stoppedAt = pos; + } + // Returns an updated version of the given stack, or null if the + // stack can't advance normally. When `split` and `stacks` are + // given, stacks split off by ambiguous operations will be pushed to + // `split`, or added to `stacks` if they move `pos` forward. + advanceStack(stack, stacks, split) { + let start = stack.pos, { parser } = this; + let base = verbose ? this.stackID(stack) + " -> " : ""; + if (this.stoppedAt != null && start > this.stoppedAt) + return stack.forceReduce() ? stack : null; + if (this.fragments) { + let strictCx = stack.curContext && stack.curContext.tracker.strict, cxHash = strictCx ? stack.curContext.hash : 0; + for (let cached = this.fragments.nodeAt(start); cached;) { + let match = this.parser.nodeSet.types[cached.type.id] == cached.type ? parser.getGoto(stack.state, cached.type.id) : -1; + if (match > -1 && cached.length && (!strictCx || (cached.prop(NodeProp.contextHash) || 0) == cxHash)) { + stack.useNode(cached, match); + if (verbose) + console.log(base + this.stackID(stack) + ` (via reuse of ${parser.getName(cached.type.id)})`); + return true; + } + if (!(cached instanceof Tree) || cached.children.length == 0 || cached.positions[0] > 0) + break; + let inner = cached.children[0]; + if (inner instanceof Tree && cached.positions[0] == 0) + cached = inner; + else + break; + } + } + let defaultReduce = parser.stateSlot(stack.state, 4 /* DefaultReduce */); + if (defaultReduce > 0) { + stack.reduce(defaultReduce); + if (verbose) + console.log(base + this.stackID(stack) + ` (via always-reduce ${parser.getName(defaultReduce & 65535 /* ValueMask */)})`); + return true; + } + if (stack.stack.length >= 15000 /* CutDepth */) { + while (stack.stack.length > 9000 /* CutTo */ && stack.forceReduce()) { } + } + let actions = this.tokens.getActions(stack); + for (let i = 0; i < actions.length;) { + let action = actions[i++], term = actions[i++], end = actions[i++]; + let last = i == actions.length || !split; + let localStack = last ? stack : stack.split(); + localStack.apply(action, term, end); + if (verbose) + console.log(base + this.stackID(localStack) + ` (via ${(action & 65536 /* ReduceFlag */) == 0 ? "shift" + : `reduce of ${parser.getName(action & 65535 /* ValueMask */)}`} for ${parser.getName(term)} @ ${start}${localStack == stack ? "" : ", split"})`); + if (last) + return true; + else if (localStack.pos > start) + stacks.push(localStack); + else + split.push(localStack); + } + return false; + } + // Advance a given stack forward as far as it will go. Returns the + // (possibly updated) stack if it got stuck, or null if it moved + // forward and was given to `pushStackDedup`. + advanceFully(stack, newStacks) { + let pos = stack.pos; + for (;;) { + if (!this.advanceStack(stack, null, null)) + return false; + if (stack.pos > pos) { + pushStackDedup(stack, newStacks); + return true; + } + } + } + runRecovery(stacks, tokens, newStacks) { + let finished = null, restarted = false; + for (let i = 0; i < stacks.length; i++) { + let stack = stacks[i], token = tokens[i << 1], tokenEnd = tokens[(i << 1) + 1]; + let base = verbose ? this.stackID(stack) + " -> " : ""; + if (stack.deadEnd) { + if (restarted) + continue; + restarted = true; + stack.restart(); + if (verbose) + console.log(base + this.stackID(stack) + " (restarted)"); + let done = this.advanceFully(stack, newStacks); + if (done) + continue; + } + let force = stack.split(), forceBase = base; + for (let j = 0; force.forceReduce() && j < 10 /* ForceReduceLimit */; j++) { + if (verbose) + console.log(forceBase + this.stackID(force) + " (via force-reduce)"); + let done = this.advanceFully(force, newStacks); + if (done) + break; + if (verbose) + forceBase = this.stackID(force) + " -> "; + } + for (let insert of stack.recoverByInsert(token)) { + if (verbose) + console.log(base + this.stackID(insert) + " (via recover-insert)"); + this.advanceFully(insert, newStacks); + } + if (this.stream.end > stack.pos) { + if (tokenEnd == stack.pos) { + tokenEnd++; + token = 0 /* Err */; + } + stack.recoverByDelete(token, tokenEnd); + if (verbose) + console.log(base + this.stackID(stack) + ` (via recover-delete ${this.parser.getName(token)})`); + pushStackDedup(stack, newStacks); + } + else if (!finished || finished.score < stack.score) { + finished = stack; + } + } + return finished; + } + // Convert the stack's buffer to a syntax tree. + stackToTree(stack) { + stack.close(); + return Tree.build({ buffer: StackBufferCursor.create(stack), + nodeSet: this.parser.nodeSet, + topID: this.topTerm, + maxBufferLength: this.parser.bufferLength, + reused: this.reused, + start: this.ranges[0].from, + length: stack.pos - this.ranges[0].from, + minRepeatType: this.parser.minRepeatTerm }); + } + stackID(stack) { + let id = (stackIDs || (stackIDs = new WeakMap)).get(stack); + if (!id) + stackIDs.set(stack, id = String.fromCodePoint(this.nextStackID++)); + return id + stack; + } + } + function pushStackDedup(stack, newStacks) { + for (let i = 0; i < newStacks.length; i++) { + let other = newStacks[i]; + if (other.pos == stack.pos && other.sameState(stack)) { + if (newStacks[i].score < stack.score) + newStacks[i] = stack; + return; + } + } + newStacks.push(stack); + } + class Dialect { + constructor(source, flags, disabled) { + this.source = source; + this.flags = flags; + this.disabled = disabled; + } + allows(term) { return !this.disabled || this.disabled[term] == 0; } + } + const id = x => x; + /// Context trackers are used to track stateful context (such as + /// indentation in the Python grammar, or parent elements in the XML + /// grammar) needed by external tokenizers. You declare them in a + /// grammar file as `@context exportName from "module"`. + /// + /// Context values should be immutable, and can be updated (replaced) + /// on shift or reduce actions. + /// + /// The export used in a `@context` declaration should be of this + /// type. + class ContextTracker { + /// Define a context tracker. + constructor(spec) { + this.start = spec.start; + this.shift = spec.shift || id; + this.reduce = spec.reduce || id; + this.reuse = spec.reuse || id; + this.hash = spec.hash || (() => 0); + this.strict = spec.strict !== false; + } + } + /// Holds the parse tables for a given grammar, as generated by + /// `lezer-generator`, and provides [methods](#common.Parser) to parse + /// content with. + class LRParser extends Parser { + /// @internal + constructor(spec) { + super(); + /// @internal + this.wrappers = []; + if (spec.version != 14 /* Version */) + throw new RangeError(`Parser version (${spec.version}) doesn't match runtime version (${14 /* Version */})`); + let nodeNames = spec.nodeNames.split(" "); + this.minRepeatTerm = nodeNames.length; + for (let i = 0; i < spec.repeatNodeCount; i++) + nodeNames.push(""); + let topTerms = Object.keys(spec.topRules).map(r => spec.topRules[r][1]); + let nodeProps = []; + for (let i = 0; i < nodeNames.length; i++) + nodeProps.push([]); + function setProp(nodeID, prop, value) { + nodeProps[nodeID].push([prop, prop.deserialize(String(value))]); + } + if (spec.nodeProps) + for (let propSpec of spec.nodeProps) { + let prop = propSpec[0]; + if (typeof prop == "string") + prop = NodeProp[prop]; + for (let i = 1; i < propSpec.length;) { + let next = propSpec[i++]; + if (next >= 0) { + setProp(next, prop, propSpec[i++]); + } + else { + let value = propSpec[i + -next]; + for (let j = -next; j > 0; j--) + setProp(propSpec[i++], prop, value); + i++; + } + } + } + this.nodeSet = new NodeSet(nodeNames.map((name, i) => NodeType.define({ + name: i >= this.minRepeatTerm ? undefined : name, + id: i, + props: nodeProps[i], + top: topTerms.indexOf(i) > -1, + error: i == 0, + skipped: spec.skippedNodes && spec.skippedNodes.indexOf(i) > -1 + }))); + if (spec.propSources) + this.nodeSet = this.nodeSet.extend(...spec.propSources); + this.strict = false; + this.bufferLength = DefaultBufferLength; + let tokenArray = decodeArray(spec.tokenData); + this.context = spec.context; + this.specializerSpecs = spec.specialized || []; + this.specialized = new Uint16Array(this.specializerSpecs.length); + for (let i = 0; i < this.specializerSpecs.length; i++) + this.specialized[i] = this.specializerSpecs[i].term; + this.specializers = this.specializerSpecs.map(getSpecializer); + this.states = decodeArray(spec.states, Uint32Array); + this.data = decodeArray(spec.stateData); + this.goto = decodeArray(spec.goto); + this.maxTerm = spec.maxTerm; + this.tokenizers = spec.tokenizers.map(value => typeof value == "number" ? new TokenGroup(tokenArray, value) : value); + this.topRules = spec.topRules; + this.dialects = spec.dialects || {}; + this.dynamicPrecedences = spec.dynamicPrecedences || null; + this.tokenPrecTable = spec.tokenPrec; + this.termNames = spec.termNames || null; + this.maxNode = this.nodeSet.types.length - 1; + this.dialect = this.parseDialect(); + this.top = this.topRules[Object.keys(this.topRules)[0]]; + } + createParse(input, fragments, ranges) { + let parse = new Parse(this, input, fragments, ranges); + for (let w of this.wrappers) + parse = w(parse, input, fragments, ranges); + return parse; + } + /// Get a goto table entry @internal + getGoto(state, term, loose = false) { + let table = this.goto; + if (term >= table[0]) + return -1; + for (let pos = table[term + 1];;) { + let groupTag = table[pos++], last = groupTag & 1; + let target = table[pos++]; + if (last && loose) + return target; + for (let end = pos + (groupTag >> 1); pos < end; pos++) + if (table[pos] == state) + return target; + if (last) + return -1; + } + } + /// Check if this state has an action for a given terminal @internal + hasAction(state, terminal) { + let data = this.data; + for (let set = 0; set < 2; set++) { + for (let i = this.stateSlot(state, set ? 2 /* Skip */ : 1 /* Actions */), next;; i += 3) { + if ((next = data[i]) == 65535 /* End */) { + if (data[i + 1] == 1 /* Next */) + next = data[i = pair(data, i + 2)]; + else if (data[i + 1] == 2 /* Other */) + return pair(data, i + 2); + else + break; + } + if (next == terminal || next == 0 /* Err */) + return pair(data, i + 1); + } + } + return 0; + } + /// @internal + stateSlot(state, slot) { + return this.states[(state * 6 /* Size */) + slot]; + } + /// @internal + stateFlag(state, flag) { + return (this.stateSlot(state, 0 /* Flags */) & flag) > 0; + } + /// @internal + validAction(state, action) { + if (action == this.stateSlot(state, 4 /* DefaultReduce */)) + return true; + for (let i = this.stateSlot(state, 1 /* Actions */);; i += 3) { + if (this.data[i] == 65535 /* End */) { + if (this.data[i + 1] == 1 /* Next */) + i = pair(this.data, i + 2); + else + return false; + } + if (action == pair(this.data, i + 1)) + return true; + } + } + /// Get the states that can follow this one through shift actions or + /// goto jumps. @internal + nextStates(state) { + let result = []; + for (let i = this.stateSlot(state, 1 /* Actions */);; i += 3) { + if (this.data[i] == 65535 /* End */) { + if (this.data[i + 1] == 1 /* Next */) + i = pair(this.data, i + 2); + else + break; + } + if ((this.data[i + 2] & (65536 /* ReduceFlag */ >> 16)) == 0) { + let value = this.data[i + 1]; + if (!result.some((v, i) => (i & 1) && v == value)) + result.push(this.data[i], value); + } + } + return result; + } + /// @internal + overrides(token, prev) { + let iPrev = findOffset(this.data, this.tokenPrecTable, prev); + return iPrev < 0 || findOffset(this.data, this.tokenPrecTable, token) < iPrev; + } + /// Configure the parser. Returns a new parser instance that has the + /// given settings modified. Settings not provided in `config` are + /// kept from the original parser. + configure(config) { + // Hideous reflection-based kludge to make it easy to create a + // slightly modified copy of a parser. + let copy = Object.assign(Object.create(LRParser.prototype), this); + if (config.props) + copy.nodeSet = this.nodeSet.extend(...config.props); + if (config.top) { + let info = this.topRules[config.top]; + if (!info) + throw new RangeError(`Invalid top rule name ${config.top}`); + copy.top = info; + } + if (config.tokenizers) + copy.tokenizers = this.tokenizers.map(t => { + let found = config.tokenizers.find(r => r.from == t); + return found ? found.to : t; + }); + if (config.specializers) { + copy.specializers = this.specializers.slice(); + copy.specializerSpecs = this.specializerSpecs.map((s, i) => { + let found = config.specializers.find(r => r.from == s.external); + if (!found) + return s; + let spec = Object.assign(Object.assign({}, s), { external: found.to }); + copy.specializers[i] = getSpecializer(spec); + return spec; + }); + } + if (config.contextTracker) + copy.context = config.contextTracker; + if (config.dialect) + copy.dialect = this.parseDialect(config.dialect); + if (config.strict != null) + copy.strict = config.strict; + if (config.wrap) + copy.wrappers = copy.wrappers.concat(config.wrap); + if (config.bufferLength != null) + copy.bufferLength = config.bufferLength; + return copy; + } + /// Tells you whether any [parse wrappers](#lr.ParserConfig.wrap) + /// are registered for this parser. + hasWrappers() { + return this.wrappers.length > 0; + } + /// Returns the name associated with a given term. This will only + /// work for all terms when the parser was generated with the + /// `--names` option. By default, only the names of tagged terms are + /// stored. + getName(term) { + return this.termNames ? this.termNames[term] : String(term <= this.maxNode && this.nodeSet.types[term].name || term); + } + /// The eof term id is always allocated directly after the node + /// types. @internal + get eofTerm() { return this.maxNode + 1; } + /// The type of top node produced by the parser. + get topNode() { return this.nodeSet.types[this.top[1]]; } + /// @internal + dynamicPrecedence(term) { + let prec = this.dynamicPrecedences; + return prec == null ? 0 : prec[term] || 0; + } + /// @internal + parseDialect(dialect) { + let values = Object.keys(this.dialects), flags = values.map(() => false); + if (dialect) + for (let part of dialect.split(" ")) { + let id = values.indexOf(part); + if (id >= 0) + flags[id] = true; + } + let disabled = null; + for (let i = 0; i < values.length; i++) + if (!flags[i]) { + for (let j = this.dialects[values[i]], id; (id = this.data[j++]) != 65535 /* End */;) + (disabled || (disabled = new Uint8Array(this.maxTerm + 1)))[id] = 1; + } + return new Dialect(dialect, flags, disabled); + } + /// Used by the output of the parser generator. Not available to + /// user code. + static deserialize(spec) { + return new LRParser(spec); + } + } + function pair(data, off) { return data[off] | (data[off + 1] << 16); } + function findOffset(data, start, term) { + for (let i = start, next; (next = data[i]) != 65535 /* End */; i++) + if (next == term) + return i - start; + return -1; + } + function findFinished(stacks) { + let best = null; + for (let stack of stacks) { + let stopped = stack.p.stoppedAt; + if ((stack.pos == stack.p.stream.end || stopped != null && stack.pos > stopped) && + stack.p.parser.stateFlag(stack.state, 2 /* Accepting */) && + (!best || best.score < stack.score)) + best = stack; + } + return best; + } + function getSpecializer(spec) { + if (spec.external) { + let mask = spec.extend ? 1 /* Extend */ : 0 /* Specialize */; + return (value, stack) => (spec.external(value, stack) << 1) | mask; + } + return spec.get; + } + + // This file was generated by lezer-generator. You probably shouldn't edit it. + const printKeyword = 1, + indent = 189, + dedent = 190, + newline$1 = 191, + newlineBracketed = 192, + newlineEmpty = 193, + eof = 194, + ParenL = 22, + ParenthesizedExpression = 23, + TupleExpression = 47, + ComprehensionExpression = 48, + BracketL = 53, + ArrayExpression = 54, + ArrayComprehensionExpression = 55, + BraceL = 57, + DictionaryExpression = 58, + DictionaryComprehensionExpression = 59, + SetExpression = 60, + SetComprehensionExpression = 61, + ArgList = 63, + subscript = 230, + FormatReplacement = 71, + importList = 255, + ParamList = 121, + SequencePattern = 142, + MappingPattern = 143, + PatternArgList = 146; + + const newline = 10, carriageReturn = 13, space = 32, tab = 9, hash = 35, parenOpen = 40, dot = 46; + + const bracketed = new Set([ + ParenthesizedExpression, TupleExpression, ComprehensionExpression, importList, ArgList, ParamList, + ArrayExpression, ArrayComprehensionExpression, subscript, + SetExpression, SetComprehensionExpression, + DictionaryExpression, DictionaryComprehensionExpression, FormatReplacement, + SequencePattern, MappingPattern, PatternArgList + ]); + + const newlines = new ExternalTokenizer((input, stack) => { + if (input.next < 0) { + input.acceptToken(eof); + } else if (input.next != newline && input.next != carriageReturn) ; else if (stack.context.depth < 0) { + input.acceptToken(newlineBracketed, 1); + } else { + input.advance(); + let spaces = 0; + while (input.next == space || input.next == tab) { input.advance(); spaces++; } + let empty = input.next == newline || input.next == carriageReturn || input.next == hash; + input.acceptToken(empty ? newlineEmpty : newline$1, -spaces); + } + }, {contextual: true, fallback: true}); + + const indentation = new ExternalTokenizer((input, stack) => { + let cDepth = stack.context.depth; + if (cDepth < 0) return + let prev = input.peek(-1); + if ((prev == newline || prev == carriageReturn) && stack.context.depth >= 0) { + let depth = 0, chars = 0; + for (;;) { + if (input.next == space) depth++; + else if (input.next == tab) depth += 8 - (depth % 8); + else break + input.advance(); + chars++; + } + if (depth != cDepth && + input.next != newline && input.next != carriageReturn && input.next != hash) { + if (depth < cDepth) input.acceptToken(dedent, -chars); + else input.acceptToken(indent); + } + } + }); + + function IndentLevel(parent, depth) { + this.parent = parent; + // -1 means this is not an actual indent level but a set of brackets + this.depth = depth; + this.hash = (parent ? parent.hash + parent.hash << 8 : 0) + depth + (depth << 4); + } + + const topIndent = new IndentLevel(null, 0); + + function countIndent(space) { + let depth = 0; + for (let i = 0; i < space.length; i++) + depth += space.charCodeAt(i) == tab ? 8 - (depth % 8) : 1; + return depth + } + + const trackIndent = new ContextTracker({ + start: topIndent, + reduce(context, term) { + return context.depth < 0 && bracketed.has(term) ? context.parent : context + }, + shift(context, term, stack, input) { + if (term == indent) return new IndentLevel(context, countIndent(input.read(input.pos, stack.pos))) + if (term == dedent) return context.parent + if (term == ParenL || term == BracketL || term == BraceL) return new IndentLevel(context, -1) + return context + }, + hash(context) { return context.hash } + }); + + const legacyPrint = new ExternalTokenizer(input => { + for (let i = 0; i < 5; i++) { + if (input.next != "print".charCodeAt(i)) return + input.advance(); + } + if (/\w/.test(String.fromCharCode(input.next))) return + for (let off = 0;; off++) { + let next = input.peek(off); + if (next == space || next == tab) continue + if (next != parenOpen && next != dot && next != newline && next != carriageReturn && next != hash) + input.acceptToken(printKeyword); + return + } + }); + + const pythonHighlighting = styleTags({ + "async \"*\" \"**\" FormatConversion FormatSpec": tags.modifier, + "for while if elif else try except finally return raise break continue with pass assert await yield": tags.controlKeyword, + "in not and or is del": tags.operatorKeyword, + "from def class global nonlocal lambda": tags.definitionKeyword, + import: tags.moduleKeyword, + "with as print": tags.keyword, + Boolean: tags.bool, + None: tags.null, + VariableName: tags.variableName, + "CallExpression/VariableName": tags.function(tags.variableName), + "FunctionDefinition/VariableName": tags.function(tags.definition(tags.variableName)), + "ClassDefinition/VariableName": tags.definition(tags.className), + PropertyName: tags.propertyName, + "CallExpression/MemberExpression/PropertyName": tags.function(tags.propertyName), + Comment: tags.lineComment, + Number: tags.number, + String: tags.string, + FormatString: tags.special(tags.string), + UpdateOp: tags.updateOperator, + ArithOp: tags.arithmeticOperator, + BitOp: tags.bitwiseOperator, + CompareOp: tags.compareOperator, + AssignOp: tags.definitionOperator, + Ellipsis: tags.punctuation, + At: tags.meta, + "( )": tags.paren, + "[ ]": tags.squareBracket, + "{ }": tags.brace, + ".": tags.derefOperator, + ", ;": tags.separator + }); + + // This file was generated by lezer-generator. You probably shouldn't edit it. + const spec_identifier = {__proto__:null,await:40, or:50, and:52, in:56, not:58, is:60, if:66, else:68, lambda:72, yield:90, from:92, async:98, for:100, None:152, True:154, False:154, del:168, pass:172, break:176, continue:180, return:184, raise:192, import:196, as:198, global:202, nonlocal:204, assert:208, elif:218, while:222, try:228, except:230, finally:232, with:236, def:240, class:250, match:261, case:267}; + const parser = LRParser.deserialize({ + version: 14, + states: "!L`O`Q$IXOOO%fQ$I[O'#G|OOQ$IS'#Cm'#CmOOQ$IS'#Cn'#CnO'UQ$IWO'#ClO(wQ$I[O'#G{OOQ$IS'#G|'#G|OOQ$IS'#DS'#DSOOQ$IS'#G{'#G{O)eQ$IWO'#CsO)uQ$IWO'#DdO*VQ$IWO'#DhOOQ$IS'#Ds'#DsO*jO`O'#DsO*rOpO'#DsO*zO!bO'#DtO+VO#tO'#DtO+bO&jO'#DtO+mO,UO'#DtO-oQ$I[O'#GmOOQ$IS'#Gm'#GmO'UQ$IWO'#GlO/RQ$I[O'#GlOOQ$IS'#E]'#E]O/jQ$IWO'#E^OOQ$IS'#Gk'#GkO/tQ$IWO'#GjOOQ$IV'#Gj'#GjO0PQ$IWO'#FPOOQ$IS'#GX'#GXO0UQ$IWO'#FOOOQ$IV'#Hx'#HxOOQ$IV'#Gi'#GiOOQ$IT'#Fh'#FhQ`Q$IXOOO'UQ$IWO'#CoO0dQ$IWO'#C{O0kQ$IWO'#DPO0yQ$IWO'#HQO1ZQ$I[O'#EQO'UQ$IWO'#EROOQ$IS'#ET'#ETOOQ$IS'#EV'#EVOOQ$IS'#EX'#EXO1oQ$IWO'#EZO2VQ$IWO'#E_O0PQ$IWO'#EaO2jQ$I[O'#EaO0PQ$IWO'#EdO/jQ$IWO'#EgO/jQ$IWO'#EkO/jQ$IWO'#EnO2uQ$IWO'#EpO2|Q$IWO'#EuO3XQ$IWO'#EqO/jQ$IWO'#EuO0PQ$IWO'#EwO0PQ$IWO'#E|O3^Q$IWO'#FROOQ$IS'#Cc'#CcOOQ$IS'#Cd'#CdOOQ$IS'#Ce'#CeOOQ$IS'#Cf'#CfOOQ$IS'#Cg'#CgOOQ$IS'#Ch'#ChOOQ$IS'#Cj'#CjO'UQ$IWO,58|O'UQ$IWO,58|O'UQ$IWO,58|O'UQ$IWO,58|O'UQ$IWO,58|O'UQ$IWO,58|O3eQ$IWO'#DmOOQ$IS,5:W,5:WO3xQ$IWO'#H[OOQ$IS,5:Z,5:ZO4VQ%1`O,5:ZO4[Q$I[O,59WO0dQ$IWO,59`O0dQ$IWO,59`O0dQ$IWO,59`O6zQ$IWO,59`O7PQ$IWO,59`O7WQ$IWO,59hO7_Q$IWO'#G{O8eQ$IWO'#GzOOQ$IS'#Gz'#GzOOQ$IS'#DY'#DYO8|Q$IWO,59_O'UQ$IWO,59_O9[Q$IWO,59_O9aQ$IWO,5:PO'UQ$IWO,5:POOQ$IS,5:O,5:OO9oQ$IWO,5:OO9tQ$IWO,5:VO'UQ$IWO,5:VO'UQ$IWO,5:TOOQ$IS,5:S,5:SO:VQ$IWO,5:SO:[Q$IWO,5:UOOOO'#Fp'#FpO:aO`O,5:_OOQ$IS,5:_,5:_OOOO'#Fq'#FqO:iOpO,5:_O:qQ$IWO'#DuOOOO'#Fr'#FrO;RO!bO,5:`OOQ$IS,5:`,5:`OOOO'#Fu'#FuO;^O#tO,5:`OOOO'#Fv'#FvO;iO&jO,5:`OOOO'#Fw'#FwO;tO,UO,5:`OOQ$IS'#Fx'#FxO<PQ$I[O,5:dO>qQ$I[O,5=WO?[Q%GlO,5=WO?{Q$I[O,5=WOOQ$IS,5:x,5:xO@dQ$IXO'#GQOAsQ$IWO,5;TOOQ$IV,5=U,5=UOBOQ$I[O'#HtOBgQ$IWO,5;kOOQ$IS-E:V-E:VOOQ$IV,5;j,5;jO3SQ$IWO'#EwOOQ$IT-E9f-E9fOBoQ$I[O,59ZODvQ$I[O,59gOEaQ$IWO'#G}OElQ$IWO'#G}O0PQ$IWO'#G}OEwQ$IWO'#DROFPQ$IWO,59kOFUQ$IWO'#HRO'UQ$IWO'#HRO/jQ$IWO,5=lOOQ$IS,5=l,5=lO/jQ$IWO'#D|OOQ$IS'#D}'#D}OFsQ$IWO'#FzOGTQ$IWO,58zOGTQ$IWO,58zO)hQ$IWO,5:jOGcQ$I[O'#HTOOQ$IS,5:m,5:mOOQ$IS,5:u,5:uOGvQ$IWO,5:yOHXQ$IWO,5:{OOQ$IS'#F}'#F}OHgQ$I[O,5:{OHuQ$IWO,5:{OHzQ$IWO'#HwOOQ$IS,5;O,5;OOIYQ$IWO'#HsOOQ$IS,5;R,5;RO3XQ$IWO,5;VO3XQ$IWO,5;YOIkQ$I[O'#HyO'UQ$IWO'#HyOIuQ$IWO,5;[O2uQ$IWO,5;[O/jQ$IWO,5;aO0PQ$IWO,5;cOIzQ$IXO'#ElOKTQ$IZO,5;]ONiQ$IWO'#HzO3XQ$IWO,5;aONtQ$IWO,5;cONyQ$IWO,5;hO! RQ$I[O,5;mO'UQ$IWO,5;mO!#uQ$I[O1G.hO!#|Q$I[O1G.hO!&mQ$I[O1G.hO!&wQ$I[O1G.hO!)bQ$I[O1G.hO!)uQ$I[O1G.hO!*YQ$IWO'#HZO!*hQ$I[O'#GmO/jQ$IWO'#HZO!*rQ$IWO'#HYOOQ$IS,5:X,5:XO!*zQ$IWO,5:XO!+PQ$IWO'#H]O!+[Q$IWO'#H]O!+oQ$IWO,5=vOOQ$IS'#Dq'#DqOOQ$IS1G/u1G/uOOQ$IS1G.z1G.zO!,oQ$I[O1G.zO!,vQ$I[O1G.zO0dQ$IWO1G.zO!-cQ$IWO1G/SOOQ$IS'#DX'#DXO/jQ$IWO,59rOOQ$IS1G.y1G.yO!-jQ$IWO1G/cO!-zQ$IWO1G/cO!.SQ$IWO1G/dO'UQ$IWO'#HSO!.XQ$IWO'#HSO!.^Q$I[O1G.yO!.nQ$IWO,59gO!/tQ$IWO,5=rO!0UQ$IWO,5=rO!0^Q$IWO1G/kO!0cQ$I[O1G/kOOQ$IS1G/j1G/jO!0sQ$IWO,5=mO!1jQ$IWO,5=mO/jQ$IWO1G/oO!2XQ$IWO1G/qO!2^Q$I[O1G/qO!2nQ$I[O1G/oOOQ$IS1G/n1G/nOOQ$IS1G/p1G/pOOOO-E9n-E9nOOQ$IS1G/y1G/yOOOO-E9o-E9oO!3OQ$IWO'#HhO/jQ$IWO'#HhO!3^Q$IWO,5:aOOOO-E9p-E9pOOQ$IS1G/z1G/zOOOO-E9s-E9sOOOO-E9t-E9tOOOO-E9u-E9uOOQ$IS-E9v-E9vO!3iQ%GlO1G2rO!4YQ$I[O1G2rO'UQ$IWO,5<eOOQ$IS,5<e,5<eOOQ$IS-E9w-E9wOOQ$IS,5<l,5<lOOQ$IS-E:O-E:OOOQ$IV1G0o1G0oO0PQ$IWO'#F|O!4qQ$I[O,5>`OOQ$IS1G1V1G1VO!5YQ$IWO1G1VOOQ$IS'#DT'#DTO/jQ$IWO,5=iOOQ$IS,5=i,5=iO!5_Q$IWO'#FiO!5jQ$IWO,59mO!5rQ$IWO1G/VO!5|Q$I[O,5=mOOQ$IS1G3W1G3WOOQ$IS,5:h,5:hO!6mQ$IWO'#GlOOQ$IS,5<f,5<fOOQ$IS-E9x-E9xO!7OQ$IWO1G.fOOQ$IS1G0U1G0UO!7^Q$IWO,5=oO!7nQ$IWO,5=oO/jQ$IWO1G0eO/jQ$IWO1G0eO0PQ$IWO1G0gOOQ$IS-E9{-E9{O!8PQ$IWO1G0gO!8[Q$IWO1G0gO!8aQ$IWO,5>cO!8oQ$IWO,5>cO!8}Q$IWO,5>_O!9eQ$IWO,5>_O!9vQ$IZO1G0qO!=XQ$IZO1G0tO!@gQ$IWO,5>eO!@qQ$IWO,5>eO!@yQ$I[O,5>eO/jQ$IWO1G0vO!ATQ$IWO1G0vO3XQ$IWO1G0{ONtQ$IWO1G0}OOQ$IV,5;W,5;WO!AYQ$IYO,5;WO!A_Q$IZO1G0wO!DsQ$IWO'#GUO3XQ$IWO1G0wO3XQ$IWO1G0wO!EQQ$IWO,5>fO!E_Q$IWO,5>fO0PQ$IWO,5>fOOQ$IV1G0{1G0{O!EgQ$IWO'#EyO!ExQ%1`O1G0}OOQ$IV1G1S1G1SO3XQ$IWO1G1SO!FQQ$IWO'#FTOOQ$IV1G1X1G1XO! RQ$I[O1G1XOOQ$IS,5=u,5=uOOQ$IS'#Dn'#DnO/jQ$IWO,5=uO!FVQ$IWO,5=tO!FjQ$IWO,5=tOOQ$IS1G/s1G/sO!FrQ$IWO,5=wO!GSQ$IWO,5=wO!G[Q$IWO,5=wO!GoQ$IWO,5=wO!HPQ$IWO,5=wOOQ$IS1G3b1G3bOOQ$IS7+$f7+$fO!5rQ$IWO7+$nO!IrQ$IWO1G.zO!IyQ$IWO1G.zOOQ$IS1G/^1G/^OOQ$IS,5<V,5<VO'UQ$IWO,5<VOOQ$IS7+$}7+$}O!JQQ$IWO7+$}OOQ$IS-E9i-E9iOOQ$IS7+%O7+%OO!JbQ$IWO,5=nO'UQ$IWO,5=nOOQ$IS7+$e7+$eO!JgQ$IWO7+$}O!JoQ$IWO7+%OO!JtQ$IWO1G3^OOQ$IS7+%V7+%VO!KUQ$IWO1G3^O!K^Q$IWO7+%VOOQ$IS,5<U,5<UO'UQ$IWO,5<UO!KcQ$IWO1G3XOOQ$IS-E9h-E9hO!LYQ$IWO7+%ZOOQ$IS7+%]7+%]O!LhQ$IWO1G3XO!MVQ$IWO7+%]O!M[Q$IWO1G3_O!MlQ$IWO1G3_O!MtQ$IWO7+%ZO!MyQ$IWO,5>SO!NaQ$IWO,5>SO!NaQ$IWO,5>SO!NoO!LQO'#DwO!NzOSO'#HiOOOO1G/{1G/{O# PQ$IWO1G/{O# XQ%GlO7+(^O# xQ$I[O1G2PP#!cQ$IWO'#FyOOQ$IS,5<h,5<hOOQ$IS-E9z-E9zOOQ$IS7+&q7+&qOOQ$IS1G3T1G3TOOQ$IS,5<T,5<TOOQ$IS-E9g-E9gOOQ$IS7+$q7+$qO#!pQ$IWO,5=WO##ZQ$IWO,5=WO##lQ$I[O,5<WO#$PQ$IWO1G3ZOOQ$IS-E9j-E9jOOQ$IS7+&P7+&PO#$aQ$IWO7+&POOQ$IS7+&R7+&RO#$oQ$IWO'#HvO0PQ$IWO'#HuO#%TQ$IWO7+&ROOQ$IS,5<k,5<kO#%`Q$IWO1G3}OOQ$IS-E9}-E9}OOQ$IS,5<g,5<gO#%nQ$IWO1G3yOOQ$IS-E9y-E9yO#&UQ$IZO7+&]O!DsQ$IWO'#GSO3XQ$IWO7+&]O3XQ$IWO7+&`O#)gQ$I[O,5<oO'UQ$IWO,5<oO#)qQ$IWO1G4POOQ$IS-E:R-E:RO#){Q$IWO1G4PO3XQ$IWO7+&bO/jQ$IWO7+&bOOQ$IV7+&g7+&gO!ExQ%1`O7+&iO#*TQ$IXO1G0rOOQ$IV-E:S-E:SO3XQ$IWO7+&cO3XQ$IWO7+&cOOQ$IV,5<p,5<pO#+yQ$IWO,5<pOOQ$IV7+&c7+&cO#,UQ$IZO7+&cO#/dQ$IWO,5<qO#/oQ$IWO1G4QOOQ$IS-E:T-E:TO#/|Q$IWO1G4QO#0UQ$IWO'#H|O#0dQ$IWO'#H|O0PQ$IWO'#H|OOQ$IS'#H|'#H|O#0oQ$IWO'#H{OOQ$IS,5;e,5;eO#0wQ$IWO,5;eO/jQ$IWO'#E{OOQ$IV7+&i7+&iO3XQ$IWO7+&iOOQ$IV7+&n7+&nO#0|Q$IYO,5;oOOQ$IV7+&s7+&sOOQ$IS1G3a1G3aOOQ$IS,5<Y,5<YO#1RQ$IWO1G3`OOQ$IS-E9l-E9lO#1fQ$IWO,5<ZO#1qQ$IWO,5<ZO#2UQ$IWO1G3cOOQ$IS-E9m-E9mO#2fQ$IWO1G3cO#2nQ$IWO1G3cO#3OQ$IWO1G3cO#2fQ$IWO1G3cOOQ$IS<<HY<<HYO#3ZQ$I[O1G1qOOQ$IS<<Hi<<HiP#3hQ$IWO'#FkO7WQ$IWO1G3YO#3uQ$IWO1G3YO#3zQ$IWO<<HiOOQ$IS<<Hj<<HjO#4[Q$IWO7+(xOOQ$IS<<Hq<<HqO#4lQ$I[O1G1pP#5]Q$IWO'#FjO#5jQ$IWO7+(yO#5zQ$IWO7+(yO#6SQ$IWO<<HuO#6XQ$IWO7+(sOOQ$IS<<Hw<<HwO#7OQ$IWO,5<XO'UQ$IWO,5<XOOQ$IS-E9k-E9kOOQ$IS<<Hu<<HuOOQ$IS,5<_,5<_O/jQ$IWO,5<_O#7TQ$IWO1G3nOOQ$IS-E9q-E9qO#7kQ$IWO1G3nOOOO'#Ft'#FtO#7yO!LQO,5:cOOOO,5>T,5>TOOOO7+%g7+%gO#8UQ$IWO1G2rO#8oQ$IWO1G2rP'UQ$IWO'#FlO/jQ$IWO<<IkO#9QQ$IWO,5>bO#9cQ$IWO,5>bO0PQ$IWO,5>bO#9tQ$IWO,5>aOOQ$IS<<Im<<ImP0PQ$IWO'#GPP/jQ$IWO'#F{OOQ$IV-E:Q-E:QO3XQ$IWO<<IwOOQ$IV,5<n,5<nO3XQ$IWO,5<nOOQ$IV<<Iw<<IwOOQ$IV<<Iz<<IzO#9yQ$I[O1G2ZP#:TQ$IWO'#GTO#:[Q$IWO7+)kO#:fQ$IZO<<I|O3XQ$IWO<<I|OOQ$IV<<JT<<JTO3XQ$IWO<<JTOOQ$IV'#GR'#GRO#=tQ$IZO7+&^OOQ$IV<<I}<<I}O#?pQ$IZO<<I}OOQ$IV1G2[1G2[O0PQ$IWO1G2[O3XQ$IWO<<I}O0PQ$IWO1G2]P/jQ$IWO'#GVO#COQ$IWO7+)lO#C]Q$IWO7+)lOOQ$IS'#Ez'#EzO/jQ$IWO,5>hO#CeQ$IWO,5>hOOQ$IS,5>h,5>hO#CpQ$IWO,5>gO#DRQ$IWO,5>gOOQ$IS1G1P1G1POOQ$IS,5;g,5;gO#DZQ$IWO1G1ZP#D`Q$IWO'#FnO#DpQ$IWO1G1uO#ETQ$IWO1G1uO#EeQ$IWO1G1uP#EpQ$IWO'#FoO#E}Q$IWO7+(}O#F_Q$IWO7+(}O#F_Q$IWO7+(}O#FgQ$IWO7+(}O#FwQ$IWO7+(tO7WQ$IWO7+(tOOQ$ISAN>TAN>TO#GbQ$IWO<<LeOOQ$ISAN>aAN>aO/jQ$IWO1G1sO#GrQ$I[O1G1sP#G|Q$IWO'#FmOOQ$IS1G1y1G1yP#HZQ$IWO'#FsO#HhQ$IWO7+)YOOOO-E9r-E9rO#IOQ$IWO7+(^OOQ$ISAN?VAN?VO#IiQ$IWO,5<jO#I}Q$IWO1G3|OOQ$IS-E9|-E9|O#J`Q$IWO1G3|OOQ$IS1G3{1G3{OOQ$IVAN?cAN?cOOQ$IV1G2Y1G2YO3XQ$IWOAN?hO#JqQ$IZOAN?hOOQ$IVAN?oAN?oOOQ$IV-E:P-E:POOQ$IV<<Ix<<IxO3XQ$IWOAN?iO3XQ$IWO7+'vOOQ$IVAN?iAN?iOOQ$IS7+'w7+'wO#NPQ$IWO<<MWOOQ$IS1G4S1G4SO/jQ$IWO1G4SOOQ$IS,5<r,5<rO#N^Q$IWO1G4ROOQ$IS-E:U-E:UOOQ$IU'#GY'#GYO#NoQ$IYO7+&uO#NzQ$IWO'#FUO$ rQ$IWO7+'aO$!SQ$IWO7+'aOOQ$IS7+'a7+'aO$!_Q$IWO<<LiO$!oQ$IWO<<LiO$!oQ$IWO<<LiO$!wQ$IWO'#HUOOQ$IS<<L`<<L`O$#RQ$IWO<<L`OOQ$IS7+'_7+'_O0PQ$IWO1G2UP0PQ$IWO'#GOO$#lQ$IWO7+)hO$#}Q$IWO7+)hOOQ$IVG25SG25SO3XQ$IWOG25SOOQ$IVG25TG25TOOQ$IV<<Kb<<KbOOQ$IS7+)n7+)nP$$`Q$IWO'#GWOOQ$IU-E:W-E:WOOQ$IV<<Ja<<JaO$%SQ$I[O'#FWOOQ$IS'#FY'#FYO$%dQ$IWO'#FXO$&UQ$IWO'#FXOOQ$IS'#FX'#FXO$&ZQ$IWO'#IOO#NzQ$IWO'#F`O#NzQ$IWO'#F`O$&rQ$IWO'#FaO#NzQ$IWO'#FbO$&yQ$IWO'#IPOOQ$IS'#IP'#IPO$'hQ$IWO,5;pOOQ$IS<<J{<<J{O$'pQ$IWO<<J{O$(QQ$IWOANBTO$(bQ$IWOANBTO$(jQ$IWO'#HVOOQ$IS'#HV'#HVO0kQ$IWO'#DaO$)TQ$IWO,5=pOOQ$ISANAzANAzOOQ$IS7+'p7+'pO$)lQ$IWO<<MSOOQ$IVLD*nLD*nO4VQ%1`O'#G[O$)}Q$I[O,5;yO#NzQ$IWO'#FdOOQ$IS,5;},5;}OOQ$IS'#FZ'#FZO$*oQ$IWO,5;sO$*tQ$IWO,5;sOOQ$IS'#F^'#F^O#NzQ$IWO'#GZO$+fQ$IWO,5;wO$,QQ$IWO,5>jO$,bQ$IWO,5>jO0PQ$IWO,5;vO$,sQ$IWO,5;zO$,xQ$IWO,5;zO#NzQ$IWO'#IQO$,}Q$IWO'#IQO$-SQ$IWO,5;{OOQ$IS,5;|,5;|O'UQ$IWO'#FgOOQ$IU1G1[1G1[O3XQ$IWO1G1[OOQ$ISAN@gAN@gO$-XQ$IWOG27oO$-iQ$IWO,59{OOQ$IS1G3[1G3[OOQ$IS,5<v,5<vOOQ$IS-E:Y-E:YO$-nQ$I[O'#FWO$-uQ$IWO'#IRO$.TQ$IWO'#IRO$.]Q$IWO,5<OOOQ$IS1G1_1G1_O$.bQ$IWO1G1_O$.gQ$IWO,5<uOOQ$IS-E:X-E:XO$/RQ$IWO,5<yO$/jQ$IWO1G4UOOQ$IS-E:]-E:]OOQ$IS1G1b1G1bOOQ$IS1G1f1G1fO$/zQ$IWO,5>lO#NzQ$IWO,5>lOOQ$IS1G1g1G1gO$0YQ$I[O,5<ROOQ$IU7+&v7+&vO$!wQ$IWO1G/gO#NzQ$IWO,5<PO$0aQ$IWO,5>mO$0hQ$IWO,5>mOOQ$IS1G1j1G1jOOQ$IS7+&y7+&yP#NzQ$IWO'#G_O$0pQ$IWO1G4WO$0zQ$IWO1G4WO$1SQ$IWO1G4WOOQ$IS7+%R7+%RO$1bQ$IWO1G1kO$1pQ$I[O'#FWO$1wQ$IWO,5<xOOQ$IS,5<x,5<xO$2VQ$IWO1G4XOOQ$IS-E:[-E:[O#NzQ$IWO,5<wO$2^Q$IWO,5<wO$2cQ$IWO7+)rOOQ$IS-E:Z-E:ZO$2mQ$IWO7+)rO#NzQ$IWO,5<QP#NzQ$IWO'#G^O$2uQ$IWO1G2cO#NzQ$IWO1G2cP$3TQ$IWO'#G]O$3[Q$IWO<<M^O$3fQ$IWO1G1lO$3tQ$IWO7+'}O7WQ$IWO'#C{O7WQ$IWO,59`O7WQ$IWO,59`O7WQ$IWO,59`O$4SQ$I[O,5=WO7WQ$IWO1G.zO/jQ$IWO1G/VO/jQ$IWO7+$nP$4gQ$IWO'#FyO'UQ$IWO'#GlO$4tQ$IWO,59`O$4yQ$IWO,59`O$5QQ$IWO,59kO$5VQ$IWO1G/SO0kQ$IWO'#DPO7WQ$IWO,59h", + stateData: "$5m~O%[OS%XOS%WOSQOS~OPhOTeOdsOfXOmtOq!SOtuO}vO!O!PO!R!VO!S!UO!VYO!ZZO!fdO!mdO!ndO!odO!vxO!xyO!zzO!|{O#O|O#S}O#U!OO#X!QO#Y!QO#[!RO#c!TO#f!WO#j!XO#l!YO#q!ZO#tlO#v![O%VqO%gQO%hQO%lRO%mVO&R[O&S]O&V^O&Y_O&``O&caO&ebO~OT!bO]!bO_!cOf!jO!V!lO!d!nO%b!]O%c!^O%d!_O%e!`O%f!`O%g!aO%h!aO%i!bO%j!bO%k!bO~Oi%pXj%pXk%pXl%pXm%pXn%pXq%pXx%pXy%pX!s%pX#^%pX%V%pX%Y%pX%r%pXe%pX!R%pX!S%pX%s%pX!U%pX!Y%pX!O%pX#V%pXr%pX!j%pX~P$bOdsOfXO!VYO!ZZO!fdO!mdO!ndO!odO%gQO%hQO%lRO%mVO&R[O&S]O&V^O&Y_O&``O&caO&ebO~Ox%oXy%oX#^%oX%V%oX%Y%oX%r%oX~Oi!qOj!rOk!pOl!pOm!sOn!tOq!uO!s%oX~P(cOT!{Om/iOt/wO}vO~P'UOT#OOm/iOt/wO!U#PO~P'UOT#SO_#TOm/iOt/wO!Y#UO~P'UO&T#XO&U#ZO~O&W#[O&X#ZO~O!Z#^O&Z#_O&_#aO~O!Z#^O&a#bO&b#aO~O!Z#^O&U#aO&d#dO~O!Z#^O&X#aO&f#fO~OT%aX]%aX_%aXf%aXi%aXj%aXk%aXl%aXm%aXn%aXq%aXx%aX!V%aX!d%aX%b%aX%c%aX%d%aX%e%aX%f%aX%g%aX%h%aX%i%aX%j%aX%k%aXe%aX!R%aX!S%aX~O&R[O&S]O&V^O&Y_O&``O&caO&ebOy%aX!s%aX#^%aX%V%aX%Y%aX%r%aX%s%aX!U%aX!Y%aX!O%aX#V%aXr%aX!j%aX~P+xOx#kOy%`X!s%`X#^%`X%V%`X%Y%`X%r%`X~Om/iOt/wO~P'UO#^#nO%V#pO%Y#pO~O%mVO~O!R#uO#l!YO#q!ZO#tlO~OmtO~P'UOT#zO_#{O%mVOyuP~OT$POm/iOt/wO!O$QO~P'UOy$SO!s$XO%r$TO#^!tX%V!tX%Y!tX~OT$POm/iOt/wO#^!}X%V!}X%Y!}X~P'UOm/iOt/wO#^#RX%V#RX%Y#RX~P'UO!d$_O!m$_O%mVO~OT$iO~P'UO!S$kO#j$lO#l$mO~Oy$nO~OT$uO~P'UOT%OO_%OOe%QOm/iOt/wO~P'UOm/iOt/wOy%TO~P'UO&Q%VO~O_!cOf!jO!V!lO!d!nOT`a]`ai`aj`ak`al`am`an`aq`ax`ay`a!s`a#^`a%V`a%Y`a%b`a%c`a%d`a%e`a%f`a%g`a%h`a%i`a%j`a%k`a%r`ae`a!R`a!S`a%s`a!U`a!Y`a!O`a#V`ar`a!j`a~Ol%[O~Om%[O~P'UOm/iO~P'UOi/kOj/lOk/jOl/jOm/sOn/tOq/xOe%oX!R%oX!S%oX%s%oX!U%oX!Y%oX!O%oX#V%oX!j%oX~P(cO%s%^Oe%nXx%nX!R%nX!S%nX!U%nXy%nX~Oe%`Ox%aO!R%eO!S%dO~Oe%`O~Ox%hO!R%eO!S%dO!U%zX~O!U%lO~Ox%mOy%oO!R%eO!S%dO!Y%uX~O!Y%sO~O!Y%tO~O&T#XO&U%vO~O&W#[O&X%vO~OT%yOm/iOt/wO}vO~P'UO!Z#^O&Z#_O&_%|O~O!Z#^O&a#bO&b%|O~O!Z#^O&U%|O&d#dO~O!Z#^O&X%|O&f#fO~OT!la]!la_!laf!lai!laj!lak!lal!lam!lan!laq!lax!lay!la!V!la!d!la!s!la#^!la%V!la%Y!la%b!la%c!la%d!la%e!la%f!la%g!la%h!la%i!la%j!la%k!la%r!lae!la!R!la!S!la%s!la!U!la!Y!la!O!la#V!lar!la!j!la~P#yOx&ROy%`a!s%`a#^%`a%V%`a%Y%`a%r%`a~P$bOT&TOmtOtuOy%`a!s%`a#^%`a%V%`a%Y%`a%r%`a~P'UOx&ROy%`a!s%`a#^%`a%V%`a%Y%`a%r%`a~OPhOTeOmtOtuO}vO!O!PO!vxO!xyO!zzO!|{O#O|O#S}O#U!OO#X!QO#Y!QO#[!RO#^$tX%V$tX%Y$tX~P'UO#^#nO%V&YO%Y&YO~O!d&ZOf&hX%V&hX#V&hX#^&hX%Y&hX#U&hX~Of!jO%V&]O~Oicajcakcalcamcancaqcaxcayca!sca#^ca%Vca%Yca%rcaeca!Rca!Sca%sca!Uca!Yca!Oca#Vcarca!jca~P$bOqoaxoayoa#^oa%Voa%Yoa%roa~Oi!qOj!rOk!pOl!pOm!sOn!tO!soa~PD_O%r&_Ox%qXy%qX~O%mVOx%qXy%qX~Ox&bOyuX~Oy&dO~Ox%mO#^%uX%V%uX%Y%uXe%uXy%uX!Y%uX!j%uX%r%uX~OT/rOm/iOt/wO}vO~P'UO%r$TO#^Sa%VSa%YSa~Ox&mO#^%wX%V%wX%Y%wXl%wX~P$bOx&pO!O&oO#^#Ra%V#Ra%Y#Ra~O#V&qO#^#Ta%V#Ta%Y#Ta~O!d$_O!m$_O#U&sO%mVO~O#U&sO~Ox&uO#^&kX%V&kX%Y&kX~Ox&wO#^&gX%V&gX%Y&gXy&gX~Ox&{Ol&mX~P$bOl'OO~OPhOTeOmtOtuO}vO!O!PO!vxO!xyO!zzO!|{O#O|O#S}O#U!OO#X!QO#Y!QO#[!RO%V'TO~P'UOr'XO#g'VO#h'WOP#eaT#ead#eaf#eam#eaq#eat#ea}#ea!O#ea!R#ea!S#ea!V#ea!Z#ea!f#ea!m#ea!n#ea!o#ea!v#ea!x#ea!z#ea!|#ea#O#ea#S#ea#U#ea#X#ea#Y#ea#[#ea#c#ea#f#ea#j#ea#l#ea#q#ea#t#ea#v#ea%S#ea%V#ea%g#ea%h#ea%l#ea%m#ea&R#ea&S#ea&V#ea&Y#ea&`#ea&c#ea&e#ea%U#ea%Y#ea~Ox'YO#V'[Oy&nX~Of'^O~Of!jOy$nO~Oy'bO~P$bOT!bO]!bO_!cOf!jO!V!lO!d!nO%d!_O%e!`O%f!`O%g!aO%h!aO%i!bO%j!bO%k!bOiUijUikUilUimUinUiqUixUiyUi!sUi#^Ui%VUi%YUi%bUi%rUieUi!RUi!SUi%sUi!UUi!YUi!OUi#VUirUi!jUi~O%c!^O~P! YO%cUi~P! YOT!bO]!bO_!cOf!jO!V!lO!d!nO%g!aO%h!aO%i!bO%j!bO%k!bOiUijUikUilUimUinUiqUixUiyUi!sUi#^Ui%VUi%YUi%bUi%cUi%dUi%rUieUi!RUi!SUi%sUi!UUi!YUi!OUi#VUirUi!jUi~O%e!`O%f!`O~P!$TO%eUi%fUi~P!$TO_!cOf!jO!V!lO!d!nOiUijUikUilUimUinUiqUixUiyUi!sUi#^Ui%VUi%YUi%bUi%cUi%dUi%eUi%fUi%gUi%hUi%rUieUi!RUi!SUi%sUi!UUi!YUi!OUi#VUirUi!jUi~OT!bO]!bO%i!bO%j!bO%k!bO~P!'ROTUi]Ui%iUi%jUi%kUi~P!'RO!R%eO!S%dOe%}Xx%}X~O%r'fO%s'fO~P+xOx'hOe%|X~Oe'jO~Ox'kOy'mO!U&PX~Om/iOt/wOx'kOy'nO!U&PX~P'UO!U'pO~Ok!pOl!pOm!sOn!tOihiqhixhiyhi!shi#^hi%Vhi%Yhi%rhi~Oj!rO~P!+tOjhi~P!+tOi/kOj/lOk/jOl/jOm/sOn/tO~Or'rO~P!,}OT'wOe'xOm/iOt/wO~P'UOe'xOx'yO~Oe'{O~O!S'}O~Oe(OOx'yO!R%eO!S%dO~P$bOi/kOj/lOk/jOl/jOm/sOn/tOeoa!Roa!Soa%soa!Uoa!Yoa!Ooa#Voaroa!joa~PD_OT'wOm/iOt/wO!U%za~P'UOx(RO!U%za~O!U(SO~Ox(RO!R%eO!S%dO!U%za~P$bOT(WOm/iOt/wO!Y%ua#^%ua%V%ua%Y%uae%uay%ua!j%ua%r%ua~P'UOx(XO!Y%ua#^%ua%V%ua%Y%uae%uay%ua!j%ua%r%ua~O!Y([O~Ox(XO!R%eO!S%dO!Y%ua~P$bOx(_O!R%eO!S%dO!Y%{a~P$bOx(bOy&[X!Y&[X!j&[X~Oy(eO!Y(gO!j(hO~OT&TOmtOtuOy%`i!s%`i#^%`i%V%`i%Y%`i%r%`i~P'UOx(iOy%`i!s%`i#^%`i%V%`i%Y%`i%r%`i~O!d&ZOf&ha%V&ha#V&ha#^&ha%Y&ha#U&ha~O%V(nO~OT#zO_#{O%mVO~Ox&bOyua~OmtOtuO~P'UOx(XO#^%ua%V%ua%Y%uae%uay%ua!Y%ua!j%ua%r%ua~P$bOx(sO#^%`X%V%`X%Y%`X%r%`X~O%r$TO#^Si%VSi%YSi~O#^%wa%V%wa%Y%wal%wa~P'UOx(vO#^%wa%V%wa%Y%wal%wa~OT(zOf(|O%mVO~O#U(}O~O%mVO#^&ka%V&ka%Y&ka~Ox)PO#^&ka%V&ka%Y&ka~Om/iOt/wO#^&ga%V&ga%Y&gay&ga~P'UOx)SO#^&ga%V&ga%Y&gay&ga~Or)WO#a)VOP#_iT#_id#_if#_im#_iq#_it#_i}#_i!O#_i!R#_i!S#_i!V#_i!Z#_i!f#_i!m#_i!n#_i!o#_i!v#_i!x#_i!z#_i!|#_i#O#_i#S#_i#U#_i#X#_i#Y#_i#[#_i#c#_i#f#_i#j#_i#l#_i#q#_i#t#_i#v#_i%S#_i%V#_i%g#_i%h#_i%l#_i%m#_i&R#_i&S#_i&V#_i&Y#_i&`#_i&c#_i&e#_i%U#_i%Y#_i~Or)XOP#biT#bid#bif#bim#biq#bit#bi}#bi!O#bi!R#bi!S#bi!V#bi!Z#bi!f#bi!m#bi!n#bi!o#bi!v#bi!x#bi!z#bi!|#bi#O#bi#S#bi#U#bi#X#bi#Y#bi#[#bi#c#bi#f#bi#j#bi#l#bi#q#bi#t#bi#v#bi%S#bi%V#bi%g#bi%h#bi%l#bi%m#bi&R#bi&S#bi&V#bi&Y#bi&`#bi&c#bi&e#bi%U#bi%Y#bi~OT)ZOl&ma~P'UOx)[Ol&ma~Ox)[Ol&ma~P$bOl)`O~O%T)cO~Or)fO#g'VO#h)eOP#eiT#eid#eif#eim#eiq#eit#ei}#ei!O#ei!R#ei!S#ei!V#ei!Z#ei!f#ei!m#ei!n#ei!o#ei!v#ei!x#ei!z#ei!|#ei#O#ei#S#ei#U#ei#X#ei#Y#ei#[#ei#c#ei#f#ei#j#ei#l#ei#q#ei#t#ei#v#ei%S#ei%V#ei%g#ei%h#ei%l#ei%m#ei&R#ei&S#ei&V#ei&Y#ei&`#ei&c#ei&e#ei%U#ei%Y#ei~Om/iOt/wOy$nO~P'UOm/iOt/wOy&na~P'UOx)lOy&na~OT)pO_)qOe)tO%i)rO%mVO~Oy$nO&q)vO~O%V)zO~OT%OO_%OOm/iOt/wOe%|a~P'UOx*OOe%|a~Om/iOt/wOy*RO!U&Pa~P'UOx*SO!U&Pa~Om/iOt/wOx*SOy*VO!U&Pa~P'UOm/iOt/wOx*SO!U&Pa~P'UOx*SOy*VO!U&Pa~Ok/jOl/jOm/sOn/tOehiihiqhixhi!Rhi!Shi%shi!Uhiyhi!Yhi#^hi%Vhi%Yhi!Ohi#Vhirhi!jhi%rhi~Oj/lO~P!H[Ojhi~P!H[OT'wOe*[Om/iOt/wO~P'UOl*^O~Oe*[Ox*`O~Oe*aO~OT'wOm/iOt/wO!U%zi~P'UOx*bO!U%zi~O!U*cO~OT(WOm/iOt/wO!Y%ui#^%ui%V%ui%Y%uie%uiy%ui!j%ui%r%ui~P'UOx*fO!R%eO!S%dO!Y%{i~Ox*iO!Y%ui#^%ui%V%ui%Y%uie%uiy%ui!j%ui%r%ui~O!Y*jO~O_*lOm/iOt/wO!Y%{i~P'UOx*fO!Y%{i~O!Y*nO~OT*pOm/iOt/wOy&[a!Y&[a!j&[a~P'UOx*qOy&[a!Y&[a!j&[a~O!Z#^O&^*tO!Y!kX~O!Y*vO~Oy(eO!Y*wO~OT&TOmtOtuOy%`q!s%`q#^%`q%V%`q%Y%`q%r%`q~P'UOx$miy$mi!s$mi#^$mi%V$mi%Y$mi%r$mi~P$bOT&TOmtOtuO~P'UOT&TOm/iOt/wO#^%`a%V%`a%Y%`a%r%`a~P'UOx*xO#^%`a%V%`a%Y%`a%r%`a~Ox$`a#^$`a%V$`a%Y$`al$`a~P$bO#^%wi%V%wi%Y%wil%wi~P'UOx*{O#^#Rq%V#Rq%Y#Rq~Ox*|O#V+OO#^&jX%V&jX%Y&jXe&jX~OT+QOf(|O%mVO~O%mVO#^&ki%V&ki%Y&ki~Om/iOt/wO#^&gi%V&gi%Y&giy&gi~P'UOr+UO#a)VOP#_qT#_qd#_qf#_qm#_qq#_qt#_q}#_q!O#_q!R#_q!S#_q!V#_q!Z#_q!f#_q!m#_q!n#_q!o#_q!v#_q!x#_q!z#_q!|#_q#O#_q#S#_q#U#_q#X#_q#Y#_q#[#_q#c#_q#f#_q#j#_q#l#_q#q#_q#t#_q#v#_q%S#_q%V#_q%g#_q%h#_q%l#_q%m#_q&R#_q&S#_q&V#_q&Y#_q&`#_q&c#_q&e#_q%U#_q%Y#_q~Ol$wax$wa~P$bOT)ZOl&mi~P'UOx+]Ol&mi~OPhOTeOmtOq!SOtuO}vO!O!PO!R!VO!S!UO!vxO!xyO!zzO!|{O#O|O#S}O#U!OO#X!QO#Y!QO#[!RO#c!TO#f!WO#j!XO#l!YO#q!ZO#tlO#v![O~P'UOx+gOy$nO#V+gO~O#h+hOP#eqT#eqd#eqf#eqm#eqq#eqt#eq}#eq!O#eq!R#eq!S#eq!V#eq!Z#eq!f#eq!m#eq!n#eq!o#eq!v#eq!x#eq!z#eq!|#eq#O#eq#S#eq#U#eq#X#eq#Y#eq#[#eq#c#eq#f#eq#j#eq#l#eq#q#eq#t#eq#v#eq%S#eq%V#eq%g#eq%h#eq%l#eq%m#eq&R#eq&S#eq&V#eq&Y#eq&`#eq&c#eq&e#eq%U#eq%Y#eq~O#V+iOx$yay$ya~Om/iOt/wOy&ni~P'UOx+kOy&ni~Oy$SO%r+mOe&pXx&pX~O%mVOe&pXx&pX~Ox+qOe&oX~Oe+sO~O%T+uO~OT%OO_%OOm/iOt/wOe%|i~P'UOy+wOx$ca!U$ca~Om/iOt/wOy+xOx$ca!U$ca~P'UOm/iOt/wOy*RO!U&Pi~P'UOx+{O!U&Pi~Om/iOt/wOx+{O!U&Pi~P'UOx+{Oy,OO!U&Pi~Oe$_ix$_i!U$_i~P$bOT'wOm/iOt/wO~P'UOl,QO~OT'wOe,ROm/iOt/wO~P'UOT'wOm/iOt/wO!U%zq~P'UOx$^i!Y$^i#^$^i%V$^i%Y$^ie$^iy$^i!j$^i%r$^i~P$bOT(WOm/iOt/wO~P'UO_*lOm/iOt/wO!Y%{q~P'UOx,SO!Y%{q~O!Y,TO~OT(WOm/iOt/wO!Y%uq#^%uq%V%uq%Y%uqe%uqy%uq!j%uq%r%uq~P'UOy,UO~OT*pOm/iOt/wOy&[i!Y&[i!j&[i~P'UOx,ZOy&[i!Y&[i!j&[i~O!Z#^O&^*tO!Y!ka~OT&TOm/iOt/wO#^%`i%V%`i%Y%`i%r%`i~P'UOx,]O#^%`i%V%`i%Y%`i%r%`i~O%mVO#^&ja%V&ja%Y&jae&ja~Ox,`O#^&ja%V&ja%Y&jae&ja~Oe,cO~Ol$wix$wi~P$bOT)ZO~P'UOT)ZOl&mq~P'UOr,fOP#dyT#dyd#dyf#dym#dyq#dyt#dy}#dy!O#dy!R#dy!S#dy!V#dy!Z#dy!f#dy!m#dy!n#dy!o#dy!v#dy!x#dy!z#dy!|#dy#O#dy#S#dy#U#dy#X#dy#Y#dy#[#dy#c#dy#f#dy#j#dy#l#dy#q#dy#t#dy#v#dy%S#dy%V#dy%g#dy%h#dy%l#dy%m#dy&R#dy&S#dy&V#dy&Y#dy&`#dy&c#dy&e#dy%U#dy%Y#dy~OPhOTeOmtOq!SOtuO}vO!O!PO!R!VO!S!UO!vxO!xyO!zzO!|{O#O|O#S}O#U!OO#X!QO#Y!QO#[!RO#c!TO#f!WO#j!XO#l!YO#q!ZO#tlO#v![O%U,jO%Y,jO~P'UO#h,kOP#eyT#eyd#eyf#eym#eyq#eyt#ey}#ey!O#ey!R#ey!S#ey!V#ey!Z#ey!f#ey!m#ey!n#ey!o#ey!v#ey!x#ey!z#ey!|#ey#O#ey#S#ey#U#ey#X#ey#Y#ey#[#ey#c#ey#f#ey#j#ey#l#ey#q#ey#t#ey#v#ey%S#ey%V#ey%g#ey%h#ey%l#ey%m#ey&R#ey&S#ey&V#ey&Y#ey&`#ey&c#ey&e#ey%U#ey%Y#ey~Om/iOt/wOy&nq~P'UOx,oOy&nq~O%r+mOe&pax&pa~OT)pO_)qO%i)rO%mVOe&oa~Ox,sOe&oa~O#y,wO~OT%OO_%OOm/iOt/wO~P'UOm/iOt/wOy,xOx$ci!U$ci~P'UOm/iOt/wOx$ci!U$ci~P'UOy,xOx$ci!U$ci~Om/iOt/wOy*RO~P'UOm/iOt/wOy*RO!U&Pq~P'UOx,{O!U&Pq~Om/iOt/wOx,{O!U&Pq~P'UOq-OO!R%eO!S%dOe%vq!U%vq!Y%vqx%vq~P!,}O_*lOm/iOt/wO!Y%{y~P'UOx$ai!Y$ai~P$bO_*lOm/iOt/wO~P'UOT*pOm/iOt/wO~P'UOT*pOm/iOt/wOy&[q!Y&[q!j&[q~P'UOT&TOm/iOt/wO#^%`q%V%`q%Y%`q%r%`q~P'UO#V-SOx$ra#^$ra%V$ra%Y$rae$ra~O%mVO#^&ji%V&ji%Y&jie&ji~Ox-UO#^&ji%V&ji%Y&jie&ji~Or-XOP#d!RT#d!Rd#d!Rf#d!Rm#d!Rq#d!Rt#d!R}#d!R!O#d!R!R#d!R!S#d!R!V#d!R!Z#d!R!f#d!R!m#d!R!n#d!R!o#d!R!v#d!R!x#d!R!z#d!R!|#d!R#O#d!R#S#d!R#U#d!R#X#d!R#Y#d!R#[#d!R#c#d!R#f#d!R#j#d!R#l#d!R#q#d!R#t#d!R#v#d!R%S#d!R%V#d!R%g#d!R%h#d!R%l#d!R%m#d!R&R#d!R&S#d!R&V#d!R&Y#d!R&`#d!R&c#d!R&e#d!R%U#d!R%Y#d!R~Om/iOt/wOy&ny~P'UOT)pO_)qO%i)rO%mVOe&oi~O#y,wO%U-_O%Y-_O~OT-iOf-gO!V-fO!Z-hO!f-bO!n-dO!o-dO%h-aO%mVO&R[O&S]O&V^O~Om/iOt/wOx$cq!U$cq~P'UOy-nOx$cq!U$cq~Om/iOt/wOy*RO!U&Py~P'UOx-oO!U&Py~Om/iOt-sO~P'UOq-OO!R%eO!S%dOe%vy!U%vy!Y%vyx%vy~P!,}O%mVO#^&jq%V&jq%Y&jqe&jq~Ox-wO#^&jq%V&jq%Y&jqe&jq~OT)pO_)qO%i)rO%mVO~Of-{O!d-yOx#zX#V#zX%b#zXe#zX~Oq#zXy#zX!U#zX!Y#zX~P$$nO%g-}O%h-}Oq#{Xx#{Xy#{X#V#{X%b#{X!U#{Xe#{X!Y#{X~O!f.PO~Ox.TO#V.VO%b.QOq&rXy&rX!U&rXe&rX~O_.YO~P$ WOf-{Oq&sXx&sXy&sX#V&sX%b&sX!U&sXe&sX!Y&sX~Oq.^Oy$nO~Om/iOt/wOx$cy!U$cy~P'UOm/iOt/wOy*RO!U&P!R~P'UOx.bO!U&P!R~Oe%yXq%yX!R%yX!S%yX!U%yX!Y%yXx%yX~P!,}Oq-OO!R%eO!S%dOe%xa!U%xa!Y%xax%xa~O%mVO#^&jy%V&jy%Y&jye&jy~O!d-yOf$Raq$Rax$Ray$Ra#V$Ra%b$Ra!U$Rae$Ra!Y$Ra~O!f.kO~O%g-}O%h-}Oq#{ax#{ay#{a#V#{a%b#{a!U#{ae#{a!Y#{a~O%b.QOq$Pax$Pay$Pa#V$Pa!U$Pae$Pa!Y$Pa~Oq&ray&ra!U&rae&ra~P#NzOx.pOq&ray&ra!U&rae&ra~O!U.sO~Oe.sO~Oy.uO~O!Y.vO~Om/iOt/wOy*RO!U&P!Z~P'UOy.yO~O%r.zO~P$$nOx.{O#V.VO%b.QOe&uX~Ox.{Oe&uX~Oe.}O~O!f/OO~O#V.VOq$}ax$}ay$}a%b$}a!U$}ae$}a!Y$}a~O#V.VO%b.QOq%Rax%Ray%Ra!U%Rae%Ra~Oq&riy&ri!U&rie&ri~P#NzOx/QO#V.VO%b.QO!Y&ta~Oy$Za~P$bOe&ua~P#NzOx/YOe&ua~O_/[O!Y&ti~P$ WOx/^O!Y&ti~Ox/^O#V.VO%b.QO!Y&ti~O#V.VO%b.QOe$Xix$Xi~O%r/aO~P$$nO#V.VO%b.QOe%Qax%Qa~Oe&ui~P#NzOy/dO~O_/[O!Y&tq~P$ WOx/fO!Y&tq~O#V.VO%b.QOx%Pi!Y%Pi~O_/[O~P$ WO_/[O!Y&ty~P$ WO#V.VO%b.QOe$Yix$Yi~O#V.VO%b.QOx%Pq!Y%Pq~Ox*xO#^%`a%V%`a%Y%`a%r%`a~P$bOT&TOm/iOt/wO~P'UOl/nO~Om/nO~P'UOy/oO~Or/pO~P!,}O&S&V&c&e&R!Z&Z&a&d&f&Y&`&Y%m~", + goto: "!9p&vPPPP&wP'P*e*}+h,S,o-]P-zP'P.k.k'PPPP'P2PPPPPPP2P4oPP4oP6{7U=QPP=T=c=fPP'P'PPP=rPP'P'PPP'P'P'P'P'P=v>m'PP>pP>vByFcPFw'PPPPF{GR&wP&w&wP&wP&wP&wP&wP&w&w&wP&wPP&wPP&wPGXPG`GfPG`PG`G`PPPG`PIePInItIzIePG`JQPG`PJXJ_PJcJwKfLPJcJcLVLdJcJcJcJcLxMOMRMWMZMaMgMsNVN]NgNm! Z! a! g! m! w! }!!T!!Z!!a!!g!!y!#T!#Z!#a!#g!#q!#w!#}!$T!$Z!$e!$k!$u!${!%U!%[!%k!%s!%}!&UPPPPPPPPP!&[!&d!&m!&w!'SPPPPPPPPPPPP!+r!,[!0j!3vPP!4O!4^!4g!5]!5S!5f!5l!5o!5r!5u!5}!6nPPPPPPPPPP!6q!6tPPPPPPPPP!6z!7W!7d!7j!7s!7v!7|!8S!8Y!8]P!8e!8n!9j!9m]iOr#n$n)c+c'udOSXYZehrstvx|}!R!S!T!U!X![!d!e!f!g!h!i!j!l!p!q!r!t!u!{#O#S#T#^#k#n$P$Q$S$U$X$i$k$l$n$u%O%T%[%_%a%d%h%m%o%y&R&T&`&d&m&o&p&w&{'O'V'Y'g'h'k'm'n'r'w'y'}(R(W(X(_(b(i(k(s(v)S)V)Z)[)`)c)l)v*O*R*S*V*]*^*`*b*e*f*i*l*p*q*x*z*{+S+[+]+c+j+k+n+v+w+x+z+{,O,Q,S,U,W,Y,Z,],o,q,x,{-O-n-o.^.b.y/i/j/k/l/n/o/p/q/r/t/x}!dP#j#w$Y$h$t%f%k%q%r&e&}'d(j(u)Y*Z*d+Z,V.w/m!P!eP#j#w$Y$h$t$v%f%k%q%r&e&}'d(j(u)Y*Z*d+Z,V.w/m!R!fP#j#w$Y$h$t$v$w%f%k%q%r&e&}'d(j(u)Y*Z*d+Z,V.w/m!T!gP#j#w$Y$h$t$v$w$x%f%k%q%r&e&}'d(j(u)Y*Z*d+Z,V.w/m!V!hP#j#w$Y$h$t$v$w$x$y%f%k%q%r&e&}'d(j(u)Y*Z*d+Z,V.w/m!X!iP#j#w$Y$h$t$v$w$x$y$z%f%k%q%r&e&}'d(j(u)Y*Z*d+Z,V.w/m!]!iP!o#j#w$Y$h$t$v$w$x$y$z${%f%k%q%r&e&}'d(j(u)Y*Z*d+Z,V.w/m'uSOSXYZehrstvx|}!R!S!T!U!X![!d!e!f!g!h!i!j!l!p!q!r!t!u!{#O#S#T#^#k#n$P$Q$S$U$X$i$k$l$n$u%O%T%[%_%a%d%h%m%o%y&R&T&`&d&m&o&p&w&{'O'V'Y'g'h'k'm'n'r'w'y'}(R(W(X(_(b(i(k(s(v)S)V)Z)[)`)c)l)v*O*R*S*V*]*^*`*b*e*f*i*l*p*q*x*z*{+S+[+]+c+j+k+n+v+w+x+z+{,O,Q,S,U,W,Y,Z,],o,q,x,{-O-n-o.^.b.y/i/j/k/l/n/o/p/q/r/t/x&ZUOXYZhrtv|}!R!S!T!X!j!l!p!q!r!t!u#^#k#n$Q$S$U$X$l$n%O%T%[%_%a%h%m%o%y&R&`&d&o&p&w'O'V'Y'g'h'k'm'n'r'y(R(X(_(b(i(k(s)S)V)`)c)l)v*O*R*S*V*]*^*`*b*e*f*i*p*q*x*{+S+c+j+k+n+v+w+x+z+{,O,Q,S,U,W,Y,Z,],o,q,x,{-O-n-o.b.y/i/j/k/l/n/o/p/q/t/x%eWOXYZhrv|}!R!S!T!X!j!l#^#k#n$Q$S$U$X$l$n%O%T%_%a%h%m%o%y&R&`&d&o&p&w'O'V'Y'g'h'k'm'n'r'y(R(X(_(b(i(k(s)S)V)`)c)l)v*O*R*S*V*]*`*b*e*f*i*p*q*x*{+S+c+j+k+n+v+w+x+z+{,O,S,U,W,Y,Z,],o,q,x,{-n-o.b/o/p/qQ#}uQ.c-sR/u/w'ldOSXYZehrstvx|}!R!S!T!U!X![!d!e!f!g!h!i!l!p!q!r!t!u!{#O#S#T#^#k#n$P$Q$S$U$X$i$k$l$n$u%O%T%[%_%a%d%h%m%o%y&R&T&`&d&m&o&p&w&{'O'V'Y'g'k'm'n'r'w'y'}(R(W(X(_(b(i(k(s(v)S)V)Z)[)`)c)l)v*R*S*V*]*^*`*b*e*f*i*l*p*q*x*z*{+S+[+]+c+j+k+n+w+x+z+{,O,Q,S,U,W,Y,Z,],o,q,x,{-O-n-o.^.b.y/i/j/k/l/n/o/p/q/r/t/xW#ql!O!P$`W#yu&b-s/wQ$b!QQ$r!YQ$s!ZW$}!j'h*O+vS&a#z#{Q'R$mQ(l&ZQ(z&qU({&s(|(}U)O&u)P+RQ)n'[W)o'^+q,s-]S+p)p)qY,_*|,`-T-U-wQ,b+OQ,l+gQ,n+il-`,w-f-g-i.R.T.Y.p.u.z/P/[/a/dQ-v-SQ.Z-hQ.g-{Q.r.VU/V.{/Y/bX/]/Q/^/e/fR&`#yi!xXY!S!T%a%h'y(R)V*]*`*bR%_!wQ!|XQ%z#^Q&i$UR&l$XT-r-O.y![!kP!o#j#w$Y$h$t$v$w$x$y$z${%f%k%q%r&e&}'d(j(u)Y*Z*d+Z,V.w/mQ&^#rR'a$sR'g$}Q%W!nR.e-y'tcOSXYZehrstvx|}!R!S!T!U!X![!d!e!f!g!h!i!j!l!p!q!r!t!u!{#O#S#T#^#k#n$P$Q$S$U$X$i$k$l$n$u%O%T%[%_%a%d%h%m%o%y&R&T&`&d&m&o&p&w&{'O'V'Y'g'h'k'm'n'r'w'y'}(R(W(X(_(b(i(k(s(v)S)V)Z)[)`)c)l)v*O*R*S*V*]*^*`*b*e*f*i*l*p*q*x*z*{+S+[+]+c+j+k+n+v+w+x+z+{,O,Q,S,U,W,Y,Z,],o,q,x,{-O-n-o.^.b.y/i/j/k/l/n/o/p/q/r/t/xS#hc#i!P-d,w-f-g-h-i-{.R.T.Y.p.u.z.{/P/Q/Y/[/^/a/b/d/e/f'tcOSXYZehrstvx|}!R!S!T!U!X![!d!e!f!g!h!i!j!l!p!q!r!t!u!{#O#S#T#^#k#n$P$Q$S$U$X$i$k$l$n$u%O%T%[%_%a%d%h%m%o%y&R&T&`&d&m&o&p&w&{'O'V'Y'g'h'k'm'n'r'w'y'}(R(W(X(_(b(i(k(s(v)S)V)Z)[)`)c)l)v*O*R*S*V*]*^*`*b*e*f*i*l*p*q*x*z*{+S+[+]+c+j+k+n+v+w+x+z+{,O,Q,S,U,W,Y,Z,],o,q,x,{-O-n-o.^.b.y/i/j/k/l/n/o/p/q/r/t/xT#hc#iS#__#`S#b`#cS#da#eS#fb#gT*t(e*uT(f%z(hQ$WwR+o)oX$Uw$V$W&kZkOr$n)c+cXoOr)c+cQ$o!WQ&y$fQ&z$gQ']$qQ'`$sQ)a'QQ)g'VQ)i'WQ)j'XQ)w'_Q)y'aQ+V)VQ+X)WQ+Y)XQ+^)_S+`)b)xQ+d)eQ+e)fQ+f)hQ,d+UQ,e+WQ,g+_Q,h+aQ,m+hQ-W,fQ-Y,kQ-Z,lQ-x-XQ._-lR.x.`WoOr)c+cR#tnQ'_$rR)b'RQ+n)oR,q+oQ)x'_R+a)bZmOnr)c+cQ'c$tR){'dT,u+u,vu-k,w-f-g-i-{.R.T.Y.p.u.z.{/P/Y/[/a/b/dt-k,w-f-g-i-{.R.T.Y.p.u.z.{/P/Y/[/a/b/dQ.Z-hX/]/Q/^/e/f!P-c,w-f-g-h-i-{.R.T.Y.p.u.z.{/P/Q/Y/[/^/a/b/d/e/fQ.O-bR.l.Pg.R-e.S.h.o.t/S/U/W/c/g/hu-j,w-f-g-i-{.R.T.Y.p.u.z.{/P/Y/[/a/b/dX-|-`-j.g/VR.i-{V/X.{/Y/bR.`-lQrOR#vrQ&c#|R(q&cS%n#R$OS(Y%n(]T(]%q&eQ%b!zQ%i!}W'z%b%i(P(TQ(P%fR(T%kQ&n$YR(w&nQ(`%rQ*g(ZT*m(`*gQ'i%PR*P'iS'l%S%TY*T'l*U+|,|-pU*U'm'n'oU+|*V*W*XS,|+},OR-p,}Q#Y]R%u#YQ#]^R%w#]Q#`_R%{#`Q(c%xS*r(c*sR*s(dQ*u(eR,[*uQ#c`R%}#cQ#eaR&O#eQ#gbR&P#gQ#icR&Q#iQ#lfQ&S#jW&V#l&S(t*yQ(t&hR*y/mQ$VwS&j$V&kR&k$WQ&x$dR)T&xQ&[#qR(m&[Q$`!PR&r$`Q*}({S,a*}-VR-V,bQ&v$bR)Q&vQ#ojR&X#oQ+c)cR,i+cQ)U&yR+T)UQ&|$hS)]&|)^R)^&}Q'U$oR)d'UQ'Z$pS)m'Z+lR+l)nQ+r)sR,t+rWnOr)c+cR#snQ,v+uR-^,vd.S-e.h.o.t/S/U/W/c/g/hR.n.SU-z-`.g/VR.f-zQ/R.tS/_/R/`R/`/SS.|.h.iR/Z.|Q.U-eR.q.USqOrT+b)c+cWpOr)c+cR'S$nYjOr$n)c+cR&W#n[wOr#n$n)c+cR&i$U&YPOXYZhrtv|}!R!S!T!X!j!l!p!q!r!t!u#^#k#n$Q$S$U$X$l$n%O%T%[%_%a%h%m%o%y&R&`&d&o&p&w'O'V'Y'g'h'k'm'n'r'y(R(X(_(b(i(k(s)S)V)`)c)l)v*O*R*S*V*]*^*`*b*e*f*i*p*q*x*{+S+c+j+k+n+v+w+x+z+{,O,Q,S,U,W,Y,Z,],o,q,x,{-O-n-o.b.y/i/j/k/l/n/o/p/q/t/xQ!oSQ#jeQ#wsU$Yx%d'}S$h!U$kQ$t![Q$v!dQ$w!eQ$x!fQ$y!gQ$z!hQ${!iQ%f!{Q%k#OQ%q#SQ%r#TQ&e$PQ&}$iQ'd$uQ(j&TU(u&m(v*zW)Y&{)[+[+]Q*Z'wQ*d(WQ+Z)ZQ,V*lQ.w.^R/m/rQ!zXQ!}YQ$f!SQ$g!T^'v%a%h'y(R*]*`*bR+W)V[fOr#n$n)c+ch!wXY!S!T%a%h'y(R)V*]*`*bQ#RZQ#mhS$Ov|Q$]}W$d!R$X'O)`S$p!X$lW$|!j'h*O+vQ%S!lQ%x#^`&U#k&R(i(k(s*x,]/qQ&f$QQ&g$SQ&h$UQ'e%OQ'o%TQ'u%_W(V%m(X*e*iQ(Z%oQ(d%yQ(o&`S(r&d/oQ(x&oQ(y&pU)R&w)S+SQ)h'VY)k'Y)l+j+k,oQ)|'g^*Q'k*S+z+{,{-o.bQ*W'mQ*X'nS*Y'r/pW*k(_*f,S,WW*o(b*q,Y,ZQ+t)vQ+y*RQ+}*VQ,X*pQ,^*{Q,p+nQ,y+wQ,z+xQ,},OQ-R,UQ-[,qQ-m,xR.a-nhTOr#k#n$n&R&d'r(i(k)c+c$z!vXYZhv|}!R!S!T!X!j!l#^$Q$S$U$X$l%O%T%_%a%h%m%o%y&`&o&p&w'O'V'Y'g'h'k'm'n'y(R(X(_(b(s)S)V)`)l)v*O*R*S*V*]*`*b*e*f*i*p*q*x*{+S+j+k+n+v+w+x+z+{,O,S,U,W,Y,Z,],o,q,x,{-n-o.b/o/p/qQ#xtW%X!p!t/j/tQ%Y!qQ%Z!rQ%]!uQ%g/iS'q%[/nQ's/kQ't/lQ,P*^Q-Q,QS-q-O.yR/v/xU#|u-s/wR(p&b[gOr#n$n)c+cX!yX#^$U$XQ#WZQ$RvR$[|Q%c!zQ%j!}Q%p#RQ'e$|Q(Q%fQ(U%kQ(^%qQ(a%rQ*h(ZQ-P,PQ-u-QR.d-tQ$ZxQ'|%dR*_'}Q-t-OR/T.yR#QYR#VZR%R!jQ%P!jV)}'h*O+v!]!mP!o#j#w$Y$h$t$v$w$x$y$z${%f%k%q%r&e&}'d(j(u)Y*Z*d+Z,V.w/mR%U!lR%z#^Q(g%zR*w(hQ$e!RQ&l$XQ)_'OR+_)`Q#rlQ$^!OQ$a!PR&t$`Q(z&sR+Q(}Q(z&sQ+P(|R+Q(}R$c!QXpOr)c+cQ$j!UR'P$kQ$q!XR'Q$lR)u'^Q)s'^V,r+q,s-]Q-l,wQ.W-fR.X-gU-e,w-f-gQ.]-iQ.h-{Q.m.RU.o.T.p/PQ.t.YQ/S.uQ/U.zU/W.{/Y/bQ/c/[Q/g/aR/h/dR.[-hR.j-{", + nodeNames: "⚠ print Comment Script AssignStatement * BinaryExpression BitOp BitOp BitOp BitOp ArithOp ArithOp @ ArithOp ** UnaryExpression ArithOp BitOp AwaitExpression await ) ( ParenthesizedExpression BinaryExpression or and CompareOp in not is UnaryExpression ConditionalExpression if else LambdaExpression lambda ParamList VariableName AssignOp , : NamedExpression AssignOp YieldExpression yield from TupleExpression ComprehensionExpression async for LambdaExpression ] [ ArrayExpression ArrayComprehensionExpression } { DictionaryExpression DictionaryComprehensionExpression SetExpression SetComprehensionExpression CallExpression ArgList AssignOp MemberExpression . PropertyName Number String FormatString FormatReplacement FormatConversion FormatSpec ContinuedString Ellipsis None Boolean TypeDef AssignOp UpdateStatement UpdateOp ExpressionStatement DeleteStatement del PassStatement pass BreakStatement break ContinueStatement continue ReturnStatement return YieldStatement PrintStatement RaiseStatement raise ImportStatement import as ScopeStatement global nonlocal AssertStatement assert StatementGroup ; IfStatement Body elif WhileStatement while ForStatement TryStatement try except finally WithStatement with FunctionDefinition def ParamList AssignOp TypeDef ClassDefinition class DecoratedStatement Decorator At MatchStatement match MatchBody MatchClause case CapturePattern LiteralPattern ArithOp ArithOp AsPattern OrPattern LogicOp AttributePattern SequencePattern MappingPattern StarPattern ClassPattern PatternArgList KeywordPattern KeywordPattern Guard", + maxTerm: 267, + context: trackIndent, + nodeProps: [ + ["group", -14,4,80,82,83,85,87,89,91,93,94,95,97,100,103,"Statement Statement",-22,6,16,19,23,38,47,48,54,55,58,59,60,61,62,65,68,69,70,74,75,76,77,"Expression",-10,105,107,110,112,113,117,119,124,126,129,"Statement",-9,134,135,138,139,141,142,143,144,145,"Pattern"], + ["openedBy", 21,"(",52,"[",56,"{"], + ["closedBy", 22,")",53,"]",57,"}"] + ], + propSources: [pythonHighlighting], + skippedNodes: [0,2], + repeatNodeCount: 38, + tokenData: "&JdMgR!^OX$}XY!&]Y[$}[]!&]]p$}pq!&]qr!(grs!,^st!IYtu$}uv$5[vw$7nwx$8zxy%'vyz%(|z{%*S{|%,r|}%.O}!O%/U!O!P%1k!P!Q%<q!Q!R%?a!R![%Cc![!]%N_!]!^&!q!^!_&#w!_!`&&g!`!a&'s!a!b$}!b!c&*`!c!d&+n!d!e&-`!e!h&+n!h!i&7[!i!t&+n!t!u&@j!u!w&+n!w!x&5j!x!}&+n!}#O&Bt#O#P!'u#P#Q&Cz#Q#R&EQ#R#S&+n#S#T$}#T#U&+n#U#V&-`#V#Y&+n#Y#Z&7[#Z#f&+n#f#g&@j#g#i&+n#i#j&5j#j#o&+n#o#p&F^#p#q&GS#q#r&H`#r#s&I^#s$g$}$g~&+n<r%`Z&^7[&TS&WW&Z`&ap&d!b&f#tOr$}rs&Rsw$}wxHsx#O$}#O#P!$R#P#o$}#o#p!%i#p#q$}#q#r!$g#r~$}<Q&^Z&^7[&TS&Z`&d!bOr'PrsFisw'Pwx(Rx#O'P#O#PAe#P#o'P#o#pEu#p#q'P#q#rAy#r~'P<Q'`Z&^7[&TS&WW&Z`&d!b&f#tOr'Prs&Rsw'Pwx(Rx#O'P#O#PAe#P#o'P#o#pEu#p#q'P#q#rAy#r~'P;p([Z&^7[&WW&f#tOr(}rs)}sw(}wx={x#O(}#O#P2]#P#o(}#o#p:X#p#q(}#q#r2q#r~(};p)[Z&^7[&TS&WW&d!b&f#tOr(}rs)}sw(}wx(Rx#O(}#O#P2]#P#o(}#o#p:X#p#q(}#q#r2q#r~(};p*WZ&^7[&TS&d!bOr(}rs*ysw(}wx(Rx#O(}#O#P2]#P#o(}#o#p:X#p#q(}#q#r2q#r~(};p+SZ&^7[&TS&d!bOr(}rs+usw(}wx(Rx#O(}#O#P2]#P#o(}#o#p:X#p#q(}#q#r2q#r~(}8r,OX&^7[&TS&d!bOw+uwx,kx#O+u#O#P.]#P#o+u#o#p0d#p#q+u#q#r.q#r~+u8r,pX&^7[Ow+uwx-]x#O+u#O#P.]#P#o+u#o#p0d#p#q+u#q#r.q#r~+u8r-bX&^7[Ow+uwx-}x#O+u#O#P.]#P#o+u#o#p0d#p#q+u#q#r.q#r~+u7[.SR&^7[O#o-}#p#q-}#r~-}8r.bT&^7[O#o+u#o#p.q#p#q+u#q#r.q#r~+u!f.xV&TS&d!bOw.qwx/_x#O.q#O#P0^#P#o.q#o#p0d#p~.q!f/bVOw.qwx/wx#O.q#O#P0^#P#o.q#o#p0d#p~.q!f/zUOw.qx#O.q#O#P0^#P#o.q#o#p0d#p~.q!f0aPO~.q!f0iV&TSOw1Owx1dx#O1O#O#P2V#P#o1O#o#p.q#p~1OS1TT&TSOw1Owx1dx#O1O#O#P2V#P~1OS1gTOw1Owx1vx#O1O#O#P2V#P~1OS1ySOw1Ox#O1O#O#P2V#P~1OS2YPO~1O;p2bT&^7[O#o(}#o#p2q#p#q(}#q#r2q#r~(}%d2|X&TS&WW&d!b&f#tOr2qrs3isw2qwx5Px#O2q#O#P:R#P#o2q#o#p:X#p~2q%d3pX&TS&d!bOr2qrs4]sw2qwx5Px#O2q#O#P:R#P#o2q#o#p:X#p~2q%d4dX&TS&d!bOr2qrs.qsw2qwx5Px#O2q#O#P:R#P#o2q#o#p:X#p~2q%d5WX&WW&f#tOr2qrs3isw2qwx5sx#O2q#O#P:R#P#o2q#o#p:X#p~2q%d5zX&WW&f#tOr2qrs3isw2qwx6gx#O2q#O#P:R#P#o2q#o#p:X#p~2q#|6nV&WW&f#tOr6grs7Ts#O6g#O#P8S#P#o6g#o#p8Y#p~6g#|7WVOr6grs7ms#O6g#O#P8S#P#o6g#o#p8Y#p~6g#|7pUOr6gs#O6g#O#P8S#P#o6g#o#p8Y#p~6g#|8VPO~6g#|8_V&WWOr8trs9Ys#O8t#O#P9{#P#o8t#o#p6g#p~8tW8yT&WWOr8trs9Ys#O8t#O#P9{#P~8tW9]TOr8trs9ls#O8t#O#P9{#P~8tW9oSOr8ts#O8t#O#P9{#P~8tW:OPO~8t%d:UPO~2q%d:`X&TS&WWOr:{rs;isw:{wx<ox#O:{#O#P=u#P#o:{#o#p2q#p~:{[;SV&TS&WWOr:{rs;isw:{wx<ox#O:{#O#P=u#P~:{[;nV&TSOr:{rs<Tsw:{wx<ox#O:{#O#P=u#P~:{[<YV&TSOr:{rs1Osw:{wx<ox#O:{#O#P=u#P~:{[<tV&WWOr:{rs;isw:{wx=Zx#O:{#O#P=u#P~:{[=`V&WWOr:{rs;isw:{wx8tx#O:{#O#P=u#P~:{[=xPO~:{;p>UZ&^7[&WW&f#tOr(}rs)}sw(}wx>wx#O(}#O#P2]#P#o(}#o#p:X#p#q(}#q#r2q#r~(}:Y?QX&^7[&WW&f#tOr>wrs?ms#O>w#O#PAP#P#o>w#o#p8Y#p#q>w#q#r6g#r~>w:Y?rX&^7[Or>wrs@_s#O>w#O#PAP#P#o>w#o#p8Y#p#q>w#q#r6g#r~>w:Y@dX&^7[Or>wrs-}s#O>w#O#PAP#P#o>w#o#p8Y#p#q>w#q#r6g#r~>w:YAUT&^7[O#o>w#o#p6g#p#q>w#q#r6g#r~>w<QAjT&^7[O#o'P#o#pAy#p#q'P#q#rAy#r~'P%tBWX&TS&WW&Z`&d!b&f#tOrAyrsBsswAywx5Px#OAy#O#PEo#P#oAy#o#pEu#p~Ay%tB|X&TS&Z`&d!bOrAyrsCiswAywx5Px#OAy#O#PEo#P#oAy#o#pEu#p~Ay%tCrX&TS&Z`&d!bOrAyrsD_swAywx5Px#OAy#O#PEo#P#oAy#o#pEu#p~Ay!vDhV&TS&Z`&d!bOwD_wx/_x#OD_#O#PD}#P#oD_#o#pET#p~D_!vEQPO~D_!vEYV&TSOw1Owx1dx#O1O#O#P2V#P#o1O#o#pD_#p~1O%tErPO~Ay%tE|X&TS&WWOr:{rs;isw:{wx<ox#O:{#O#P=u#P#o:{#o#pAy#p~:{<QFtZ&^7[&TS&Z`&d!bOr'PrsGgsw'Pwx(Rx#O'P#O#PAe#P#o'P#o#pEu#p#q'P#q#rAy#r~'P9SGrX&^7[&TS&Z`&d!bOwGgwx,kx#OGg#O#PH_#P#oGg#o#pET#p#qGg#q#rD_#r~Gg9SHdT&^7[O#oGg#o#pD_#p#qGg#q#rD_#r~Gg<bIOZ&^7[&WW&ap&f#tOrIqrs)}swIqwx! wx#OIq#O#PJs#P#oIq#o#p! T#p#qIq#q#rKX#r~Iq<bJQZ&^7[&TS&WW&ap&d!b&f#tOrIqrs)}swIqwxHsx#OIq#O#PJs#P#oIq#o#p! T#p#qIq#q#rKX#r~Iq<bJxT&^7[O#oIq#o#pKX#p#qIq#q#rKX#r~Iq&UKfX&TS&WW&ap&d!b&f#tOrKXrs3iswKXwxLRx#OKX#O#PN}#P#oKX#o#p! T#p~KX&UL[X&WW&ap&f#tOrKXrs3iswKXwxLwx#OKX#O#PN}#P#oKX#o#p! T#p~KX&UMQX&WW&ap&f#tOrKXrs3iswKXwxMmx#OKX#O#PN}#P#oKX#o#p! T#p~KX$nMvV&WW&ap&f#tOrMmrs7Ts#OMm#O#PN]#P#oMm#o#pNc#p~Mm$nN`PO~Mm$nNhV&WWOr8trs9Ys#O8t#O#P9{#P#o8t#o#pMm#p~8t&U! QPO~KX&U! [X&TS&WWOr:{rs;isw:{wx<ox#O:{#O#P=u#P#o:{#o#pKX#p~:{<b!!SZ&^7[&WW&ap&f#tOrIqrs)}swIqwx!!ux#OIq#O#PJs#P#oIq#o#p! T#p#qIq#q#rKX#r~Iq:z!#QX&^7[&WW&ap&f#tOr!!urs?ms#O!!u#O#P!#m#P#o!!u#o#pNc#p#q!!u#q#rMm#r~!!u:z!#rT&^7[O#o!!u#o#pMm#p#q!!u#q#rMm#r~!!u<r!$WT&^7[O#o$}#o#p!$g#p#q$}#q#r!$g#r~$}&f!$vX&TS&WW&Z`&ap&d!b&f#tOr!$grsBssw!$gwxLRx#O!$g#O#P!%c#P#o!$g#o#p!%i#p~!$g&f!%fPO~!$g&f!%pX&TS&WWOr:{rs;isw:{wx<ox#O:{#O#P=u#P#o:{#o#p!$g#p~:{Mg!&pa&^7[&TS&WW%[1s&Z`&ap&d!b&f#tOX$}XY!&]Y[$}[]!&]]p$}pq!&]qr$}rs&Rsw$}wxHsx#O$}#O#P!'u#P#o$}#o#p!%i#p#q$}#q#r!$g#r~$}Mg!'zX&^7[OY$}YZ!&]Z]$}]^!&]^#o$}#o#p!$g#p#q$}#q#r!$g#r~$}<u!(xb&^7[&TS&WW&Z`&ap&d!b&f#tOr$}rs&Rsw$}wxHsx!_$}!_!`!*Q!`#O$}#O#P!$R#P#T$}#T#U!+W#U#f$}#f#g!+W#g#h!+W#h#o$}#o#p!%i#p#q$}#q#r!$g#r~$}<u!*eZkR&^7[&TS&WW&Z`&ap&d!b&f#tOr$}rs&Rsw$}wxHsx#O$}#O#P!$R#P#o$}#o#p!%i#p#q$}#q#r!$g#r~$}<u!+kZ!jR&^7[&TS&WW&Z`&ap&d!b&f#tOr$}rs&Rsw$}wxHsx#O$}#O#P!$R#P#o$}#o#p!%i#p#q$}#q#r!$g#r~$}G{!,m_&bp&^7[&TS&R,X&Z`&d!bOY!-lYZ'PZ]!-l]^'P^r!-lrs!G^sw!-lwx!/|x#O!-l#O#P!Cp#P#o!-l#o#p!F[#p#q!-l#q#r!DU#r~!-lGZ!-}_&^7[&TS&WW&R,X&Z`&d!b&f#tOY!-lYZ'PZ]!-l]^'P^r!-lrs!.|sw!-lwx!/|x#O!-l#O#P!Cp#P#o!-l#o#p!F[#p#q!-l#q#r!DU#r~!-lGZ!/ZZ&^7[&TS&R,X&Z`&d!bOr'PrsFisw'Pwx(Rx#O'P#O#PAe#P#o'P#o#pEu#p#q'P#q#rAy#r~'PFy!0X_&^7[&WW&R,X&f#tOY!1WYZ(}Z]!1W]^(}^r!1Wrs!2fsw!1Wwx!@Yx#O!1W#O#P!3d#P#o!1W#o#p!;t#p#q!1W#q#r!3x#r~!1WFy!1g_&^7[&TS&WW&R,X&d!b&f#tOY!1WYZ(}Z]!1W]^(}^r!1Wrs!2fsw!1Wwx!/|x#O!1W#O#P!3d#P#o!1W#o#p!;t#p#q!1W#q#r!3x#r~!1WFy!2qZ&^7[&TS&R,X&d!bOr(}rs*ysw(}wx(Rx#O(}#O#P2]#P#o(}#o#p:X#p#q(}#q#r2q#r~(}Fy!3iT&^7[O#o!1W#o#p!3x#p#q!1W#q#r!3x#r~!1W0m!4V]&TS&WW&R,X&d!b&f#tOY!3xYZ2qZ]!3x]^2q^r!3xrs!5Osw!3xwx!5tx#O!3x#O#P!;n#P#o!3x#o#p!;t#p~!3x0m!5XX&TS&R,X&d!bOr2qrs4]sw2qwx5Px#O2q#O#P:R#P#o2q#o#p:X#p~2q0m!5}]&WW&R,X&f#tOY!3xYZ2qZ]!3x]^2q^r!3xrs!5Osw!3xwx!6vx#O!3x#O#P!;n#P#o!3x#o#p!;t#p~!3x0m!7P]&WW&R,X&f#tOY!3xYZ2qZ]!3x]^2q^r!3xrs!5Osw!3xwx!7xx#O!3x#O#P!;n#P#o!3x#o#p!;t#p~!3x/V!8RZ&WW&R,X&f#tOY!7xYZ6gZ]!7x]^6g^r!7xrs!8ts#O!7x#O#P!9`#P#o!7x#o#p!9f#p~!7x/V!8yV&R,XOr6grs7ms#O6g#O#P8S#P#o6g#o#p8Y#p~6g/V!9cPO~!7x/V!9mZ&WW&R,XOY!:`YZ8tZ]!:`]^8t^r!:`rs!;Ss#O!:`#O#P!;h#P#o!:`#o#p!7x#p~!:`,a!:gX&WW&R,XOY!:`YZ8tZ]!:`]^8t^r!:`rs!;Ss#O!:`#O#P!;h#P~!:`,a!;XT&R,XOr8trs9ls#O8t#O#P9{#P~8t,a!;kPO~!:`0m!;qPO~!3x0m!;}]&TS&WW&R,XOY!<vYZ:{Z]!<v]^:{^r!<vrs!=rsw!<vwx!>`x#O!<v#O#P!@S#P#o!<v#o#p!3x#p~!<v,e!=PZ&TS&WW&R,XOY!<vYZ:{Z]!<v]^:{^r!<vrs!=rsw!<vwx!>`x#O!<v#O#P!@S#P~!<v,e!=yV&TS&R,XOr:{rs<Tsw:{wx<ox#O:{#O#P=u#P~:{,e!>gZ&WW&R,XOY!<vYZ:{Z]!<v]^:{^r!<vrs!=rsw!<vwx!?Yx#O!<v#O#P!@S#P~!<v,e!?aZ&WW&R,XOY!<vYZ:{Z]!<v]^:{^r!<vrs!=rsw!<vwx!:`x#O!<v#O#P!@S#P~!<v,e!@VPO~!<vFy!@e_&^7[&WW&R,X&f#tOY!1WYZ(}Z]!1W]^(}^r!1Wrs!2fsw!1Wwx!Adx#O!1W#O#P!3d#P#o!1W#o#p!;t#p#q!1W#q#r!3x#r~!1WEc!Ao]&^7[&WW&R,X&f#tOY!AdYZ>wZ]!Ad]^>w^r!Adrs!Bhs#O!Ad#O#P!C[#P#o!Ad#o#p!9f#p#q!Ad#q#r!7x#r~!AdEc!BoX&^7[&R,XOr>wrs@_s#O>w#O#PAP#P#o>w#o#p8Y#p#q>w#q#r6g#r~>wEc!CaT&^7[O#o!Ad#o#p!7x#p#q!Ad#q#r!7x#r~!AdGZ!CuT&^7[O#o!-l#o#p!DU#p#q!-l#q#r!DU#r~!-l0}!De]&TS&WW&R,X&Z`&d!b&f#tOY!DUYZAyZ]!DU]^Ay^r!DUrs!E^sw!DUwx!5tx#O!DU#O#P!FU#P#o!DU#o#p!F[#p~!DU0}!EiX&TS&R,X&Z`&d!bOrAyrsCiswAywx5Px#OAy#O#PEo#P#oAy#o#pEu#p~Ay0}!FXPO~!DU0}!Fe]&TS&WW&R,XOY!<vYZ:{Z]!<v]^:{^r!<vrs!=rsw!<vwx!>`x#O!<v#O#P!@S#P#o!<v#o#p!DU#p~!<vGZ!GkZ&^7[&TS&R,X&Z`&d!bOr'Prs!H^sw'Pwx(Rx#O'P#O#PAe#P#o'P#o#pEu#p#q'P#q#rAy#r~'PGZ!HmX&X#|&^7[&TS&V,X&Z`&d!bOwGgwx,kx#OGg#O#PH_#P#oGg#o#pET#p#qGg#q#rD_#r~GgMg!Im_Q1s&^7[&TS&WW&Z`&ap&d!b&f#tOY!IYYZ$}Z]!IY]^$}^r!IYrs!Jlsw!IYwx$$[x#O!IY#O#P$1v#P#o!IY#o#p$4Y#p#q!IY#q#r$2j#r~!IYLu!Jy_Q1s&^7[&TS&Z`&d!bOY!KxYZ'PZ]!Kx]^'P^r!Kxrs$ Usw!Kxwx!MYx#O!Kx#O#P#G^#P#o!Kx#o#p#NS#p#q!Kx#q#r#HQ#r~!KxLu!LZ_Q1s&^7[&TS&WW&Z`&d!b&f#tOY!KxYZ'PZ]!Kx]^'P^r!Kxrs!Jlsw!Kxwx!MYx#O!Kx#O#P#G^#P#o!Kx#o#p#NS#p#q!Kx#q#r#HQ#r~!KxLe!Me_Q1s&^7[&WW&f#tOY!NdYZ(}Z]!Nd]^(}^r!Ndrs# rsw!Ndwx#B[x#O!Nd#O#P#/f#P#o!Nd#o#p#<b#p#q!Nd#q#r#0Y#r~!NdLe!Ns_Q1s&^7[&TS&WW&d!b&f#tOY!NdYZ(}Z]!Nd]^(}^r!Ndrs# rsw!Ndwx!MYx#O!Nd#O#P#/f#P#o!Nd#o#p#<b#p#q!Nd#q#r#0Y#r~!NdLe# }_Q1s&^7[&TS&d!bOY!NdYZ(}Z]!Nd]^(}^r!Ndrs#!|sw!Ndwx!MYx#O!Nd#O#P#/f#P#o!Nd#o#p#<b#p#q!Nd#q#r#0Y#r~!NdLe##X_Q1s&^7[&TS&d!bOY!NdYZ(}Z]!Nd]^(}^r!Ndrs#$Wsw!Ndwx!MYx#O!Nd#O#P#/f#P#o!Nd#o#p#<b#p#q!Nd#q#r#0Y#r~!NdIg#$c]Q1s&^7[&TS&d!bOY#$WYZ+uZ]#$W]^+u^w#$Wwx#%[x#O#$W#O#P#(^#P#o#$W#o#p#,Q#p#q#$W#q#r#)Q#r~#$WIg#%c]Q1s&^7[OY#$WYZ+uZ]#$W]^+u^w#$Wwx#&[x#O#$W#O#P#(^#P#o#$W#o#p#,Q#p#q#$W#q#r#)Q#r~#$WIg#&c]Q1s&^7[OY#$WYZ+uZ]#$W]^+u^w#$Wwx#'[x#O#$W#O#P#(^#P#o#$W#o#p#,Q#p#q#$W#q#r#)Q#r~#$WHP#'cXQ1s&^7[OY#'[YZ-}Z]#'[]^-}^#o#'[#o#p#(O#p#q#'[#q#r#(O#r~#'[1s#(TRQ1sOY#(OZ]#(O^~#(OIg#(eXQ1s&^7[OY#$WYZ+uZ]#$W]^+u^#o#$W#o#p#)Q#p#q#$W#q#r#)Q#r~#$W3Z#)ZZQ1s&TS&d!bOY#)QYZ.qZ]#)Q]^.q^w#)Qwx#)|x#O#)Q#O#P#+l#P#o#)Q#o#p#,Q#p~#)Q3Z#*RZQ1sOY#)QYZ.qZ]#)Q]^.q^w#)Qwx#*tx#O#)Q#O#P#+l#P#o#)Q#o#p#,Q#p~#)Q3Z#*yZQ1sOY#)QYZ.qZ]#)Q]^.q^w#)Qwx#(Ox#O#)Q#O#P#+l#P#o#)Q#o#p#,Q#p~#)Q3Z#+qTQ1sOY#)QYZ.qZ]#)Q]^.q^~#)Q3Z#,XZQ1s&TSOY#,zYZ1OZ]#,z]^1O^w#,zwx#-nx#O#,z#O#P#/Q#P#o#,z#o#p#)Q#p~#,z1w#-RXQ1s&TSOY#,zYZ1OZ]#,z]^1O^w#,zwx#-nx#O#,z#O#P#/Q#P~#,z1w#-sXQ1sOY#,zYZ1OZ]#,z]^1O^w#,zwx#.`x#O#,z#O#P#/Q#P~#,z1w#.eXQ1sOY#,zYZ1OZ]#,z]^1O^w#,zwx#(Ox#O#,z#O#P#/Q#P~#,z1w#/VTQ1sOY#,zYZ1OZ]#,z]^1O^~#,zLe#/mXQ1s&^7[OY!NdYZ(}Z]!Nd]^(}^#o!Nd#o#p#0Y#p#q!Nd#q#r#0Y#r~!Nd6X#0g]Q1s&TS&WW&d!b&f#tOY#0YYZ2qZ]#0Y]^2q^r#0Yrs#1`sw#0Ywx#3dx#O#0Y#O#P#;|#P#o#0Y#o#p#<b#p~#0Y6X#1i]Q1s&TS&d!bOY#0YYZ2qZ]#0Y]^2q^r#0Yrs#2bsw#0Ywx#3dx#O#0Y#O#P#;|#P#o#0Y#o#p#<b#p~#0Y6X#2k]Q1s&TS&d!bOY#0YYZ2qZ]#0Y]^2q^r#0Yrs#)Qsw#0Ywx#3dx#O#0Y#O#P#;|#P#o#0Y#o#p#<b#p~#0Y6X#3m]Q1s&WW&f#tOY#0YYZ2qZ]#0Y]^2q^r#0Yrs#1`sw#0Ywx#4fx#O#0Y#O#P#;|#P#o#0Y#o#p#<b#p~#0Y6X#4o]Q1s&WW&f#tOY#0YYZ2qZ]#0Y]^2q^r#0Yrs#1`sw#0Ywx#5hx#O#0Y#O#P#;|#P#o#0Y#o#p#<b#p~#0Y4q#5qZQ1s&WW&f#tOY#5hYZ6gZ]#5h]^6g^r#5hrs#6ds#O#5h#O#P#8S#P#o#5h#o#p#8h#p~#5h4q#6iZQ1sOY#5hYZ6gZ]#5h]^6g^r#5hrs#7[s#O#5h#O#P#8S#P#o#5h#o#p#8h#p~#5h4q#7aZQ1sOY#5hYZ6gZ]#5h]^6g^r#5hrs#(Os#O#5h#O#P#8S#P#o#5h#o#p#8h#p~#5h4q#8XTQ1sOY#5hYZ6gZ]#5h]^6g^~#5h4q#8oZQ1s&WWOY#9bYZ8tZ]#9b]^8t^r#9brs#:Us#O#9b#O#P#;h#P#o#9b#o#p#5h#p~#9b1{#9iXQ1s&WWOY#9bYZ8tZ]#9b]^8t^r#9brs#:Us#O#9b#O#P#;h#P~#9b1{#:ZXQ1sOY#9bYZ8tZ]#9b]^8t^r#9brs#:vs#O#9b#O#P#;h#P~#9b1{#:{XQ1sOY#9bYZ8tZ]#9b]^8t^r#9brs#(Os#O#9b#O#P#;h#P~#9b1{#;mTQ1sOY#9bYZ8tZ]#9b]^8t^~#9b6X#<RTQ1sOY#0YYZ2qZ]#0Y]^2q^~#0Y6X#<k]Q1s&TS&WWOY#=dYZ:{Z]#=d]^:{^r#=drs#>`sw#=dwx#@Sx#O#=d#O#P#Av#P#o#=d#o#p#0Y#p~#=d2P#=mZQ1s&TS&WWOY#=dYZ:{Z]#=d]^:{^r#=drs#>`sw#=dwx#@Sx#O#=d#O#P#Av#P~#=d2P#>gZQ1s&TSOY#=dYZ:{Z]#=d]^:{^r#=drs#?Ysw#=dwx#@Sx#O#=d#O#P#Av#P~#=d2P#?aZQ1s&TSOY#=dYZ:{Z]#=d]^:{^r#=drs#,zsw#=dwx#@Sx#O#=d#O#P#Av#P~#=d2P#@ZZQ1s&WWOY#=dYZ:{Z]#=d]^:{^r#=drs#>`sw#=dwx#@|x#O#=d#O#P#Av#P~#=d2P#ATZQ1s&WWOY#=dYZ:{Z]#=d]^:{^r#=drs#>`sw#=dwx#9bx#O#=d#O#P#Av#P~#=d2P#A{TQ1sOY#=dYZ:{Z]#=d]^:{^~#=dLe#Bg_Q1s&^7[&WW&f#tOY!NdYZ(}Z]!Nd]^(}^r!Ndrs# rsw!Ndwx#Cfx#O!Nd#O#P#/f#P#o!Nd#o#p#<b#p#q!Nd#q#r#0Y#r~!NdJ}#Cq]Q1s&^7[&WW&f#tOY#CfYZ>wZ]#Cf]^>w^r#Cfrs#Djs#O#Cf#O#P#Fj#P#o#Cf#o#p#8h#p#q#Cf#q#r#5h#r~#CfJ}#Dq]Q1s&^7[OY#CfYZ>wZ]#Cf]^>w^r#Cfrs#Ejs#O#Cf#O#P#Fj#P#o#Cf#o#p#8h#p#q#Cf#q#r#5h#r~#CfJ}#Eq]Q1s&^7[OY#CfYZ>wZ]#Cf]^>w^r#Cfrs#'[s#O#Cf#O#P#Fj#P#o#Cf#o#p#8h#p#q#Cf#q#r#5h#r~#CfJ}#FqXQ1s&^7[OY#CfYZ>wZ]#Cf]^>w^#o#Cf#o#p#5h#p#q#Cf#q#r#5h#r~#CfLu#GeXQ1s&^7[OY!KxYZ'PZ]!Kx]^'P^#o!Kx#o#p#HQ#p#q!Kx#q#r#HQ#r~!Kx6i#Ha]Q1s&TS&WW&Z`&d!b&f#tOY#HQYZAyZ]#HQ]^Ay^r#HQrs#IYsw#HQwx#3dx#O#HQ#O#P#Mn#P#o#HQ#o#p#NS#p~#HQ6i#Ie]Q1s&TS&Z`&d!bOY#HQYZAyZ]#HQ]^Ay^r#HQrs#J^sw#HQwx#3dx#O#HQ#O#P#Mn#P#o#HQ#o#p#NS#p~#HQ6i#Ji]Q1s&TS&Z`&d!bOY#HQYZAyZ]#HQ]^Ay^r#HQrs#Kbsw#HQwx#3dx#O#HQ#O#P#Mn#P#o#HQ#o#p#NS#p~#HQ3k#KmZQ1s&TS&Z`&d!bOY#KbYZD_Z]#Kb]^D_^w#Kbwx#)|x#O#Kb#O#P#L`#P#o#Kb#o#p#Lt#p~#Kb3k#LeTQ1sOY#KbYZD_Z]#Kb]^D_^~#Kb3k#L{ZQ1s&TSOY#,zYZ1OZ]#,z]^1O^w#,zwx#-nx#O#,z#O#P#/Q#P#o#,z#o#p#Kb#p~#,z6i#MsTQ1sOY#HQYZAyZ]#HQ]^Ay^~#HQ6i#N]]Q1s&TS&WWOY#=dYZ:{Z]#=d]^:{^r#=drs#>`sw#=dwx#@Sx#O#=d#O#P#Av#P#o#=d#o#p#HQ#p~#=dLu$ c_Q1s&^7[&TS&Z`&d!bOY!KxYZ'PZ]!Kx]^'P^r!Kxrs$!bsw!Kxwx!MYx#O!Kx#O#P#G^#P#o!Kx#o#p#NS#p#q!Kx#q#r#HQ#r~!KxIw$!o]Q1s&^7[&TS&Z`&d!bOY$!bYZGgZ]$!b]^Gg^w$!bwx#%[x#O$!b#O#P$#h#P#o$!b#o#p#Lt#p#q$!b#q#r#Kb#r~$!bIw$#oXQ1s&^7[OY$!bYZGgZ]$!b]^Gg^#o$!b#o#p#Kb#p#q$!b#q#r#Kb#r~$!bMV$$i_Q1s&^7[&WW&ap&f#tOY$%hYZIqZ]$%h]^Iq^r$%hrs# rsw$%hwx$.px#O$%h#O#P$&x#P#o$%h#o#p$-n#p#q$%h#q#r$'l#r~$%hMV$%y_Q1s&^7[&TS&WW&ap&d!b&f#tOY$%hYZIqZ]$%h]^Iq^r$%hrs# rsw$%hwx$$[x#O$%h#O#P$&x#P#o$%h#o#p$-n#p#q$%h#q#r$'l#r~$%hMV$'PXQ1s&^7[OY$%hYZIqZ]$%h]^Iq^#o$%h#o#p$'l#p#q$%h#q#r$'l#r~$%h6y$'{]Q1s&TS&WW&ap&d!b&f#tOY$'lYZKXZ]$'l]^KX^r$'lrs#1`sw$'lwx$(tx#O$'l#O#P$-Y#P#o$'l#o#p$-n#p~$'l6y$)P]Q1s&WW&ap&f#tOY$'lYZKXZ]$'l]^KX^r$'lrs#1`sw$'lwx$)xx#O$'l#O#P$-Y#P#o$'l#o#p$-n#p~$'l6y$*T]Q1s&WW&ap&f#tOY$'lYZKXZ]$'l]^KX^r$'lrs#1`sw$'lwx$*|x#O$'l#O#P$-Y#P#o$'l#o#p$-n#p~$'l5c$+XZQ1s&WW&ap&f#tOY$*|YZMmZ]$*|]^Mm^r$*|rs#6ds#O$*|#O#P$+z#P#o$*|#o#p$,`#p~$*|5c$,PTQ1sOY$*|YZMmZ]$*|]^Mm^~$*|5c$,gZQ1s&WWOY#9bYZ8tZ]#9b]^8t^r#9brs#:Us#O#9b#O#P#;h#P#o#9b#o#p$*|#p~#9b6y$-_TQ1sOY$'lYZKXZ]$'l]^KX^~$'l6y$-w]Q1s&TS&WWOY#=dYZ:{Z]#=d]^:{^r#=drs#>`sw#=dwx#@Sx#O#=d#O#P#Av#P#o#=d#o#p$'l#p~#=dMV$.}_Q1s&^7[&WW&ap&f#tOY$%hYZIqZ]$%h]^Iq^r$%hrs# rsw$%hwx$/|x#O$%h#O#P$&x#P#o$%h#o#p$-n#p#q$%h#q#r$'l#r~$%hKo$0Z]Q1s&^7[&WW&ap&f#tOY$/|YZ!!uZ]$/|]^!!u^r$/|rs#Djs#O$/|#O#P$1S#P#o$/|#o#p$,`#p#q$/|#q#r$*|#r~$/|Ko$1ZXQ1s&^7[OY$/|YZ!!uZ]$/|]^!!u^#o$/|#o#p$*|#p#q$/|#q#r$*|#r~$/|Mg$1}XQ1s&^7[OY!IYYZ$}Z]!IY]^$}^#o!IY#o#p$2j#p#q!IY#q#r$2j#r~!IY7Z$2{]Q1s&TS&WW&Z`&ap&d!b&f#tOY$2jYZ!$gZ]$2j]^!$g^r$2jrs#IYsw$2jwx$(tx#O$2j#O#P$3t#P#o$2j#o#p$4Y#p~$2j7Z$3yTQ1sOY$2jYZ!$gZ]$2j]^!$g^~$2j7Z$4c]Q1s&TS&WWOY#=dYZ:{Z]#=d]^:{^r#=drs#>`sw#=dwx#@Sx#O#=d#O#P#Av#P#o#=d#o#p$2j#p~#=dGz$5o]%jQ&^7[&TS&WW&Z`&ap&d!b&f#tOr$}rs&Rsw$}wxHsx!_$}!_!`$6h!`#O$}#O#P!$R#P#o$}#o#p!%i#p#q$}#q#r!$g#r~$}Gz$6{Z!s,W&^7[&TS&WW&Z`&ap&d!b&f#tOr$}rs&Rsw$}wxHsx#O$}#O#P!$R#P#o$}#o#p!%i#p#q$}#q#r!$g#r~$}Gz$8R]%dQ&^7[&TS&WW&Z`&ap&d!b&f#tOr$}rs&Rsw$}wxHsx!_$}!_!`$6h!`#O$}#O#P!$R#P#o$}#o#p!%i#p#q$}#q#r!$g#r~$}G{$9Z_&_`&^7[&WW&R,X&ap&f#tOY$:YYZIqZ]$:Y]^Iq^r$:Yrs$;jsw$:Ywx%%zx#O$:Y#O#P%!^#P#o$:Y#o#p%$x#p#q$:Y#q#r%!r#r~$:YGk$:k_&^7[&TS&WW&R,X&ap&d!b&f#tOY$:YYZIqZ]$:Y]^Iq^r$:Yrs$;jsw$:Ywx% ^x#O$:Y#O#P%!^#P#o$:Y#o#p%$x#p#q$:Y#q#r%!r#r~$:YFy$;u_&^7[&TS&R,X&d!bOY$<tYZ(}Z]$<t]^(}^r$<trs$Kvsw$<twx$>Sx#O$<t#O#P$?Q#P#o$<t#o#p$Gb#p#q$<t#q#r$?f#r~$<tFy$=T_&^7[&TS&WW&R,X&d!b&f#tOY$<tYZ(}Z]$<t]^(}^r$<trs$;jsw$<twx$>Sx#O$<t#O#P$?Q#P#o$<t#o#p$Gb#p#q$<t#q#r$?f#r~$<tFy$>_Z&^7[&WW&R,X&f#tOr(}rs)}sw(}wx={x#O(}#O#P2]#P#o(}#o#p:X#p#q(}#q#r2q#r~(}Fy$?VT&^7[O#o$<t#o#p$?f#p#q$<t#q#r$?f#r~$<t0m$?s]&TS&WW&R,X&d!b&f#tOY$?fYZ2qZ]$?f]^2q^r$?frs$@lsw$?fwx$Ffx#O$?f#O#P$G[#P#o$?f#o#p$Gb#p~$?f0m$@u]&TS&R,X&d!bOY$?fYZ2qZ]$?f]^2q^r$?frs$Answ$?fwx$Ffx#O$?f#O#P$G[#P#o$?f#o#p$Gb#p~$?f0m$Aw]&TS&R,X&d!bOY$?fYZ2qZ]$?f]^2q^r$?frs$Bpsw$?fwx$Ffx#O$?f#O#P$G[#P#o$?f#o#p$Gb#p~$?f-o$ByZ&TS&R,X&d!bOY$BpYZ.qZ]$Bp]^.q^w$Bpwx$Clx#O$Bp#O#P$DW#P#o$Bp#o#p$D^#p~$Bp-o$CqV&R,XOw.qwx/wx#O.q#O#P0^#P#o.q#o#p0d#p~.q-o$DZPO~$Bp-o$DeZ&TS&R,XOY$EWYZ1OZ]$EW]^1O^w$EWwx$Ezx#O$EW#O#P$F`#P#o$EW#o#p$Bp#p~$EW,]$E_X&TS&R,XOY$EWYZ1OZ]$EW]^1O^w$EWwx$Ezx#O$EW#O#P$F`#P~$EW,]$FPT&R,XOw1Owx1vx#O1O#O#P2V#P~1O,]$FcPO~$EW0m$FoX&WW&R,X&f#tOr2qrs3isw2qwx5sx#O2q#O#P:R#P#o2q#o#p:X#p~2q0m$G_PO~$?f0m$Gk]&TS&WW&R,XOY$HdYZ:{Z]$Hd]^:{^r$Hdrs$I`sw$Hdwx$KSx#O$Hd#O#P$Kp#P#o$Hd#o#p$?f#p~$Hd,e$HmZ&TS&WW&R,XOY$HdYZ:{Z]$Hd]^:{^r$Hdrs$I`sw$Hdwx$KSx#O$Hd#O#P$Kp#P~$Hd,e$IgZ&TS&R,XOY$HdYZ:{Z]$Hd]^:{^r$Hdrs$JYsw$Hdwx$KSx#O$Hd#O#P$Kp#P~$Hd,e$JaZ&TS&R,XOY$HdYZ:{Z]$Hd]^:{^r$Hdrs$EWsw$Hdwx$KSx#O$Hd#O#P$Kp#P~$Hd,e$KZV&WW&R,XOr:{rs;isw:{wx=Zx#O:{#O#P=u#P~:{,e$KsPO~$HdFy$LR_&^7[&TS&R,X&d!bOY$<tYZ(}Z]$<t]^(}^r$<trs$MQsw$<twx$>Sx#O$<t#O#P$?Q#P#o$<t#o#p$Gb#p#q$<t#q#r$?f#r~$<tC{$M]]&^7[&TS&R,X&d!bOY$MQYZ+uZ]$MQ]^+u^w$MQwx$NUx#O$MQ#O#P$Nx#P#o$MQ#o#p$D^#p#q$MQ#q#r$Bp#r~$MQC{$N]X&^7[&R,XOw+uwx-]x#O+u#O#P.]#P#o+u#o#p0d#p#q+u#q#r.q#r~+uC{$N}T&^7[O#o$MQ#o#p$Bp#p#q$MQ#q#r$Bp#r~$MQGk% kZ&^7[&WW&R,X&ap&f#tOrIqrs)}swIqwx! wx#OIq#O#PJs#P#oIq#o#p! T#p#qIq#q#rKX#r~IqGk%!cT&^7[O#o$:Y#o#p%!r#p#q$:Y#q#r%!r#r~$:Y1_%#R]&TS&WW&R,X&ap&d!b&f#tOY%!rYZKXZ]%!r]^KX^r%!rrs$@lsw%!rwx%#zx#O%!r#O#P%$r#P#o%!r#o#p%$x#p~%!r1_%$VX&WW&R,X&ap&f#tOrKXrs3iswKXwxLwx#OKX#O#PN}#P#oKX#o#p! T#p~KX1_%$uPO~%!r1_%%R]&TS&WW&R,XOY$HdYZ:{Z]$Hd]^:{^r$Hdrs$I`sw$Hdwx$KSx#O$Hd#O#P$Kp#P#o$Hd#o#p%!r#p~$HdGk%&XZ&^7[&WW&R,X&ap&f#tOrIqrs)}swIqwx%&zx#OIq#O#PJs#P#oIq#o#p! T#p#qIq#q#rKX#r~IqGk%'ZX&U!f&^7[&WW&S,X&ap&f#tOr!!urs?ms#O!!u#O#P!#m#P#o!!u#o#pNc#p#q!!u#q#rMm#r~!!uG{%(ZZf,X&^7[&TS&WW&Z`&ap&d!b&f#tOr$}rs&Rsw$}wxHsx#O$}#O#P!$R#P#o$}#o#p!%i#p#q$}#q#r!$g#r~$}<u%)aZeR&^7[&TS&WW&Z`&ap&d!b&f#tOr$}rs&Rsw$}wxHsx#O$}#O#P!$R#P#o$}#o#p!%i#p#q$}#q#r!$g#r~$}G{%*g_T,X&^7[&TS&WW&Z`&ap&d!b&f#tOr$}rs&Rsw$}wxHsxz$}z{%+f{!_$}!_!`$6h!`#O$}#O#P!$R#P#o$}#o#p!%i#p#q$}#q#r!$g#r~$}G{%+y]_R&^7[&TS&WW&Z`&ap&d!b&f#tOr$}rs&Rsw$}wxHsx!_$}!_!`$6h!`#O$}#O#P!$R#P#o$}#o#p!%i#p#q$}#q#r!$g#r~$}G{%-V]%g,X&^7[&TS&WW&Z`&ap&d!b&f#tOr$}rs&Rsw$}wxHsx!_$}!_!`$6h!`#O$}#O#P!$R#P#o$}#o#p!%i#p#q$}#q#r!$g#r~$}<u%.cZxR&^7[&TS&WW&Z`&ap&d!b&f#tOr$}rs&Rsw$}wxHsx#O$}#O#P!$R#P#o$}#o#p!%i#p#q$}#q#r!$g#r~$}Mg%/i^%h,X&^7[&TS&WW&Z`&ap&d!b&f#tOr$}rs&Rsw$}wxHsx!_$}!_!`$6h!`!a%0e!a#O$}#O#P!$R#P#o$}#o#p!%i#p#q$}#q#r!$g#r~$}B^%0xZ&q&j&^7[&TS&WW&Z`&ap&d!b&f#tOr$}rs&Rsw$}wxHsx#O$}#O#P!$R#P#o$}#o#p!%i#p#q$}#q#r!$g#r~$}G{%2O_!dQ&^7[&TS&WW&Z`&ap&d!b&f#tOr$}rs&Rsw$}wxHsx!O$}!O!P%2}!P!Q$}!Q![%5_![#O$}#O#P!$R#P#o$}#o#p!%i#p#q$}#q#r!$g#r~$}G{%3`]&^7[&TS&WW&Z`&ap&d!b&f#tOr$}rs&Rsw$}wxHsx!O$}!O!P%4X!P#O$}#O#P!$R#P#o$}#o#p!%i#p#q$}#q#r!$g#r~$}G{%4lZ!m,X&^7[&TS&WW&Z`&ap&d!b&f#tOr$}rs&Rsw$}wxHsx#O$}#O#P!$R#P#o$}#o#p!%i#p#q$}#q#r!$g#r~$}Gy%5rg!f,V&^7[&TS&WW&Z`&ap&d!b&f#tOr$}rs&Rsw$}wxHsx!Q$}!Q![%5_![!g$}!g!h%7Z!h!l$}!l!m%;k!m#O$}#O#P!$R#P#R$}#R#S%5_#S#X$}#X#Y%7Z#Y#^$}#^#_%;k#_#o$}#o#p!%i#p#q$}#q#r!$g#r~$}Gy%7la&^7[&TS&WW&Z`&ap&d!b&f#tOr$}rs&Rsw$}wxHsx{$}{|%8q|}$}}!O%8q!O!Q$}!Q![%9{![#O$}#O#P!$R#P#o$}#o#p!%i#p#q$}#q#r!$g#r~$}Gy%9S]&^7[&TS&WW&Z`&ap&d!b&f#tOr$}rs&Rsw$}wxHsx!Q$}!Q![%9{![#O$}#O#P!$R#P#o$}#o#p!%i#p#q$}#q#r!$g#r~$}Gy%:`c!f,V&^7[&TS&WW&Z`&ap&d!b&f#tOr$}rs&Rsw$}wxHsx!Q$}!Q![%9{![!l$}!l!m%;k!m#O$}#O#P!$R#P#R$}#R#S%9{#S#^$}#^#_%;k#_#o$}#o#p!%i#p#q$}#q#r!$g#r~$}Gy%<OZ!f,V&^7[&TS&WW&Z`&ap&d!b&f#tOr$}rs&Rsw$}wxHsx#O$}#O#P!$R#P#o$}#o#p!%i#p#q$}#q#r!$g#r~$}G{%=U_%iR&^7[&TS&WW&Z`&ap&d!b&f#tOr$}rs&Rsw$}wxHsx!P$}!P!Q%>T!Q!_$}!_!`$6h!`#O$}#O#P!$R#P#o$}#o#p!%i#p#q$}#q#r!$g#r~$}Gz%>h]%kQ&^7[&TS&WW&Z`&ap&d!b&f#tOr$}rs&Rsw$}wxHsx!_$}!_!`$6h!`#O$}#O#P!$R#P#o$}#o#p!%i#p#q$}#q#r!$g#r~$}Gy%?tu!f,V&^7[&TS&WW&Z`&ap&d!b&f#tOr$}rs&Rsw$}wxHsx!O$}!O!P%BX!P!Q$}!Q![%Cc![!d$}!d!e%Ee!e!g$}!g!h%7Z!h!l$}!l!m%;k!m!q$}!q!r%H_!r!z$}!z!{%KR!{#O$}#O#P!$R#P#R$}#R#S%Cc#S#U$}#U#V%Ee#V#X$}#X#Y%7Z#Y#^$}#^#_%;k#_#c$}#c#d%H_#d#l$}#l#m%KR#m#o$}#o#p!%i#p#q$}#q#r!$g#r~$}Gy%Bj]&^7[&TS&WW&Z`&ap&d!b&f#tOr$}rs&Rsw$}wxHsx!Q$}!Q![%5_![#O$}#O#P!$R#P#o$}#o#p!%i#p#q$}#q#r!$g#r~$}Gy%Cvi!f,V&^7[&TS&WW&Z`&ap&d!b&f#tOr$}rs&Rsw$}wxHsx!O$}!O!P%BX!P!Q$}!Q![%Cc![!g$}!g!h%7Z!h!l$}!l!m%;k!m#O$}#O#P!$R#P#R$}#R#S%Cc#S#X$}#X#Y%7Z#Y#^$}#^#_%;k#_#o$}#o#p!%i#p#q$}#q#r!$g#r~$}Gy%Ev`&^7[&TS&WW&Z`&ap&d!b&f#tOr$}rs&Rsw$}wxHsx!Q$}!Q!R%Fx!R!S%Fx!S#O$}#O#P!$R#P#R$}#R#S%Fx#S#o$}#o#p!%i#p#q$}#q#r!$g#r~$}Gy%G]`!f,V&^7[&TS&WW&Z`&ap&d!b&f#tOr$}rs&Rsw$}wxHsx!Q$}!Q!R%Fx!R!S%Fx!S#O$}#O#P!$R#P#R$}#R#S%Fx#S#o$}#o#p!%i#p#q$}#q#r!$g#r~$}Gy%Hp_&^7[&TS&WW&Z`&ap&d!b&f#tOr$}rs&Rsw$}wxHsx!Q$}!Q!Y%Io!Y#O$}#O#P!$R#P#R$}#R#S%Io#S#o$}#o#p!%i#p#q$}#q#r!$g#r~$}Gy%JS_!f,V&^7[&TS&WW&Z`&ap&d!b&f#tOr$}rs&Rsw$}wxHsx!Q$}!Q!Y%Io!Y#O$}#O#P!$R#P#R$}#R#S%Io#S#o$}#o#p!%i#p#q$}#q#r!$g#r~$}Gy%Kdc&^7[&TS&WW&Z`&ap&d!b&f#tOr$}rs&Rsw$}wxHsx!Q$}!Q![%Lo![!c$}!c!i%Lo!i#O$}#O#P!$R#P#R$}#R#S%Lo#S#T$}#T#Z%Lo#Z#o$}#o#p!%i#p#q$}#q#r!$g#r~$}Gy%MSc!f,V&^7[&TS&WW&Z`&ap&d!b&f#tOr$}rs&Rsw$}wxHsx!Q$}!Q![%Lo![!c$}!c!i%Lo!i#O$}#O#P!$R#P#R$}#R#S%Lo#S#T$}#T#Z%Lo#Z#o$}#o#p!%i#p#q$}#q#r!$g#r~$}Mg%Nr]y1s&^7[&TS&WW&Z`&ap&d!b&f#tOr$}rs&Rsw$}wxHsx!_$}!_!`& k!`#O$}#O#P!$R#P#o$}#o#p!%i#p#q$}#q#r!$g#r~$}<u&!OZ%sR&^7[&TS&WW&Z`&ap&d!b&f#tOr$}rs&Rsw$}wxHsx#O$}#O#P!$R#P#o$}#o#p!%i#p#q$}#q#r!$g#r~$}G{&#UZ#^,X&^7[&TS&WW&Z`&ap&d!b&f#tOr$}rs&Rsw$}wxHsx#O$}#O#P!$R#P#o$}#o#p!%i#p#q$}#q#r!$g#r~$}G{&$[_kR&^7[&TS&WW&Z`&ap&d!b&f#tOr$}rs&Rsw$}wxHsx!^$}!^!_&%Z!_!`!*Q!`!a!*Q!a#O$}#O#P!$R#P#o$}#o#p!%i#p#q$}#q#r!$g#r~$}Gz&%n]%eQ&^7[&TS&WW&Z`&ap&d!b&f#tOr$}rs&Rsw$}wxHsx!_$}!_!`$6h!`#O$}#O#P!$R#P#o$}#o#p!%i#p#q$}#q#r!$g#r~$}G{&&z]%r,X&^7[&TS&WW&Z`&ap&d!b&f#tOr$}rs&Rsw$}wxHsx!_$}!_!`!*Q!`#O$}#O#P!$R#P#o$}#o#p!%i#p#q$}#q#r!$g#r~$}G{&(W^kR&^7[&TS&WW&Z`&ap&d!b&f#tOr$}rs&Rsw$}wxHsx!_$}!_!`!*Q!`!a&)S!a#O$}#O#P!$R#P#o$}#o#p!%i#p#q$}#q#r!$g#r~$}Gz&)g]%fQ&^7[&TS&WW&Z`&ap&d!b&f#tOr$}rs&Rsw$}wxHsx!_$}!_!`$6h!`#O$}#O#P!$R#P#o$}#o#p!%i#p#q$}#q#r!$g#r~$}G{&*u]]Q#tP&^7[&TS&WW&Z`&ap&d!b&f#tOr$}rs&Rsw$}wxHsx!_$}!_!`$6h!`#O$}#O#P!$R#P#o$}#o#p!%i#p#q$}#q#r!$g#r~$}Mg&,Tc&^7[&TS&WW&Q&j&Z`&ap&d!b&f#t%m,XOr$}rs&Rsw$}wxHsx!Q$}!Q![&+n![!c$}!c!}&+n!}#O$}#O#P!$R#P#R$}#R#S&+n#S#T$}#T#o&+n#o#p!%i#p#q$}#q#r!$g#r$g$}$g~&+nMg&-ug&^7[&TS&WW&Q&j&Z`&ap&d!b&f#t%m,XOr$}rs&/^sw$}wx&2dx!Q$}!Q![&+n![!c$}!c!t&+n!t!u&5j!u!}&+n!}#O$}#O#P!$R#P#R$}#R#S&+n#S#T$}#T#f&+n#f#g&5j#g#o&+n#o#p!%i#p#q$}#q#r!$g#r$g$}$g~&+nGZ&/k_&^7[&TS&R,X&Z`&d!bOY!-lYZ'PZ]!-l]^'P^r!-lrs&0jsw!-lwx!/|x#O!-l#O#P!Cp#P#o!-l#o#p!F[#p#q!-l#q#r!DU#r~!-lGZ&0wZ&^7[&TS&R,X&Z`&d!bOr'Prs&1jsw'Pwx(Rx#O'P#O#PAe#P#o'P#o#pEu#p#q'P#q#rAy#r~'PD]&1wX&^7[&TS&V,X&Z`&d!bOwGgwx,kx#OGg#O#PH_#P#oGg#o#pET#p#qGg#q#rD_#r~GgGk&2q_&^7[&WW&R,X&ap&f#tOY$:YYZIqZ]$:Y]^Iq^r$:Yrs$;jsw$:Ywx&3px#O$:Y#O#P%!^#P#o$:Y#o#p%$x#p#q$:Y#q#r%!r#r~$:YGk&3}Z&^7[&WW&R,X&ap&f#tOrIqrs)}swIqwx&4px#OIq#O#PJs#P#oIq#o#p! T#p#qIq#q#rKX#r~IqFT&4}X&^7[&WW&S,X&ap&f#tOr!!urs?ms#O!!u#O#P!#m#P#o!!u#o#pNc#p#q!!u#q#rMm#r~!!uMg&6Pc&^7[&TS&WW&Q&j&Z`&ap&d!b&f#t%m,XOr$}rs&/^sw$}wx&2dx!Q$}!Q![&+n![!c$}!c!}&+n!}#O$}#O#P!$R#P#R$}#R#S&+n#S#T$}#T#o&+n#o#p!%i#p#q$}#q#r!$g#r$g$}$g~&+nMg&7qg&^7[&TS&WW&Q&j&Z`&ap&d!b&f#t%m,XOr$}rs&9Ysw$}wx&<Qx!Q$}!Q![&+n![!c$}!c!t&+n!t!u&>x!u!}&+n!}#O$}#O#P!$R#P#R$}#R#S&+n#S#T$}#T#f&+n#f#g&>x#g#o&+n#o#p!%i#p#q$}#q#r!$g#r$g$}$g~&+nGZ&9gZ&^7[&TS&Z`&d!b&`,XOr'Prs&:Ysw'Pwx(Rx#O'P#O#PAe#P#o'P#o#pEu#p#q'P#q#rAy#r~'PGZ&:eZ&^7[&TS&Z`&d!bOr'Prs&;Wsw'Pwx(Rx#O'P#O#PAe#P#o'P#o#pEu#p#q'P#q#rAy#r~'PD]&;eX&^7[&TS&e,X&Z`&d!bOwGgwx,kx#OGg#O#PH_#P#oGg#o#pET#p#qGg#q#rD_#r~GgGk&<_Z&^7[&WW&ap&f#t&Y,XOrIqrs)}swIqwx&=Qx#OIq#O#PJs#P#oIq#o#p! T#p#qIq#q#rKX#r~IqGk&=]Z&^7[&WW&ap&f#tOrIqrs)}swIqwx&>Ox#OIq#O#PJs#P#oIq#o#p! T#p#qIq#q#rKX#r~IqFT&>]X&^7[&WW&c,X&ap&f#tOr!!urs?ms#O!!u#O#P!#m#P#o!!u#o#pNc#p#q!!u#q#rMm#r~!!uMg&?_c&^7[&TS&WW&Q&j&Z`&ap&d!b&f#t%m,XOr$}rs&9Ysw$}wx&<Qx!Q$}!Q![&+n![!c$}!c!}&+n!}#O$}#O#P!$R#P#R$}#R#S&+n#S#T$}#T#o&+n#o#p!%i#p#q$}#q#r!$g#r$g$}$g~&+nMg&APk&^7[&TS&WW&Q&j&Z`&ap&d!b&f#t%m,XOr$}rs&/^sw$}wx&2dx!Q$}!Q![&+n![!c$}!c!h&+n!h!i&>x!i!t&+n!t!u&5j!u!}&+n!}#O$}#O#P!$R#P#R$}#R#S&+n#S#T$}#T#U&+n#U#V&5j#V#Y&+n#Y#Z&>x#Z#o&+n#o#p!%i#p#q$}#q#r!$g#r$g$}$g~&+nG{&CXZ!V,X&^7[&TS&WW&Z`&ap&d!b&f#tOr$}rs&Rsw$}wxHsx#O$}#O#P!$R#P#o$}#o#p!%i#p#q$}#q#r!$g#r~$}<u&D_Z!UR&^7[&TS&WW&Z`&ap&d!b&f#tOr$}rs&Rsw$}wxHsx#O$}#O#P!$R#P#o$}#o#p!%i#p#q$}#q#r!$g#r~$}Gz&Ee]%cQ&^7[&TS&WW&Z`&ap&d!b&f#tOr$}rs&Rsw$}wxHsx!_$}!_!`$6h!`#O$}#O#P!$R#P#o$}#o#p!%i#p#q$}#q#r!$g#r~$}Gy&FgX&TS&WW!ZGmOr:{rs;isw:{wx<ox#O:{#O#P=u#P#o:{#o#p!$g#p~:{G{&Gg]%bR&^7[&TS&WW&Z`&ap&d!b&f#tOr$}rs&Rsw$}wxHsx!_$}!_!`$6h!`#O$}#O#P!$R#P#o$}#o#p!%i#p#q$}#q#r!$g#r~$}<u&HqX!Y7_&TS&WW&Z`&ap&d!b&f#tOr!$grsBssw!$gwxLRx#O!$g#O#P!%c#P#o!$g#o#p!%i#p~!$gGy&IqZ%l,V&^7[&TS&WW&Z`&ap&d!b&f#tOr$}rs&Rsw$}wxHsx#O$}#O#P!$R#P#o$}#o#p!%i#p#q$}#q#r!$g#r~$}", + tokenizers: [legacyPrint, indentation, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, newlines], + topRules: {"Script":[0,3]}, + specialized: [{term: 213, get: value => spec_identifier[value] || -1}], + tokenPrec: 7282 + }); + + function indentBody(context, node) { + let base = context.lineIndent(node.from); + let line = context.lineAt(context.pos, -1), to = line.from + line.text.length; + // Don't consider blank, deindented lines at the end of the + // block part of the block + if (!/\S/.test(line.text) && + context.node.to < to + 100 && + !/\S/.test(context.state.sliceDoc(to, context.node.to)) && + context.lineIndent(context.pos, -1) <= base) + return null; + // A normally deindenting keyword that appears at a higher + // indentation than the block should probably be handled by the next + // level + if (/^\s*(else:|elif |except |finally:)/.test(context.textAfter) && context.lineIndent(context.pos, -1) > base) + return null; + return base + context.unit; + } + /** + A language provider based on the [Lezer Python + parser](https://github.com/lezer-parser/python), extended with + highlighting and indentation information. + */ + const pythonLanguage = /*@__PURE__*/LRLanguage.define({ + parser: /*@__PURE__*/parser.configure({ + props: [ + /*@__PURE__*/indentNodeProp.add({ + Body: context => { var _a; return (_a = indentBody(context, context.node)) !== null && _a !== void 0 ? _a : context.continue(); }, + IfStatement: cx => /^\s*(else:|elif )/.test(cx.textAfter) ? cx.baseIndent : cx.continue(), + TryStatement: cx => /^\s*(except |finally:)/.test(cx.textAfter) ? cx.baseIndent : cx.continue(), + "TupleExpression ComprehensionExpression ParamList ArgList ParenthesizedExpression": /*@__PURE__*/delimitedIndent({ closing: ")" }), + "DictionaryExpression DictionaryComprehensionExpression SetExpression SetComprehensionExpression": /*@__PURE__*/delimitedIndent({ closing: "}" }), + "ArrayExpression ArrayComprehensionExpression": /*@__PURE__*/delimitedIndent({ closing: "]" }), + "String FormatString": () => null, + Script: context => { + if (context.pos + /\s*/.exec(context.textAfter)[0].length >= context.node.to) { + let endBody = null; + for (let cur = context.node, to = cur.to;;) { + cur = cur.lastChild; + if (!cur || cur.to != to) + break; + if (cur.type.name == "Body") + endBody = cur; + } + if (endBody) { + let bodyIndent = indentBody(context, endBody); + if (bodyIndent != null) + return bodyIndent; + } + } + return context.continue(); + } + }), + /*@__PURE__*/foldNodeProp.add({ + "ArrayExpression DictionaryExpression SetExpression TupleExpression": foldInside, + Body: (node, state) => ({ from: node.from + 1, to: node.to - (node.to == state.doc.length ? 0 : 1) }) + }) + ], + }), + languageData: { + closeBrackets: { + brackets: ["(", "[", "{", "'", '"', "'''", '"""'], + stringPrefixes: ["f", "fr", "rf", "r", "u", "b", "br", "rb", + "F", "FR", "RF", "R", "U", "B", "BR", "RB"] + }, + commentTokens: { line: "#" }, + indentOnInput: /^\s*([\}\]\)]|else:|elif |except |finally:)$/ + } + }); + /** + Python language support. + */ + function python() { + return new LanguageSupport(pythonLanguage); + } + + // Using https://github.com/one-dark/vscode-one-dark-theme/ as reference for the colors + const ivory = "#abb2bf", stone = "#7d8799", // Brightened compared to original to increase contrast + darkBackground = "#21252b", highlightBackground = "#2c313a", background = "#282c34", tooltipBackground = "#353a42", selection = "#3E4451", cursor = "#528bff"; + /** + The editor theme styles for One Dark. + */ + const oneDarkTheme = /*@__PURE__*/EditorView.theme({ + "&": { + color: ivory, + backgroundColor: background + }, + ".cm-content": { + caretColor: cursor + }, + ".cm-cursor, .cm-dropCursor": { borderLeftColor: cursor }, + "&.cm-focused .cm-selectionBackground, .cm-selectionBackground, .cm-content ::selection": { backgroundColor: selection }, + ".cm-panels": { backgroundColor: darkBackground, color: ivory }, + ".cm-panels.cm-panels-top": { borderBottom: "2px solid black" }, + ".cm-panels.cm-panels-bottom": { borderTop: "2px solid black" }, + ".cm-searchMatch": { + backgroundColor: "#72a1ff59", + outline: "1px solid #457dff" + }, + ".cm-searchMatch.cm-searchMatch-selected": { + backgroundColor: "#6199ff2f" + }, + ".cm-activeLine": { backgroundColor: "#6699ff0b" }, + ".cm-selectionMatch": { backgroundColor: "#aafe661a" }, + "&.cm-focused .cm-matchingBracket, &.cm-focused .cm-nonmatchingBracket": { + backgroundColor: "#bad0f847", + outline: "1px solid #515a6b" + }, + ".cm-gutters": { + backgroundColor: background, + color: stone, + border: "none" + }, + ".cm-activeLineGutter": { + backgroundColor: highlightBackground + }, + ".cm-foldPlaceholder": { + backgroundColor: "transparent", + border: "none", + color: "#ddd" + }, + ".cm-tooltip": { + border: "none", + backgroundColor: tooltipBackground + }, + ".cm-tooltip .cm-tooltip-arrow:before": { + borderTopColor: "transparent", + borderBottomColor: "transparent" + }, + ".cm-tooltip .cm-tooltip-arrow:after": { + borderTopColor: tooltipBackground, + borderBottomColor: tooltipBackground + }, + ".cm-tooltip-autocomplete": { + "& > ul > li[aria-selected]": { + backgroundColor: highlightBackground, + color: ivory + } + } + }, { dark: true }); + + const logger$5 = getLogger('py-repl'); + const RUNBUTTON = `<svg style="height:20px;width:20px;vertical-align:-.125em;transform-origin:center;overflow:visible;color:green" viewBox="0 0 384 512" aria-hidden="true" role="img" xmlns="http://www.w3.org/2000/svg"><g transform="translate(192 256)" transform-origin="96 0"><g transform="translate(0,0) scale(1,1)"><path d="M361 215C375.3 223.8 384 239.3 384 256C384 272.7 375.3 288.2 361 296.1L73.03 472.1C58.21 482 39.66 482.4 24.52 473.9C9.377 465.4 0 449.4 0 432V80C0 62.64 9.377 46.63 24.52 38.13C39.66 29.64 58.21 29.99 73.03 39.04L361 215z" fill="currentColor" transform="translate(-192 -256)"></path></g></g></svg>`; + function make_PyRepl(interpreter) { + /* High level structure of py-repl DOM, and the corresponding JS names. + + this <py-repl> + shadow #shadow-root + <slot></slot> + boxDiv <div class='py-repl-box'> + editorLabel <label>...</label> + editorDiv <div class="py-repl-editor"></div> + outDiv <div class="py-repl-output"></div> + </div> + </py-repl> + */ + class PyRepl extends HTMLElement { + constructor() { + super(); + } + connectedCallback() { + ensureUniqueId(this); + this.shadow = this.attachShadow({ mode: 'open' }); + const slot = document.createElement('slot'); + this.shadow.appendChild(slot); + if (!this.hasAttribute('exec-id')) { + this.setAttribute('exec-id', '0'); + } + if (!this.hasAttribute('root')) { + this.setAttribute('root', this.id); + } + const pySrc = htmlDecode(this.innerHTML).trim(); + this.innerHTML = ''; + this.editor = this.makeEditor(pySrc); + const boxDiv = this.makeBoxDiv(); + this.appendChild(boxDiv); + this.editor.focus(); + logger$5.debug(`element ${this.id} successfully connected`); + } + /** Create and configure the codemirror editor + */ + makeEditor(pySrc) { + const languageConf = new Compartment(); + const extensions = [ + indentUnit.of(' '), + basicSetup, + languageConf.of(python()), + keymap.of([ + ...defaultKeymap, + { key: 'Ctrl-Enter', run: this.execute.bind(this), preventDefault: true }, + { key: 'Shift-Enter', run: this.execute.bind(this), preventDefault: true }, + ]), + ]; + if (getAttribute(this, 'theme') === 'dark') { + extensions.push(oneDarkTheme); + } + return new EditorView({ + doc: pySrc, + extensions, + }); + } + // ******** main entry point for py-repl DOM building ********** + // + // The following functions are written in a top-down, depth-first + // order (so that the order of code roughly matches the order of + // execution) + makeBoxDiv() { + const boxDiv = document.createElement('div'); + boxDiv.className = 'py-repl-box'; + const editorDiv = this.makeEditorDiv(); + const editorLabel = this.makeLabel('Python Script Area', editorDiv); + this.outDiv = this.makeOutDiv(); + boxDiv.append(editorLabel); + boxDiv.appendChild(editorDiv); + boxDiv.appendChild(this.outDiv); + return boxDiv; + } + makeEditorDiv() { + const editorDiv = document.createElement('div'); + editorDiv.id = 'code-editor'; + editorDiv.className = 'py-repl-editor'; + editorDiv.appendChild(this.editor.dom); + const runButton = this.makeRunButton(); + const runLabel = this.makeLabel('Python Script Run Button', runButton); + editorDiv.appendChild(runLabel); + editorDiv.appendChild(runButton); + return editorDiv; + } + makeLabel(text, elementFor) { + ensureUniqueId(elementFor); + const lbl = document.createElement('label'); + lbl.innerHTML = text; + lbl.htmlFor = elementFor.id; + // XXX this should be a CSS class + // Styles that we use to hide the labels whilst also keeping it accessible for screen readers + const labelStyle = 'overflow:hidden; display:block; width:1px; height:1px'; + lbl.setAttribute('style', labelStyle); + return lbl; + } + makeRunButton() { + const runButton = document.createElement('button'); + runButton.id = 'runButton'; + runButton.className = 'absolute py-repl-run-button'; + runButton.innerHTML = RUNBUTTON; + runButton.addEventListener('click', this.execute.bind(this)); + return runButton; + } + makeOutDiv() { + const outDiv = document.createElement('div'); + outDiv.className = 'py-repl-output'; + outDiv.id = this.id + '-repl-output'; + return outDiv; + } + // ********************* execution logic ********************* + /** Execute the python code written in the editor, and automatically + * display() the last evaluated expression + */ + async execute() { + const pySrc = this.getPySrc(); + // determine the output element + const outEl = this.getOutputElement(); + if (outEl === undefined) { + // this happens if we specified output="..." but we couldn't + // find the ID. We already displayed an error message inside + // getOutputElement, stop the execution. + return; + } + // clear the old output before executing the new code + outEl.innerHTML = ''; + // execute the python code + const pyResult = (await pyExec(interpreter, pySrc, outEl)).result; + // display the value of the last evaluated expression (REPL-style) + if (pyResult !== undefined) { + pyDisplay(interpreter, pyResult, { target: outEl.id }); + } + this.autogenerateMaybe(); + } + getPySrc() { + return this.editor.state.doc.toString(); + } + getOutputElement() { + const outputID = getAttribute(this, 'output'); + if (outputID !== null) { + const el = document.getElementById(outputID); + if (el === null) { + const err = `py-repl ERROR: cannot find the output element #${outputID} in the DOM`; + this.outDiv.innerText = err; + return undefined; + } + return el; + } + else { + return this.outDiv; + } + } + // XXX the autogenerate logic is very messy. We should redo it, and it + // should be the default. + autogenerateMaybe() { + if (this.hasAttribute('auto-generate')) { + const allPyRepls = document.querySelectorAll(`py-repl[root='${this.getAttribute('root')}'][exec-id]`); + const lastRepl = allPyRepls[allPyRepls.length - 1]; + const lastExecId = lastRepl.getAttribute('exec-id'); + const nextExecId = parseInt(lastExecId) + 1; + const newPyRepl = document.createElement('py-repl'); + newPyRepl.setAttribute('root', this.getAttribute('root')); + newPyRepl.id = this.getAttribute('root') + '-' + nextExecId.toString(); + if (this.hasAttribute('auto-generate')) { + newPyRepl.setAttribute('auto-generate', ''); + this.removeAttribute('auto-generate'); + } + const outputMode = getAttribute(this, 'output-mode'); + if (outputMode) { + newPyRepl.setAttribute('output-mode', outputMode); + } + const addReplAttribute = (attribute) => { + const attr = getAttribute(this, attribute); + if (attr) { + newPyRepl.setAttribute(attribute, attr); + } + }; + addReplAttribute('output'); + newPyRepl.setAttribute('exec-id', nextExecId.toString()); + if (this.parentElement) { + this.parentElement.appendChild(newPyRepl); + } + } + } + } + return PyRepl; + } + + const logger$4 = getLogger('py-register-widget'); + function createWidget(interpreter, name, code, klass) { + class CustomWidget extends HTMLElement { + constructor() { + super(); + this.name = name; + this.klass = klass; + this.code = code; + // attach shadow so we can preserve the element original innerHtml content + this.shadow = this.attachShadow({ mode: 'open' }); + this.wrapper = document.createElement('slot'); + this.shadow.appendChild(this.wrapper); + } + async connectedCallback() { + await interpreter.runButDontRaise(this.code); + this.proxyClass = interpreter.globals.get(this.klass); + this.proxy = this.proxyClass(this); + this.proxy.connect(); + this.registerWidget(); + } + registerWidget() { + logger$4.info('new widget registered:', this.name); + interpreter.globals.set(this.id, this.proxy); + } + } + /* eslint-disable @typescript-eslint/no-unused-vars */ + customElements.define(name, CustomWidget); + /* eslint-enable @typescript-eslint/no-unused-vars */ + } + function make_PyWidget(interpreter) { + class PyWidget extends HTMLElement { + constructor() { + super(); + // attach shadow so we can preserve the element original innerHtml content + this.shadow = this.attachShadow({ mode: 'open' }); + this.wrapper = document.createElement('slot'); + this.shadow.appendChild(this.wrapper); + this.addAttributes('src', 'name', 'klass'); + } + addAttributes(...attrs) { + for (const each of attrs) { + const property = each === 'src' ? 'source' : each; + if (this.hasAttribute(each)) { + this[property] = this.getAttribute(each); + } + } + } + async connectedCallback() { + if (this.id === undefined) { + throw new ReferenceError(`No id specified for component. Components must have an explicit id. Please use id="" to specify your component id.`); + } + const mainDiv = document.createElement('div'); + mainDiv.id = this.id + '-main'; + this.appendChild(mainDiv); + logger$4.debug('PyWidget: reading source', this.source); + this.code = await this.getSourceFromFile(this.source); + createWidget(interpreter, this.name, this.code, this.klass); + } + async getSourceFromFile(s) { + const response = await robustFetch(s); + return await response.text(); + } + } + return PyWidget; + } + + function createCustomElements(interpreter) { + const PyWidget = make_PyWidget(interpreter); + const PyRepl = make_PyRepl(interpreter); + /* eslint-disable @typescript-eslint/no-unused-vars */ + customElements.define('py-repl', PyRepl); + customElements.define('py-register-widget', PyWidget); + /* eslint-enable @typescript-eslint/no-unused-vars */ + } + + /** Default implementation of Stdio: stdout and stderr are both sent to the + * console + */ + const DEFAULT_STDIO = { + stdout_writeline: console.log, + stderr_writeline: console.log, + }; + /** Stdio provider for sending output to DOM element + * specified by ID. Used with "output" keyword. + * + */ + class TargetedStdio { + constructor(source_element, source_attribute, capture_stdout = true, capture_stderr = true) { + this.source_element = source_element; + this.source_attribute = source_attribute; + this.capture_stdout = capture_stdout; + this.capture_stderr = capture_stderr; + } + /** Writes the given msg to an element with a given ID. The ID is the value an attribute + * of the source_element specified by source_attribute. + * Both the element to be targeted and the ID of the element to write to + * are determined at write-time, not when the TargetdStdio object is + * created. This way, if either the 'output' attribute of the HTML tag + * or the ID of the target element changes during execution of the Python + * code, the output is still routed (or not) as expected + * + * @param msg The output to be written + */ + writeline_by_attribute(msg) { + const target_id = this.source_element.getAttribute(this.source_attribute); + const target = document.getElementById(target_id); + if (target === null) { + // No matching ID + createSingularWarning(`${this.source_attribute} = "${target_id}" does not match the id of any element on the page.`); + } + else { + msg = escape(msg).replace('\n', '<br>'); + if (!msg.endsWith('<br/>') && !msg.endsWith('<br>')) { + msg = msg + '<br>'; + } + target.innerHTML += msg; + } + } + stdout_writeline(msg) { + if (this.capture_stdout) { + this.writeline_by_attribute(msg); + } + } + stderr_writeline(msg) { + if (this.capture_stderr) { + this.writeline_by_attribute(msg); + } + } + } + /** Redirect stdio streams to multiple listeners + */ + class StdioMultiplexer { + constructor() { + this._listeners = []; + } + addListener(obj) { + this._listeners.push(obj); + } + removeListener(obj) { + const index = this._listeners.indexOf(obj); + if (index > -1) { + this._listeners.splice(index, 1); + } + } + stdout_writeline(msg) { + for (const obj of this._listeners) + obj.stdout_writeline(msg); + } + stderr_writeline(msg) { + for (const obj of this._listeners) + obj.stderr_writeline(msg); + } + } + + const logger$3 = getLogger('py-terminal'); + class PyTerminalPlugin extends Plugin { + constructor(app) { + super(); + this.app = app; + } + configure(config) { + // validate the terminal config and handle default values + const t = config.terminal; + if (t !== undefined && t !== true && t !== false && t !== 'auto') { + const got = JSON.stringify(t); + throw new UserError(ErrorCode.BAD_CONFIG, 'Invalid value for config.terminal: the only accepted' + + `values are true, false and "auto", got "${got}".`); + } + if (t === undefined) { + config.terminal = 'auto'; // default value + } + } + beforeLaunch(config) { + // if config.terminal is "yes" or "auto", let's add a <py-terminal> to + // the document, unless it's already present. + const t = config.terminal; + if (t === true || t === 'auto') { + if (document.querySelector('py-terminal') === null) { + logger$3.info('No <py-terminal> found, adding one'); + const termElem = document.createElement('py-terminal'); + if (t === 'auto') + termElem.setAttribute('auto', ''); + document.body.appendChild(termElem); + } + } + } + afterSetup(interpreter) { + // the Python interpreter has been initialized and we are ready to + // execute user code: + // + // 1. define the "py-terminal" custom element + // + // 2. if there is a <py-terminal> tag on the page, it will register + // a Stdio listener just before the user code executes, ensuring + // that we capture all the output + // + // 3. everything which was written to stdout BEFORE this moment will + // NOT be shown on the py-terminal; in particular, pyodide + // startup messages will not be shown (but they will go to the + // console as usual). This is by design, else we would display + // e.g. "Python initialization complete" on every page, which we + // don't want. + // + // 4. (in the future we might want to add an option to start the + // capture earlier, but I don't think it's important now). + const PyTerminal = make_PyTerminal(this.app); + customElements.define('py-terminal', PyTerminal); + } + } + function make_PyTerminal(app) { + /** The <py-terminal> custom element, which automatically register a stdio + * listener to capture and display stdout/stderr + */ + class PyTerminal extends HTMLElement { + connectedCallback() { + // should we use a shadowRoot instead? It looks unnecessarily + // complicated to me, but I'm not really sure about the + // implications + this.outElem = document.createElement('pre'); + this.outElem.className = 'py-terminal'; + this.appendChild(this.outElem); + if (this.isAuto()) { + this.classList.add('py-terminal-hidden'); + this.autoShowOnNextLine = true; + } + else { + this.autoShowOnNextLine = false; + } + logger$3.info('Registering stdio listener'); + app.registerStdioListener(this); + } + isAuto() { + return this.hasAttribute('auto'); + } + // implementation of the Stdio interface + stdout_writeline(msg) { + this.outElem.innerText += msg + '\n'; + if (this.autoShowOnNextLine) { + this.classList.remove('py-terminal-hidden'); + this.autoShowOnNextLine = false; + } + } + stderr_writeline(msg) { + this.stdout_writeline(msg); + } + } + return PyTerminal; + } + + const logger$2 = getLogger('py-splashscreen'); + const AUTOCLOSE_LOADER_DEPRECATED = ` +The setting autoclose_loader is deprecated. Please use the +following instead:<br> +<pre> +<py-config> +[splashscreen] +autoclose = false +</py-config> +</pre>`; + class SplashscreenPlugin extends Plugin { + configure(config) { + // the officially supported setting is config.splashscreen.autoclose, + // but we still also support the old config.autoclose_loader (with a + // deprecation warning) + this.autoclose = true; + this.enabled = true; + if ('autoclose_loader' in config) { + this.autoclose = config.autoclose_loader; + showWarning(AUTOCLOSE_LOADER_DEPRECATED, 'html'); + } + if (config.splashscreen) { + this.autoclose = config.splashscreen.autoclose ?? true; + this.enabled = config.splashscreen.enabled ?? true; + } + } + beforeLaunch(config) { + if (!this.enabled) { + return; + } + // add the splashscreen to the DOM + logger$2.info('add py-splashscreen'); + customElements.define('py-splashscreen', PySplashscreen); + this.elem = document.createElement('py-splashscreen'); + document.body.append(this.elem); + document.addEventListener('py-status-message', (e) => { + const msg = e.detail; + this.elem.log(msg); + }); + } + afterStartup(interpreter) { + if (this.autoclose && this.enabled) { + this.elem.close(); + } + } + onUserError(error) { + if (this.elem !== undefined && this.enabled) { + // Remove the splashscreen so users can see the banner better + this.elem.close(); + } + } + } + class PySplashscreen extends HTMLElement { + constructor() { + super(); + } + connectedCallback() { + this.innerHTML = `<div id="pyscript_loading_splash" class="py-overlay"> <div class="py-pop-up"> <div class="smooth spinner"></div> <div id="pyscript-loading-label" class="label"> @@ -4170,23687 +28474,434 @@ </div> </div> </div>`; - this.mount_name = this.id.split('-').join('_'); - this.operation = document.getElementById('pyscript-operation'); - this.details = document.getElementById('pyscript-operation-details'); - } - log(msg) { - // loader messages are showed both in the HTML and in the console - logger$8.info(msg); - const newLog = document.createElement('p'); - newLog.innerText = msg; - this.details.appendChild(newLog); - } - close() { - logger$8.info('Closing'); - this.remove(); - } - } + this.mount_name = this.id.split('-').join('_'); + this.operation = document.getElementById('pyscript-operation'); + this.details = document.getElementById('pyscript-operation-details'); + } + log(msg) { + const newLog = document.createElement('p'); + newLog.innerText = msg; + this.details.appendChild(newLog); + } + close() { + logger$2.info('Closing'); + this.remove(); + } + } - // Compressed representation of the Grapheme_Cluster_Break=Extend - // information from - // http://www.unicode.org/Public/13.0.0/ucd/auxiliary/GraphemeBreakProperty.txt. - // Each pair of elements represents a range, as an offet from the - // previous range and a length. Numbers are in base-36, with the empty - // string being a shorthand for 1. - let extend = /*@__PURE__*/"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(s => s ? parseInt(s, 36) : 1); - // Convert offsets into absolute values - for (let i = 1; i < extend.length; i++) - extend[i] += extend[i - 1]; - function isExtendingChar(code) { - for (let i = 1; i < extend.length; i += 2) - if (extend[i] > code) - return extend[i - 1] <= code; - return false; - } - function isRegionalIndicator(code) { - return code >= 0x1F1E6 && code <= 0x1F1FF; - } - const ZWJ = 0x200d; - /** - Returns a next grapheme cluster break _after_ (not equal to) - `pos`, if `forward` is true, or before otherwise. Returns `pos` - itself if no further cluster break is available in the string. - Moves across surrogate pairs, extending characters (when - `includeExtending` is true), characters joined with zero-width - joiners, and flag emoji. - */ - function findClusterBreak(str, pos, forward = true, includeExtending = true) { - return (forward ? nextClusterBreak : prevClusterBreak)(str, pos, includeExtending); - } - function nextClusterBreak(str, pos, includeExtending) { - if (pos == str.length) - return pos; - // If pos is in the middle of a surrogate pair, move to its start - if (pos && surrogateLow(str.charCodeAt(pos)) && surrogateHigh(str.charCodeAt(pos - 1))) - pos--; - let prev = codePointAt(str, pos); - pos += codePointSize(prev); - while (pos < str.length) { - let next = codePointAt(str, pos); - if (prev == ZWJ || next == ZWJ || includeExtending && isExtendingChar(next)) { - pos += codePointSize(next); - prev = next; - } - else if (isRegionalIndicator(next)) { - let countBefore = 0, i = pos - 2; - while (i >= 0 && isRegionalIndicator(codePointAt(str, i))) { - countBefore++; - i -= 2; - } - if (countBefore % 2 == 0) - break; - else - pos += 2; - } - else { - break; - } - } - return pos; - } - function prevClusterBreak(str, pos, includeExtending) { - while (pos > 0) { - let found = nextClusterBreak(str, pos - 2, includeExtending); - if (found < pos) - return found; - pos--; - } - return 0; - } - function surrogateLow(ch) { return ch >= 0xDC00 && ch < 0xE000; } - function surrogateHigh(ch) { return ch >= 0xD800 && ch < 0xDC00; } - /** - Find the code point at the given position in a string (like the - [`codePointAt`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/codePointAt) - string method). - */ - function codePointAt(str, pos) { - let code0 = str.charCodeAt(pos); - if (!surrogateHigh(code0) || pos + 1 == str.length) - return code0; - let code1 = str.charCodeAt(pos + 1); - if (!surrogateLow(code1)) - return code0; - return ((code0 - 0xd800) << 10) + (code1 - 0xdc00) + 0x10000; - } - /** - Given a Unicode codepoint, return the JavaScript string that - respresents it (like - [`String.fromCodePoint`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/fromCodePoint)). - */ - function fromCodePoint(code) { - if (code <= 0xffff) - return String.fromCharCode(code); - code -= 0x10000; - return String.fromCharCode((code >> 10) + 0xd800, (code & 1023) + 0xdc00); - } - /** - The first character that takes up two positions in a JavaScript - string. It is often useful to compare with this after calling - `codePointAt`, to figure out whether your character takes up 1 or - 2 index positions. - */ - function codePointSize(code) { return code < 0x10000 ? 1 : 2; } + const logger$1 = getLogger('plugins/importmap'); + class ImportmapPlugin extends Plugin { + async afterSetup(interpreter) { + // make importmap ES modules available from python using 'import'. + // + // XXX: this code can probably be improved because errors are silently + // ignored. + // + // Moreover, it's also wrong because it's async and currently we don't + // await the module to be fully registered before executing the code + // inside py-script. It's also unclear whether we want to wait or not + // (or maybe only wait only if we do an actual 'import'?) + for (const node of document.querySelectorAll("script[type='importmap']")) { + const importmap = (() => { + try { + return JSON.parse(node.textContent); + } + catch (error) { + showWarning('Failed to parse import map: ' + error.message); + } + })(); + if (importmap?.imports == null) + continue; + for (const [name, url] of Object.entries(importmap.imports)) { + if (typeof name != 'string' || typeof url != 'string') + continue; + let exports; + try { + // XXX: pyodide doesn't like Module(), failing with + // "can't read 'name' of undefined" at import time + exports = { ...(await import(url)) }; + } + catch { + logger$1.warn(`failed to fetch '${url}' for '${name}'`); + continue; + } + logger$1.info('Registering JS module', name); + interpreter._remote.registerJsModule(name, exports); + } + } + } + } - /** - Count the column position at the given offset into the string, - taking extending characters and tab size into account. - */ - function countColumn(string, tabSize, to = string.length) { - let n = 0; - for (let i = 0; i < to;) { - if (string.charCodeAt(i) == 9) { - n += tabSize - (n % tabSize); - i++; - } - else { - n++; - i = findClusterBreak(string, i); - } - } - return n; - } - /** - Find the offset that corresponds to the given column position in a - string, taking extending characters and tab size into account. By - default, the string length is returned when it is too short to - reach the column. Pass `strict` true to make it return -1 in that - situation. - */ - function findColumn(string, col, tabSize, strict) { - for (let i = 0, n = 0;;) { - if (n >= col) - return i; - if (i == string.length) - break; - n += string.charCodeAt(i) == 9 ? tabSize - (n % tabSize) : 1; - i = findClusterBreak(string, i); - } - return strict === true ? -1 : string.length; - } + /** + * The StdioDirector plugin captures the output to Python's sys.stdio and + * sys.stderr and writes it to a specific element in the DOM. It does this by + * creating a new TargetedStdio manager and adding it to the global stdioMultiplexer's + * list of listeners prior to executing the Python in a specific tag. Following + * execution of the Python in that tag, it removes the TargetedStdio as a listener + * + */ + class StdioDirector extends Plugin { + constructor(stdio) { + super(); + this._stdioMultiplexer = stdio; + } + /** Prior to a <py-script> tag being evaluated, if that tag itself has + * an 'output' attribute, a new TargetedStdio object is created and added + * to the stdioMultiplexer to route sys.stdout and sys.stdout to the DOM object + * with that ID for the duration of the evaluation. + * + */ + beforePyScriptExec(options) { + if (options.pyScriptTag.hasAttribute('output')) { + const targeted_io = new TargetedStdio(options.pyScriptTag, 'output', true, true); + options.pyScriptTag.stdout_manager = targeted_io; + this._stdioMultiplexer.addListener(targeted_io); + } + if (options.pyScriptTag.hasAttribute('stderr')) { + const targeted_io = new TargetedStdio(options.pyScriptTag, 'stderr', false, true); + options.pyScriptTag.stderr_manager = targeted_io; + this._stdioMultiplexer.addListener(targeted_io); + } + } + /** After a <py-script> tag is evaluated, if that tag has a 'stdout_manager' + * (presumably TargetedStdio, or some other future IO handler), it is removed. + */ + afterPyScriptExec(options) { + if (options.pyScriptTag.stdout_manager != null) { + this._stdioMultiplexer.removeListener(options.pyScriptTag.stdout_manager); + options.pyScriptTag.stdout_manager = null; + } + if (options.pyScriptTag.stderr_manager != null) { + this._stdioMultiplexer.removeListener(options.pyScriptTag.stderr_manager); + options.pyScriptTag.stderr_manager = null; + } + } + } - /** - The data structure for documents. - */ - class Text { - /** - @internal - */ - constructor() { } - /** - Get the line description around the given position. - */ - lineAt(pos) { - if (pos < 0 || pos > this.length) - throw new RangeError(`Invalid position ${pos} in document of length ${this.length}`); - return this.lineInner(pos, false, 1, 0); - } - /** - Get the description for the given (1-based) line number. - */ - line(n) { - if (n < 1 || n > this.lines) - throw new RangeError(`Invalid line number ${n} in ${this.lines}-line document`); - return this.lineInner(n, true, 1, 0); - } - /** - Replace a range of the text with the given content. - */ - replace(from, to, text) { - let parts = []; - this.decompose(0, from, parts, 2 /* To */); - if (text.length) - text.decompose(0, text.length, parts, 1 /* From */ | 2 /* To */); - this.decompose(to, this.length, parts, 1 /* From */); - return TextNode.from(parts, this.length - (to - from) + text.length); - } - /** - Append another document to this one. - */ - append(other) { - return this.replace(this.length, this.length, other); - } - /** - Retrieve the text between the given points. - */ - slice(from, to = this.length) { - let parts = []; - this.decompose(from, to, parts, 0); - return TextNode.from(parts, to - from); - } - /** - Test whether this text is equal to another instance. - */ - eq(other) { - if (other == this) - return true; - if (other.length != this.length || other.lines != this.lines) - return false; - let start = this.scanIdentical(other, 1), end = this.length - this.scanIdentical(other, -1); - let a = new RawTextCursor(this), b = new RawTextCursor(other); - for (let skip = start, pos = start;;) { - a.next(skip); - b.next(skip); - skip = 0; - if (a.lineBreak != b.lineBreak || a.done != b.done || a.value != b.value) - return false; - pos += a.value.length; - if (a.done || pos >= end) - return true; - } - } - /** - Iterate over the text. When `dir` is `-1`, iteration happens - from end to start. This will return lines and the breaks between - them as separate strings, and for long lines, might split lines - themselves into multiple chunks as well. - */ - iter(dir = 1) { return new RawTextCursor(this, dir); } - /** - Iterate over a range of the text. When `from` > `to`, the - iterator will run in reverse. - */ - iterRange(from, to = this.length) { return new PartialTextCursor(this, from, to); } - /** - Return a cursor that iterates over the given range of lines, - _without_ returning the line breaks between, and yielding empty - strings for empty lines. - - When `from` and `to` are given, they should be 1-based line numbers. - */ - iterLines(from, to) { - let inner; - if (from == null) { - inner = this.iter(); - } - else { - if (to == null) - to = this.lines + 1; - let start = this.line(from).from; - inner = this.iterRange(start, Math.max(start, to == this.lines + 1 ? this.length : to <= 1 ? 0 : this.line(to - 1).to)); - } - return new LineCursor(inner); - } - /** - @internal - */ - toString() { return this.sliceString(0); } - /** - Convert the document to an array of lines (which can be - deserialized again via [`Text.of`](https://codemirror.net/6/docs/ref/#text.Text^of)). - */ - toJSON() { - let lines = []; - this.flatten(lines); - return lines; - } - /** - Create a `Text` instance for the given array of lines. - */ - static of(text) { - if (text.length == 0) - throw new RangeError("A document must have at least one line"); - if (text.length == 1 && !text[0]) - return Text.empty; - return text.length <= 32 /* Branch */ ? new TextLeaf(text) : TextNode.from(TextLeaf.split(text, [])); - } - } - // Leaves store an array of line strings. There are always line breaks - // between these strings. Leaves are limited in size and have to be - // contained in TextNode instances for bigger documents. - class TextLeaf extends Text { - constructor(text, length = textLength(text)) { - super(); - this.text = text; - this.length = length; - } - get lines() { return this.text.length; } - get children() { return null; } - lineInner(target, isLine, line, offset) { - for (let i = 0;; i++) { - let string = this.text[i], end = offset + string.length; - if ((isLine ? line : end) >= target) - return new Line(offset, end, line, string); - offset = end + 1; - line++; - } - } - decompose(from, to, target, open) { - let text = from <= 0 && to >= this.length ? this - : new TextLeaf(sliceText(this.text, from, to), Math.min(to, this.length) - Math.max(0, from)); - if (open & 1 /* From */) { - let prev = target.pop(); - let joined = appendText(text.text, prev.text.slice(), 0, text.length); - if (joined.length <= 32 /* Branch */) { - target.push(new TextLeaf(joined, prev.length + text.length)); - } - else { - let mid = joined.length >> 1; - target.push(new TextLeaf(joined.slice(0, mid)), new TextLeaf(joined.slice(mid))); - } - } - else { - target.push(text); - } - } - replace(from, to, text) { - if (!(text instanceof TextLeaf)) - return super.replace(from, to, text); - let lines = appendText(this.text, appendText(text.text, sliceText(this.text, 0, from)), to); - let newLen = this.length + text.length - (to - from); - if (lines.length <= 32 /* Branch */) - return new TextLeaf(lines, newLen); - return TextNode.from(TextLeaf.split(lines, []), newLen); - } - sliceString(from, to = this.length, lineSep = "\n") { - let result = ""; - for (let pos = 0, i = 0; pos <= to && i < this.text.length; i++) { - let line = this.text[i], end = pos + line.length; - if (pos > from && i) - result += lineSep; - if (from < end && to > pos) - result += line.slice(Math.max(0, from - pos), to - pos); - pos = end + 1; - } - return result; - } - flatten(target) { - for (let line of this.text) - target.push(line); - } - scanIdentical() { return 0; } - static split(text, target) { - let part = [], len = -1; - for (let line of text) { - part.push(line); - len += line.length + 1; - if (part.length == 32 /* Branch */) { - target.push(new TextLeaf(part, len)); - part = []; - len = -1; - } - } - if (len > -1) - target.push(new TextLeaf(part, len)); - return target; - } - } - // Nodes provide the tree structure of the `Text` type. They store a - // number of other nodes or leaves, taking care to balance themselves - // on changes. There are implied line breaks _between_ the children of - // a node (but not before the first or after the last child). - class TextNode extends Text { - constructor(children, length) { - super(); - this.children = children; - this.length = length; - this.lines = 0; - for (let child of children) - this.lines += child.lines; - } - lineInner(target, isLine, line, offset) { - for (let i = 0;; i++) { - let child = this.children[i], end = offset + child.length, endLine = line + child.lines - 1; - if ((isLine ? endLine : end) >= target) - return child.lineInner(target, isLine, line, offset); - offset = end + 1; - line = endLine + 1; - } - } - decompose(from, to, target, open) { - for (let i = 0, pos = 0; pos <= to && i < this.children.length; i++) { - let child = this.children[i], end = pos + child.length; - if (from <= end && to >= pos) { - let childOpen = open & ((pos <= from ? 1 /* From */ : 0) | (end >= to ? 2 /* To */ : 0)); - if (pos >= from && end <= to && !childOpen) - target.push(child); - else - child.decompose(from - pos, to - pos, target, childOpen); - } - pos = end + 1; - } - } - replace(from, to, text) { - if (text.lines < this.lines) - for (let i = 0, pos = 0; i < this.children.length; i++) { - let child = this.children[i], end = pos + child.length; - // Fast path: if the change only affects one child and the - // child's size remains in the acceptable range, only update - // that child - if (from >= pos && to <= end) { - let updated = child.replace(from - pos, to - pos, text); - let totalLines = this.lines - child.lines + updated.lines; - if (updated.lines < (totalLines >> (5 /* BranchShift */ - 1)) && - updated.lines > (totalLines >> (5 /* BranchShift */ + 1))) { - let copy = this.children.slice(); - copy[i] = updated; - return new TextNode(copy, this.length - (to - from) + text.length); - } - return super.replace(pos, end, updated); - } - pos = end + 1; - } - return super.replace(from, to, text); - } - sliceString(from, to = this.length, lineSep = "\n") { - let result = ""; - for (let i = 0, pos = 0; i < this.children.length && pos <= to; i++) { - let child = this.children[i], end = pos + child.length; - if (pos > from && i) - result += lineSep; - if (from < end && to > pos) - result += child.sliceString(from - pos, to - pos, lineSep); - pos = end + 1; - } - return result; - } - flatten(target) { - for (let child of this.children) - child.flatten(target); - } - scanIdentical(other, dir) { - if (!(other instanceof TextNode)) - return 0; - let length = 0; - let [iA, iB, eA, eB] = dir > 0 ? [0, 0, this.children.length, other.children.length] - : [this.children.length - 1, other.children.length - 1, -1, -1]; - for (;; iA += dir, iB += dir) { - if (iA == eA || iB == eB) - return length; - let chA = this.children[iA], chB = other.children[iB]; - if (chA != chB) - return length + chA.scanIdentical(chB, dir); - length += chA.length + 1; - } - } - static from(children, length = children.reduce((l, ch) => l + ch.length + 1, -1)) { - let lines = 0; - for (let ch of children) - lines += ch.lines; - if (lines < 32 /* Branch */) { - let flat = []; - for (let ch of children) - ch.flatten(flat); - return new TextLeaf(flat, length); - } - let chunk = Math.max(32 /* Branch */, lines >> 5 /* BranchShift */), maxChunk = chunk << 1, minChunk = chunk >> 1; - let chunked = [], currentLines = 0, currentLen = -1, currentChunk = []; - function add(child) { - let last; - if (child.lines > maxChunk && child instanceof TextNode) { - for (let node of child.children) - add(node); - } - else if (child.lines > minChunk && (currentLines > minChunk || !currentLines)) { - flush(); - chunked.push(child); - } - else if (child instanceof TextLeaf && currentLines && - (last = currentChunk[currentChunk.length - 1]) instanceof TextLeaf && - child.lines + last.lines <= 32 /* Branch */) { - currentLines += child.lines; - currentLen += child.length + 1; - currentChunk[currentChunk.length - 1] = new TextLeaf(last.text.concat(child.text), last.length + 1 + child.length); - } - else { - if (currentLines + child.lines > chunk) - flush(); - currentLines += child.lines; - currentLen += child.length + 1; - currentChunk.push(child); - } - } - function flush() { - if (currentLines == 0) - return; - chunked.push(currentChunk.length == 1 ? currentChunk[0] : TextNode.from(currentChunk, currentLen)); - currentLen = -1; - currentLines = currentChunk.length = 0; - } - for (let child of children) - add(child); - flush(); - return chunked.length == 1 ? chunked[0] : new TextNode(chunked, length); - } - } - Text.empty = /*@__PURE__*/new TextLeaf([""], 0); - function textLength(text) { - let length = -1; - for (let line of text) - length += line.length + 1; - return length; - } - function appendText(text, target, from = 0, to = 1e9) { - for (let pos = 0, i = 0, first = true; i < text.length && pos <= to; i++) { - let line = text[i], end = pos + line.length; - if (end >= from) { - if (end > to) - line = line.slice(0, to - pos); - if (pos < from) - line = line.slice(from - pos); - if (first) { - target[target.length - 1] += line; - first = false; - } - else - target.push(line); - } - pos = end + 1; - } - return target; - } - function sliceText(text, from, to) { - return appendText(text, [""], from, to); - } - class RawTextCursor { - constructor(text, dir = 1) { - this.dir = dir; - this.done = false; - this.lineBreak = false; - this.value = ""; - this.nodes = [text]; - this.offsets = [dir > 0 ? 1 : (text instanceof TextLeaf ? text.text.length : text.children.length) << 1]; - } - nextInner(skip, dir) { - this.done = this.lineBreak = false; - for (;;) { - let last = this.nodes.length - 1; - let top = this.nodes[last], offsetValue = this.offsets[last], offset = offsetValue >> 1; - let size = top instanceof TextLeaf ? top.text.length : top.children.length; - if (offset == (dir > 0 ? size : 0)) { - if (last == 0) { - this.done = true; - this.value = ""; - return this; - } - if (dir > 0) - this.offsets[last - 1]++; - this.nodes.pop(); - this.offsets.pop(); - } - else if ((offsetValue & 1) == (dir > 0 ? 0 : 1)) { - this.offsets[last] += dir; - if (skip == 0) { - this.lineBreak = true; - this.value = "\n"; - return this; - } - skip--; - } - else if (top instanceof TextLeaf) { - // Move to the next string - let next = top.text[offset + (dir < 0 ? -1 : 0)]; - this.offsets[last] += dir; - if (next.length > Math.max(0, skip)) { - this.value = skip == 0 ? next : dir > 0 ? next.slice(skip) : next.slice(0, next.length - skip); - return this; - } - skip -= next.length; - } - else { - let next = top.children[offset + (dir < 0 ? -1 : 0)]; - if (skip > next.length) { - skip -= next.length; - this.offsets[last] += dir; - } - else { - if (dir < 0) - this.offsets[last]--; - this.nodes.push(next); - this.offsets.push(dir > 0 ? 1 : (next instanceof TextLeaf ? next.text.length : next.children.length) << 1); - } - } - } - } - next(skip = 0) { - if (skip < 0) { - this.nextInner(-skip, (-this.dir)); - skip = this.value.length; - } - return this.nextInner(skip, this.dir); - } - } - class PartialTextCursor { - constructor(text, start, end) { - this.value = ""; - this.done = false; - this.cursor = new RawTextCursor(text, start > end ? -1 : 1); - this.pos = start > end ? text.length : 0; - this.from = Math.min(start, end); - this.to = Math.max(start, end); - } - nextInner(skip, dir) { - if (dir < 0 ? this.pos <= this.from : this.pos >= this.to) { - this.value = ""; - this.done = true; - return this; - } - skip += Math.max(0, dir < 0 ? this.pos - this.to : this.from - this.pos); - let limit = dir < 0 ? this.pos - this.from : this.to - this.pos; - if (skip > limit) - skip = limit; - limit -= skip; - let { value } = this.cursor.next(skip); - this.pos += (value.length + skip) * dir; - this.value = value.length <= limit ? value : dir < 0 ? value.slice(value.length - limit) : value.slice(0, limit); - this.done = !this.value; - return this; - } - next(skip = 0) { - if (skip < 0) - skip = Math.max(skip, this.from - this.pos); - else if (skip > 0) - skip = Math.min(skip, this.to - this.pos); - return this.nextInner(skip, this.cursor.dir); - } - get lineBreak() { return this.cursor.lineBreak && this.value != ""; } - } - class LineCursor { - constructor(inner) { - this.inner = inner; - this.afterBreak = true; - this.value = ""; - this.done = false; - } - next(skip = 0) { - let { done, lineBreak, value } = this.inner.next(skip); - if (done) { - this.done = true; - this.value = ""; - } - else if (lineBreak) { - if (this.afterBreak) { - this.value = ""; - } - else { - this.afterBreak = true; - this.next(); - } - } - else { - this.value = value; - this.afterBreak = false; - } - return this; - } - get lineBreak() { return false; } - } - if (typeof Symbol != "undefined") { - Text.prototype[Symbol.iterator] = function () { return this.iter(); }; - RawTextCursor.prototype[Symbol.iterator] = PartialTextCursor.prototype[Symbol.iterator] = - LineCursor.prototype[Symbol.iterator] = function () { return this; }; - } - /** - This type describes a line in the document. It is created - on-demand when lines are [queried](https://codemirror.net/6/docs/ref/#text.Text.lineAt). - */ - class Line { - /** - @internal - */ - constructor( - /** - The position of the start of the line. - */ - from, - /** - The position at the end of the line (_before_ the line break, - or at the end of document for the last line). - */ - to, - /** - This line's line number (1-based). - */ - number, - /** - The line's content. - */ - text) { - this.from = from; - this.to = to; - this.number = number; - this.text = text; - } - /** - The length of the line (not including any line break after it). - */ - get length() { return this.to - this.from; } - } + var pyscript = "import ast\nimport asyncio\nimport base64\nimport html\nimport io\nimport re\nimport time\nfrom collections import namedtuple\nfrom textwrap import dedent\n\nimport js\n\ntry:\n from pyodide.ffi import create_proxy\nexcept ImportError:\n from pyodide import create_proxy\n\nloop = asyncio.get_event_loop()\n\nMIME_METHODS = {\n \"__repr__\": \"text/plain\",\n \"_repr_html_\": \"text/html\",\n \"_repr_markdown_\": \"text/markdown\",\n \"_repr_svg_\": \"image/svg+xml\",\n \"_repr_png_\": \"image/png\",\n \"_repr_pdf_\": \"application/pdf\",\n \"_repr_jpeg_\": \"image/jpeg\",\n \"_repr_latex\": \"text/latex\",\n \"_repr_json_\": \"application/json\",\n \"_repr_javascript_\": \"application/javascript\",\n \"savefig\": \"image/png\",\n}\n\n\ndef render_image(mime, value, meta):\n # If the image value is using bytes we should convert it to base64\n # otherwise it will return raw bytes and the browser will not be able to\n # render it.\n if isinstance(value, bytes):\n value = base64.b64encode(value).decode(\"utf-8\")\n\n # This is the pattern of base64 strings\n base64_pattern = re.compile(\n r\"^([A-Za-z0-9+/]{4})*([A-Za-z0-9+/]{3}=|[A-Za-z0-9+/]{2}==)?$\"\n )\n # If value doesn't match the base64 pattern we should encode it to base64\n if len(value) > 0 and not base64_pattern.match(value):\n value = base64.b64encode(value.encode(\"utf-8\")).decode(\"utf-8\")\n\n data = f\"data:{mime};charset=utf-8;base64,{value}\"\n attrs = \" \".join(['{k}=\"{v}\"' for k, v in meta.items()])\n return f'<img src=\"{data}\" {attrs}></img>'\n\n\ndef identity(value, meta):\n return value\n\n\nMIME_RENDERERS = {\n \"text/plain\": html.escape,\n \"text/html\": identity,\n \"image/png\": lambda value, meta: render_image(\"image/png\", value, meta),\n \"image/jpeg\": lambda value, meta: render_image(\"image/jpeg\", value, meta),\n \"image/svg+xml\": identity,\n \"application/json\": identity,\n \"application/javascript\": lambda value, meta: f\"<script>{value}</script>\",\n}\n\n\n# these are set by _set_version_info\n__version__ = None\nversion_info = None\n\n\ndef _set_version_info(version_from_interpreter: str):\n \"\"\"Sets the __version__ and version_info properties from provided JSON data\n Args:\n version_from_interpreter (str): A \"dotted\" representation of the version:\n YYYY.MM.m(m).releaselevel\n Year, Month, and Minor should be integers; releaselevel can be any string\n \"\"\"\n global __version__\n global version_info\n\n __version__ = version_from_interpreter\n\n version_parts = version_from_interpreter.split(\".\")\n year = int(version_parts[0])\n month = int(version_parts[1])\n minor = int(version_parts[2])\n if len(version_parts) > 3:\n releaselevel = version_parts[3]\n else:\n releaselevel = \"\"\n\n VersionInfo = namedtuple(\"version_info\", (\"year\", \"month\", \"minor\", \"releaselevel\"))\n version_info = VersionInfo(year, month, minor, releaselevel)\n\n # we ALSO set PyScript.__version__ and version_info for backwards\n # compatibility. Should be killed eventually.\n PyScript.__version__ = __version__\n PyScript.version_info = version_info\n\n\nclass HTML:\n \"\"\"\n Wrap a string so that display() can render it as plain HTML\n \"\"\"\n\n def __init__(self, html):\n self._html = html\n\n def _repr_html_(self):\n return self._html\n\n\ndef eval_formatter(obj, print_method):\n \"\"\"\n Evaluates a formatter method.\n \"\"\"\n if print_method == \"__repr__\":\n return repr(obj)\n elif hasattr(obj, print_method):\n if print_method == \"savefig\":\n buf = io.BytesIO()\n obj.savefig(buf, format=\"png\")\n buf.seek(0)\n return base64.b64encode(buf.read()).decode(\"utf-8\")\n return getattr(obj, print_method)()\n elif print_method == \"_repr_mimebundle_\":\n return {}, {}\n return None\n\n\ndef format_mime(obj):\n \"\"\"\n Formats object using _repr_x_ methods.\n \"\"\"\n if isinstance(obj, str):\n return html.escape(obj), \"text/plain\"\n\n mimebundle = eval_formatter(obj, \"_repr_mimebundle_\")\n if isinstance(mimebundle, tuple):\n format_dict, _ = mimebundle\n else:\n format_dict = mimebundle\n\n output, not_available = None, []\n for method, mime_type in reversed(MIME_METHODS.items()):\n if mime_type in format_dict:\n output = format_dict[mime_type]\n else:\n output = eval_formatter(obj, method)\n\n if output is None:\n continue\n elif mime_type not in MIME_RENDERERS:\n not_available.append(mime_type)\n continue\n break\n if output is None:\n if not_available:\n js.console.warn(\n f\"Rendered object requested unavailable MIME renderers: {not_available}\"\n )\n output = repr(output)\n mime_type = \"text/plain\"\n elif isinstance(output, tuple):\n output, meta = output\n else:\n meta = {}\n return MIME_RENDERERS[mime_type](output, meta), mime_type\n\n\ndef run_until_complete(f):\n _ = loop.run_until_complete(f)\n\n\ndef write(element_id, value, append=False, exec_id=0):\n \"\"\"Writes value to the element with id \"element_id\"\"\"\n Element(element_id).write(value=value, append=append)\n js.console.warn(\n dedent(\n \"\"\"PyScript Deprecation Warning: PyScript.write is\n marked as deprecated and will be removed sometime soon. Please, use\n Element(<id>).write instead.\"\"\"\n )\n )\n\n\ndef set_current_display_target(target_id):\n get_current_display_target._id = target_id\n\n\ndef get_current_display_target():\n return get_current_display_target._id\n\n\nget_current_display_target._id = None\n\n\ndef display(*values, target=None, append=True):\n default_target = get_current_display_target()\n if default_target is None and target is None:\n raise Exception(\n \"Implicit target not allowed here. Please use display(..., target=...)\"\n )\n if target is not None:\n for v in values:\n Element(target).write(v, append=append)\n else:\n for v in values:\n Element(default_target).write(v, append=append)\n\n\nclass Element:\n def __init__(self, element_id, element=None):\n self._id = element_id\n self._element = element\n\n @property\n def id(self):\n return self._id\n\n @property\n def element(self):\n \"\"\"Return the dom element\"\"\"\n if not self._element:\n self._element = js.document.querySelector(f\"#{self._id}\")\n return self._element\n\n @property\n def value(self):\n return self.element.value\n\n @property\n def innerHtml(self):\n return self.element.innerHTML\n\n def write(self, value, append=False):\n html, mime_type = format_mime(value)\n if html == \"\\n\":\n return\n\n if append:\n child = js.document.createElement(\"div\")\n self.element.appendChild(child)\n\n if append and self.element.children:\n out_element = self.element.children[-1]\n else:\n out_element = self.element\n\n if mime_type in (\"application/javascript\", \"text/html\"):\n script_element = js.document.createRange().createContextualFragment(html)\n out_element.appendChild(script_element)\n else:\n out_element.innerHTML = html\n\n def clear(self):\n if hasattr(self.element, \"value\"):\n self.element.value = \"\"\n else:\n self.write(\"\", append=False)\n\n def select(self, query, from_content=False):\n el = self.element\n\n if from_content:\n el = el.content\n\n _el = el.querySelector(query)\n if _el:\n return Element(_el.id, _el)\n else:\n js.console.warn(f\"WARNING: can't find element matching query {query}\")\n\n def clone(self, new_id=None, to=None):\n if new_id is None:\n new_id = self.element.id\n\n clone = self.element.cloneNode(True)\n clone.id = new_id\n\n if to:\n to.element.appendChild(clone)\n # Inject it into the DOM\n to.element.after(clone)\n else:\n # Inject it into the DOM\n self.element.after(clone)\n\n return Element(clone.id, clone)\n\n def remove_class(self, classname):\n if isinstance(classname, list):\n for cl in classname:\n self.remove_class(cl)\n else:\n self.element.classList.remove(classname)\n\n def add_class(self, classname):\n if isinstance(classname, list):\n for cl in classname:\n self.element.classList.add(cl)\n else:\n self.element.classList.add(classname)\n\n\ndef add_classes(element, class_list):\n for klass in class_list.split(\" \"):\n element.classList.add(klass)\n\n\ndef create(what, id_=None, classes=\"\"):\n element = js.document.createElement(what)\n if id_:\n element.id = id_\n add_classes(element, classes)\n return Element(id_, element)\n\n\nclass PyWidgetTheme:\n def __init__(self, main_style_classes):\n self.main_style_classes = main_style_classes\n\n def theme_it(self, widget):\n for klass in self.main_style_classes.split(\" \"):\n widget.classList.add(klass)\n\n\nclass PyItemTemplate(Element):\n label_fields = None\n\n def __init__(self, data, labels=None, state_key=None, parent=None):\n self.data = data\n\n self.register_parent(parent)\n\n if not labels:\n labels = list(self.data.keys())\n self.labels = labels\n\n self.state_key = state_key\n\n super().__init__(self._id)\n\n def register_parent(self, parent):\n self._parent = parent\n if parent:\n self._id = f\"{self._parent._id}-c-{len(self._parent._children)}\"\n self.data[\"id\"] = self._id\n else:\n self._id = None\n\n def create(self):\n new_child = create(\"div\", self._id, \"py-li-element\")\n new_child._element.innerHTML = dedent(\n f\"\"\"\n <label id=\"{self._id}\" for=\"flex items-center p-2 \">\n <input class=\"mr-2\" type=\"checkbox\" class=\"task-check\">\n <p>{self.render_content()}</p>\n </label>\n \"\"\"\n )\n return new_child\n\n def on_click(self, evt):\n pass\n\n def pre_append(self):\n pass\n\n def post_append(self):\n self.element.click = self.on_click\n self.element.onclick = self.on_click\n\n self._post_append()\n\n def _post_append(self):\n pass\n\n def strike(self, value, extra=None):\n if value:\n self.add_class(\"line-through\")\n else:\n self.remove_class(\"line-through\")\n\n def render_content(self):\n return \" - \".join([self.data[f] for f in self.labels])\n\n\nclass PyListTemplate:\n theme = PyWidgetTheme(\"py-li-element\")\n item_class = PyItemTemplate\n\n def __init__(self, parent):\n self.parent = parent\n self._children = []\n self._id = self.parent.id\n\n @property\n def children(self):\n return self._children\n\n @property\n def data(self):\n return [c.data for c in self._children]\n\n def render_children(self):\n binds = {}\n for i, c in enumerate(self._children):\n txt = c.element.innerHTML\n rnd = str(time.time()).replace(\".\", \"\")[-5:]\n new_id = f\"{c.element.id}-{i}-{rnd}\"\n binds[new_id] = c.element.id\n txt = txt.replace(\">\", f\" id='{new_id}'>\")\n print(txt)\n\n def foo(evt):\n evtEl = evt.srcElement\n srcEl = Element(binds[evtEl.id])\n srcEl.element.onclick()\n evtEl.classList = srcEl.element.classList\n\n for new_id in binds:\n Element(new_id).element.onclick = foo\n\n def connect(self):\n self.md = main_div = js.document.createElement(\"div\")\n main_div.id = self._id + \"-list-tasks-container\"\n\n if self.theme:\n self.theme.theme_it(main_div)\n\n self.parent.appendChild(main_div)\n\n def add(self, *args, **kws):\n if not isinstance(args[0], self.item_class):\n child = self.item_class(*args, **kws)\n else:\n child = args[0]\n child.register_parent(self)\n return self._add(child)\n\n def _add(self, child_elem):\n self.pre_child_append(child_elem)\n child_elem.pre_append()\n self._children.append(child_elem)\n self.md.appendChild(child_elem.create().element)\n child_elem.post_append()\n self.child_appended(child_elem)\n return child_elem\n\n def pre_child_append(self, child):\n pass\n\n def child_appended(self, child):\n \"\"\"Overwrite me to define logic\"\"\"\n pass\n\n\nclass TopLevelAsyncFinder(ast.NodeVisitor):\n def is_source_top_level_await(self, source):\n self.async_found = False\n node = ast.parse(source)\n self.generic_visit(node)\n return self.async_found\n\n def visit_Await(self, node):\n self.async_found = True\n\n def visit_AsyncFor(self, node):\n self.async_found = True\n\n def visit_AsyncWith(self, node):\n self.async_found = True\n\n def visit_AsyncFunctionDef(self, node: ast.AsyncFunctionDef):\n pass # Do not visit children of async function defs\n\n\ndef uses_top_level_await(source: str) -> bool:\n return TopLevelAsyncFinder().is_source_top_level_await(source)\n\n\nclass Plugin:\n def __init__(self, name=None):\n if not name:\n name = self.__class__.__name__\n\n self.name = name\n self._custom_elements = []\n self.app = None\n\n def init(self, app):\n self.app = app\n\n def register_custom_element(self, tag):\n \"\"\"\n Decorator to register a new custom element as part of a Plugin and associate\n tag to it. Internally, it delegates the registration to the PyScript internal\n [JS] plugin manager, who actually creates the JS custom element that can be\n attached to the page and instantiate an instance of the class passing the custom\n element to the plugin constructor.\n\n Exammple:\n >> plugin = Plugin(\"PyTutorial\")\n >> @plugin.register_custom_element(\"py-tutor\")\n >> class PyTutor:\n >> def __init__(self, element):\n >> self.element = element\n \"\"\"\n # TODO: Ideally would be better to use the logger.\n js.console.info(f\"Defining new custom element {tag}\")\n\n def wrapper(class_):\n # TODO: this is very pyodide specific but will have to do\n # until we have JS interface that works across interpreters\n define_custom_element(tag, create_proxy(class_)) # noqa: F821\n\n self._custom_elements.append(tag)\n return create_proxy(wrapper)\n\n\nclass DeprecatedGlobal:\n \"\"\"\n Proxy for globals which are deprecated.\n\n The intendend usage is as follows:\n\n # in the global namespace\n Element = pyscript.DeprecatedGlobal('Element', pyscript.Element, \"...\")\n console = pyscript.DeprecatedGlobal('console', js.console, \"...\")\n ...\n\n The proxy forwards __getattr__ and __call__ to the underlying object, and\n emit a warning on the first usage.\n\n This way users see a warning only if they actually access the top-level\n name.\n \"\"\"\n\n def __init__(self, name, obj, message):\n self.__name = name\n self.__obj = obj\n self.__message = message\n self.__warning_already_shown = False\n\n def __repr__(self):\n return f\"<DeprecatedGlobal({self.__name!r})>\"\n\n def _show_warning(self, message):\n \"\"\"\n NOTE: this is overridden by unit tests\n \"\"\"\n # this showWarning is implemented in js and injected into this\n # namespace by main.ts\n showWarning(message, \"html\") # noqa: F821\n\n def _show_warning_maybe(self):\n if self.__warning_already_shown:\n return\n self._show_warning(self.__message)\n self.__warning_already_shown = True\n\n def __getattr__(self, attr):\n self._show_warning_maybe()\n return getattr(self.__obj, attr)\n\n def __call__(self, *args, **kwargs):\n self._show_warning_maybe()\n return self.__obj(*args, **kwargs)\n\n def __iter__(self):\n self._show_warning_maybe()\n return iter(self.__obj)\n\n def __getitem__(self, key):\n self._show_warning_maybe()\n return self.__obj[key]\n\n def __setitem__(self, key, value):\n self._show_warning_maybe()\n self.__obj[key] = value\n\n\nclass PyScript:\n \"\"\"\n This class is deprecated since 2022.12.1.\n\n All its old functionalities are available as module-level functions. This\n class should be killed eventually.\n \"\"\"\n\n loop = loop\n\n @staticmethod\n def run_until_complete(f):\n run_until_complete(f)\n\n @staticmethod\n def write(element_id, value, append=False, exec_id=0):\n write(element_id, value, append, exec_id)\n\n\ndef _install_deprecated_globals_2022_12_1(ns):\n \"\"\"\n Install into the given namespace all the globals which have been\n deprecated since the 2022.12.1 release. Eventually they should be killed.\n \"\"\"\n\n def deprecate(name, obj, instead):\n message = f\"Direct usage of <code>{name}</code> is deprecated. \" + instead\n ns[name] = DeprecatedGlobal(name, obj, message)\n\n # function/classes defined in pyscript.py ===> pyscript.XXX\n pyscript_names = [\n \"PyItemTemplate\",\n \"PyListTemplate\",\n \"PyWidgetTheme\",\n \"add_classes\",\n \"create\",\n \"loop\",\n ]\n for name in pyscript_names:\n deprecate(\n name, globals()[name], f\"Please use <code>pyscript.{name}</code> instead.\"\n )\n\n # stdlib modules ===> import XXX\n stdlib_names = [\n \"asyncio\",\n \"base64\",\n \"io\",\n \"sys\",\n \"time\",\n \"datetime\",\n \"pyodide\",\n \"micropip\",\n ]\n for name in stdlib_names:\n obj = __import__(name)\n deprecate(name, obj, f\"Please use <code>import {name}</code> instead.\")\n\n # special case\n deprecate(\n \"dedent\", dedent, \"Please use <code>from textwrap import dedent</code> instead.\"\n )\n\n # these are names that used to leak in the globals but they are just\n # implementation details. People should not use them.\n private_names = [\n \"eval_formatter\",\n \"format_mime\",\n \"identity\",\n \"render_image\",\n \"MIME_RENDERERS\",\n \"MIME_METHODS\",\n ]\n for name in private_names:\n obj = globals()[name]\n message = (\n f\"<code>{name}</code> is deprecated. \"\n \"This is a private implementation detail of pyscript. \"\n \"You should not use it.\"\n )\n ns[name] = DeprecatedGlobal(name, obj, message)\n\n # these names are available as js.XXX\n for name in [\"document\", \"console\"]:\n obj = getattr(js, name)\n deprecate(name, obj, f\"Please use <code>js.{name}</code> instead.\")\n\n # PyScript is special, use a different message\n message = (\n \"The <code>PyScript</code> object is deprecated. \"\n \"Please use <code>pyscript</code> instead.\"\n )\n ns[\"PyScript\"] = DeprecatedGlobal(\"PyScript\", PyScript, message)\n"; - const DefaultSplit = /\r\n?|\n/; - /** - Distinguishes different ways in which positions can be mapped. - */ - var MapMode = /*@__PURE__*/(function (MapMode) { - /** - Map a position to a valid new position, even when its context - was deleted. - */ - MapMode[MapMode["Simple"] = 0] = "Simple"; - /** - Return null if deletion happens across the position. - */ - MapMode[MapMode["TrackDel"] = 1] = "TrackDel"; - /** - Return null if the character _before_ the position is deleted. - */ - MapMode[MapMode["TrackBefore"] = 2] = "TrackBefore"; - /** - Return null if the character _after_ the position is deleted. - */ - MapMode[MapMode["TrackAfter"] = 3] = "TrackAfter"; - return MapMode})(MapMode || (MapMode = {})); - /** - A change description is a variant of [change set](https://codemirror.net/6/docs/ref/#state.ChangeSet) - that doesn't store the inserted text. As such, it can't be - applied, but is cheaper to store and manipulate. - */ - class ChangeDesc { - // Sections are encoded as pairs of integers. The first is the - // length in the current document, and the second is -1 for - // unaffected sections, and the length of the replacement content - // otherwise. So an insertion would be (0, n>0), a deletion (n>0, - // 0), and a replacement two positive numbers. - /** - @internal - */ - constructor( - /** - @internal - */ - sections) { - this.sections = sections; - } - /** - The length of the document before the change. - */ - get length() { - let result = 0; - for (let i = 0; i < this.sections.length; i += 2) - result += this.sections[i]; - return result; - } - /** - The length of the document after the change. - */ - get newLength() { - let result = 0; - for (let i = 0; i < this.sections.length; i += 2) { - let ins = this.sections[i + 1]; - result += ins < 0 ? this.sections[i] : ins; - } - return result; - } - /** - False when there are actual changes in this set. - */ - get empty() { return this.sections.length == 0 || this.sections.length == 2 && this.sections[1] < 0; } - /** - Iterate over the unchanged parts left by these changes. - */ - iterGaps(f) { - for (let i = 0, posA = 0, posB = 0; i < this.sections.length;) { - let len = this.sections[i++], ins = this.sections[i++]; - if (ins < 0) { - f(posA, posB, len); - posB += len; - } - else { - posB += ins; - } - posA += len; - } - } - /** - Iterate over the ranges changed by these changes. (See - [`ChangeSet.iterChanges`](https://codemirror.net/6/docs/ref/#state.ChangeSet.iterChanges) for a - variant that also provides you with the inserted text.) - - When `individual` is true, adjacent changes (which are kept - separate for [position mapping](https://codemirror.net/6/docs/ref/#state.ChangeDesc.mapPos)) are - reported separately. - */ - iterChangedRanges(f, individual = false) { - iterChanges(this, f, individual); - } - /** - Get a description of the inverted form of these changes. - */ - get invertedDesc() { - let sections = []; - for (let i = 0; i < this.sections.length;) { - let len = this.sections[i++], ins = this.sections[i++]; - if (ins < 0) - sections.push(len, ins); - else - sections.push(ins, len); - } - return new ChangeDesc(sections); - } - /** - Compute the combined effect of applying another set of changes - after this one. The length of the document after this set should - match the length before `other`. - */ - composeDesc(other) { return this.empty ? other : other.empty ? this : composeSets(this, other); } - /** - Map this description, which should start with the same document - as `other`, over another set of changes, so that it can be - applied after it. When `before` is true, map as if the changes - in `other` happened before the ones in `this`. - */ - mapDesc(other, before = false) { return other.empty ? this : mapSet(this, other, before); } - mapPos(pos, assoc = -1, mode = MapMode.Simple) { - let posA = 0, posB = 0; - for (let i = 0; i < this.sections.length;) { - let len = this.sections[i++], ins = this.sections[i++], endA = posA + len; - if (ins < 0) { - if (endA > pos) - return posB + (pos - posA); - posB += len; - } - else { - if (mode != MapMode.Simple && endA >= pos && - (mode == MapMode.TrackDel && posA < pos && endA > pos || - mode == MapMode.TrackBefore && posA < pos || - mode == MapMode.TrackAfter && endA > pos)) - return null; - if (endA > pos || endA == pos && assoc < 0 && !len) - return pos == posA || assoc < 0 ? posB : posB + ins; - posB += ins; - } - posA = endA; - } - if (pos > posA) - throw new RangeError(`Position ${pos} is out of range for changeset of length ${posA}`); - return posB; - } - /** - Check whether these changes touch a given range. When one of the - changes entirely covers the range, the string `"cover"` is - returned. - */ - touchesRange(from, to = from) { - for (let i = 0, pos = 0; i < this.sections.length && pos <= to;) { - let len = this.sections[i++], ins = this.sections[i++], end = pos + len; - if (ins >= 0 && pos <= to && end >= from) - return pos < from && end > to ? "cover" : true; - pos = end; - } - return false; - } - /** - @internal - */ - toString() { - let result = ""; - for (let i = 0; i < this.sections.length;) { - let len = this.sections[i++], ins = this.sections[i++]; - result += (result ? " " : "") + len + (ins >= 0 ? ":" + ins : ""); - } - return result; - } - /** - Serialize this change desc to a JSON-representable value. - */ - toJSON() { return this.sections; } - /** - Create a change desc from its JSON representation (as produced - by [`toJSON`](https://codemirror.net/6/docs/ref/#state.ChangeDesc.toJSON). - */ - static fromJSON(json) { - if (!Array.isArray(json) || json.length % 2 || json.some(a => typeof a != "number")) - throw new RangeError("Invalid JSON representation of ChangeDesc"); - return new ChangeDesc(json); - } - } - /** - A change set represents a group of modifications to a document. It - stores the document length, and can only be applied to documents - with exactly that length. - */ - class ChangeSet extends ChangeDesc { - /** - @internal - */ - constructor(sections, - /** - @internal - */ - inserted) { - super(sections); - this.inserted = inserted; - } - /** - Apply the changes to a document, returning the modified - document. - */ - apply(doc) { - if (this.length != doc.length) - throw new RangeError("Applying change set to a document with the wrong length"); - iterChanges(this, (fromA, toA, fromB, _toB, text) => doc = doc.replace(fromB, fromB + (toA - fromA), text), false); - return doc; - } - mapDesc(other, before = false) { return mapSet(this, other, before, true); } - /** - Given the document as it existed _before_ the changes, return a - change set that represents the inverse of this set, which could - be used to go from the document created by the changes back to - the document as it existed before the changes. - */ - invert(doc) { - let sections = this.sections.slice(), inserted = []; - for (let i = 0, pos = 0; i < sections.length; i += 2) { - let len = sections[i], ins = sections[i + 1]; - if (ins >= 0) { - sections[i] = ins; - sections[i + 1] = len; - let index = i >> 1; - while (inserted.length < index) - inserted.push(Text.empty); - inserted.push(len ? doc.slice(pos, pos + len) : Text.empty); - } - pos += len; - } - return new ChangeSet(sections, inserted); - } - /** - Combine two subsequent change sets into a single set. `other` - must start in the document produced by `this`. If `this` goes - `docA` → `docB` and `other` represents `docB` → `docC`, the - returned value will represent the change `docA` → `docC`. - */ - compose(other) { return this.empty ? other : other.empty ? this : composeSets(this, other, true); } - /** - Given another change set starting in the same document, maps this - change set over the other, producing a new change set that can be - applied to the document produced by applying `other`. When - `before` is `true`, order changes as if `this` comes before - `other`, otherwise (the default) treat `other` as coming first. - - Given two changes `A` and `B`, `A.compose(B.map(A))` and - `B.compose(A.map(B, true))` will produce the same document. This - provides a basic form of [operational - transformation](https://en.wikipedia.org/wiki/Operational_transformation), - and can be used for collaborative editing. - */ - map(other, before = false) { return other.empty ? this : mapSet(this, other, before, true); } - /** - Iterate over the changed ranges in the document, calling `f` for - each, with the range in the original document (`fromA`-`toA`) - and the range that replaces it in the new document - (`fromB`-`toB`). - - When `individual` is true, adjacent changes are reported - separately. - */ - iterChanges(f, individual = false) { - iterChanges(this, f, individual); - } - /** - Get a [change description](https://codemirror.net/6/docs/ref/#state.ChangeDesc) for this change - set. - */ - get desc() { return new ChangeDesc(this.sections); } - /** - @internal - */ - filter(ranges) { - let resultSections = [], resultInserted = [], filteredSections = []; - let iter = new SectionIter(this); - done: for (let i = 0, pos = 0;;) { - let next = i == ranges.length ? 1e9 : ranges[i++]; - while (pos < next || pos == next && iter.len == 0) { - if (iter.done) - break done; - let len = Math.min(iter.len, next - pos); - addSection(filteredSections, len, -1); - let ins = iter.ins == -1 ? -1 : iter.off == 0 ? iter.ins : 0; - addSection(resultSections, len, ins); - if (ins > 0) - addInsert(resultInserted, resultSections, iter.text); - iter.forward(len); - pos += len; - } - let end = ranges[i++]; - while (pos < end) { - if (iter.done) - break done; - let len = Math.min(iter.len, end - pos); - addSection(resultSections, len, -1); - addSection(filteredSections, len, iter.ins == -1 ? -1 : iter.off == 0 ? iter.ins : 0); - iter.forward(len); - pos += len; - } - } - return { changes: new ChangeSet(resultSections, resultInserted), - filtered: new ChangeDesc(filteredSections) }; - } - /** - Serialize this change set to a JSON-representable value. - */ - toJSON() { - let parts = []; - for (let i = 0; i < this.sections.length; i += 2) { - let len = this.sections[i], ins = this.sections[i + 1]; - if (ins < 0) - parts.push(len); - else if (ins == 0) - parts.push([len]); - else - parts.push([len].concat(this.inserted[i >> 1].toJSON())); - } - return parts; - } - /** - Create a change set for the given changes, for a document of the - given length, using `lineSep` as line separator. - */ - static of(changes, length, lineSep) { - let sections = [], inserted = [], pos = 0; - let total = null; - function flush(force = false) { - if (!force && !sections.length) - return; - if (pos < length) - addSection(sections, length - pos, -1); - let set = new ChangeSet(sections, inserted); - total = total ? total.compose(set.map(total)) : set; - sections = []; - inserted = []; - pos = 0; - } - function process(spec) { - if (Array.isArray(spec)) { - for (let sub of spec) - process(sub); - } - else if (spec instanceof ChangeSet) { - if (spec.length != length) - throw new RangeError(`Mismatched change set length (got ${spec.length}, expected ${length})`); - flush(); - total = total ? total.compose(spec.map(total)) : spec; - } - else { - let { from, to = from, insert } = spec; - if (from > to || from < 0 || to > length) - throw new RangeError(`Invalid change range ${from} to ${to} (in doc of length ${length})`); - let insText = !insert ? Text.empty : typeof insert == "string" ? Text.of(insert.split(lineSep || DefaultSplit)) : insert; - let insLen = insText.length; - if (from == to && insLen == 0) - return; - if (from < pos) - flush(); - if (from > pos) - addSection(sections, from - pos, -1); - addSection(sections, to - from, insLen); - addInsert(inserted, sections, insText); - pos = to; - } - } - process(changes); - flush(!total); - return total; - } - /** - Create an empty changeset of the given length. - */ - static empty(length) { - return new ChangeSet(length ? [length, -1] : [], []); - } - /** - Create a changeset from its JSON representation (as produced by - [`toJSON`](https://codemirror.net/6/docs/ref/#state.ChangeSet.toJSON). - */ - static fromJSON(json) { - if (!Array.isArray(json)) - throw new RangeError("Invalid JSON representation of ChangeSet"); - let sections = [], inserted = []; - for (let i = 0; i < json.length; i++) { - let part = json[i]; - if (typeof part == "number") { - sections.push(part, -1); - } - else if (!Array.isArray(part) || typeof part[0] != "number" || part.some((e, i) => i && typeof e != "string")) { - throw new RangeError("Invalid JSON representation of ChangeSet"); - } - else if (part.length == 1) { - sections.push(part[0], 0); - } - else { - while (inserted.length < i) - inserted.push(Text.empty); - inserted[i] = Text.of(part.slice(1)); - sections.push(part[0], inserted[i].length); - } - } - return new ChangeSet(sections, inserted); - } - } - function addSection(sections, len, ins, forceJoin = false) { - if (len == 0 && ins <= 0) - return; - let last = sections.length - 2; - if (last >= 0 && ins <= 0 && ins == sections[last + 1]) - sections[last] += len; - else if (len == 0 && sections[last] == 0) - sections[last + 1] += ins; - else if (forceJoin) { - sections[last] += len; - sections[last + 1] += ins; - } - else - sections.push(len, ins); - } - function addInsert(values, sections, value) { - if (value.length == 0) - return; - let index = (sections.length - 2) >> 1; - if (index < values.length) { - values[values.length - 1] = values[values.length - 1].append(value); - } - else { - while (values.length < index) - values.push(Text.empty); - values.push(value); - } - } - function iterChanges(desc, f, individual) { - let inserted = desc.inserted; - for (let posA = 0, posB = 0, i = 0; i < desc.sections.length;) { - let len = desc.sections[i++], ins = desc.sections[i++]; - if (ins < 0) { - posA += len; - posB += len; - } - else { - let endA = posA, endB = posB, text = Text.empty; - for (;;) { - endA += len; - endB += ins; - if (ins && inserted) - text = text.append(inserted[(i - 2) >> 1]); - if (individual || i == desc.sections.length || desc.sections[i + 1] < 0) - break; - len = desc.sections[i++]; - ins = desc.sections[i++]; - } - f(posA, endA, posB, endB, text); - posA = endA; - posB = endB; - } - } - } - function mapSet(setA, setB, before, mkSet = false) { - let sections = [], insert = mkSet ? [] : null; - let a = new SectionIter(setA), b = new SectionIter(setB); - for (let posA = 0, posB = 0;;) { - if (a.ins == -1) { - posA += a.len; - a.next(); - } - else if (b.ins == -1 && posB < posA) { - let skip = Math.min(b.len, posA - posB); - b.forward(skip); - addSection(sections, skip, -1); - posB += skip; - } - else if (b.ins >= 0 && (a.done || posB < posA || posB == posA && (b.len < a.len || b.len == a.len && !before))) { - addSection(sections, b.ins, -1); - while (posA > posB && !a.done && posA + a.len < posB + b.len) { - posA += a.len; - a.next(); - } - posB += b.len; - b.next(); - } - else if (a.ins >= 0) { - let len = 0, end = posA + a.len; - for (;;) { - if (b.ins >= 0 && posB > posA && posB + b.len < end) { - len += b.ins; - posB += b.len; - b.next(); - } - else if (b.ins == -1 && posB < end) { - let skip = Math.min(b.len, end - posB); - len += skip; - b.forward(skip); - posB += skip; - } - else { - break; - } - } - addSection(sections, len, a.ins); - if (insert) - addInsert(insert, sections, a.text); - posA = end; - a.next(); - } - else if (a.done && b.done) { - return insert ? new ChangeSet(sections, insert) : new ChangeDesc(sections); - } - else { - throw new Error("Mismatched change set lengths"); - } - } - } - function composeSets(setA, setB, mkSet = false) { - let sections = []; - let insert = mkSet ? [] : null; - let a = new SectionIter(setA), b = new SectionIter(setB); - for (let open = false;;) { - if (a.done && b.done) { - return insert ? new ChangeSet(sections, insert) : new ChangeDesc(sections); - } - else if (a.ins == 0) { // Deletion in A - addSection(sections, a.len, 0, open); - a.next(); - } - else if (b.len == 0 && !b.done) { // Insertion in B - addSection(sections, 0, b.ins, open); - if (insert) - addInsert(insert, sections, b.text); - b.next(); - } - else if (a.done || b.done) { - throw new Error("Mismatched change set lengths"); - } - else { - let len = Math.min(a.len2, b.len), sectionLen = sections.length; - if (a.ins == -1) { - let insB = b.ins == -1 ? -1 : b.off ? 0 : b.ins; - addSection(sections, len, insB, open); - if (insert && insB) - addInsert(insert, sections, b.text); - } - else if (b.ins == -1) { - addSection(sections, a.off ? 0 : a.len, len, open); - if (insert) - addInsert(insert, sections, a.textBit(len)); - } - else { - addSection(sections, a.off ? 0 : a.len, b.off ? 0 : b.ins, open); - if (insert && !b.off) - addInsert(insert, sections, b.text); - } - open = (a.ins > len || b.ins >= 0 && b.len > len) && (open || sections.length > sectionLen); - a.forward2(len); - b.forward(len); - } - } - } - class SectionIter { - constructor(set) { - this.set = set; - this.i = 0; - this.next(); - } - next() { - let { sections } = this.set; - if (this.i < sections.length) { - this.len = sections[this.i++]; - this.ins = sections[this.i++]; - } - else { - this.len = 0; - this.ins = -2; - } - this.off = 0; - } - get done() { return this.ins == -2; } - get len2() { return this.ins < 0 ? this.len : this.ins; } - get text() { - let { inserted } = this.set, index = (this.i - 2) >> 1; - return index >= inserted.length ? Text.empty : inserted[index]; - } - textBit(len) { - let { inserted } = this.set, index = (this.i - 2) >> 1; - return index >= inserted.length && !len ? Text.empty - : inserted[index].slice(this.off, len == null ? undefined : this.off + len); - } - forward(len) { - if (len == this.len) - this.next(); - else { - this.len -= len; - this.off += len; - } - } - forward2(len) { - if (this.ins == -1) - this.forward(len); - else if (len == this.ins) - this.next(); - else { - this.ins -= len; - this.off += len; - } - } - } + const logger = getLogger('pyscript/main'); + /* High-level overview of the lifecycle of a PyScript App: - /** - A single selection range. When - [`allowMultipleSelections`](https://codemirror.net/6/docs/ref/#state.EditorState^allowMultipleSelections) - is enabled, a [selection](https://codemirror.net/6/docs/ref/#state.EditorSelection) may hold - multiple ranges. By default, selections hold exactly one range. - */ - class SelectionRange { - /** - @internal - */ - constructor( - /** - The lower boundary of the range. - */ - from, - /** - The upper boundary of the range. - */ - to, flags) { - this.from = from; - this.to = to; - this.flags = flags; - } - /** - The anchor of the range—the side that doesn't move when you - extend it. - */ - get anchor() { return this.flags & 16 /* Inverted */ ? this.to : this.from; } - /** - The head of the range, which is moved when the range is - [extended](https://codemirror.net/6/docs/ref/#state.SelectionRange.extend). - */ - get head() { return this.flags & 16 /* Inverted */ ? this.from : this.to; } - /** - True when `anchor` and `head` are at the same position. - */ - get empty() { return this.from == this.to; } - /** - If this is a cursor that is explicitly associated with the - character on one of its sides, this returns the side. -1 means - the character before its position, 1 the character after, and 0 - means no association. - */ - get assoc() { return this.flags & 4 /* AssocBefore */ ? -1 : this.flags & 8 /* AssocAfter */ ? 1 : 0; } - /** - The bidirectional text level associated with this cursor, if - any. - */ - get bidiLevel() { - let level = this.flags & 3 /* BidiLevelMask */; - return level == 3 ? null : level; - } - /** - The goal column (stored vertical offset) associated with a - cursor. This is used to preserve the vertical position when - [moving](https://codemirror.net/6/docs/ref/#view.EditorView.moveVertically) across - lines of different length. - */ - get goalColumn() { - let value = this.flags >> 5 /* GoalColumnOffset */; - return value == 33554431 /* NoGoalColumn */ ? undefined : value; - } - /** - Map this range through a change, producing a valid range in the - updated document. - */ - map(change, assoc = -1) { - let from, to; - if (this.empty) { - from = to = change.mapPos(this.from, assoc); - } - else { - from = change.mapPos(this.from, 1); - to = change.mapPos(this.to, -1); - } - return from == this.from && to == this.to ? this : new SelectionRange(from, to, this.flags); - } - /** - Extend this range to cover at least `from` to `to`. - */ - extend(from, to = from) { - if (from <= this.anchor && to >= this.anchor) - return EditorSelection.range(from, to); - let head = Math.abs(from - this.anchor) > Math.abs(to - this.anchor) ? from : to; - return EditorSelection.range(this.anchor, head); - } - /** - Compare this range to another range. - */ - eq(other) { - return this.anchor == other.anchor && this.head == other.head; - } - /** - Return a JSON-serializable object representing the range. - */ - toJSON() { return { anchor: this.anchor, head: this.head }; } - /** - Convert a JSON representation of a range to a `SelectionRange` - instance. - */ - static fromJSON(json) { - if (!json || typeof json.anchor != "number" || typeof json.head != "number") - throw new RangeError("Invalid JSON representation for SelectionRange"); - return EditorSelection.range(json.anchor, json.head); - } - } - /** - An editor selection holds one or more selection ranges. - */ - class EditorSelection { - /** - @internal - */ - constructor( - /** - The ranges in the selection, sorted by position. Ranges cannot - overlap (but they may touch, if they aren't empty). - */ - ranges, - /** - The index of the _main_ range in the selection (which is - usually the range that was added last). - */ - mainIndex = 0) { - this.ranges = ranges; - this.mainIndex = mainIndex; - } - /** - Map a selection through a change. Used to adjust the selection - position for changes. - */ - map(change, assoc = -1) { - if (change.empty) - return this; - return EditorSelection.create(this.ranges.map(r => r.map(change, assoc)), this.mainIndex); - } - /** - Compare this selection to another selection. - */ - eq(other) { - if (this.ranges.length != other.ranges.length || - this.mainIndex != other.mainIndex) - return false; - for (let i = 0; i < this.ranges.length; i++) - if (!this.ranges[i].eq(other.ranges[i])) - return false; - return true; - } - /** - Get the primary selection range. Usually, you should make sure - your code applies to _all_ ranges, by using methods like - [`changeByRange`](https://codemirror.net/6/docs/ref/#state.EditorState.changeByRange). - */ - get main() { return this.ranges[this.mainIndex]; } - /** - Make sure the selection only has one range. Returns a selection - holding only the main range from this selection. - */ - asSingle() { - return this.ranges.length == 1 ? this : new EditorSelection([this.main]); - } - /** - Extend this selection with an extra range. - */ - addRange(range, main = true) { - return EditorSelection.create([range].concat(this.ranges), main ? 0 : this.mainIndex + 1); - } - /** - Replace a given range with another range, and then normalize the - selection to merge and sort ranges if necessary. - */ - replaceRange(range, which = this.mainIndex) { - let ranges = this.ranges.slice(); - ranges[which] = range; - return EditorSelection.create(ranges, this.mainIndex); - } - /** - Convert this selection to an object that can be serialized to - JSON. - */ - toJSON() { - return { ranges: this.ranges.map(r => r.toJSON()), main: this.mainIndex }; - } - /** - Create a selection from a JSON representation. - */ - static fromJSON(json) { - if (!json || !Array.isArray(json.ranges) || typeof json.main != "number" || json.main >= json.ranges.length) - throw new RangeError("Invalid JSON representation for EditorSelection"); - return new EditorSelection(json.ranges.map((r) => SelectionRange.fromJSON(r)), json.main); - } - /** - Create a selection holding a single range. - */ - static single(anchor, head = anchor) { - return new EditorSelection([EditorSelection.range(anchor, head)], 0); - } - /** - Sort and merge the given set of ranges, creating a valid - selection. - */ - static create(ranges, mainIndex = 0) { - if (ranges.length == 0) - throw new RangeError("A selection needs at least one range"); - for (let pos = 0, i = 0; i < ranges.length; i++) { - let range = ranges[i]; - if (range.empty ? range.from <= pos : range.from < pos) - return normalized(ranges.slice(), mainIndex); - pos = range.to; - } - return new EditorSelection(ranges, mainIndex); - } - /** - Create a cursor selection range at the given position. You can - safely ignore the optional arguments in most situations. - */ - static cursor(pos, assoc = 0, bidiLevel, goalColumn) { - return new SelectionRange(pos, pos, (assoc == 0 ? 0 : assoc < 0 ? 4 /* AssocBefore */ : 8 /* AssocAfter */) | - (bidiLevel == null ? 3 : Math.min(2, bidiLevel)) | - ((goalColumn !== null && goalColumn !== void 0 ? goalColumn : 33554431 /* NoGoalColumn */) << 5 /* GoalColumnOffset */)); - } - /** - Create a selection range. - */ - static range(anchor, head, goalColumn) { - let goal = (goalColumn !== null && goalColumn !== void 0 ? goalColumn : 33554431 /* NoGoalColumn */) << 5 /* GoalColumnOffset */; - return head < anchor ? new SelectionRange(head, anchor, 16 /* Inverted */ | goal | 8 /* AssocAfter */) - : new SelectionRange(anchor, head, goal | (head > anchor ? 4 /* AssocBefore */ : 0)); - } - } - function normalized(ranges, mainIndex = 0) { - let main = ranges[mainIndex]; - ranges.sort((a, b) => a.from - b.from); - mainIndex = ranges.indexOf(main); - for (let i = 1; i < ranges.length; i++) { - let range = ranges[i], prev = ranges[i - 1]; - if (range.empty ? range.from <= prev.to : range.from < prev.to) { - let from = prev.from, to = Math.max(range.to, prev.to); - if (i <= mainIndex) - mainIndex--; - ranges.splice(--i, 2, range.anchor > range.head ? EditorSelection.range(to, from) : EditorSelection.range(from, to)); - } - } - return new EditorSelection(ranges, mainIndex); - } - function checkSelection(selection, docLength) { - for (let range of selection.ranges) - if (range.to > docLength) - throw new RangeError("Selection points outside of document"); - } + 1. pyscript.js is loaded by the browser. PyScriptApp().main() is called - let nextID = 0; - /** - A facet is a labeled value that is associated with an editor - state. It takes inputs from any number of extensions, and combines - those into a single output value. + 2. loadConfig(): search for py-config and compute the config for the app - Examples of facets are the [theme](https://codemirror.net/6/docs/ref/#view.EditorView^theme) styles - associated with an editor or the [tab - size](https://codemirror.net/6/docs/ref/#state.EditorState^tabSize) (which is reduced to a single - value, using the input with the hightest precedence). - */ - class Facet { - constructor( - /** - @internal - */ - combine, - /** - @internal - */ - compareInput, - /** - @internal - */ - compare, isStatic, - /** - @internal - */ - extensions) { - this.combine = combine; - this.compareInput = compareInput; - this.compare = compare; - this.isStatic = isStatic; - this.extensions = extensions; - /** - @internal - */ - this.id = nextID++; - this.default = combine([]); - } - /** - Define a new facet. - */ - static define(config = {}) { - return new Facet(config.combine || ((a) => a), config.compareInput || ((a, b) => a === b), config.compare || (!config.combine ? sameArray$1 : (a, b) => a === b), !!config.static, config.enables); - } - /** - Returns an extension that adds the given value for this facet. - */ - of(value) { - return new FacetProvider([], this, 0 /* Static */, value); - } - /** - Create an extension that computes a value for the facet from a - state. You must take care to declare the parts of the state that - this value depends on, since your function is only called again - for a new state when one of those parts changed. - - In most cases, you'll want to use the - [`provide`](https://codemirror.net/6/docs/ref/#state.StateField^define^config.provide) option when - defining a field instead. - */ - compute(deps, get) { - if (this.isStatic) - throw new Error("Can't compute a static facet"); - return new FacetProvider(deps, this, 1 /* Single */, get); - } - /** - Create an extension that computes zero or more values for this - facet from a state. - */ - computeN(deps, get) { - if (this.isStatic) - throw new Error("Can't compute a static facet"); - return new FacetProvider(deps, this, 2 /* Multi */, get); - } - from(field, get) { - if (!get) - get = x => x; - return this.compute([field], state => get(state.field(field))); - } - } - function sameArray$1(a, b) { - return a == b || a.length == b.length && a.every((e, i) => e === b[i]); - } - class FacetProvider { - constructor(dependencies, facet, type, value) { - this.dependencies = dependencies; - this.facet = facet; - this.type = type; - this.value = value; - this.id = nextID++; - } - dynamicSlot(addresses) { - var _a; - let getter = this.value; - let compare = this.facet.compareInput; - let id = this.id, idx = addresses[id] >> 1, multi = this.type == 2 /* Multi */; - let depDoc = false, depSel = false, depAddrs = []; - for (let dep of this.dependencies) { - if (dep == "doc") - depDoc = true; - else if (dep == "selection") - depSel = true; - else if ((((_a = addresses[dep.id]) !== null && _a !== void 0 ? _a : 1) & 1) == 0) - depAddrs.push(addresses[dep.id]); - } - return { - create(state) { - state.values[idx] = getter(state); - return 1 /* Changed */; - }, - update(state, tr) { - if ((depDoc && tr.docChanged) || (depSel && (tr.docChanged || tr.selection)) || - depAddrs.some(addr => (ensureAddr(state, addr) & 1 /* Changed */) > 0)) { - let newVal = getter(state); - if (multi ? !compareArray(newVal, state.values[idx], compare) : !compare(newVal, state.values[idx])) { - state.values[idx] = newVal; - return 1 /* Changed */; - } - } - return 0; - }, - reconfigure(state, oldState) { - let newVal = getter(state); - let oldAddr = oldState.config.address[id]; - if (oldAddr != null) { - let oldVal = getAddr(oldState, oldAddr); - if (multi ? compareArray(newVal, oldVal, compare) : compare(newVal, oldVal)) { - state.values[idx] = oldVal; - return 0; - } - } - state.values[idx] = newVal; - return 1 /* Changed */; - } - }; - } - } - function compareArray(a, b, compare) { - if (a.length != b.length) - return false; - for (let i = 0; i < a.length; i++) - if (!compare(a[i], b[i])) - return false; - return true; - } - function dynamicFacetSlot(addresses, facet, providers) { - let providerAddrs = providers.map(p => addresses[p.id]); - let providerTypes = providers.map(p => p.type); - let dynamic = providerAddrs.filter(p => !(p & 1)); - let idx = addresses[facet.id] >> 1; - function get(state) { - let values = []; - for (let i = 0; i < providerAddrs.length; i++) { - let value = getAddr(state, providerAddrs[i]); - if (providerTypes[i] == 2 /* Multi */) - for (let val of value) - values.push(val); - else - values.push(value); - } - return facet.combine(values); - } - return { - create(state) { - for (let addr of providerAddrs) - ensureAddr(state, addr); - state.values[idx] = get(state); - return 1 /* Changed */; - }, - update(state, tr) { - if (!dynamic.some(dynAddr => ensureAddr(state, dynAddr) & 1 /* Changed */)) - return 0; - let value = get(state); - if (facet.compare(value, state.values[idx])) - return 0; - state.values[idx] = value; - return 1 /* Changed */; - }, - reconfigure(state, oldState) { - let depChanged = providerAddrs.some(addr => ensureAddr(state, addr) & 1 /* Changed */); - let oldProviders = oldState.config.facets[facet.id], oldValue = oldState.facet(facet); - if (oldProviders && !depChanged && sameArray$1(providers, oldProviders)) { - state.values[idx] = oldValue; - return 0; - } - let value = get(state); - if (facet.compare(value, oldValue)) { - state.values[idx] = oldValue; - return 0; - } - state.values[idx] = value; - return 1 /* Changed */; - } - }; - } - const initField = /*@__PURE__*/Facet.define({ static: true }); - /** - Fields can store additional information in an editor state, and - keep it in sync with the rest of the state. - */ - class StateField { - constructor( - /** - @internal - */ - id, createF, updateF, compareF, - /** - @internal - */ - spec) { - this.id = id; - this.createF = createF; - this.updateF = updateF; - this.compareF = compareF; - this.spec = spec; - /** - @internal - */ - this.provides = undefined; - } - /** - Define a state field. - */ - static define(config) { - let field = new StateField(nextID++, config.create, config.update, config.compare || ((a, b) => a === b), config); - if (config.provide) - field.provides = config.provide(field); - return field; - } - create(state) { - let init = state.facet(initField).find(i => i.field == this); - return ((init === null || init === void 0 ? void 0 : init.create) || this.createF)(state); - } - /** - @internal - */ - slot(addresses) { - let idx = addresses[this.id] >> 1; - return { - create: (state) => { - state.values[idx] = this.create(state); - return 1 /* Changed */; - }, - update: (state, tr) => { - let oldVal = state.values[idx]; - let value = this.updateF(oldVal, tr); - if (this.compareF(oldVal, value)) - return 0; - state.values[idx] = value; - return 1 /* Changed */; - }, - reconfigure: (state, oldState) => { - if (oldState.config.address[this.id] != null) { - state.values[idx] = oldState.field(this); - return 0; - } - state.values[idx] = this.create(state); - return 1 /* Changed */; - } - }; - } - /** - Returns an extension that enables this field and overrides the - way it is initialized. Can be useful when you need to provide a - non-default starting value for the field. - */ - init(create) { - return [this, initField.of({ field: this, create })]; - } - /** - State field instances can be used as - [`Extension`](https://codemirror.net/6/docs/ref/#state.Extension) values to enable the field in a - given state. - */ - get extension() { return this; } - } - const Prec_ = { lowest: 4, low: 3, default: 2, high: 1, highest: 0 }; - function prec(value) { - return (ext) => new PrecExtension(ext, value); - } - /** - By default extensions are registered in the order they are found - in the flattened form of nested array that was provided. - Individual extension values can be assigned a precedence to - override this. Extensions that do not have a precedence set get - the precedence of the nearest parent with a precedence, or - [`default`](https://codemirror.net/6/docs/ref/#state.Prec.default) if there is no such parent. The - final ordering of extensions is determined by first sorting by - precedence and then by order within each precedence. - */ - const Prec = { - /** - The lowest precedence level. Meant for things that should end up - near the end of the extension order. - */ - lowest: /*@__PURE__*/prec(Prec_.lowest), - /** - A lower-than-default precedence, for extensions. - */ - low: /*@__PURE__*/prec(Prec_.low), - /** - The default precedence, which is also used for extensions - without an explicit precedence. - */ - default: /*@__PURE__*/prec(Prec_.default), - /** - A higher-than-default precedence, for extensions that should - come before those with default precedence. - */ - high: /*@__PURE__*/prec(Prec_.high), - /** - The highest precedence level, for extensions that should end up - near the start of the precedence ordering. - */ - highest: /*@__PURE__*/prec(Prec_.highest), - // FIXME Drop these in some future breaking version - /** - Backwards-compatible synonym for `Prec.lowest`. - */ - fallback: /*@__PURE__*/prec(Prec_.lowest), - /** - Backwards-compatible synonym for `Prec.high`. - */ - extend: /*@__PURE__*/prec(Prec_.high), - /** - Backwards-compatible synonym for `Prec.highest`. - */ - override: /*@__PURE__*/prec(Prec_.highest) - }; - class PrecExtension { - constructor(inner, prec) { - this.inner = inner; - this.prec = prec; - } - } - /** - Extension compartments can be used to make a configuration - dynamic. By [wrapping](https://codemirror.net/6/docs/ref/#state.Compartment.of) part of your - configuration in a compartment, you can later - [replace](https://codemirror.net/6/docs/ref/#state.Compartment.reconfigure) that part through a - transaction. - */ - class Compartment { - /** - Create an instance of this compartment to add to your [state - configuration](https://codemirror.net/6/docs/ref/#state.EditorStateConfig.extensions). - */ - of(ext) { return new CompartmentInstance(this, ext); } - /** - Create an [effect](https://codemirror.net/6/docs/ref/#state.TransactionSpec.effects) that - reconfigures this compartment. - */ - reconfigure(content) { - return Compartment.reconfigure.of({ compartment: this, extension: content }); - } - /** - Get the current content of the compartment in the state, or - `undefined` if it isn't present. - */ - get(state) { - return state.config.compartments.get(this); - } - } - class CompartmentInstance { - constructor(compartment, inner) { - this.compartment = compartment; - this.inner = inner; - } - } - class Configuration { - constructor(base, compartments, dynamicSlots, address, staticValues, facets) { - this.base = base; - this.compartments = compartments; - this.dynamicSlots = dynamicSlots; - this.address = address; - this.staticValues = staticValues; - this.facets = facets; - this.statusTemplate = []; - while (this.statusTemplate.length < dynamicSlots.length) - this.statusTemplate.push(0 /* Unresolved */); - } - staticFacet(facet) { - let addr = this.address[facet.id]; - return addr == null ? facet.default : this.staticValues[addr >> 1]; - } - static resolve(base, compartments, oldState) { - let fields = []; - let facets = Object.create(null); - let newCompartments = new Map(); - for (let ext of flatten(base, compartments, newCompartments)) { - if (ext instanceof StateField) - fields.push(ext); - else - (facets[ext.facet.id] || (facets[ext.facet.id] = [])).push(ext); - } - let address = Object.create(null); - let staticValues = []; - let dynamicSlots = []; - for (let field of fields) { - address[field.id] = dynamicSlots.length << 1; - dynamicSlots.push(a => field.slot(a)); - } - let oldFacets = oldState === null || oldState === void 0 ? void 0 : oldState.config.facets; - for (let id in facets) { - let providers = facets[id], facet = providers[0].facet; - let oldProviders = oldFacets && oldFacets[id] || []; - if (providers.every(p => p.type == 0 /* Static */)) { - address[facet.id] = (staticValues.length << 1) | 1; - if (sameArray$1(oldProviders, providers)) { - staticValues.push(oldState.facet(facet)); - } - else { - let value = facet.combine(providers.map(p => p.value)); - staticValues.push(oldState && facet.compare(value, oldState.facet(facet)) ? oldState.facet(facet) : value); - } - } - else { - for (let p of providers) { - if (p.type == 0 /* Static */) { - address[p.id] = (staticValues.length << 1) | 1; - staticValues.push(p.value); - } - else { - address[p.id] = dynamicSlots.length << 1; - dynamicSlots.push(a => p.dynamicSlot(a)); - } - } - address[facet.id] = dynamicSlots.length << 1; - dynamicSlots.push(a => dynamicFacetSlot(a, facet, providers)); - } - } - let dynamic = dynamicSlots.map(f => f(address)); - return new Configuration(base, newCompartments, dynamic, address, staticValues, facets); - } - } - function flatten(extension, compartments, newCompartments) { - let result = [[], [], [], [], []]; - let seen = new Map(); - function inner(ext, prec) { - let known = seen.get(ext); - if (known != null) { - if (known >= prec) - return; - let found = result[known].indexOf(ext); - if (found > -1) - result[known].splice(found, 1); - if (ext instanceof CompartmentInstance) - newCompartments.delete(ext.compartment); - } - seen.set(ext, prec); - if (Array.isArray(ext)) { - for (let e of ext) - inner(e, prec); - } - else if (ext instanceof CompartmentInstance) { - if (newCompartments.has(ext.compartment)) - throw new RangeError(`Duplicate use of compartment in extensions`); - let content = compartments.get(ext.compartment) || ext.inner; - newCompartments.set(ext.compartment, content); - inner(content, prec); - } - else if (ext instanceof PrecExtension) { - inner(ext.inner, ext.prec); - } - else if (ext instanceof StateField) { - result[prec].push(ext); - if (ext.provides) - inner(ext.provides, prec); - } - else if (ext instanceof FacetProvider) { - result[prec].push(ext); - if (ext.facet.extensions) - inner(ext.facet.extensions, prec); - } - else { - let content = ext.extension; - if (!content) - throw new Error(`Unrecognized extension value in extension set (${ext}). This sometimes happens because multiple instances of @codemirror/state are loaded, breaking instanceof checks.`); - inner(content, prec); - } - } - inner(extension, Prec_.default); - return result.reduce((a, b) => a.concat(b)); - } - function ensureAddr(state, addr) { - if (addr & 1) - return 2 /* Computed */; - let idx = addr >> 1; - let status = state.status[idx]; - if (status == 4 /* Computing */) - throw new Error("Cyclic dependency between fields and/or facets"); - if (status & 2 /* Computed */) - return status; - state.status[idx] = 4 /* Computing */; - let changed = state.computeSlot(state, state.config.dynamicSlots[idx]); - return state.status[idx] = 2 /* Computed */ | changed; - } - function getAddr(state, addr) { - return addr & 1 ? state.config.staticValues[addr >> 1] : state.values[addr >> 1]; - } + 3. (it used to be "show the splashscreen", but now it's a plugin) - const languageData = /*@__PURE__*/Facet.define(); - const allowMultipleSelections = /*@__PURE__*/Facet.define({ - combine: values => values.some(v => v), - static: true - }); - const lineSeparator = /*@__PURE__*/Facet.define({ - combine: values => values.length ? values[0] : undefined, - static: true - }); - const changeFilter = /*@__PURE__*/Facet.define(); - const transactionFilter = /*@__PURE__*/Facet.define(); - const transactionExtender = /*@__PURE__*/Facet.define(); - const readOnly = /*@__PURE__*/Facet.define({ - combine: values => values.length ? values[0] : false - }); + 4. loadInterpreter(): start downloading the actual interpreter (e.g. pyodide.js) - /** - Annotations are tagged values that are used to add metadata to - transactions in an extensible way. They should be used to model - things that effect the entire transaction (such as its [time - stamp](https://codemirror.net/6/docs/ref/#state.Transaction^time) or information about its - [origin](https://codemirror.net/6/docs/ref/#state.Transaction^userEvent)). For effects that happen - _alongside_ the other changes made by the transaction, [state - effects](https://codemirror.net/6/docs/ref/#state.StateEffect) are more appropriate. - */ - class Annotation { - /** - @internal - */ - constructor( - /** - The annotation type. - */ - type, - /** - The value of this annotation. - */ - value) { - this.type = type; - this.value = value; - } - /** - Define a new type of annotation. - */ - static define() { return new AnnotationType(); } - } - /** - Marker that identifies a type of [annotation](https://codemirror.net/6/docs/ref/#state.Annotation). - */ - class AnnotationType { - /** - Create an instance of this annotation. - */ - of(value) { return new Annotation(this, value); } - } - /** - Representation of a type of state effect. Defined with - [`StateEffect.define`](https://codemirror.net/6/docs/ref/#state.StateEffect^define). - */ - class StateEffectType { - /** - @internal - */ - constructor( - // The `any` types in these function types are there to work - // around TypeScript issue #37631, where the type guard on - // `StateEffect.is` mysteriously stops working when these properly - // have type `Value`. - /** - @internal - */ - map) { - this.map = map; - } - /** - Create a [state effect](https://codemirror.net/6/docs/ref/#state.StateEffect) instance of this - type. - */ - of(value) { return new StateEffect(this, value); } - } - /** - State effects can be used to represent additional effects - associated with a [transaction](https://codemirror.net/6/docs/ref/#state.Transaction.effects). They - are often useful to model changes to custom [state - fields](https://codemirror.net/6/docs/ref/#state.StateField), when those changes aren't implicit in - document or selection changes. - */ - class StateEffect { - /** - @internal - */ - constructor( - /** - @internal - */ - type, - /** - The value of this effect. - */ - value) { - this.type = type; - this.value = value; - } - /** - Map this effect through a position mapping. Will return - `undefined` when that ends up deleting the effect. - */ - map(mapping) { - let mapped = this.type.map(this.value, mapping); - return mapped === undefined ? undefined : mapped == this.value ? this : new StateEffect(this.type, mapped); - } - /** - Tells you whether this effect object is of a given - [type](https://codemirror.net/6/docs/ref/#state.StateEffectType). - */ - is(type) { return this.type == type; } - /** - Define a new effect type. The type parameter indicates the type - of values that his effect holds. - */ - static define(spec = {}) { - return new StateEffectType(spec.map || (v => v)); - } - /** - Map an array of effects through a change set. - */ - static mapEffects(effects, mapping) { - if (!effects.length) - return effects; - let result = []; - for (let effect of effects) { - let mapped = effect.map(mapping); - if (mapped) - result.push(mapped); - } - return result; - } - } - /** - This effect can be used to reconfigure the root extensions of - the editor. Doing this will discard any extensions - [appended](https://codemirror.net/6/docs/ref/#state.StateEffect^appendConfig), but does not reset - the content of [reconfigured](https://codemirror.net/6/docs/ref/#state.Compartment.reconfigure) - compartments. - */ - StateEffect.reconfigure = /*@__PURE__*/StateEffect.define(); - /** - Append extensions to the top-level configuration of the editor. - */ - StateEffect.appendConfig = /*@__PURE__*/StateEffect.define(); - /** - Changes to the editor state are grouped into transactions. - Typically, a user action creates a single transaction, which may - contain any number of document changes, may change the selection, - or have other effects. Create a transaction by calling - [`EditorState.update`](https://codemirror.net/6/docs/ref/#state.EditorState.update). - */ - class Transaction { - /** - @internal - */ - constructor( - /** - The state from which the transaction starts. - */ - startState, - /** - The document changes made by this transaction. - */ - changes, - /** - The selection set by this transaction, or undefined if it - doesn't explicitly set a selection. - */ - selection, - /** - The effects added to the transaction. - */ - effects, - /** - @internal - */ - annotations, - /** - Whether the selection should be scrolled into view after this - transaction is dispatched. - */ - scrollIntoView) { - this.startState = startState; - this.changes = changes; - this.selection = selection; - this.effects = effects; - this.annotations = annotations; - this.scrollIntoView = scrollIntoView; - /** - @internal - */ - this._doc = null; - /** - @internal - */ - this._state = null; - if (selection) - checkSelection(selection, changes.newLength); - if (!annotations.some((a) => a.type == Transaction.time)) - this.annotations = annotations.concat(Transaction.time.of(Date.now())); - } - /** - The new document produced by the transaction. Contrary to - [`.state`](https://codemirror.net/6/docs/ref/#state.Transaction.state)`.doc`, accessing this won't - force the entire new state to be computed right away, so it is - recommended that [transaction - filters](https://codemirror.net/6/docs/ref/#state.EditorState^transactionFilter) use this getter - when they need to look at the new document. - */ - get newDoc() { - return this._doc || (this._doc = this.changes.apply(this.startState.doc)); - } - /** - The new selection produced by the transaction. If - [`this.selection`](https://codemirror.net/6/docs/ref/#state.Transaction.selection) is undefined, - this will [map](https://codemirror.net/6/docs/ref/#state.EditorSelection.map) the start state's - current selection through the changes made by the transaction. - */ - get newSelection() { - return this.selection || this.startState.selection.map(this.changes); - } - /** - The new state created by the transaction. Computed on demand - (but retained for subsequent access), so itis recommended not to - access it in [transaction - filters](https://codemirror.net/6/docs/ref/#state.EditorState^transactionFilter) when possible. - */ - get state() { - if (!this._state) - this.startState.applyTransaction(this); - return this._state; - } - /** - Get the value of the given annotation type, if any. - */ - annotation(type) { - for (let ann of this.annotations) - if (ann.type == type) - return ann.value; - return undefined; - } - /** - Indicates whether the transaction changed the document. - */ - get docChanged() { return !this.changes.empty; } - /** - Indicates whether this transaction reconfigures the state - (through a [configuration compartment](https://codemirror.net/6/docs/ref/#state.Compartment) or - with a top-level configuration - [effect](https://codemirror.net/6/docs/ref/#state.StateEffect^reconfigure). - */ - get reconfigured() { return this.startState.config != this.state.config; } - /** - Returns true if the transaction has a [user - event](https://codemirror.net/6/docs/ref/#state.Transaction^userEvent) annotation that is equal to - or more specific than `event`. For example, if the transaction - has `"select.pointer"` as user event, `"select"` and - `"select.pointer"` will match it. - */ - isUserEvent(event) { - let e = this.annotation(Transaction.userEvent); - return !!(e && (e == event || e.length > event.length && e.slice(0, event.length) == event && e[event.length] == ".")); - } - } - /** - Annotation used to store transaction timestamps. - */ - Transaction.time = /*@__PURE__*/Annotation.define(); - /** - Annotation used to associate a transaction with a user interface - event. Holds a string identifying the event, using a - dot-separated format to support attaching more specific - information. The events used by the core libraries are: + --- wait until (4) has finished --- - - `"input"` when content is entered - - `"input.type"` for typed input - - `"input.type.compose"` for composition - - `"input.paste"` for pasted input - - `"input.drop"` when adding content with drag-and-drop - - `"input.complete"` when autocompleting - - `"delete"` when the user deletes content - - `"delete.selection"` when deleting the selection - - `"delete.forward"` when deleting forward from the selection - - `"delete.backward"` when deleting backward from the selection - - `"delete.cut"` when cutting to the clipboard - - `"move"` when content is moved - - `"move.drop"` when content is moved within the editor through drag-and-drop - - `"select"` when explicitly changing the selection - - `"select.pointer"` when selecting with a mouse or other pointing device - - `"undo"` and `"redo"` for history actions + 5. now the pyodide src is available. Initialize the engine - Use [`isUserEvent`](https://codemirror.net/6/docs/ref/#state.Transaction.isUserEvent) to check - whether the annotation matches a given event. - */ - Transaction.userEvent = /*@__PURE__*/Annotation.define(); - /** - Annotation indicating whether a transaction should be added to - the undo history or not. - */ - Transaction.addToHistory = /*@__PURE__*/Annotation.define(); - /** - Annotation indicating (when present and true) that a transaction - represents a change made by some other actor, not the user. This - is used, for example, to tag other people's changes in - collaborative editing. - */ - Transaction.remote = /*@__PURE__*/Annotation.define(); - function joinRanges(a, b) { - let result = []; - for (let iA = 0, iB = 0;;) { - let from, to; - if (iA < a.length && (iB == b.length || b[iB] >= a[iA])) { - from = a[iA++]; - to = a[iA++]; - } - else if (iB < b.length) { - from = b[iB++]; - to = b[iB++]; - } - else - return result; - if (!result.length || result[result.length - 1] < from) - result.push(from, to); - else if (result[result.length - 1] < to) - result[result.length - 1] = to; - } - } - function mergeTransaction(a, b, sequential) { - var _a; - let mapForA, mapForB, changes; - if (sequential) { - mapForA = b.changes; - mapForB = ChangeSet.empty(b.changes.length); - changes = a.changes.compose(b.changes); - } - else { - mapForA = b.changes.map(a.changes); - mapForB = a.changes.mapDesc(b.changes, true); - changes = a.changes.compose(mapForA); - } - return { - changes, - selection: b.selection ? b.selection.map(mapForB) : (_a = a.selection) === null || _a === void 0 ? void 0 : _a.map(mapForA), - effects: StateEffect.mapEffects(a.effects, mapForA).concat(StateEffect.mapEffects(b.effects, mapForB)), - annotations: a.annotations.length ? a.annotations.concat(b.annotations) : b.annotations, - scrollIntoView: a.scrollIntoView || b.scrollIntoView - }; - } - function resolveTransactionInner(state, spec, docSize) { - let sel = spec.selection, annotations = asArray$1(spec.annotations); - if (spec.userEvent) - annotations = annotations.concat(Transaction.userEvent.of(spec.userEvent)); - return { - changes: spec.changes instanceof ChangeSet ? spec.changes - : ChangeSet.of(spec.changes || [], docSize, state.facet(lineSeparator)), - selection: sel && (sel instanceof EditorSelection ? sel : EditorSelection.single(sel.anchor, sel.head)), - effects: asArray$1(spec.effects), - annotations, - scrollIntoView: !!spec.scrollIntoView - }; - } - function resolveTransaction(state, specs, filter) { - let s = resolveTransactionInner(state, specs.length ? specs[0] : {}, state.doc.length); - if (specs.length && specs[0].filter === false) - filter = false; - for (let i = 1; i < specs.length; i++) { - if (specs[i].filter === false) - filter = false; - let seq = !!specs[i].sequential; - s = mergeTransaction(s, resolveTransactionInner(state, specs[i], seq ? s.changes.newLength : state.doc.length), seq); - } - let tr = new Transaction(state, s.changes, s.selection, s.effects, s.annotations, s.scrollIntoView); - return extendTransaction(filter ? filterTransaction(tr) : tr); - } - // Finish a transaction by applying filters if necessary. - function filterTransaction(tr) { - let state = tr.startState; - // Change filters - let result = true; - for (let filter of state.facet(changeFilter)) { - let value = filter(tr); - if (value === false) { - result = false; - break; - } - if (Array.isArray(value)) - result = result === true ? value : joinRanges(result, value); - } - if (result !== true) { - let changes, back; - if (result === false) { - back = tr.changes.invertedDesc; - changes = ChangeSet.empty(state.doc.length); - } - else { - let filtered = tr.changes.filter(result); - changes = filtered.changes; - back = filtered.filtered.invertedDesc; - } - tr = new Transaction(state, changes, tr.selection && tr.selection.map(back), StateEffect.mapEffects(tr.effects, back), tr.annotations, tr.scrollIntoView); - } - // Transaction filters - let filters = state.facet(transactionFilter); - for (let i = filters.length - 1; i >= 0; i--) { - let filtered = filters[i](tr); - if (filtered instanceof Transaction) - tr = filtered; - else if (Array.isArray(filtered) && filtered.length == 1 && filtered[0] instanceof Transaction) - tr = filtered[0]; - else - tr = resolveTransaction(state, asArray$1(filtered), false); - } - return tr; - } - function extendTransaction(tr) { - let state = tr.startState, extenders = state.facet(transactionExtender), spec = tr; - for (let i = extenders.length - 1; i >= 0; i--) { - let extension = extenders[i](tr); - if (extension && Object.keys(extension).length) - spec = mergeTransaction(tr, resolveTransactionInner(state, extension, tr.changes.newLength), true); - } - return spec == tr ? tr : new Transaction(state, tr.changes, tr.selection, spec.effects, spec.annotations, spec.scrollIntoView); - } - const none$3 = []; - function asArray$1(value) { - return value == null ? none$3 : Array.isArray(value) ? value : [value]; - } + 6. setup the environment, install packages - /** - The categories produced by a [character - categorizer](https://codemirror.net/6/docs/ref/#state.EditorState.charCategorizer). These are used - do things like selecting by word. - */ - var CharCategory = /*@__PURE__*/(function (CharCategory) { - /** - Word characters. - */ - CharCategory[CharCategory["Word"] = 0] = "Word"; - /** - Whitespace. - */ - CharCategory[CharCategory["Space"] = 1] = "Space"; - /** - Anything else. - */ - CharCategory[CharCategory["Other"] = 2] = "Other"; - return CharCategory})(CharCategory || (CharCategory = {})); - const nonASCIISingleCaseWordChar = /[\u00df\u0587\u0590-\u05f4\u0600-\u06ff\u3040-\u309f\u30a0-\u30ff\u3400-\u4db5\u4e00-\u9fcc\uac00-\ud7af]/; - let wordChar; - try { - wordChar = /*@__PURE__*/new RegExp("[\\p{Alphabetic}\\p{Number}_]", "u"); - } - catch (_) { } - function hasWordChar(str) { - if (wordChar) - return wordChar.test(str); - for (let i = 0; i < str.length; i++) { - let ch = str[i]; - if (/\w/.test(ch) || ch > "\x80" && (ch.toUpperCase() != ch.toLowerCase() || nonASCIISingleCaseWordChar.test(ch))) - return true; - } - return false; - } - function makeCategorizer(wordChars) { - return (char) => { - if (!/\S/.test(char)) - return CharCategory.Space; - if (hasWordChar(char)) - return CharCategory.Word; - for (let i = 0; i < wordChars.length; i++) - if (char.indexOf(wordChars[i]) > -1) - return CharCategory.Word; - return CharCategory.Other; - }; - } + 6.5: call the Plugin.afterSetup() hook - /** - The editor state class is a persistent (immutable) data structure. - To update a state, you [create](https://codemirror.net/6/docs/ref/#state.EditorState.update) a - [transaction](https://codemirror.net/6/docs/ref/#state.Transaction), which produces a _new_ state - instance, without modifying the original object. + 7. connect the py-script web component. This causes the execution of all the + user scripts - As such, _never_ mutate properties of a state directly. That'll - just break things. - */ - class EditorState { - /** - @internal - */ - constructor( - /** - @internal - */ - config, - /** - The current document. - */ - doc, - /** - The current selection. - */ - selection, - /** - @internal - */ - values, computeSlot, tr) { - this.config = config; - this.doc = doc; - this.selection = selection; - this.values = values; - this.status = config.statusTemplate.slice(); - this.computeSlot = computeSlot; - // Fill in the computed state immediately, so that further queries - // for it made during the update return this state - if (tr) - tr._state = this; - for (let i = 0; i < this.config.dynamicSlots.length; i++) - ensureAddr(this, i << 1); - this.computeSlot = null; - } - field(field, require = true) { - let addr = this.config.address[field.id]; - if (addr == null) { - if (require) - throw new RangeError("Field is not present in this state"); - return undefined; - } - ensureAddr(this, addr); - return getAddr(this, addr); - } - /** - Create a [transaction](https://codemirror.net/6/docs/ref/#state.Transaction) that updates this - state. Any number of [transaction specs](https://codemirror.net/6/docs/ref/#state.TransactionSpec) - can be passed. Unless - [`sequential`](https://codemirror.net/6/docs/ref/#state.TransactionSpec.sequential) is set, the - [changes](https://codemirror.net/6/docs/ref/#state.TransactionSpec.changes) (if any) of each spec - are assumed to start in the _current_ document (not the document - produced by previous specs), and its - [selection](https://codemirror.net/6/docs/ref/#state.TransactionSpec.selection) and - [effects](https://codemirror.net/6/docs/ref/#state.TransactionSpec.effects) are assumed to refer - to the document created by its _own_ changes. The resulting - transaction contains the combined effect of all the different - specs. For [selection](https://codemirror.net/6/docs/ref/#state.TransactionSpec.selection), later - specs take precedence over earlier ones. - */ - update(...specs) { - return resolveTransaction(this, specs, true); - } - /** - @internal - */ - applyTransaction(tr) { - let conf = this.config, { base, compartments } = conf; - for (let effect of tr.effects) { - if (effect.is(Compartment.reconfigure)) { - if (conf) { - compartments = new Map; - conf.compartments.forEach((val, key) => compartments.set(key, val)); - conf = null; - } - compartments.set(effect.value.compartment, effect.value.extension); - } - else if (effect.is(StateEffect.reconfigure)) { - conf = null; - base = effect.value; - } - else if (effect.is(StateEffect.appendConfig)) { - conf = null; - base = asArray$1(base).concat(effect.value); - } - } - let startValues; - if (!conf) { - conf = Configuration.resolve(base, compartments, this); - let intermediateState = new EditorState(conf, this.doc, this.selection, conf.dynamicSlots.map(() => null), (state, slot) => slot.reconfigure(state, this), null); - startValues = intermediateState.values; - } - else { - startValues = tr.startState.values.slice(); - } - new EditorState(conf, tr.newDoc, tr.newSelection, startValues, (state, slot) => slot.update(state, tr), tr); - } - /** - Create a [transaction spec](https://codemirror.net/6/docs/ref/#state.TransactionSpec) that - replaces every selection range with the given content. - */ - replaceSelection(text) { - if (typeof text == "string") - text = this.toText(text); - return this.changeByRange(range => ({ changes: { from: range.from, to: range.to, insert: text }, - range: EditorSelection.cursor(range.from + text.length) })); - } - /** - Create a set of changes and a new selection by running the given - function for each range in the active selection. The function - can return an optional set of changes (in the coordinate space - of the start document), plus an updated range (in the coordinate - space of the document produced by the call's own changes). This - method will merge all the changes and ranges into a single - changeset and selection, and return it as a [transaction - spec](https://codemirror.net/6/docs/ref/#state.TransactionSpec), which can be passed to - [`update`](https://codemirror.net/6/docs/ref/#state.EditorState.update). - */ - changeByRange(f) { - let sel = this.selection; - let result1 = f(sel.ranges[0]); - let changes = this.changes(result1.changes), ranges = [result1.range]; - let effects = asArray$1(result1.effects); - for (let i = 1; i < sel.ranges.length; i++) { - let result = f(sel.ranges[i]); - let newChanges = this.changes(result.changes), newMapped = newChanges.map(changes); - for (let j = 0; j < i; j++) - ranges[j] = ranges[j].map(newMapped); - let mapBy = changes.mapDesc(newChanges, true); - ranges.push(result.range.map(mapBy)); - changes = changes.compose(newMapped); - effects = StateEffect.mapEffects(effects, newMapped).concat(StateEffect.mapEffects(asArray$1(result.effects), mapBy)); - } - return { - changes, - selection: EditorSelection.create(ranges, sel.mainIndex), - effects - }; - } - /** - Create a [change set](https://codemirror.net/6/docs/ref/#state.ChangeSet) from the given change - description, taking the state's document length and line - separator into account. - */ - changes(spec = []) { - if (spec instanceof ChangeSet) - return spec; - return ChangeSet.of(spec, this.doc.length, this.facet(EditorState.lineSeparator)); - } - /** - Using the state's [line - separator](https://codemirror.net/6/docs/ref/#state.EditorState^lineSeparator), create a - [`Text`](https://codemirror.net/6/docs/ref/#text.Text) instance from the given string. - */ - toText(string) { - return Text.of(string.split(this.facet(EditorState.lineSeparator) || DefaultSplit)); - } - /** - Return the given range of the document as a string. - */ - sliceDoc(from = 0, to = this.doc.length) { - return this.doc.sliceString(from, to, this.lineBreak); - } - /** - Get the value of a state [facet](https://codemirror.net/6/docs/ref/#state.Facet). - */ - facet(facet) { - let addr = this.config.address[facet.id]; - if (addr == null) - return facet.default; - ensureAddr(this, addr); - return getAddr(this, addr); - } - /** - Convert this state to a JSON-serializable object. When custom - fields should be serialized, you can pass them in as an object - mapping property names (in the resulting object, which should - not use `doc` or `selection`) to fields. - */ - toJSON(fields) { - let result = { - doc: this.sliceDoc(), - selection: this.selection.toJSON() - }; - if (fields) - for (let prop in fields) { - let value = fields[prop]; - if (value instanceof StateField) - result[prop] = value.spec.toJSON(this.field(fields[prop]), this); - } - return result; - } - /** - Deserialize a state from its JSON representation. When custom - fields should be deserialized, pass the same object you passed - to [`toJSON`](https://codemirror.net/6/docs/ref/#state.EditorState.toJSON) when serializing as - third argument. - */ - static fromJSON(json, config = {}, fields) { - if (!json || typeof json.doc != "string") - throw new RangeError("Invalid JSON representation for EditorState"); - let fieldInit = []; - if (fields) - for (let prop in fields) { - let field = fields[prop], value = json[prop]; - fieldInit.push(field.init(state => field.spec.fromJSON(value, state))); - } - return EditorState.create({ - doc: json.doc, - selection: EditorSelection.fromJSON(json.selection), - extensions: config.extensions ? fieldInit.concat([config.extensions]) : fieldInit - }); - } - /** - Create a new state. You'll usually only need this when - initializing an editor—updated states are created by applying - transactions. - */ - static create(config = {}) { - let configuration = Configuration.resolve(config.extensions || [], new Map); - let doc = config.doc instanceof Text ? config.doc - : Text.of((config.doc || "").split(configuration.staticFacet(EditorState.lineSeparator) || DefaultSplit)); - let selection = !config.selection ? EditorSelection.single(0) - : config.selection instanceof EditorSelection ? config.selection - : EditorSelection.single(config.selection.anchor, config.selection.head); - checkSelection(selection, doc.length); - if (!configuration.staticFacet(allowMultipleSelections)) - selection = selection.asSingle(); - return new EditorState(configuration, doc, selection, configuration.dynamicSlots.map(() => null), (state, slot) => slot.create(state), null); - } - /** - The size (in columns) of a tab in the document, determined by - the [`tabSize`](https://codemirror.net/6/docs/ref/#state.EditorState^tabSize) facet. - */ - get tabSize() { return this.facet(EditorState.tabSize); } - /** - Get the proper [line-break](https://codemirror.net/6/docs/ref/#state.EditorState^lineSeparator) - string for this state. - */ - get lineBreak() { return this.facet(EditorState.lineSeparator) || "\n"; } - /** - Returns true when the editor is - [configured](https://codemirror.net/6/docs/ref/#state.EditorState^readOnly) to be read-only. - */ - get readOnly() { return this.facet(readOnly); } - /** - Look up a translation for the given phrase (via the - [`phrases`](https://codemirror.net/6/docs/ref/#state.EditorState^phrases) facet), or return the - original string if no translation is found. - */ - phrase(phrase) { - for (let map of this.facet(EditorState.phrases)) - if (Object.prototype.hasOwnProperty.call(map, phrase)) - return map[phrase]; - return phrase; - } - /** - Find the values for a given language data field, provided by the - the [`languageData`](https://codemirror.net/6/docs/ref/#state.EditorState^languageData) facet. - */ - languageDataAt(name, pos, side = -1) { - let values = []; - for (let provider of this.facet(languageData)) { - for (let result of provider(this, pos, side)) { - if (Object.prototype.hasOwnProperty.call(result, name)) - values.push(result[name]); - } - } - return values; - } - /** - Return a function that can categorize strings (expected to - represent a single [grapheme cluster](https://codemirror.net/6/docs/ref/#text.findClusterBreak)) - into one of: - - - Word (contains an alphanumeric character or a character - explicitly listed in the local language's `"wordChars"` - language data, which should be a string) - - Space (contains only whitespace) - - Other (anything else) - */ - charCategorizer(at) { - return makeCategorizer(this.languageDataAt("wordChars", at).join("")); - } - /** - Find the word at the given position, meaning the range - containing all [word](https://codemirror.net/6/docs/ref/#state.CharCategory.Word) characters - around it. If no word characters are adjacent to the position, - this returns null. - */ - wordAt(pos) { - let { text, from, length } = this.doc.lineAt(pos); - let cat = this.charCategorizer(pos); - let start = pos - from, end = pos - from; - while (start > 0) { - let prev = findClusterBreak(text, start, false); - if (cat(text.slice(prev, start)) != CharCategory.Word) - break; - start = prev; - } - while (end < length) { - let next = findClusterBreak(text, end); - if (cat(text.slice(end, next)) != CharCategory.Word) - break; - end = next; - } - return start == end ? null : EditorSelection.range(start + from, end + from); - } - } - /** - A facet that, when enabled, causes the editor to allow multiple - ranges to be selected. Be careful though, because by default the - editor relies on the native DOM selection, which cannot handle - multiple selections. An extension like - [`drawSelection`](https://codemirror.net/6/docs/ref/#view.drawSelection) can be used to make - secondary selections visible to the user. - */ - EditorState.allowMultipleSelections = allowMultipleSelections; - /** - Configures the tab size to use in this state. The first - (highest-precedence) value of the facet is used. If no value is - given, this defaults to 4. - */ - EditorState.tabSize = /*@__PURE__*/Facet.define({ - combine: values => values.length ? values[0] : 4 - }); - /** - The line separator to use. By default, any of `"\n"`, `"\r\n"` - and `"\r"` is treated as a separator when splitting lines, and - lines are joined with `"\n"`. + 8. initialize the rest of web components such as py-button, py-repl, etc. - When you configure a value here, only that precise separator - will be used, allowing you to round-trip documents through the - editor without normalizing line separators. - */ - EditorState.lineSeparator = lineSeparator; - /** - This facet controls the value of the - [`readOnly`](https://codemirror.net/6/docs/ref/#state.EditorState.readOnly) getter, which is - consulted by commands and extensions that implement editing - functionality to determine whether they should apply. It - defaults to false, but when its highest-precedence value is - `true`, such functionality disables itself. + More concretely: - Not to be confused with - [`EditorView.editable`](https://codemirror.net/6/docs/ref/#view.EditorView^editable), which - controls whether the editor's DOM is set to be editable (and - thus focusable). - */ - EditorState.readOnly = readOnly; - /** - Registers translation phrases. The - [`phrase`](https://codemirror.net/6/docs/ref/#state.EditorState.phrase) method will look through - all objects registered with this facet to find translations for - its argument. - */ - EditorState.phrases = /*@__PURE__*/Facet.define(); - /** - A facet used to register [language - data](https://codemirror.net/6/docs/ref/#state.EditorState.languageDataAt) providers. - */ - EditorState.languageData = languageData; - /** - Facet used to register change filters, which are called for each - transaction (unless explicitly - [disabled](https://codemirror.net/6/docs/ref/#state.TransactionSpec.filter)), and can suppress - part of the transaction's changes. + - Points 1-4 are implemented sequentially in PyScriptApp.main(). - Such a function can return `true` to indicate that it doesn't - want to do anything, `false` to completely stop the changes in - the transaction, or a set of ranges in which changes should be - suppressed. Such ranges are represented as an array of numbers, - with each pair of two number indicating the start and end of a - range. So for example `[10, 20, 100, 110]` suppresses changes - between 10 and 20, and between 100 and 110. - */ - EditorState.changeFilter = changeFilter; - /** - Facet used to register a hook that gets a chance to update or - replace transaction specs before they are applied. This will - only be applied for transactions that don't have - [`filter`](https://codemirror.net/6/docs/ref/#state.TransactionSpec.filter) set to `false`. You - can either return a single transaction spec (possibly the input - transaction), or an array of specs (which will be combined in - the same way as the arguments to - [`EditorState.update`](https://codemirror.net/6/docs/ref/#state.EditorState.update)). + - PyScriptApp.loadInterpreter adds a <script> tag to the document to initiate + the download, and then adds an event listener for the 'load' event, which + in turns calls PyScriptApp.afterInterpreterLoad(). - When possible, it is recommended to avoid accessing - [`Transaction.state`](https://codemirror.net/6/docs/ref/#state.Transaction.state) in a filter, - since it will force creation of a state that will then be - discarded again, if the transaction is actually filtered. - - (This functionality should be used with care. Indiscriminately - modifying transaction is likely to break something or degrade - the user experience.) - */ - EditorState.transactionFilter = transactionFilter; - /** - This is a more limited form of - [`transactionFilter`](https://codemirror.net/6/docs/ref/#state.EditorState^transactionFilter), - which can only add - [annotations](https://codemirror.net/6/docs/ref/#state.TransactionSpec.annotations) and - [effects](https://codemirror.net/6/docs/ref/#state.TransactionSpec.effects). _But_, this type - of filter runs even the transaction has disabled regular - [filtering](https://codemirror.net/6/docs/ref/#state.TransactionSpec.filter), making it suitable - for effects that don't need to touch the changes or selection, - but do want to process every transaction. - - Extenders run _after_ filters, when both are applied. - */ - EditorState.transactionExtender = transactionExtender; - Compartment.reconfigure = /*@__PURE__*/StateEffect.define(); - - /** - Utility function for combining behaviors to fill in a config - object from an array of provided configs. Will, by default, error - when a field gets two values that aren't `===`-equal, but you can - provide combine functions per field to do something else. - */ - function combineConfig(configs, defaults, // Should hold only the optional properties of Config, but I haven't managed to express that - combine = {}) { - let result = {}; - for (let config of configs) - for (let key of Object.keys(config)) { - let value = config[key], current = result[key]; - if (current === undefined) - result[key] = value; - else if (current === value || value === undefined) ; // No conflict - else if (Object.hasOwnProperty.call(combine, key)) - result[key] = combine[key](current, value); - else - throw new Error("Config merge conflict for field " + key); - } - for (let key in defaults) - if (result[key] === undefined) - result[key] = defaults[key]; - return result; - } - - const C = "\u037c"; - const COUNT = typeof Symbol == "undefined" ? "__" + C : Symbol.for(C); - const SET = typeof Symbol == "undefined" ? "__styleSet" + Math.floor(Math.random() * 1e8) : Symbol("styleSet"); - const top = typeof globalThis != "undefined" ? globalThis : typeof window != "undefined" ? window : {}; - - // :: - Style modules encapsulate a set of CSS rules defined from - // JavaScript. Their definitions are only available in a given DOM - // root after it has been _mounted_ there with `StyleModule.mount`. - // - // Style modules should be created once and stored somewhere, as - // opposed to re-creating them every time you need them. The amount of - // CSS rules generated for a given DOM root is bounded by the amount - // of style modules that were used. So to avoid leaking rules, don't - // create these dynamically, but treat them as one-time allocations. - class StyleModule { - // :: (Object<Style>, ?{finish: ?(string) → string}) - // Create a style module from the given spec. + - PyScriptApp.afterInterpreterLoad() implements all the points >= 5. + */ + class PyScriptApp { + constructor() { + // initialize the builtin plugins + this.plugins = new PluginManager(); + this.plugins.add(new SplashscreenPlugin(), new PyTerminalPlugin(this), new ImportmapPlugin()); + this._stdioMultiplexer = new StdioMultiplexer(); + this._stdioMultiplexer.addListener(DEFAULT_STDIO); + this.plugins.add(new StdioDirector(this._stdioMultiplexer)); + this.tagExecutionLock = createLock(); + } + // Error handling logic: if during the execution we encounter an error + // which is ultimate responsibility of the user (e.g.: syntax error in the + // config, file not found in fetch, etc.), we can throw UserError(). It is + // responsibility of main() to catch it and show it to the user in a + // proper way (e.g. by using a banner at the top of the page). + main() { + try { + this._realMain(); + } + catch (error) { + this._handleUserErrorMaybe(error); + } + } + _handleUserErrorMaybe(error) { + if (error instanceof UserError) { + _createAlertBanner(error.message, 'error', error.messageType); + this.plugins.onUserError(error); + } + else { + throw error; + } + } + // ============ lifecycle ============ + // lifecycle (1) + _realMain() { + this.loadConfig(); + this.plugins.configure(this.config); + this.plugins.beforeLaunch(this.config); + this.loadInterpreter(); + } + // lifecycle (2) + loadConfig() { + // find the <py-config> tag. If not found, we get null which means + // "use the default config" + // XXX: we should actively complain if there are multiple <py-config> + // and show a big error. PRs welcome :) + logger.info('searching for <py-config>'); + const elements = document.getElementsByTagName('py-config'); + let el = null; + if (elements.length > 0) + el = elements[0]; + if (elements.length >= 2) { + showWarning('Multiple <py-config> tags detected. Only the first is ' + + 'going to be parsed, all the others will be ignored'); + } + this.config = loadConfigFromElement(el); + logger.info('config loaded:\n' + JSON.stringify(this.config, null, 2)); + } + // lifecycle (4) + loadInterpreter() { + logger.info('Initializing interpreter'); + if (this.config.interpreters.length == 0) { + throw new UserError(ErrorCode.BAD_CONFIG, 'Fatal error: config.interpreter is empty'); + } + if (this.config.interpreters.length > 1) { + showWarning('Multiple interpreters are not supported yet.<br />Only the first will be used', 'html'); + } + const interpreter_cfg = this.config.interpreters[0]; + this.interpreter = new InterpreterClient(this.config, this._stdioMultiplexer); + this.logStatus(`Downloading ${interpreter_cfg.name}...`); + // download pyodide by using a <script> tag. Once it's ready, the + // "load" event will be fired and the exeuction logic will continue. + // Note that the load event is fired asynchronously and thus any + // exception which is throw inside the event handler is *NOT* caught + // by the try/catch inside main(): that's why we need to .catch() it + // explicitly and call _handleUserErrorMaybe also there. + const script = document.createElement('script'); // create a script DOM node + script.src = this.interpreter._remote.src; + script.addEventListener('load', () => { + this.afterInterpreterLoad(this.interpreter).catch(error => { + this._handleUserErrorMaybe(error); + }); + }); + document.head.appendChild(script); + } + // lifecycle (5) + // See the overview comment above for an explanation of how we jump from + // point (4) to point (5). // - // When `finish` is given, it is called on regular (non-`@`) - // selectors (after `&` expansion) to compute the final selector. - constructor(spec, options) { - this.rules = []; - let {finish} = options || {}; - - function splitSelector(selector) { - return /^@/.test(selector) ? [selector] : selector.split(/,\s*/) - } - - function render(selectors, spec, target, isKeyframes) { - let local = [], isAt = /^@(\w+)\b/.exec(selectors[0]), keyframes = isAt && isAt[1] == "keyframes"; - if (isAt && spec == null) return target.push(selectors[0] + ";") - for (let prop in spec) { - let value = spec[prop]; - if (/&/.test(prop)) { - render(prop.split(/,\s*/).map(part => selectors.map(sel => part.replace(/&/, sel))).reduce((a, b) => a.concat(b)), - value, target); - } else if (value && typeof value == "object") { - if (!isAt) throw new RangeError("The value of a property (" + prop + ") should be a primitive value.") - render(splitSelector(prop), value, local, keyframes); - } else if (value != null) { - local.push(prop.replace(/_.*/, "").replace(/[A-Z]/g, l => "-" + l.toLowerCase()) + ": " + value + ";"); - } + // Invariant: this.config is set and available. + async afterInterpreterLoad(interpreter) { + console.assert(this.config !== undefined); + this.logStatus('Python startup...'); + await this.interpreter.initializeRemote(); + this.logStatus('Python ready!'); + this.logStatus('Setting up virtual environment...'); + await this.setupVirtualEnv(interpreter); + await mountElements(interpreter); + // lifecycle (6.5) + this.plugins.afterSetup(interpreter); + //Refresh module cache in case plugins have modified the filesystem + interpreter._remote.invalidate_module_path_cache(); + this.logStatus('Executing <py-script> tags...'); + this.executeScripts(interpreter); + this.logStatus('Initializing web components...'); + // lifecycle (8) + createCustomElements(interpreter); + initHandlers(interpreter); + // NOTE: interpreter message is used by integration tests to know that + // pyscript initialization has complete. If you change it, you need to + // change it also in tests/integration/support.py + this.logStatus('Startup complete'); + this.plugins.afterStartup(interpreter); + logger.info('PyScript page fully initialized'); + } + // lifecycle (6) + async setupVirtualEnv(interpreter) { + // XXX: maybe the following calls could be parallelized, instead of + // await()ing immediately. For now I'm using await to be 100% + // compatible with the old behavior. + logger.info('importing pyscript'); + // Save and load pyscript.py from FS + interpreter._remote.interface.FS.mkdirTree('/home/pyodide/pyscript'); + interpreter._remote.interface.FS.writeFile('pyscript/__init__.py', pyscript); + //Refresh the module cache so Python consistently finds pyscript module + interpreter._remote.invalidate_module_path_cache(); + // inject `define_custom_element` and showWarning it into the PyScript + // module scope + const pyscript_module = interpreter._remote.interface.pyimport('pyscript'); + pyscript_module.define_custom_element = define_custom_element; + pyscript_module.showWarning = showWarning; + pyscript_module._set_version_info(version); + pyscript_module.destroy(); + // import some carefully selected names into the global namespace + await interpreter.run(` + import js + import pyscript + from pyscript import Element, display, HTML + pyscript._install_deprecated_globals_2022_12_1(globals()) + `); + if (this.config.packages) { + logger.info('Packages to install: ', this.config.packages); + await interpreter._remote.installPackage(this.config.packages); } - if (local.length || keyframes) { - target.push((finish && !isAt && !isKeyframes ? selectors.map(finish) : selectors).join(", ") + - " {" + local.join(" ") + "}"); + await this.fetchPaths(interpreter); + //This may be unnecessary - only useful if plugins try to import files fetch'd in fetchPaths() + interpreter._remote.invalidate_module_path_cache(); + // Finally load plugins + await this.fetchUserPlugins(interpreter); + } + async fetchPaths(interpreter) { + // XXX this can be VASTLY improved: for each path we need to fetch a + // URL and write to the virtual filesystem: pyodide.loadFromFile does + // it in Python, which means we need to have the interpreter + // initialized. But we could easily do it in JS in parallel with the + // download/startup of pyodide. + const [paths, fetchPaths] = calculatePaths(this.config.fetch); + logger.info('Paths to write: ', paths); + logger.info('Paths to fetch: ', fetchPaths); + for (let i = 0; i < paths.length; i++) { + logger.info(` fetching path: ${fetchPaths[i]}`); + // Exceptions raised from here will create an alert banner + await interpreter._remote.loadFromFile(paths[i], fetchPaths[i]); } - } - - for (let prop in spec) render(splitSelector(prop), spec[prop], this.rules); + logger.info('All paths fetched'); } - - // :: () → string - // Returns a string containing the module's CSS rules. - getRules() { return this.rules.join("\n") } - - // :: () → string - // Generate a new unique CSS class name. - static newName() { - let id = top[COUNT] || 1; - top[COUNT] = id + 1; - return C + id.toString(36) - } - - // :: (union<Document, ShadowRoot>, union<[StyleModule], StyleModule>) - // - // Mount the given set of modules in the given DOM root, which ensures - // that the CSS rules defined by the module are available in that - // context. - // - // Rules are only added to the document once per root. - // - // Rule order will follow the order of the modules, so that rules from - // modules later in the array take precedence of those from earlier - // modules. If you call this function multiple times for the same root - // in a way that changes the order of already mounted modules, the old - // order will be changed. - static mount(root, modules) { - (root[SET] || new StyleSet(root)).mount(Array.isArray(modules) ? modules : [modules]); - } - } - - let adoptedSet = null; - - class StyleSet { - constructor(root) { - if (!root.head && root.adoptedStyleSheets && typeof CSSStyleSheet != "undefined") { - if (adoptedSet) { - root.adoptedStyleSheets = [adoptedSet.sheet].concat(root.adoptedStyleSheets); - return root[SET] = adoptedSet + /** + * Fetch user plugins and adds them to `this.plugins` so they can + * be loaded by the PluginManager. Currently, we are just looking + * for .py and .js files and calling the appropriate methods. + * + * @param interpreter - the interpreter that will be used to execute the plugins that need it. + */ + async fetchUserPlugins(interpreter) { + const plugins = this.config.plugins; + logger.info('Plugins to fetch: ', plugins); + for (const singleFile of plugins) { + logger.info(` fetching plugins: ${singleFile}`); + if (singleFile.endsWith('.py')) { + await this.fetchPythonPlugin(interpreter, singleFile); + } + else if (singleFile.endsWith('.js')) { + await this.fetchJSPlugin(singleFile); + } + else { + throw new UserError(ErrorCode.BAD_PLUGIN_FILE_EXTENSION, `Unable to load plugin from '${singleFile}'. ` + + `Plugins need to contain a file extension and be ` + + `either a python or javascript file.`); + } + logger.info('All plugins fetched'); } - this.sheet = new CSSStyleSheet; - root.adoptedStyleSheets = [this.sheet].concat(root.adoptedStyleSheets); - adoptedSet = this; - } else { - this.styleTag = (root.ownerDocument || root).createElement("style"); - let target = root.head || root; - target.insertBefore(this.styleTag, target.firstChild); - } - this.modules = []; - root[SET] = this; } - - mount(modules) { - let sheet = this.sheet; - let pos = 0 /* Current rule offset */, j = 0; /* Index into this.modules */ - for (let i = 0; i < modules.length; i++) { - let mod = modules[i], index = this.modules.indexOf(mod); - if (index < j && index > -1) { // Ordering conflict - this.modules.splice(index, 1); - j--; - index = -1; + /** + * Fetch a javascript plugin from a filePath, it gets a blob from the + * fetch and creates a file from it, then we create a URL from the file + * so we can import it as a module. + * + * This allow us to instantiate the imported plugin with the default + * export in the module (the plugin class) and add it to the plugins + * list with `new importedPlugin()`. + * + * @param filePath - URL of the javascript file to fetch. + */ + async fetchJSPlugin(filePath) { + const pluginBlob = await (await robustFetch(filePath)).blob(); + const blobFile = new File([pluginBlob], 'plugin.js', { type: 'text/javascript' }); + const fileUrl = URL.createObjectURL(blobFile); + const module = await import(fileUrl); + // Note: We have to put module.default in a variable + // because we have seen weird behaviour when doing + // new module.default() directly. + const importedPlugin = module.default; + // If the imported plugin doesn't have a default export + // it will be undefined, so we throw a user error, so + // an alter banner will be created. + if (importedPlugin === undefined) { + throw new UserError(ErrorCode.NO_DEFAULT_EXPORT, `Unable to load plugin from '${filePath}'. ` + `Plugins need to contain a default export.`); } - if (index == -1) { - this.modules.splice(j++, 0, mod); - if (sheet) for (let k = 0; k < mod.rules.length; k++) - sheet.insertRule(mod.rules[k], pos++); - } else { - while (j < index) pos += this.modules[j++].rules.length; - pos += mod.rules.length; - j++; + else { + this.plugins.add(new importedPlugin()); } - } - - if (!sheet) { - let text = ""; - for (let i = 0; i < this.modules.length; i++) - text += this.modules[i].getRules() + "\n"; - this.styleTag.textContent = text; - } } - } - - // Style::Object<union<Style,string>> - // - // A style is an object that, in the simple case, maps CSS property - // names to strings holding their values, as in `{color: "red", - // fontWeight: "bold"}`. The property names can be given in - // camel-case—the library will insert a dash before capital letters - // when converting them to CSS. - // - // If you include an underscore in a property name, it and everything - // after it will be removed from the output, which can be useful when - // providing a property multiple times, for browser compatibility - // reasons. - // - // A property in a style object can also be a sub-selector, which - // extends the current context to add a pseudo-selector or a child - // selector. Such a property should contain a `&` character, which - // will be replaced by the current selector. For example `{"&:before": - // {content: '"hi"'}}`. Sub-selectors and regular properties can - // freely be mixed in a given object. Any property containing a `&` is - // assumed to be a sub-selector. - // - // Finally, a property can specify an @-block to be wrapped around the - // styles defined inside the object that's the property's value. For - // example to create a media query you can do `{"@media screen and - // (min-width: 400px)": {...}}`. - - /** - Each range is associated with a value, which must inherit from - this class. - */ - class RangeValue { - /** - Compare this value with another value. The default - implementation compares by identity. - */ - eq(other) { return this == other; } - /** - Create a [range](https://codemirror.net/6/docs/ref/#rangeset.Range) with this value. - */ - range(from, to = from) { return new Range$1(from, to, this); } - } - RangeValue.prototype.startSide = RangeValue.prototype.endSide = 0; - RangeValue.prototype.point = false; - RangeValue.prototype.mapMode = MapMode.TrackDel; - /** - A range associates a value with a range of positions. - */ - class Range$1 { - /** - @internal - */ - constructor( - /** - The range's start position. - */ - from, - /** - Its end position. - */ - to, - /** - The value associated with this range. - */ - value) { - this.from = from; - this.to = to; - this.value = value; - } - } - function cmpRange(a, b) { - return a.from - b.from || a.value.startSide - b.value.startSide; - } - class Chunk { - constructor(from, to, value, - // Chunks are marked with the largest point that occurs - // in them (or -1 for no points), so that scans that are - // only interested in points (such as the - // heightmap-related logic) can skip range-only chunks. - maxPoint) { - this.from = from; - this.to = to; - this.value = value; - this.maxPoint = maxPoint; - } - get length() { return this.to[this.to.length - 1]; } - // Find the index of the given position and side. Use the ranges' - // `from` pos when `end == false`, `to` when `end == true`. - findIndex(pos, side, end, startAt = 0) { - let arr = end ? this.to : this.from; - for (let lo = startAt, hi = arr.length;;) { - if (lo == hi) - return lo; - let mid = (lo + hi) >> 1; - let diff = arr[mid] - pos || (end ? this.value[mid].endSide : this.value[mid].startSide) - side; - if (mid == lo) - return diff >= 0 ? lo : hi; - if (diff >= 0) - hi = mid; - else - lo = mid + 1; - } - } - between(offset, from, to, f) { - for (let i = this.findIndex(from, -1000000000 /* Far */, true), e = this.findIndex(to, 1000000000 /* Far */, false, i); i < e; i++) - if (f(this.from[i] + offset, this.to[i] + offset, this.value[i]) === false) - return false; - } - map(offset, changes) { - let value = [], from = [], to = [], newPos = -1, maxPoint = -1; - for (let i = 0; i < this.value.length; i++) { - let val = this.value[i], curFrom = this.from[i] + offset, curTo = this.to[i] + offset, newFrom, newTo; - if (curFrom == curTo) { - let mapped = changes.mapPos(curFrom, val.startSide, val.mapMode); - if (mapped == null) - continue; - newFrom = newTo = mapped; - if (val.startSide != val.endSide) { - newTo = changes.mapPos(curFrom, val.endSide); - if (newTo < newFrom) - continue; - } - } - else { - newFrom = changes.mapPos(curFrom, val.startSide); - newTo = changes.mapPos(curTo, val.endSide); - if (newFrom > newTo || newFrom == newTo && val.startSide > 0 && val.endSide <= 0) - continue; - } - if ((newTo - newFrom || val.endSide - val.startSide) < 0) - continue; - if (newPos < 0) - newPos = newFrom; - if (val.point) - maxPoint = Math.max(maxPoint, newTo - newFrom); - value.push(val); - from.push(newFrom - newPos); - to.push(newTo - newPos); - } - return { mapped: value.length ? new Chunk(from, to, value, maxPoint) : null, pos: newPos }; - } - } - /** - A range set stores a collection of [ranges](https://codemirror.net/6/docs/ref/#rangeset.Range) in a - way that makes them efficient to [map](https://codemirror.net/6/docs/ref/#rangeset.RangeSet.map) and - [update](https://codemirror.net/6/docs/ref/#rangeset.RangeSet.update). This is an immutable data - structure. - */ - class RangeSet { - /** - @internal - */ - constructor( - /** - @internal - */ - chunkPos, - /** - @internal - */ - chunk, - /** - @internal - */ - nextLayer = RangeSet.empty, - /** - @internal - */ - maxPoint) { - this.chunkPos = chunkPos; - this.chunk = chunk; - this.nextLayer = nextLayer; - this.maxPoint = maxPoint; - } - /** - @internal - */ - get length() { - let last = this.chunk.length - 1; - return last < 0 ? 0 : Math.max(this.chunkEnd(last), this.nextLayer.length); - } - /** - The number of ranges in the set. - */ - get size() { - if (this.isEmpty) - return 0; - let size = this.nextLayer.size; - for (let chunk of this.chunk) - size += chunk.value.length; - return size; - } - /** - @internal - */ - chunkEnd(index) { - return this.chunkPos[index] + this.chunk[index].length; - } - /** - Update the range set, optionally adding new ranges or filtering - out existing ones. - - (The extra type parameter is just there as a kludge to work - around TypeScript variance issues that prevented `RangeSet<X>` - from being a subtype of `RangeSet<Y>` when `X` is a subtype of - `Y`.) - */ - update(updateSpec) { - let { add = [], sort = false, filterFrom = 0, filterTo = this.length } = updateSpec; - let filter = updateSpec.filter; - if (add.length == 0 && !filter) - return this; - if (sort) - add = add.slice().sort(cmpRange); - if (this.isEmpty) - return add.length ? RangeSet.of(add) : this; - let cur = new LayerCursor(this, null, -1).goto(0), i = 0, spill = []; - let builder = new RangeSetBuilder(); - while (cur.value || i < add.length) { - if (i < add.length && (cur.from - add[i].from || cur.startSide - add[i].value.startSide) >= 0) { - let range = add[i++]; - if (!builder.addInner(range.from, range.to, range.value)) - spill.push(range); - } - else if (cur.rangeIndex == 1 && cur.chunkIndex < this.chunk.length && - (i == add.length || this.chunkEnd(cur.chunkIndex) < add[i].from) && - (!filter || filterFrom > this.chunkEnd(cur.chunkIndex) || filterTo < this.chunkPos[cur.chunkIndex]) && - builder.addChunk(this.chunkPos[cur.chunkIndex], this.chunk[cur.chunkIndex])) { - cur.nextChunk(); - } - else { - if (!filter || filterFrom > cur.to || filterTo < cur.from || filter(cur.from, cur.to, cur.value)) { - if (!builder.addInner(cur.from, cur.to, cur.value)) - spill.push(new Range$1(cur.from, cur.to, cur.value)); - } - cur.next(); - } - } - return builder.finishInner(this.nextLayer.isEmpty && !spill.length ? RangeSet.empty - : this.nextLayer.update({ add: spill, filter, filterFrom, filterTo })); - } - /** - Map this range set through a set of changes, return the new set. - */ - map(changes) { - if (changes.empty || this.isEmpty) - return this; - let chunks = [], chunkPos = [], maxPoint = -1; - for (let i = 0; i < this.chunk.length; i++) { - let start = this.chunkPos[i], chunk = this.chunk[i]; - let touch = changes.touchesRange(start, start + chunk.length); - if (touch === false) { - maxPoint = Math.max(maxPoint, chunk.maxPoint); - chunks.push(chunk); - chunkPos.push(changes.mapPos(start)); - } - else if (touch === true) { - let { mapped, pos } = chunk.map(start, changes); - if (mapped) { - maxPoint = Math.max(maxPoint, mapped.maxPoint); - chunks.push(mapped); - chunkPos.push(pos); - } - } - } - let next = this.nextLayer.map(changes); - return chunks.length == 0 ? next : new RangeSet(chunkPos, chunks, next, maxPoint); - } - /** - Iterate over the ranges that touch the region `from` to `to`, - calling `f` for each. There is no guarantee that the ranges will - be reported in any specific order. When the callback returns - `false`, iteration stops. - */ - between(from, to, f) { - if (this.isEmpty) - return; - for (let i = 0; i < this.chunk.length; i++) { - let start = this.chunkPos[i], chunk = this.chunk[i]; - if (to >= start && from <= start + chunk.length && - chunk.between(start, from - start, to - start, f) === false) - return; - } - this.nextLayer.between(from, to, f); - } - /** - Iterate over the ranges in this set, in order, including all - ranges that end at or after `from`. - */ - iter(from = 0) { - return HeapCursor.from([this]).goto(from); - } - /** - @internal - */ - get isEmpty() { return this.nextLayer == this; } - /** - Iterate over the ranges in a collection of sets, in order, - starting from `from`. - */ - static iter(sets, from = 0) { - return HeapCursor.from(sets).goto(from); - } - /** - Iterate over two groups of sets, calling methods on `comparator` - to notify it of possible differences. - */ - static compare(oldSets, newSets, - /** - This indicates how the underlying data changed between these - ranges, and is needed to synchronize the iteration. `from` and - `to` are coordinates in the _new_ space, after these changes. - */ - textDiff, comparator, - /** - Can be used to ignore all non-point ranges, and points below - the given size. When -1, all ranges are compared. - */ - minPointSize = -1) { - let a = oldSets.filter(set => set.maxPoint > 0 || !set.isEmpty && set.maxPoint >= minPointSize); - let b = newSets.filter(set => set.maxPoint > 0 || !set.isEmpty && set.maxPoint >= minPointSize); - let sharedChunks = findSharedChunks(a, b, textDiff); - let sideA = new SpanCursor(a, sharedChunks, minPointSize); - let sideB = new SpanCursor(b, sharedChunks, minPointSize); - textDiff.iterGaps((fromA, fromB, length) => compare(sideA, fromA, sideB, fromB, length, comparator)); - if (textDiff.empty && textDiff.length == 0) - compare(sideA, 0, sideB, 0, 0, comparator); - } - /** - Compare the contents of two groups of range sets, returning true - if they are equivalent in the given range. - */ - static eq(oldSets, newSets, from = 0, to) { - if (to == null) - to = 1000000000 /* Far */; - let a = oldSets.filter(set => !set.isEmpty && newSets.indexOf(set) < 0); - let b = newSets.filter(set => !set.isEmpty && oldSets.indexOf(set) < 0); - if (a.length != b.length) - return false; - if (!a.length) - return true; - let sharedChunks = findSharedChunks(a, b); - let sideA = new SpanCursor(a, sharedChunks, 0).goto(from), sideB = new SpanCursor(b, sharedChunks, 0).goto(from); - for (;;) { - if (sideA.to != sideB.to || - !sameValues(sideA.active, sideB.active) || - sideA.point && (!sideB.point || !sideA.point.eq(sideB.point))) - return false; - if (sideA.to > to) - return true; - sideA.next(); - sideB.next(); - } - } - /** - Iterate over a group of range sets at the same time, notifying - the iterator about the ranges covering every given piece of - content. Returns the open count (see - [`SpanIterator.span`](https://codemirror.net/6/docs/ref/#rangeset.SpanIterator.span)) at the end - of the iteration. - */ - static spans(sets, from, to, iterator, - /** - When given and greater than -1, only points of at least this - size are taken into account. - */ - minPointSize = -1) { - var _a; - let cursor = new SpanCursor(sets, null, minPointSize, (_a = iterator.filterPoint) === null || _a === void 0 ? void 0 : _a.bind(iterator)).goto(from), pos = from; - let open = cursor.openStart; - for (;;) { - let curTo = Math.min(cursor.to, to); - if (cursor.point) { - iterator.point(pos, curTo, cursor.point, cursor.activeForPoint(cursor.to), open); - open = cursor.openEnd(curTo) + (cursor.to > curTo ? 1 : 0); - } - else if (curTo > pos) { - iterator.span(pos, curTo, cursor.active, open); - open = cursor.openEnd(curTo); - } - if (cursor.to > to) - break; - pos = cursor.to; - cursor.next(); - } - return open; - } - /** - Create a range set for the given range or array of ranges. By - default, this expects the ranges to be _sorted_ (by start - position and, if two start at the same position, - `value.startSide`). You can pass `true` as second argument to - cause the method to sort them. - */ - static of(ranges, sort = false) { - let build = new RangeSetBuilder(); - for (let range of ranges instanceof Range$1 ? [ranges] : sort ? lazySort(ranges) : ranges) - build.add(range.from, range.to, range.value); - return build.finish(); - } - } - /** - The empty set of ranges. - */ - RangeSet.empty = /*@__PURE__*/new RangeSet([], [], null, -1); - function lazySort(ranges) { - if (ranges.length > 1) - for (let prev = ranges[0], i = 1; i < ranges.length; i++) { - let cur = ranges[i]; - if (cmpRange(prev, cur) > 0) - return ranges.slice().sort(cmpRange); - prev = cur; - } - return ranges; - } - RangeSet.empty.nextLayer = RangeSet.empty; - /** - A range set builder is a data structure that helps build up a - [range set](https://codemirror.net/6/docs/ref/#rangeset.RangeSet) directly, without first allocating - an array of [`Range`](https://codemirror.net/6/docs/ref/#rangeset.Range) objects. - */ - class RangeSetBuilder { - /** - Create an empty builder. - */ - constructor() { - this.chunks = []; - this.chunkPos = []; - this.chunkStart = -1; - this.last = null; - this.lastFrom = -1000000000 /* Far */; - this.lastTo = -1000000000 /* Far */; - this.from = []; - this.to = []; - this.value = []; - this.maxPoint = -1; - this.setMaxPoint = -1; - this.nextLayer = null; - } - finishChunk(newArrays) { - this.chunks.push(new Chunk(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; - if (newArrays) { - this.from = []; - this.to = []; - this.value = []; - } - } - /** - Add a range. Ranges should be added in sorted (by `from` and - `value.startSide`) order. - */ - add(from, to, value) { - if (!this.addInner(from, to, value)) - (this.nextLayer || (this.nextLayer = new RangeSetBuilder)).add(from, to, value); - } - /** - @internal - */ - addInner(from, to, value) { - let diff = from - this.lastTo || value.startSide - this.last.endSide; - if (diff <= 0 && (from - this.lastFrom || value.startSide - this.last.startSide) < 0) - throw new Error("Ranges must be added sorted by `from` position and `startSide`"); - if (diff < 0) - return false; - if (this.from.length == 250 /* ChunkSize */) - this.finishChunk(true); - if (this.chunkStart < 0) - this.chunkStart = from; - this.from.push(from - this.chunkStart); - this.to.push(to - this.chunkStart); - this.last = value; - this.lastFrom = from; - this.lastTo = to; - this.value.push(value); - if (value.point) - this.maxPoint = Math.max(this.maxPoint, to - from); - return true; - } - /** - @internal - */ - addChunk(from, chunk) { - if ((from - this.lastTo || chunk.value[0].startSide - this.last.endSide) < 0) - return false; - if (this.from.length) - this.finishChunk(true); - this.setMaxPoint = Math.max(this.setMaxPoint, chunk.maxPoint); - this.chunks.push(chunk); - this.chunkPos.push(from); - let last = chunk.value.length - 1; - this.last = chunk.value[last]; - this.lastFrom = chunk.from[last] + from; - this.lastTo = chunk.to[last] + from; - return true; - } - /** - Finish the range set. Returns the new set. The builder can't be - used anymore after this has been called. - */ - finish() { return this.finishInner(RangeSet.empty); } - /** - @internal - */ - finishInner(next) { - if (this.from.length) - this.finishChunk(false); - if (this.chunks.length == 0) - return next; - let result = new RangeSet(this.chunkPos, this.chunks, this.nextLayer ? this.nextLayer.finishInner(next) : next, this.setMaxPoint); - this.from = null; // Make sure further `add` calls produce errors - return result; - } - } - function findSharedChunks(a, b, textDiff) { - let inA = new Map(); - for (let set of a) - for (let i = 0; i < set.chunk.length; i++) - if (set.chunk[i].maxPoint <= 0) - inA.set(set.chunk[i], set.chunkPos[i]); - let shared = new Set(); - for (let set of b) - for (let i = 0; i < set.chunk.length; i++) { - let known = inA.get(set.chunk[i]); - if (known != null && (textDiff ? textDiff.mapPos(known) : known) == set.chunkPos[i] && - !(textDiff === null || textDiff === void 0 ? void 0 : textDiff.touchesRange(known, known + set.chunk[i].length))) - shared.add(set.chunk[i]); - } - return shared; - } - class LayerCursor { - constructor(layer, skip, minPoint, rank = 0) { - this.layer = layer; - this.skip = skip; - this.minPoint = minPoint; - this.rank = rank; - } - get startSide() { return this.value ? this.value.startSide : 0; } - get endSide() { return this.value ? this.value.endSide : 0; } - goto(pos, side = -1000000000 /* Far */) { - this.chunkIndex = this.rangeIndex = 0; - this.gotoInner(pos, side, false); - return this; - } - gotoInner(pos, side, forward) { - while (this.chunkIndex < this.layer.chunk.length) { - let next = this.layer.chunk[this.chunkIndex]; - if (!(this.skip && this.skip.has(next) || - this.layer.chunkEnd(this.chunkIndex) < pos || - next.maxPoint < this.minPoint)) - break; - this.chunkIndex++; - forward = false; - } - if (this.chunkIndex < this.layer.chunk.length) { - let rangeIndex = this.layer.chunk[this.chunkIndex].findIndex(pos - this.layer.chunkPos[this.chunkIndex], side, true); - if (!forward || this.rangeIndex < rangeIndex) - this.setRangeIndex(rangeIndex); - } - this.next(); - } - forward(pos, side) { - if ((this.to - pos || this.endSide - side) < 0) - this.gotoInner(pos, side, true); - } - next() { - for (;;) { - if (this.chunkIndex == this.layer.chunk.length) { - this.from = this.to = 1000000000 /* Far */; - this.value = null; - break; - } - else { - let chunkPos = this.layer.chunkPos[this.chunkIndex], chunk = this.layer.chunk[this.chunkIndex]; - let from = chunkPos + chunk.from[this.rangeIndex]; - this.from = from; - this.to = chunkPos + chunk.to[this.rangeIndex]; - this.value = chunk.value[this.rangeIndex]; - this.setRangeIndex(this.rangeIndex + 1); - if (this.minPoint < 0 || this.value.point && this.to - this.from >= this.minPoint) - break; - } - } - } - setRangeIndex(index) { - if (index == this.layer.chunk[this.chunkIndex].value.length) { - this.chunkIndex++; - if (this.skip) { - while (this.chunkIndex < this.layer.chunk.length && this.skip.has(this.layer.chunk[this.chunkIndex])) - this.chunkIndex++; - } - this.rangeIndex = 0; - } - else { - this.rangeIndex = index; - } - } - nextChunk() { - this.chunkIndex++; - this.rangeIndex = 0; - this.next(); - } - compare(other) { - return this.from - other.from || this.startSide - other.startSide || this.rank - other.rank || - this.to - other.to || this.endSide - other.endSide; - } - } - class HeapCursor { - constructor(heap) { - this.heap = heap; - } - static from(sets, skip = null, minPoint = -1) { - let heap = []; - for (let i = 0; i < sets.length; i++) { - for (let cur = sets[i]; !cur.isEmpty; cur = cur.nextLayer) { - if (cur.maxPoint >= minPoint) - heap.push(new LayerCursor(cur, skip, minPoint, i)); - } - } - return heap.length == 1 ? heap[0] : new HeapCursor(heap); - } - get startSide() { return this.value ? this.value.startSide : 0; } - goto(pos, side = -1000000000 /* Far */) { - for (let cur of this.heap) - cur.goto(pos, side); - for (let i = this.heap.length >> 1; i >= 0; i--) - heapBubble(this.heap, i); - this.next(); - return this; - } - forward(pos, side) { - for (let cur of this.heap) - cur.forward(pos, side); - for (let i = this.heap.length >> 1; i >= 0; i--) - heapBubble(this.heap, i); - if ((this.to - pos || this.value.endSide - side) < 0) - this.next(); - } - next() { - if (this.heap.length == 0) { - this.from = this.to = 1000000000 /* Far */; - this.value = null; - this.rank = -1; - } - else { - let top = this.heap[0]; - this.from = top.from; - this.to = top.to; - this.value = top.value; - this.rank = top.rank; - if (top.value) - top.next(); - heapBubble(this.heap, 0); - } - } - } - function heapBubble(heap, index) { - for (let cur = heap[index];;) { - let childIndex = (index << 1) + 1; - if (childIndex >= heap.length) - break; - let child = heap[childIndex]; - if (childIndex + 1 < heap.length && child.compare(heap[childIndex + 1]) >= 0) { - child = heap[childIndex + 1]; - childIndex++; - } - if (cur.compare(child) < 0) - break; - heap[childIndex] = cur; - heap[index] = child; - index = childIndex; - } - } - class SpanCursor { - constructor(sets, skip, minPoint, filterPoint = () => true) { - this.minPoint = minPoint; - this.filterPoint = filterPoint; - this.active = []; - this.activeTo = []; - this.activeRank = []; - this.minActive = -1; - // A currently active point range, if any - this.point = null; - this.pointFrom = 0; - this.pointRank = 0; - this.to = -1000000000 /* Far */; - this.endSide = 0; - this.openStart = -1; - this.cursor = HeapCursor.from(sets, skip, minPoint); - } - goto(pos, side = -1000000000 /* Far */) { - this.cursor.goto(pos, side); - this.active.length = this.activeTo.length = this.activeRank.length = 0; - this.minActive = -1; - this.to = pos; - this.endSide = side; - this.openStart = -1; - this.next(); - return this; - } - forward(pos, side) { - while (this.minActive > -1 && (this.activeTo[this.minActive] - pos || this.active[this.minActive].endSide - side) < 0) - this.removeActive(this.minActive); - this.cursor.forward(pos, side); - } - removeActive(index) { - remove(this.active, index); - remove(this.activeTo, index); - remove(this.activeRank, index); - this.minActive = findMinIndex(this.active, this.activeTo); - } - addActive(trackOpen) { - let i = 0, { value, to, rank } = this.cursor; - while (i < this.activeRank.length && this.activeRank[i] <= rank) - i++; - insert(this.active, i, value); - insert(this.activeTo, i, to); - insert(this.activeRank, i, rank); - if (trackOpen) - insert(trackOpen, i, this.cursor.from); - this.minActive = findMinIndex(this.active, this.activeTo); - } - // After calling this, if `this.point` != null, the next range is a - // point. Otherwise, it's a regular range, covered by `this.active`. - next() { - let from = this.to, wasPoint = this.point; - this.point = null; - let trackOpen = this.openStart < 0 ? [] : null, trackExtra = 0; - for (;;) { - let a = this.minActive; - if (a > -1 && (this.activeTo[a] - this.cursor.from || this.active[a].endSide - this.cursor.startSide) < 0) { - if (this.activeTo[a] > from) { - this.to = this.activeTo[a]; - this.endSide = this.active[a].endSide; - break; - } - this.removeActive(a); - if (trackOpen) - remove(trackOpen, a); - } - else if (!this.cursor.value) { - this.to = this.endSide = 1000000000 /* Far */; - break; - } - else if (this.cursor.from > from) { - this.to = this.cursor.from; - this.endSide = this.cursor.startSide; - break; - } - else { - let nextVal = this.cursor.value; - if (!nextVal.point) { // Opening a range - this.addActive(trackOpen); - this.cursor.next(); - } - else if (wasPoint && this.cursor.to == this.to && this.cursor.from < this.cursor.to) { - // Ignore any non-empty points that end precisely at the end of the prev point - this.cursor.next(); - } - else if (!this.filterPoint(this.cursor.from, this.cursor.to, this.cursor.value, this.cursor.rank)) { - this.cursor.next(); - } - else { // New point - this.point = nextVal; - this.pointFrom = this.cursor.from; - this.pointRank = this.cursor.rank; - this.to = this.cursor.to; - this.endSide = nextVal.endSide; - if (this.cursor.from < from) - trackExtra = 1; - this.cursor.next(); - this.forward(this.to, this.endSide); - break; - } - } - } - if (trackOpen) { - let openStart = 0; - while (openStart < trackOpen.length && trackOpen[openStart] < from) - openStart++; - this.openStart = openStart + trackExtra; - } - } - activeForPoint(to) { - if (!this.active.length) - return this.active; - let active = []; - for (let i = this.active.length - 1; i >= 0; i--) { - if (this.activeRank[i] < this.pointRank) - break; - if (this.activeTo[i] > to || this.activeTo[i] == to && this.active[i].endSide >= this.point.endSide) - active.push(this.active[i]); - } - return active.reverse(); - } - openEnd(to) { - let open = 0; - for (let i = this.activeTo.length - 1; i >= 0 && this.activeTo[i] > to; i--) - open++; - return open; - } - } - function compare(a, startA, b, startB, length, comparator) { - a.goto(startA); - b.goto(startB); - let endB = startB + length; - let pos = startB, dPos = startB - startA; - for (;;) { - let diff = (a.to + dPos) - b.to || a.endSide - b.endSide; - let end = diff < 0 ? a.to + dPos : b.to, clipEnd = Math.min(end, endB); - if (a.point || b.point) { - if (!(a.point && b.point && (a.point == b.point || a.point.eq(b.point)) && - sameValues(a.activeForPoint(a.to + dPos), b.activeForPoint(b.to)))) - comparator.comparePoint(pos, clipEnd, a.point, b.point); - } - else { - if (clipEnd > pos && !sameValues(a.active, b.active)) - comparator.compareRange(pos, clipEnd, a.active, b.active); - } - if (end > endB) - break; - pos = end; - if (diff <= 0) - a.next(); - if (diff >= 0) - b.next(); - } - } - function sameValues(a, b) { - if (a.length != b.length) - return false; - for (let i = 0; i < a.length; i++) - if (a[i] != b[i] && !a[i].eq(b[i])) - return false; - return true; - } - function remove(array, index) { - for (let i = index, e = array.length - 1; i < e; i++) - array[i] = array[i + 1]; - array.pop(); - } - function insert(array, index, value) { - for (let i = array.length - 1; i >= index; i--) - array[i + 1] = array[i]; - array[index] = value; - } - function findMinIndex(value, array) { - let found = -1, foundPos = 1000000000 /* Far */; - for (let i = 0; i < array.length; i++) - if ((array[i] - foundPos || value[i].endSide - value[found].endSide) < 0) { - found = i; - foundPos = array[i]; - } - return found; - } - - var base = { - 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: "'" - }; - - var shift = { - 48: ")", - 49: "!", - 50: "@", - 51: "#", - 52: "$", - 53: "%", - 54: "^", - 55: "&", - 56: "*", - 57: "(", - 59: ":", - 61: "+", - 173: "_", - 186: ":", - 187: "+", - 188: "<", - 189: "_", - 190: ">", - 191: "?", - 192: "~", - 219: "{", - 220: "|", - 221: "}", - 222: "\"" - }; - - var chrome$1 = typeof navigator != "undefined" && /Chrome\/(\d+)/.exec(navigator.userAgent); - typeof navigator != "undefined" && /Gecko\/\d+/.test(navigator.userAgent); - var mac = typeof navigator != "undefined" && /Mac/.test(navigator.platform); - var ie$1 = typeof navigator != "undefined" && /MSIE \d|Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(navigator.userAgent); - var brokenModifierNames = mac || chrome$1 && +chrome$1[1] < 57; - - // Fill in the digit keys - for (var i = 0; i < 10; i++) base[48 + i] = base[96 + i] = String(i); - - // The function keys - for (var i = 1; i <= 24; i++) base[i + 111] = "F" + i; - - // And the alphabetic keys - for (var i = 65; i <= 90; i++) { - base[i] = String.fromCharCode(i + 32); - shift[i] = String.fromCharCode(i); - } - - // For each code that doesn't have a shift-equivalent, copy the base name - for (var code in base) if (!shift.hasOwnProperty(code)) shift[code] = base[code]; - - function keyName(event) { - var ignoreKey = brokenModifierNames && (event.ctrlKey || event.altKey || event.metaKey) || - ie$1 && event.shiftKey && event.key && event.key.length == 1 || - event.key == "Unidentified"; - var name = (!ignoreKey && event.key) || - (event.shiftKey ? shift : base)[event.keyCode] || - event.key || "Unidentified"; - // Edge sometimes produces wrong names (Issue #3) - if (name == "Esc") name = "Escape"; - if (name == "Del") name = "Delete"; - // https://developer.microsoft.com/en-us/microsoft-edge/platform/issues/8860571/ - if (name == "Left") name = "ArrowLeft"; - if (name == "Up") name = "ArrowUp"; - if (name == "Right") name = "ArrowRight"; - if (name == "Down") name = "ArrowDown"; - return name - } - - function getSelection(root) { - let target; - // Browsers differ on whether shadow roots have a getSelection - // method. If it exists, use that, otherwise, call it on the - // document. - if (root.nodeType == 11) { // Shadow root - target = root.getSelection ? root : root.ownerDocument; - } - else { - target = root; - } - return target.getSelection(); - } - function contains(dom, node) { - return node ? dom == node || dom.contains(node.nodeType != 1 ? node.parentNode : node) : false; - } - function deepActiveElement() { - let elt = document.activeElement; - while (elt && elt.shadowRoot) - elt = elt.shadowRoot.activeElement; - return elt; - } - function hasSelection(dom, selection) { - if (!selection.anchorNode) - return false; - try { - // Firefox will raise 'permission denied' errors when accessing - // properties of `sel.anchorNode` when it's in a generated CSS - // element. - return contains(dom, selection.anchorNode); - } - catch (_) { - return false; - } - } - function clientRectsFor(dom) { - if (dom.nodeType == 3) - return textRange(dom, 0, dom.nodeValue.length).getClientRects(); - else if (dom.nodeType == 1) - return dom.getClientRects(); - else - return []; - } - // Scans forward and backward through DOM positions equivalent to the - // given one to see if the two are in the same place (i.e. after a - // text node vs at the end of that text node) - function isEquivalentPosition(node, off, targetNode, targetOff) { - return targetNode ? (scanFor(node, off, targetNode, targetOff, -1) || - scanFor(node, off, targetNode, targetOff, 1)) : false; - } - function domIndex(node) { - for (var index = 0;; index++) { - node = node.previousSibling; - if (!node) - return index; - } - } - function scanFor(node, off, targetNode, targetOff, dir) { - for (;;) { - if (node == targetNode && off == targetOff) - return true; - if (off == (dir < 0 ? 0 : maxOffset(node))) { - if (node.nodeName == "DIV") - return false; - let parent = node.parentNode; - if (!parent || parent.nodeType != 1) - return false; - off = domIndex(node) + (dir < 0 ? 0 : 1); - node = parent; - } - else if (node.nodeType == 1) { - node = node.childNodes[off + (dir < 0 ? -1 : 0)]; - if (node.nodeType == 1 && node.contentEditable == "false") - return false; - off = dir < 0 ? maxOffset(node) : 0; - } - else { - return false; - } - } - } - function maxOffset(node) { - return node.nodeType == 3 ? node.nodeValue.length : node.childNodes.length; - } - const Rect0 = { left: 0, right: 0, top: 0, bottom: 0 }; - function flattenRect(rect, left) { - let x = left ? rect.left : rect.right; - return { left: x, right: x, top: rect.top, bottom: rect.bottom }; - } - function windowRect(win) { - return { left: 0, right: win.innerWidth, - top: 0, bottom: win.innerHeight }; - } - function scrollRectIntoView(dom, rect, side, x, y, xMargin, yMargin, ltr) { - let doc = dom.ownerDocument, win = doc.defaultView; - for (let cur = dom; cur;) { - if (cur.nodeType == 1) { // Element - let bounding, top = cur == doc.body; - if (top) { - bounding = windowRect(win); - } - else { - if (cur.scrollHeight <= cur.clientHeight && cur.scrollWidth <= cur.clientWidth) { - cur = cur.parentNode; - continue; - } - let rect = cur.getBoundingClientRect(); - // Make sure scrollbar width isn't included in the rectangle - bounding = { left: rect.left, right: rect.left + cur.clientWidth, - top: rect.top, bottom: rect.top + cur.clientHeight }; - } - let moveX = 0, moveY = 0; - if (y == "nearest") { - if (rect.top < bounding.top) { - moveY = -(bounding.top - rect.top + yMargin); - if (side > 0 && rect.bottom > bounding.bottom + moveY) - moveY = rect.bottom - bounding.bottom + moveY + yMargin; - } - else if (rect.bottom > bounding.bottom) { - moveY = rect.bottom - bounding.bottom + yMargin; - if (side < 0 && (rect.top - moveY) < bounding.top) - moveY = -(bounding.top + moveY - rect.top + yMargin); - } - } - else { - let rectHeight = rect.bottom - rect.top, boundingHeight = bounding.bottom - bounding.top; - let targetTop = y == "center" && rectHeight <= boundingHeight ? rect.top + rectHeight / 2 - boundingHeight / 2 : - y == "start" || y == "center" && side < 0 ? rect.top - yMargin : - rect.bottom - boundingHeight + yMargin; - moveY = targetTop - bounding.top; - } - if (x == "nearest") { - if (rect.left < bounding.left) { - moveX = -(bounding.left - rect.left + xMargin); - if (side > 0 && rect.right > bounding.right + moveX) - moveX = rect.right - bounding.right + moveX + xMargin; - } - else if (rect.right > bounding.right) { - moveX = rect.right - bounding.right + xMargin; - if (side < 0 && rect.left < bounding.left + moveX) - moveX = -(bounding.left + moveX - rect.left + xMargin); - } - } - else { - let targetLeft = x == "center" ? rect.left + (rect.right - rect.left) / 2 - (bounding.right - bounding.left) / 2 : - (x == "start") == ltr ? rect.left - xMargin : - rect.right - (bounding.right - bounding.left) + xMargin; - moveX = targetLeft - bounding.left; - } - if (moveX || moveY) { - if (top) { - win.scrollBy(moveX, moveY); - } - else { - if (moveY) { - let start = cur.scrollTop; - cur.scrollTop += moveY; - moveY = cur.scrollTop - start; - } - if (moveX) { - let start = cur.scrollLeft; - cur.scrollLeft += moveX; - moveX = cur.scrollLeft - start; - } - rect = { left: rect.left - moveX, top: rect.top - moveY, - right: rect.right - moveX, bottom: rect.bottom - moveY }; - } - } - if (top) - break; - cur = cur.assignedSlot || cur.parentNode; - x = y = "nearest"; - } - else if (cur.nodeType == 11) { // A shadow root - cur = cur.host; - } - else { - break; - } - } - } - class DOMSelectionState { - constructor() { - this.anchorNode = null; - this.anchorOffset = 0; - this.focusNode = null; - this.focusOffset = 0; - } - eq(domSel) { - return this.anchorNode == domSel.anchorNode && this.anchorOffset == domSel.anchorOffset && - this.focusNode == domSel.focusNode && this.focusOffset == domSel.focusOffset; - } - setRange(range) { - this.set(range.anchorNode, range.anchorOffset, range.focusNode, range.focusOffset); - } - set(anchorNode, anchorOffset, focusNode, focusOffset) { - this.anchorNode = anchorNode; - this.anchorOffset = anchorOffset; - this.focusNode = focusNode; - this.focusOffset = focusOffset; - } - } - let preventScrollSupported = null; - // Feature-detects support for .focus({preventScroll: true}), and uses - // a fallback kludge when not supported. - function focusPreventScroll(dom) { - if (dom.setActive) - return dom.setActive(); // in IE - if (preventScrollSupported) - return dom.focus(preventScrollSupported); - let stack = []; - for (let cur = dom; cur; cur = cur.parentNode) { - stack.push(cur, cur.scrollTop, cur.scrollLeft); - if (cur == cur.ownerDocument) - break; - } - dom.focus(preventScrollSupported == null ? { - get preventScroll() { - preventScrollSupported = { preventScroll: true }; - return true; - } - } : undefined); - if (!preventScrollSupported) { - preventScrollSupported = false; - for (let i = 0; i < stack.length;) { - let elt = stack[i++], top = stack[i++], left = stack[i++]; - if (elt.scrollTop != top) - elt.scrollTop = top; - if (elt.scrollLeft != left) - elt.scrollLeft = left; - } - } - } - let scratchRange; - function textRange(node, from, to = from) { - let range = scratchRange || (scratchRange = document.createRange()); - range.setEnd(node, to); - range.setStart(node, from); - return range; - } - function dispatchKey(elt, name, code) { - let options = { key: name, code: name, keyCode: code, which: code, cancelable: true }; - let down = new KeyboardEvent("keydown", options); - down.synthetic = true; - elt.dispatchEvent(down); - let up = new KeyboardEvent("keyup", options); - up.synthetic = true; - elt.dispatchEvent(up); - return down.defaultPrevented || up.defaultPrevented; - } - function getRoot(node) { - while (node) { - if (node && (node.nodeType == 9 || node.nodeType == 11 && node.host)) - return node; - node = node.assignedSlot || node.parentNode; - } - return null; - } - function clearAttributes(node) { - while (node.attributes.length) - node.removeAttributeNode(node.attributes[0]); - } - - class DOMPos { - constructor(node, offset, precise = true) { - this.node = node; - this.offset = offset; - this.precise = precise; - } - static before(dom, precise) { return new DOMPos(dom.parentNode, domIndex(dom), precise); } - static after(dom, precise) { return new DOMPos(dom.parentNode, domIndex(dom) + 1, precise); } - } - const noChildren = []; - class ContentView { - constructor() { - this.parent = null; - this.dom = null; - this.dirty = 2 /* Node */; - } - get editorView() { - if (!this.parent) - throw new Error("Accessing view in orphan content view"); - return this.parent.editorView; - } - get overrideDOMText() { return null; } - get posAtStart() { - return this.parent ? this.parent.posBefore(this) : 0; - } - get posAtEnd() { - return this.posAtStart + this.length; - } - posBefore(view) { - let pos = this.posAtStart; - for (let child of this.children) { - if (child == view) - return pos; - pos += child.length + child.breakAfter; - } - throw new RangeError("Invalid child in posBefore"); - } - posAfter(view) { - return this.posBefore(view) + view.length; - } - // Will return a rectangle directly before (when side < 0), after - // (side > 0) or directly on (when the browser supports it) the - // given position. - coordsAt(_pos, _side) { return null; } - sync(track) { - if (this.dirty & 2 /* Node */) { - let parent = this.dom; - let prev = null, next; - for (let child of this.children) { - if (child.dirty) { - if (!child.dom && (next = prev ? prev.nextSibling : parent.firstChild)) { - let contentView = ContentView.get(next); - if (!contentView || !contentView.parent && contentView.constructor == child.constructor) - child.reuseDOM(next); - } - child.sync(track); - child.dirty = 0 /* Not */; - } - next = prev ? prev.nextSibling : parent.firstChild; - if (track && !track.written && track.node == parent && next != child.dom) - track.written = true; - if (child.dom.parentNode == parent) { - while (next && next != child.dom) - next = rm$1(next); - } - else { - parent.insertBefore(child.dom, next); - } - prev = child.dom; - } - next = prev ? prev.nextSibling : parent.firstChild; - if (next && track && track.node == parent) - track.written = true; - while (next) - next = rm$1(next); - } - else if (this.dirty & 1 /* Child */) { - for (let child of this.children) - if (child.dirty) { - child.sync(track); - child.dirty = 0 /* Not */; - } - } - } - reuseDOM(_dom) { } - localPosFromDOM(node, offset) { - let after; - if (node == this.dom) { - after = this.dom.childNodes[offset]; - } - else { - let bias = maxOffset(node) == 0 ? 0 : offset == 0 ? -1 : 1; - for (;;) { - let parent = node.parentNode; - if (parent == this.dom) - break; - if (bias == 0 && parent.firstChild != parent.lastChild) { - if (node == parent.firstChild) - bias = -1; - else - bias = 1; - } - node = parent; - } - if (bias < 0) - after = node; - else - after = node.nextSibling; - } - if (after == this.dom.firstChild) - return 0; - while (after && !ContentView.get(after)) - after = after.nextSibling; - if (!after) - return this.length; - for (let i = 0, pos = 0;; i++) { - let child = this.children[i]; - if (child.dom == after) - return pos; - pos += child.length + child.breakAfter; - } - } - domBoundsAround(from, to, offset = 0) { - let fromI = -1, fromStart = -1, toI = -1, toEnd = -1; - for (let i = 0, pos = offset, prevEnd = offset; i < this.children.length; i++) { - let child = this.children[i], end = pos + child.length; - if (pos < from && end > to) - return child.domBoundsAround(from, to, pos); - if (end >= from && fromI == -1) { - fromI = i; - fromStart = pos; - } - if (pos > to && child.dom.parentNode == this.dom) { - toI = i; - toEnd = prevEnd; - break; - } - prevEnd = end; - pos = end + child.breakAfter; - } - return { from: fromStart, to: toEnd < 0 ? offset + this.length : toEnd, - startDOM: (fromI ? this.children[fromI - 1].dom.nextSibling : null) || this.dom.firstChild, - endDOM: toI < this.children.length && toI >= 0 ? this.children[toI].dom : null }; - } - markDirty(andParent = false) { - this.dirty |= 2 /* Node */; - this.markParentsDirty(andParent); - } - markParentsDirty(childList) { - for (let parent = this.parent; parent; parent = parent.parent) { - if (childList) - parent.dirty |= 2 /* Node */; - if (parent.dirty & 1 /* Child */) - return; - parent.dirty |= 1 /* Child */; - childList = false; - } - } - setParent(parent) { - if (this.parent != parent) { - this.parent = parent; - if (this.dirty) - this.markParentsDirty(true); - } - } - setDOM(dom) { - if (this.dom) - this.dom.cmView = null; - this.dom = dom; - dom.cmView = this; - } - get rootView() { - for (let v = this;;) { - let parent = v.parent; - if (!parent) - return v; - v = parent; - } - } - replaceChildren(from, to, children = noChildren) { - this.markDirty(); - for (let i = from; i < to; i++) { - let child = this.children[i]; - if (child.parent == this) - child.destroy(); - } - this.children.splice(from, to - from, ...children); - for (let i = 0; i < children.length; i++) - children[i].setParent(this); - } - ignoreMutation(_rec) { return false; } - ignoreEvent(_event) { return false; } - childCursor(pos = this.length) { - return new ChildCursor(this.children, pos, this.children.length); - } - childPos(pos, bias = 1) { - return this.childCursor().findPos(pos, bias); - } - toString() { - let name = this.constructor.name.replace("View", ""); - return name + (this.children.length ? "(" + this.children.join() + ")" : - this.length ? "[" + (name == "Text" ? this.text : this.length) + "]" : "") + - (this.breakAfter ? "#" : ""); - } - static get(node) { return node.cmView; } - get isEditable() { return true; } - merge(from, to, source, hasStart, openStart, openEnd) { - return false; - } - become(other) { return false; } - // When this is a zero-length view with a side, this should return a - // number <= 0 to indicate it is before its position, or a - // number > 0 when after its position. - getSide() { return 0; } - destroy() { - this.parent = null; - } - } - ContentView.prototype.breakAfter = 0; - // Remove a DOM node and return its next sibling. - function rm$1(dom) { - let next = dom.nextSibling; - dom.parentNode.removeChild(dom); - return next; - } - class ChildCursor { - constructor(children, pos, i) { - this.children = children; - this.pos = pos; - this.i = i; - this.off = 0; - } - findPos(pos, bias = 1) { - for (;;) { - if (pos > this.pos || pos == this.pos && - (bias > 0 || this.i == 0 || this.children[this.i - 1].breakAfter)) { - this.off = pos - this.pos; - return this; - } - let next = this.children[--this.i]; - this.pos -= next.length + next.breakAfter; - } - } - } - function replaceRange(parent, fromI, fromOff, toI, toOff, insert, breakAtStart, openStart, openEnd) { - let { children } = parent; - let before = children.length ? children[fromI] : null; - let last = insert.length ? insert[insert.length - 1] : null; - let breakAtEnd = last ? last.breakAfter : breakAtStart; - // Change within a single child - if (fromI == toI && before && !breakAtStart && !breakAtEnd && insert.length < 2 && - before.merge(fromOff, toOff, insert.length ? last : null, fromOff == 0, openStart, openEnd)) - return; - if (toI < children.length) { - let after = children[toI]; - // Make sure the end of the child after the update is preserved in `after` - if (after && toOff < after.length) { - // If we're splitting a child, separate part of it to avoid that - // being mangled when updating the child before the update. - if (fromI == toI) { - after = after.split(toOff); - toOff = 0; - } - // If the element after the replacement should be merged with - // the last replacing element, update `content` - if (!breakAtEnd && last && after.merge(0, toOff, last, true, 0, openEnd)) { - insert[insert.length - 1] = after; - } - else { - // Remove the start of the after element, if necessary, and - // add it to `content`. - if (toOff) - after.merge(0, toOff, null, false, 0, openEnd); - insert.push(after); - } - } - else if (after === null || after === void 0 ? void 0 : after.breakAfter) { - // The element at `toI` is entirely covered by this range. - // Preserve its line break, if any. - if (last) - last.breakAfter = 1; - else - breakAtStart = 1; - } - // Since we've handled the next element from the current elements - // now, make sure `toI` points after that. - toI++; - } - if (before) { - before.breakAfter = breakAtStart; - if (fromOff > 0) { - if (!breakAtStart && insert.length && before.merge(fromOff, before.length, insert[0], false, openStart, 0)) { - before.breakAfter = insert.shift().breakAfter; - } - else if (fromOff < before.length || before.children.length && before.children[before.children.length - 1].length == 0) { - before.merge(fromOff, before.length, null, false, openStart, 0); - } - fromI++; - } - } - // Try to merge widgets on the boundaries of the replacement - while (fromI < toI && insert.length) { - if (children[toI - 1].become(insert[insert.length - 1])) { - toI--; - insert.pop(); - openEnd = insert.length ? 0 : openStart; - } - else if (children[fromI].become(insert[0])) { - fromI++; - insert.shift(); - openStart = insert.length ? 0 : openEnd; - } - else { - break; - } - } - if (!insert.length && fromI && toI < children.length && !children[fromI - 1].breakAfter && - children[toI].merge(0, 0, children[fromI - 1], false, openStart, openEnd)) - fromI--; - if (fromI < toI || insert.length) - parent.replaceChildren(fromI, toI, insert); - } - function mergeChildrenInto(parent, from, to, insert, openStart, openEnd) { - let cur = parent.childCursor(); - let { i: toI, off: toOff } = cur.findPos(to, 1); - let { i: fromI, off: fromOff } = cur.findPos(from, -1); - let dLen = from - to; - for (let view of insert) - dLen += view.length; - parent.length += dLen; - replaceRange(parent, fromI, fromOff, toI, toOff, insert, 0, openStart, openEnd); - } - - let nav = typeof navigator != "undefined" ? navigator : { userAgent: "", vendor: "", platform: "" }; - let doc = typeof document != "undefined" ? document : { documentElement: { style: {} } }; - const ie_edge = /*@__PURE__*//Edge\/(\d+)/.exec(nav.userAgent); - const ie_upto10 = /*@__PURE__*//MSIE \d/.test(nav.userAgent); - const ie_11up = /*@__PURE__*//Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(nav.userAgent); - const ie = !!(ie_upto10 || ie_11up || ie_edge); - const gecko = !ie && /*@__PURE__*//gecko\/(\d+)/i.test(nav.userAgent); - const chrome = !ie && /*@__PURE__*//Chrome\/(\d+)/.exec(nav.userAgent); - const webkit = "webkitFontSmoothing" in doc.documentElement.style; - const safari = !ie && /*@__PURE__*//Apple Computer/.test(nav.vendor); - const ios$1 = safari && (/*@__PURE__*//Mobile\/\w+/.test(nav.userAgent) || nav.maxTouchPoints > 2); - var browser = { - mac: ios$1 || /*@__PURE__*//Mac/.test(nav.platform), - windows: /*@__PURE__*//Win/.test(nav.platform), - linux: /*@__PURE__*//Linux|X11/.test(nav.platform), - ie, - ie_version: ie_upto10 ? doc.documentMode || 6 : ie_11up ? +ie_11up[1] : ie_edge ? +ie_edge[1] : 0, - gecko, - gecko_version: gecko ? +(/*@__PURE__*//Firefox\/(\d+)/.exec(nav.userAgent) || [0, 0])[1] : 0, - chrome: !!chrome, - chrome_version: chrome ? +chrome[1] : 0, - ios: ios$1, - android: /*@__PURE__*//Android\b/.test(nav.userAgent), - webkit, - safari, - webkit_version: webkit ? +(/*@__PURE__*//\bAppleWebKit\/(\d+)/.exec(navigator.userAgent) || [0, 0])[1] : 0, - tabSize: doc.documentElement.style.tabSize != null ? "tab-size" : "-moz-tab-size" - }; - - const MaxJoinLen = 256; - class TextView extends ContentView { - constructor(text) { - super(); - this.text = text; - } - get length() { return this.text.length; } - createDOM(textDOM) { - this.setDOM(textDOM || document.createTextNode(this.text)); - } - sync(track) { - if (!this.dom) - this.createDOM(); - if (this.dom.nodeValue != this.text) { - if (track && track.node == this.dom) - track.written = true; - this.dom.nodeValue = this.text; - } - } - reuseDOM(dom) { - if (dom.nodeType == 3) - this.createDOM(dom); - } - merge(from, to, source) { - if (source && (!(source instanceof TextView) || this.length - (to - from) + source.length > MaxJoinLen)) - return false; - this.text = this.text.slice(0, from) + (source ? source.text : "") + this.text.slice(to); - this.markDirty(); - return true; - } - split(from) { - let result = new TextView(this.text.slice(from)); - this.text = this.text.slice(0, from); - this.markDirty(); - return result; - } - localPosFromDOM(node, offset) { - return node == this.dom ? offset : offset ? this.text.length : 0; - } - domAtPos(pos) { return new DOMPos(this.dom, pos); } - domBoundsAround(_from, _to, offset) { - return { from: offset, to: offset + this.length, startDOM: this.dom, endDOM: this.dom.nextSibling }; - } - coordsAt(pos, side) { - return textCoords(this.dom, pos, side); - } - } - class MarkView extends ContentView { - constructor(mark, children = [], length = 0) { - super(); - this.mark = mark; - this.children = children; - this.length = length; - for (let ch of children) - ch.setParent(this); - } - setAttrs(dom) { - clearAttributes(dom); - if (this.mark.class) - dom.className = this.mark.class; - if (this.mark.attrs) - for (let name in this.mark.attrs) - dom.setAttribute(name, this.mark.attrs[name]); - return dom; - } - reuseDOM(node) { - if (node.nodeName == this.mark.tagName.toUpperCase()) { - this.setDOM(node); - this.dirty |= 4 /* Attrs */ | 2 /* Node */; - } - } - sync(track) { - if (!this.dom) - this.setDOM(this.setAttrs(document.createElement(this.mark.tagName))); - else if (this.dirty & 4 /* Attrs */) - this.setAttrs(this.dom); - super.sync(track); - } - merge(from, to, source, _hasStart, openStart, openEnd) { - if (source && (!(source instanceof MarkView && source.mark.eq(this.mark)) || - (from && openStart <= 0) || (to < this.length && openEnd <= 0))) - return false; - mergeChildrenInto(this, from, to, source ? source.children : [], openStart - 1, openEnd - 1); - this.markDirty(); - return true; - } - split(from) { - let result = [], off = 0, detachFrom = -1, i = 0; - for (let elt of this.children) { - let end = off + elt.length; - if (end > from) - result.push(off < from ? elt.split(from - off) : elt); - if (detachFrom < 0 && off >= from) - detachFrom = i; - off = end; - i++; - } - let length = this.length - from; - this.length = from; - if (detachFrom > -1) { - this.children.length = detachFrom; - this.markDirty(); - } - return new MarkView(this.mark, result, length); - } - domAtPos(pos) { - return inlineDOMAtPos(this.dom, this.children, pos); - } - coordsAt(pos, side) { - return coordsInChildren(this, pos, side); - } - } - function textCoords(text, pos, side) { - let length = text.nodeValue.length; - if (pos > length) - pos = length; - let from = pos, to = pos, flatten = 0; - if (pos == 0 && side < 0 || pos == length && side >= 0) { - if (!(browser.chrome || browser.gecko)) { // These browsers reliably return valid rectangles for empty ranges - if (pos) { - from--; - flatten = 1; - } // FIXME this is wrong in RTL text - else { - to++; - flatten = -1; - } - } - } - else { - if (side < 0) - from--; - else - to++; - } - let rects = textRange(text, from, to).getClientRects(); - if (!rects.length) - return Rect0; - let rect = rects[(flatten ? flatten < 0 : side >= 0) ? 0 : rects.length - 1]; - if (browser.safari && !flatten && rect.width == 0) - rect = Array.prototype.find.call(rects, r => r.width) || rect; - return flatten ? flattenRect(rect, flatten < 0) : rect || null; - } - // Also used for collapsed ranges that don't have a placeholder widget! - class WidgetView extends ContentView { - constructor(widget, length, side) { - super(); - this.widget = widget; - this.length = length; - this.side = side; - this.prevWidget = null; - } - static create(widget, length, side) { - return new (widget.customView || WidgetView)(widget, length, side); - } - split(from) { - let result = WidgetView.create(this.widget, this.length - from, this.side); - this.length -= from; - return result; - } - sync() { - if (!this.dom || !this.widget.updateDOM(this.dom)) { - if (this.dom && this.prevWidget) - this.prevWidget.destroy(this.dom); - this.prevWidget = null; - this.setDOM(this.widget.toDOM(this.editorView)); - this.dom.contentEditable = "false"; - } - } - getSide() { return this.side; } - merge(from, to, source, hasStart, openStart, openEnd) { - if (source && (!(source instanceof WidgetView) || !this.widget.compare(source.widget) || - from > 0 && openStart <= 0 || to < this.length && openEnd <= 0)) - return false; - this.length = from + (source ? source.length : 0) + (this.length - to); - return true; - } - become(other) { - if (other.length == this.length && other instanceof WidgetView && other.side == this.side) { - if (this.widget.constructor == other.widget.constructor) { - if (!this.widget.eq(other.widget)) - this.markDirty(true); - if (this.dom && !this.prevWidget) - this.prevWidget = this.widget; - this.widget = other.widget; - return true; - } - } - return false; - } - ignoreMutation() { return true; } - ignoreEvent(event) { return this.widget.ignoreEvent(event); } - get overrideDOMText() { - if (this.length == 0) - return Text.empty; - let top = this; - while (top.parent) - top = top.parent; - let view = top.editorView, text = view && view.state.doc, start = this.posAtStart; - return text ? text.slice(start, start + this.length) : Text.empty; - } - domAtPos(pos) { - return pos == 0 ? DOMPos.before(this.dom) : DOMPos.after(this.dom, pos == this.length); - } - domBoundsAround() { return null; } - coordsAt(pos, side) { - let rects = this.dom.getClientRects(), rect = null; - if (!rects.length) - return Rect0; - for (let i = pos > 0 ? rects.length - 1 : 0;; i += (pos > 0 ? -1 : 1)) { - rect = rects[i]; - if (pos > 0 ? i == 0 : i == rects.length - 1 || rect.top < rect.bottom) - break; - } - return (pos == 0 && side > 0 || pos == this.length && side <= 0) ? rect : flattenRect(rect, pos == 0); - } - get isEditable() { return false; } - destroy() { - super.destroy(); - if (this.dom) - this.widget.destroy(this.dom); - } - } - class CompositionView extends WidgetView { - domAtPos(pos) { - let { topView, text } = this.widget; - if (!topView) - return new DOMPos(text, Math.min(pos, text.nodeValue.length)); - return scanCompositionTree(pos, 0, topView, text, (v, p) => v.domAtPos(p), p => new DOMPos(text, Math.min(p, text.nodeValue.length))); - } - sync() { this.setDOM(this.widget.toDOM()); } - localPosFromDOM(node, offset) { - let { topView, text } = this.widget; - if (!topView) - return Math.min(offset, this.length); - return posFromDOMInCompositionTree(node, offset, topView, text); - } - ignoreMutation() { return false; } - get overrideDOMText() { return null; } - coordsAt(pos, side) { - let { topView, text } = this.widget; - if (!topView) - return textCoords(text, pos, side); - return scanCompositionTree(pos, side, topView, text, (v, pos, side) => v.coordsAt(pos, side), (pos, side) => textCoords(text, pos, side)); - } - destroy() { - var _a; - super.destroy(); - (_a = this.widget.topView) === null || _a === void 0 ? void 0 : _a.destroy(); - } - get isEditable() { return true; } - } - // Uses the old structure of a chunk of content view frozen for - // composition to try and find a reasonable DOM location for the given - // offset. - function scanCompositionTree(pos, side, view, text, enterView, fromText) { - if (view instanceof MarkView) { - for (let child of view.children) { - let hasComp = contains(child.dom, text); - let len = hasComp ? text.nodeValue.length : child.length; - if (pos < len || pos == len && child.getSide() <= 0) - return hasComp ? scanCompositionTree(pos, side, child, text, enterView, fromText) : enterView(child, pos, side); - pos -= len; - } - return enterView(view, view.length, -1); - } - else if (view.dom == text) { - return fromText(pos, side); - } - else { - return enterView(view, pos, side); - } - } - function posFromDOMInCompositionTree(node, offset, view, text) { - if (view instanceof MarkView) { - for (let child of view.children) { - let pos = 0, hasComp = contains(child.dom, text); - if (contains(child.dom, node)) - return pos + (hasComp ? posFromDOMInCompositionTree(node, offset, child, text) : child.localPosFromDOM(node, offset)); - pos += hasComp ? text.nodeValue.length : child.length; - } - } - else if (view.dom == text) { - return Math.min(offset, text.nodeValue.length); - } - return view.localPosFromDOM(node, offset); - } - // These are drawn around uneditable widgets to avoid a number of - // browser bugs that show up when the cursor is directly next to - // uneditable inline content. - class WidgetBufferView extends ContentView { - constructor(side) { - super(); - this.side = side; - } - get length() { return 0; } - merge() { return false; } - become(other) { - return other instanceof WidgetBufferView && other.side == this.side; - } - split() { return new WidgetBufferView(this.side); } - sync() { - if (!this.dom) { - let dom = document.createElement("img"); - dom.className = "cm-widgetBuffer"; - dom.setAttribute("aria-hidden", "true"); - this.setDOM(dom); - } - } - getSide() { return this.side; } - domAtPos(pos) { return DOMPos.before(this.dom); } - localPosFromDOM() { return 0; } - domBoundsAround() { return null; } - coordsAt(pos) { - let imgRect = this.dom.getBoundingClientRect(); - // Since the <img> height doesn't correspond to text height, try - // to borrow the height from some sibling node. - let siblingRect = inlineSiblingRect(this, this.side > 0 ? -1 : 1); - return siblingRect && siblingRect.top < imgRect.bottom && siblingRect.bottom > imgRect.top - ? { left: imgRect.left, right: imgRect.right, top: siblingRect.top, bottom: siblingRect.bottom } : imgRect; - } - get overrideDOMText() { - return Text.empty; - } - } - TextView.prototype.children = WidgetView.prototype.children = WidgetBufferView.prototype.children = noChildren; - function inlineSiblingRect(view, side) { - let parent = view.parent, index = parent ? parent.children.indexOf(view) : -1; - while (parent && index >= 0) { - if (side < 0 ? index > 0 : index < parent.children.length) { - let next = parent.children[index + side]; - if (next instanceof TextView) { - let nextRect = next.coordsAt(side < 0 ? next.length : 0, side); - if (nextRect) - return nextRect; - } - index += side; - } - else if (parent instanceof MarkView && parent.parent) { - index = parent.parent.children.indexOf(parent) + (side < 0 ? 0 : 1); - parent = parent.parent; - } - else { - let last = parent.dom.lastChild; - if (last && last.nodeName == "BR") - return last.getClientRects()[0]; - break; - } - } - return undefined; - } - function inlineDOMAtPos(dom, children, pos) { - let i = 0; - for (let off = 0; i < children.length; i++) { - let child = children[i], end = off + child.length; - if (end == off && child.getSide() <= 0) - continue; - if (pos > off && pos < end && child.dom.parentNode == dom) - return child.domAtPos(pos - off); - if (pos <= off) - break; - off = end; - } - for (; i > 0; i--) { - let before = children[i - 1].dom; - if (before.parentNode == dom) - return DOMPos.after(before); - } - return new DOMPos(dom, 0); - } - // Assumes `view`, if a mark view, has precisely 1 child. - function joinInlineInto(parent, view, open) { - let last, { children } = parent; - if (open > 0 && view instanceof MarkView && children.length && - (last = children[children.length - 1]) instanceof MarkView && last.mark.eq(view.mark)) { - joinInlineInto(last, view.children[0], open - 1); - } - else { - children.push(view); - view.setParent(parent); - } - parent.length += view.length; - } - function coordsInChildren(view, pos, side) { - for (let off = 0, i = 0; i < view.children.length; i++) { - let child = view.children[i], end = off + child.length, next; - if ((side <= 0 || end == view.length || child.getSide() > 0 ? end >= pos : end > pos) && - (pos < end || i + 1 == view.children.length || (next = view.children[i + 1]).length || next.getSide() > 0)) { - let flatten = 0; - if (end == off) { - if (child.getSide() <= 0) - continue; - flatten = side = -child.getSide(); - } - let rect = child.coordsAt(Math.max(0, pos - off), side); - return flatten && rect ? flattenRect(rect, side < 0) : rect; - } - off = end; - } - let last = view.dom.lastChild; - if (!last) - return view.dom.getBoundingClientRect(); - let rects = clientRectsFor(last); - return rects[rects.length - 1] || null; - } - - function combineAttrs(source, target) { - for (let name in source) { - if (name == "class" && target.class) - target.class += " " + source.class; - else if (name == "style" && target.style) - target.style += ";" + source.style; - else - target[name] = source[name]; - } - return target; - } - function attrsEq(a, b) { - if (a == b) - return true; - if (!a || !b) - return false; - let keysA = Object.keys(a), keysB = Object.keys(b); - if (keysA.length != keysB.length) - return false; - for (let key of keysA) { - if (keysB.indexOf(key) == -1 || a[key] !== b[key]) - return false; - } - return true; - } - function updateAttrs(dom, prev, attrs) { - if (prev) - for (let name in prev) - if (!(attrs && name in attrs)) - dom.removeAttribute(name); - if (attrs) - for (let name in attrs) - if (!(prev && prev[name] == attrs[name])) - dom.setAttribute(name, attrs[name]); - } - - /** - Widgets added to the content are described by subclasses of this - class. Using a description object like that makes it possible to - delay creating of the DOM structure for a widget until it is - needed, and to avoid redrawing widgets even when the decorations - that define them are recreated. - */ - class WidgetType { - /** - Compare this instance to another instance of the same type. - (TypeScript can't express this, but only instances of the same - specific class will be passed to this method.) This is used to - avoid redrawing widgets when they are replaced by a new - decoration of the same type. The default implementation just - returns `false`, which will cause new instances of the widget to - always be redrawn. - */ - eq(_widget) { return false; } - /** - Update a DOM element created by a widget of the same type (but - different, non-`eq` content) to reflect this widget. May return - true to indicate that it could update, false to indicate it - couldn't (in which case the widget will be redrawn). The default - implementation just returns false. - */ - updateDOM(_dom) { return false; } - /** - @internal - */ - compare(other) { - return this == other || this.constructor == other.constructor && this.eq(other); - } - /** - The estimated height this widget will have, to be used when - estimating the height of content that hasn't been drawn. May - return -1 to indicate you don't know. The default implementation - returns -1. - */ - get estimatedHeight() { return -1; } - /** - Can be used to configure which kinds of events inside the widget - should be ignored by the editor. The default is to ignore all - events. - */ - ignoreEvent(_event) { return true; } - /** - @internal - */ - get customView() { return null; } - /** - This is called when the an instance of the widget is removed - from the editor view. - */ - destroy(_dom) { } - } - /** - The different types of blocks that can occur in an editor view. - */ - var BlockType = /*@__PURE__*/(function (BlockType) { - /** - A line of text. - */ - BlockType[BlockType["Text"] = 0] = "Text"; - /** - A block widget associated with the position after it. - */ - BlockType[BlockType["WidgetBefore"] = 1] = "WidgetBefore"; - /** - A block widget associated with the position before it. - */ - BlockType[BlockType["WidgetAfter"] = 2] = "WidgetAfter"; - /** - A block widget [replacing](https://codemirror.net/6/docs/ref/#view.Decoration^replace) a range of content. - */ - BlockType[BlockType["WidgetRange"] = 3] = "WidgetRange"; - return BlockType})(BlockType || (BlockType = {})); - /** - A decoration provides information on how to draw or style a piece - of content. You'll usually use it wrapped in a - [`Range`](https://codemirror.net/6/docs/ref/#rangeset.Range), which adds a start and end position. - */ - class Decoration extends RangeValue { - /** - @internal - */ - constructor( - /** - @internal - */ - startSide, - /** - @internal - */ - endSide, - /** - @internal - */ - widget, - /** - The config object used to create this decoration. You can - include additional properties in there to store metadata about - your decoration. - */ - spec) { - super(); - this.startSide = startSide; - this.endSide = endSide; - this.widget = widget; - this.spec = spec; - } - /** - @internal - */ - get heightRelevant() { return false; } - /** - Create a mark decoration, which influences the styling of the - content in its range. Nested mark decorations will cause nested - DOM elements to be created. Nesting order is determined by - precedence of the [facet](https://codemirror.net/6/docs/ref/#view.EditorView^decorations) or - (below the facet-provided decorations) [view - plugin](https://codemirror.net/6/docs/ref/#view.PluginSpec.decorations). Such elements are split - on line boundaries and on the boundaries of higher-precedence - decorations. - */ - static mark(spec) { - return new MarkDecoration(spec); - } - /** - Create a widget decoration, which adds an element at the given - position. - */ - static widget(spec) { - let side = spec.side || 0, block = !!spec.block; - side += block ? (side > 0 ? 300000000 /* BlockAfter */ : -400000000 /* BlockBefore */) : (side > 0 ? 100000000 /* InlineAfter */ : -100000000 /* InlineBefore */); - return new PointDecoration(spec, side, side, block, spec.widget || null, false); - } - /** - Create a replace decoration which replaces the given range with - a widget, or simply hides it. - */ - static replace(spec) { - let block = !!spec.block, startSide, endSide; - if (spec.isBlockGap) { - startSide = -500000000 /* GapStart */; - endSide = 400000000 /* GapEnd */; - } - else { - let { start, end } = getInclusive(spec, block); - startSide = (start ? (block ? -300000000 /* BlockIncStart */ : -1 /* InlineIncStart */) : 500000000 /* NonIncStart */) - 1; - endSide = (end ? (block ? 200000000 /* BlockIncEnd */ : 1 /* InlineIncEnd */) : -600000000 /* NonIncEnd */) + 1; - } - return new PointDecoration(spec, startSide, endSide, block, spec.widget || null, true); - } - /** - Create a line decoration, which can add DOM attributes to the - line starting at the given position. - */ - static line(spec) { - return new LineDecoration(spec); - } - /** - Build a [`DecorationSet`](https://codemirror.net/6/docs/ref/#view.DecorationSet) from the given - decorated range or ranges. If the ranges aren't already sorted, - pass `true` for `sort` to make the library sort them for you. - */ - static set(of, sort = false) { - return RangeSet.of(of, sort); - } - /** - @internal - */ - hasHeight() { return this.widget ? this.widget.estimatedHeight > -1 : false; } - } - /** - The empty set of decorations. - */ - Decoration.none = RangeSet.empty; - class MarkDecoration extends Decoration { - constructor(spec) { - let { start, end } = getInclusive(spec); - super(start ? -1 /* InlineIncStart */ : 500000000 /* NonIncStart */, end ? 1 /* InlineIncEnd */ : -600000000 /* NonIncEnd */, null, spec); - this.tagName = spec.tagName || "span"; - this.class = spec.class || ""; - this.attrs = spec.attributes || null; - } - eq(other) { - return this == other || - other instanceof MarkDecoration && - this.tagName == other.tagName && - this.class == other.class && - attrsEq(this.attrs, other.attrs); - } - range(from, to = from) { - if (from >= to) - throw new RangeError("Mark decorations may not be empty"); - return super.range(from, to); - } - } - MarkDecoration.prototype.point = false; - class LineDecoration extends Decoration { - constructor(spec) { - super(-200000000 /* Line */, -200000000 /* Line */, null, spec); - } - eq(other) { - return other instanceof LineDecoration && attrsEq(this.spec.attributes, other.spec.attributes); - } - range(from, to = from) { - if (to != from) - throw new RangeError("Line decoration ranges must be zero-length"); - return super.range(from, to); - } - } - LineDecoration.prototype.mapMode = MapMode.TrackBefore; - LineDecoration.prototype.point = true; - class PointDecoration extends Decoration { - constructor(spec, startSide, endSide, block, widget, isReplace) { - super(startSide, endSide, widget, spec); - this.block = block; - this.isReplace = isReplace; - this.mapMode = !block ? MapMode.TrackDel : startSide <= 0 ? MapMode.TrackBefore : MapMode.TrackAfter; - } - // Only relevant when this.block == true - get type() { - return this.startSide < this.endSide ? BlockType.WidgetRange - : this.startSide <= 0 ? BlockType.WidgetBefore : BlockType.WidgetAfter; - } - get heightRelevant() { return this.block || !!this.widget && this.widget.estimatedHeight >= 5; } - eq(other) { - return other instanceof PointDecoration && - widgetsEq(this.widget, other.widget) && - this.block == other.block && - this.startSide == other.startSide && this.endSide == other.endSide; - } - range(from, to = from) { - if (this.isReplace && (from > to || (from == to && this.startSide > 0 && this.endSide <= 0))) - throw new RangeError("Invalid range for replacement decoration"); - if (!this.isReplace && to != from) - throw new RangeError("Widget decorations can only have zero-length ranges"); - return super.range(from, to); - } - } - PointDecoration.prototype.point = true; - function getInclusive(spec, block = false) { - let { inclusiveStart: start, inclusiveEnd: end } = spec; - if (start == null) - start = spec.inclusive; - if (end == null) - end = spec.inclusive; - return { start: start !== null && start !== void 0 ? start : block, end: end !== null && end !== void 0 ? end : block }; - } - function widgetsEq(a, b) { - return a == b || !!(a && b && a.compare(b)); - } - function addRange(from, to, ranges, margin = 0) { - let last = ranges.length - 1; - if (last >= 0 && ranges[last] + margin >= from) - ranges[last] = Math.max(ranges[last], to); - else - ranges.push(from, to); - } - - class LineView extends ContentView { - constructor() { - super(...arguments); - this.children = []; - this.length = 0; - this.prevAttrs = undefined; - this.attrs = null; - this.breakAfter = 0; - } - // Consumes source - merge(from, to, source, hasStart, openStart, openEnd) { - if (source) { - if (!(source instanceof LineView)) - return false; - if (!this.dom) - source.transferDOM(this); // Reuse source.dom when appropriate - } - if (hasStart) - this.setDeco(source ? source.attrs : null); - mergeChildrenInto(this, from, to, source ? source.children : [], openStart, openEnd); - return true; - } - split(at) { - let end = new LineView; - end.breakAfter = this.breakAfter; - if (this.length == 0) - return end; - let { i, off } = this.childPos(at); - if (off) { - end.append(this.children[i].split(off), 0); - this.children[i].merge(off, this.children[i].length, null, false, 0, 0); - i++; - } - for (let j = i; j < this.children.length; j++) - end.append(this.children[j], 0); - while (i > 0 && this.children[i - 1].length == 0) - this.children[--i].destroy(); - this.children.length = i; - this.markDirty(); - this.length = at; - return end; - } - transferDOM(other) { - if (!this.dom) - return; - other.setDOM(this.dom); - other.prevAttrs = this.prevAttrs === undefined ? this.attrs : this.prevAttrs; - this.prevAttrs = undefined; - this.dom = null; - } - setDeco(attrs) { - if (!attrsEq(this.attrs, attrs)) { - if (this.dom) { - this.prevAttrs = this.attrs; - this.markDirty(); - } - this.attrs = attrs; - } - } - append(child, openStart) { - joinInlineInto(this, child, openStart); - } - // Only called when building a line view in ContentBuilder - addLineDeco(deco) { - let attrs = deco.spec.attributes, cls = deco.spec.class; - if (attrs) - this.attrs = combineAttrs(attrs, this.attrs || {}); - if (cls) - this.attrs = combineAttrs({ class: cls }, this.attrs || {}); - } - domAtPos(pos) { - return inlineDOMAtPos(this.dom, this.children, pos); - } - reuseDOM(node) { - if (node.nodeName == "DIV") { - this.setDOM(node); - this.dirty |= 4 /* Attrs */ | 2 /* Node */; - } - } - sync(track) { - var _a; - if (!this.dom) { - this.setDOM(document.createElement("div")); - this.dom.className = "cm-line"; - this.prevAttrs = this.attrs ? null : undefined; - } - else if (this.dirty & 4 /* Attrs */) { - clearAttributes(this.dom); - this.dom.className = "cm-line"; - this.prevAttrs = this.attrs ? null : undefined; - } - if (this.prevAttrs !== undefined) { - updateAttrs(this.dom, this.prevAttrs, this.attrs); - this.dom.classList.add("cm-line"); - this.prevAttrs = undefined; - } - super.sync(track); - let last = this.dom.lastChild; - while (last && ContentView.get(last) instanceof MarkView) - last = last.lastChild; - if (!last || !this.length || - last.nodeName != "BR" && ((_a = ContentView.get(last)) === null || _a === void 0 ? void 0 : _a.isEditable) == false && - (!browser.ios || !this.children.some(ch => ch instanceof TextView))) { - let hack = document.createElement("BR"); - hack.cmIgnore = true; - this.dom.appendChild(hack); - } - } - measureTextSize() { - if (this.children.length == 0 || this.length > 20) - return null; - let totalWidth = 0; - for (let child of this.children) { - if (!(child instanceof TextView)) - return null; - let rects = clientRectsFor(child.dom); - if (rects.length != 1) - return null; - totalWidth += rects[0].width; - } - return { lineHeight: this.dom.getBoundingClientRect().height, - charWidth: totalWidth / this.length }; - } - coordsAt(pos, side) { - return coordsInChildren(this, pos, side); - } - become(_other) { return false; } - get type() { return BlockType.Text; } - static find(docView, pos) { - for (let i = 0, off = 0; i < docView.children.length; i++) { - let block = docView.children[i], end = off + block.length; - if (end >= pos) { - if (block instanceof LineView) - return block; - if (end > pos) - break; - } - off = end + block.breakAfter; - } - return null; - } - } - class BlockWidgetView extends ContentView { - constructor(widget, length, type) { - super(); - this.widget = widget; - this.length = length; - this.type = type; - this.breakAfter = 0; - this.prevWidget = null; - } - merge(from, to, source, _takeDeco, openStart, openEnd) { - if (source && (!(source instanceof BlockWidgetView) || !this.widget.compare(source.widget) || - from > 0 && openStart <= 0 || to < this.length && openEnd <= 0)) - return false; - this.length = from + (source ? source.length : 0) + (this.length - to); - return true; - } - domAtPos(pos) { - return pos == 0 ? DOMPos.before(this.dom) : DOMPos.after(this.dom, pos == this.length); - } - split(at) { - let len = this.length - at; - this.length = at; - let end = new BlockWidgetView(this.widget, len, this.type); - end.breakAfter = this.breakAfter; - return end; - } - get children() { return noChildren; } - sync() { - if (!this.dom || !this.widget.updateDOM(this.dom)) { - if (this.dom && this.prevWidget) - this.prevWidget.destroy(this.dom); - this.prevWidget = null; - this.setDOM(this.widget.toDOM(this.editorView)); - this.dom.contentEditable = "false"; - } - } - get overrideDOMText() { - return this.parent ? this.parent.view.state.doc.slice(this.posAtStart, this.posAtEnd) : Text.empty; - } - domBoundsAround() { return null; } - become(other) { - if (other instanceof BlockWidgetView && other.type == this.type && - other.widget.constructor == this.widget.constructor) { - if (!other.widget.eq(this.widget)) - this.markDirty(true); - if (this.dom && !this.prevWidget) - this.prevWidget = this.widget; - this.widget = other.widget; - this.length = other.length; - this.breakAfter = other.breakAfter; - return true; - } - return false; - } - ignoreMutation() { return true; } - ignoreEvent(event) { return this.widget.ignoreEvent(event); } - destroy() { - super.destroy(); - if (this.dom) - this.widget.destroy(this.dom); - } - } - - class ContentBuilder { - constructor(doc, pos, end, disallowBlockEffectsBelow) { - this.doc = doc; - this.pos = pos; - this.end = end; - this.disallowBlockEffectsBelow = disallowBlockEffectsBelow; - this.content = []; - this.curLine = null; - this.breakAtStart = 0; - this.pendingBuffer = 0 /* No */; - // Set to false directly after a widget that covers the position after it - this.atCursorPos = true; - this.openStart = -1; - this.openEnd = -1; - this.text = ""; - this.textOff = 0; - this.cursor = doc.iter(); - this.skip = pos; - } - posCovered() { - if (this.content.length == 0) - return !this.breakAtStart && this.doc.lineAt(this.pos).from != this.pos; - let last = this.content[this.content.length - 1]; - return !last.breakAfter && !(last instanceof BlockWidgetView && last.type == BlockType.WidgetBefore); - } - getLine() { - if (!this.curLine) { - this.content.push(this.curLine = new LineView); - this.atCursorPos = true; - } - return this.curLine; - } - flushBuffer(active) { - if (this.pendingBuffer) { - this.curLine.append(wrapMarks(new WidgetBufferView(-1), active), active.length); - this.pendingBuffer = 0 /* No */; - } - } - addBlockWidget(view) { - this.flushBuffer([]); - this.curLine = null; - this.content.push(view); - } - finish(openEnd) { - if (!openEnd) - this.flushBuffer([]); - else - this.pendingBuffer = 0 /* No */; - if (!this.posCovered()) - this.getLine(); - } - buildText(length, active, openStart) { - while (length > 0) { - if (this.textOff == this.text.length) { - let { value, lineBreak, done } = this.cursor.next(this.skip); - this.skip = 0; - if (done) - throw new Error("Ran out of text content when drawing inline views"); - if (lineBreak) { - if (!this.posCovered()) - this.getLine(); - if (this.content.length) - this.content[this.content.length - 1].breakAfter = 1; - else - this.breakAtStart = 1; - this.flushBuffer([]); - this.curLine = null; - length--; - continue; - } - else { - this.text = value; - this.textOff = 0; - } - } - let take = Math.min(this.text.length - this.textOff, length, 512 /* Chunk */); - this.flushBuffer(active.slice(0, openStart)); - this.getLine().append(wrapMarks(new TextView(this.text.slice(this.textOff, this.textOff + take)), active), openStart); - this.atCursorPos = true; - this.textOff += take; - length -= take; - openStart = 0; - } - } - span(from, to, active, openStart) { - this.buildText(to - from, active, openStart); - this.pos = to; - if (this.openStart < 0) - this.openStart = openStart; - } - point(from, to, deco, active, openStart) { - let len = to - from; - if (deco instanceof PointDecoration) { - if (deco.block) { - let { type } = deco; - if (type == BlockType.WidgetAfter && !this.posCovered()) - this.getLine(); - this.addBlockWidget(new BlockWidgetView(deco.widget || new NullWidget("div"), len, type)); - } - else { - let view = WidgetView.create(deco.widget || new NullWidget("span"), len, deco.startSide); - let cursorBefore = this.atCursorPos && !view.isEditable && openStart <= active.length && (from < to || deco.startSide > 0); - let cursorAfter = !view.isEditable && (from < to || deco.startSide <= 0); - let line = this.getLine(); - if (this.pendingBuffer == 2 /* IfCursor */ && !cursorBefore) - this.pendingBuffer = 0 /* No */; - this.flushBuffer(active); - if (cursorBefore) { - line.append(wrapMarks(new WidgetBufferView(1), active), openStart); - openStart = active.length + Math.max(0, openStart - active.length); - } - line.append(wrapMarks(view, active), openStart); - this.atCursorPos = cursorAfter; - this.pendingBuffer = !cursorAfter ? 0 /* No */ : from < to ? 1 /* Yes */ : 2 /* IfCursor */; - } - } - else if (this.doc.lineAt(this.pos).from == this.pos) { // Line decoration - this.getLine().addLineDeco(deco); - } - if (len) { - // Advance the iterator past the replaced content - if (this.textOff + len <= this.text.length) { - this.textOff += len; - } - else { - this.skip += len - (this.text.length - this.textOff); - this.text = ""; - this.textOff = 0; - } - this.pos = to; - } - if (this.openStart < 0) - this.openStart = openStart; - } - filterPoint(from, to, value, index) { - if (index < this.disallowBlockEffectsBelow && value instanceof PointDecoration) { - if (value.block) - throw new RangeError("Block decorations may not be specified via plugins"); - if (to > this.doc.lineAt(this.pos).to) - throw new RangeError("Decorations that replace line breaks may not be specified via plugins"); - } - return true; - } - static build(text, from, to, decorations, pluginDecorationLength) { - let builder = new ContentBuilder(text, from, to, pluginDecorationLength); - builder.openEnd = RangeSet.spans(decorations, from, to, builder); - if (builder.openStart < 0) - builder.openStart = builder.openEnd; - builder.finish(builder.openEnd); - return builder; - } - } - function wrapMarks(view, active) { - for (let mark of active) - view = new MarkView(mark, [view], view.length); - return view; - } - class NullWidget extends WidgetType { - constructor(tag) { - super(); - this.tag = tag; - } - eq(other) { return other.tag == this.tag; } - toDOM() { return document.createElement(this.tag); } - updateDOM(elt) { return elt.nodeName.toLowerCase() == this.tag; } - } - - const none$2 = []; - const clickAddsSelectionRange = /*@__PURE__*/Facet.define(); - const dragMovesSelection$1 = /*@__PURE__*/Facet.define(); - const mouseSelectionStyle = /*@__PURE__*/Facet.define(); - const exceptionSink = /*@__PURE__*/Facet.define(); - const updateListener = /*@__PURE__*/Facet.define(); - const inputHandler$1 = /*@__PURE__*/Facet.define(); - // FIXME remove - const scrollTo = /*@__PURE__*/StateEffect.define({ - map: (range, changes) => range.map(changes) - }); - // FIXME remove - const centerOn = /*@__PURE__*/StateEffect.define({ - map: (range, changes) => range.map(changes) - }); - class ScrollTarget { - constructor(range, y = "nearest", x = "nearest", yMargin = 5, xMargin = 5) { - this.range = range; - this.y = y; - this.x = x; - this.yMargin = yMargin; - this.xMargin = xMargin; - } - map(changes) { - return changes.empty ? this : new ScrollTarget(this.range.map(changes), this.y, this.x, this.yMargin, this.xMargin); - } - } - const scrollIntoView$1 = /*@__PURE__*/StateEffect.define({ map: (t, ch) => t.map(ch) }); - /** - Log or report an unhandled exception in client code. Should - probably only be used by extension code that allows client code to - provide functions, and calls those functions in a context where an - exception can't be propagated to calling code in a reasonable way - (for example when in an event handler). - - Either calls a handler registered with - [`EditorView.exceptionSink`](https://codemirror.net/6/docs/ref/#view.EditorView^exceptionSink), - `window.onerror`, if defined, or `console.error` (in which case - it'll pass `context`, when given, as first argument). - */ - function logException(state, exception, context) { - let handler = state.facet(exceptionSink); - if (handler.length) - handler[0](exception); - else if (window.onerror) - window.onerror(String(exception), context, undefined, undefined, exception); - else if (context) - console.error(context + ":", exception); - else - console.error(exception); - } - const editable = /*@__PURE__*/Facet.define({ combine: values => values.length ? values[0] : true }); - /** - Used to [declare](https://codemirror.net/6/docs/ref/#view.PluginSpec.provide) which - [fields](https://codemirror.net/6/docs/ref/#view.PluginValue) a [view plugin](https://codemirror.net/6/docs/ref/#view.ViewPlugin) - provides. - */ - class PluginFieldProvider { - /** - @internal - */ - constructor( - /** - @internal - */ - field, - /** - @internal - */ - get) { - this.field = field; - this.get = get; - } - } - /** - Plugin fields are a mechanism for allowing plugins to provide - values that can be retrieved through the - [`pluginField`](https://codemirror.net/6/docs/ref/#view.EditorView.pluginField) view method. - */ - class PluginField { - /** - Create a [provider](https://codemirror.net/6/docs/ref/#view.PluginFieldProvider) for this field, - to use with a plugin's [provide](https://codemirror.net/6/docs/ref/#view.PluginSpec.provide) - option. - */ - from(get) { - return new PluginFieldProvider(this, get); - } - /** - Define a new plugin field. - */ - static define() { return new PluginField(); } - } - /** - This field can be used by plugins to provide - [decorations](https://codemirror.net/6/docs/ref/#view.Decoration). - - **Note**: For reasons of data flow (plugins are only updated - after the viewport is computed), decorations produced by plugins - are _not_ taken into account when predicting the vertical layout - structure of the editor. They **must not** introduce block - widgets (that will raise an error) or replacing decorations that - cover line breaks (these will be ignored if they occur). Such - decorations, or others that cause a large amount of vertical - size shift compared to the undecorated content, should be - provided through the state-level [`decorations` - facet](https://codemirror.net/6/docs/ref/#view.EditorView^decorations) instead. - */ - PluginField.decorations = /*@__PURE__*/PluginField.define(); - /** - Used to provide ranges that should be treated as atoms as far as - cursor motion is concerned. This causes methods like - [`moveByChar`](https://codemirror.net/6/docs/ref/#view.EditorView.moveByChar) and - [`moveVertically`](https://codemirror.net/6/docs/ref/#view.EditorView.moveVertically) (and the - commands built on top of them) to skip across such regions when - a selection endpoint would enter them. This does _not_ prevent - direct programmatic [selection - updates](https://codemirror.net/6/docs/ref/#state.TransactionSpec.selection) from moving into such - regions. - */ - PluginField.atomicRanges = /*@__PURE__*/PluginField.define(); - /** - Plugins can provide additional scroll margins (space around the - sides of the scrolling element that should be considered - invisible) through this field. This can be useful when the - plugin introduces elements that cover part of that element (for - example a horizontally fixed gutter). - */ - PluginField.scrollMargins = /*@__PURE__*/PluginField.define(); - let nextPluginID = 0; - const viewPlugin = /*@__PURE__*/Facet.define(); - /** - View plugins associate stateful values with a view. They can - influence the way the content is drawn, and are notified of things - that happen in the view. - */ - class ViewPlugin { - constructor( - /** - @internal - */ - id, - /** - @internal - */ - create, - /** - @internal - */ - fields) { - this.id = id; - this.create = create; - this.fields = fields; - this.extension = viewPlugin.of(this); - } - /** - Define a plugin from a constructor function that creates the - plugin's value, given an editor view. - */ - static define(create, spec) { - let { eventHandlers, provide, decorations } = spec || {}; - let fields = []; - if (provide) - for (let provider of Array.isArray(provide) ? provide : [provide]) - fields.push(provider); - if (eventHandlers) - fields.push(domEventHandlers.from((value) => ({ plugin: value, handlers: eventHandlers }))); - if (decorations) - fields.push(PluginField.decorations.from(decorations)); - return new ViewPlugin(nextPluginID++, create, fields); - } - /** - Create a plugin for a class whose constructor takes a single - editor view as argument. - */ - static fromClass(cls, spec) { - return ViewPlugin.define(view => new cls(view), spec); - } - } - const domEventHandlers = /*@__PURE__*/PluginField.define(); - class PluginInstance { - constructor(spec) { - this.spec = spec; - // When starting an update, all plugins have this field set to the - // update object, indicating they need to be updated. When finished - // updating, it is set to `false`. Retrieving a plugin that needs to - // be updated with `view.plugin` forces an eager update. - this.mustUpdate = null; - // This is null when the plugin is initially created, but - // initialized on the first update. - this.value = null; - } - takeField(type, target) { - if (this.spec) - for (let { field, get } of this.spec.fields) - if (field == type) - target.push(get(this.value)); - } - update(view) { - if (!this.value) { - if (this.spec) { - try { - this.value = this.spec.create(view); - } - catch (e) { - logException(view.state, e, "CodeMirror plugin crashed"); - this.deactivate(); - } - } - } - else if (this.mustUpdate) { - let update = this.mustUpdate; - this.mustUpdate = null; - if (this.value.update) { - try { - this.value.update(update); - } - catch (e) { - logException(update.state, e, "CodeMirror plugin crashed"); - if (this.value.destroy) - try { - this.value.destroy(); - } - catch (_) { } - this.deactivate(); - } - } - } - return this; - } - destroy(view) { - var _a; - if ((_a = this.value) === null || _a === void 0 ? void 0 : _a.destroy) { - try { - this.value.destroy(); - } - catch (e) { - logException(view.state, e, "CodeMirror plugin crashed"); - } - } - } - deactivate() { - this.spec = this.value = null; - } - } - const editorAttributes = /*@__PURE__*/Facet.define(); - const contentAttributes = /*@__PURE__*/Facet.define(); - // Provide decorations - const decorations = /*@__PURE__*/Facet.define(); - const styleModule = /*@__PURE__*/Facet.define(); - class ChangedRange { - constructor(fromA, toA, fromB, toB) { - this.fromA = fromA; - this.toA = toA; - this.fromB = fromB; - this.toB = toB; - } - join(other) { - return new ChangedRange(Math.min(this.fromA, other.fromA), Math.max(this.toA, other.toA), Math.min(this.fromB, other.fromB), Math.max(this.toB, other.toB)); - } - addToSet(set) { - let i = set.length, me = this; - for (; i > 0; i--) { - let range = set[i - 1]; - if (range.fromA > me.toA) - continue; - if (range.toA < me.fromA) - break; - me = me.join(range); - set.splice(i - 1, 1); - } - set.splice(i, 0, me); - return set; - } - static extendWithRanges(diff, ranges) { - if (ranges.length == 0) - return diff; - let result = []; - for (let dI = 0, rI = 0, posA = 0, posB = 0;; dI++) { - let next = dI == diff.length ? null : diff[dI], off = posA - posB; - let end = next ? next.fromB : 1e9; - while (rI < ranges.length && ranges[rI] < end) { - let from = ranges[rI], to = ranges[rI + 1]; - let fromB = Math.max(posB, from), toB = Math.min(end, to); - if (fromB <= toB) - new ChangedRange(fromB + off, toB + off, fromB, toB).addToSet(result); - if (to > end) - break; - else - rI += 2; - } - if (!next) - return result; - new ChangedRange(next.fromA, next.toA, next.fromB, next.toB).addToSet(result); - posA = next.toA; - posB = next.toB; - } - } - } - /** - View [plugins](https://codemirror.net/6/docs/ref/#view.ViewPlugin) are given instances of this - class, which describe what happened, whenever the view is updated. - */ - class ViewUpdate { - /** - @internal - */ - constructor( - /** - The editor view that the update is associated with. - */ - view, - /** - The new editor state. - */ - state, - /** - The transactions involved in the update. May be empty. - */ - transactions = none$2) { - this.view = view; - this.state = state; - this.transactions = transactions; - /** - @internal - */ - this.flags = 0; - this.startState = view.state; - this.changes = ChangeSet.empty(this.startState.doc.length); - for (let tr of transactions) - this.changes = this.changes.compose(tr.changes); - let changedRanges = []; - this.changes.iterChangedRanges((fromA, toA, fromB, toB) => changedRanges.push(new ChangedRange(fromA, toA, fromB, toB))); - this.changedRanges = changedRanges; - let focus = view.hasFocus; - if (focus != view.inputState.notifiedFocused) { - view.inputState.notifiedFocused = focus; - this.flags |= 1 /* Focus */; - } - } - /** - Tells you whether the [viewport](https://codemirror.net/6/docs/ref/#view.EditorView.viewport) or - [visible ranges](https://codemirror.net/6/docs/ref/#view.EditorView.visibleRanges) changed in this - update. - */ - get viewportChanged() { - return (this.flags & 4 /* Viewport */) > 0; - } - /** - Indicates whether the height of an element in the editor changed - in this update. - */ - get heightChanged() { - return (this.flags & 2 /* Height */) > 0; - } - /** - Returns true when the document was modified or the size of the - editor, or elements within the editor, changed. - */ - get geometryChanged() { - return this.docChanged || (this.flags & (8 /* Geometry */ | 2 /* Height */)) > 0; - } - /** - True when this update indicates a focus change. - */ - get focusChanged() { - return (this.flags & 1 /* Focus */) > 0; - } - /** - Whether the document changed in this update. - */ - get docChanged() { - return !this.changes.empty; - } - /** - Whether the selection was explicitly set in this update. - */ - get selectionSet() { - return this.transactions.some(tr => tr.selection); - } - /** - @internal - */ - get empty() { return this.flags == 0 && this.transactions.length == 0; } - } - - /** - Used to indicate [text direction](https://codemirror.net/6/docs/ref/#view.EditorView.textDirection). - */ - var Direction = /*@__PURE__*/(function (Direction) { - // (These are chosen to match the base levels, in bidi algorithm - // terms, of spans in that direction.) - /** - Left-to-right. - */ - Direction[Direction["LTR"] = 0] = "LTR"; - /** - Right-to-left. - */ - Direction[Direction["RTL"] = 1] = "RTL"; - return Direction})(Direction || (Direction = {})); - const LTR = Direction.LTR, RTL = Direction.RTL; - // Decode a string with each type encoded as log2(type) - function dec(str) { - let result = []; - for (let i = 0; i < str.length; i++) - result.push(1 << +str[i]); - return result; - } - // Character types for codepoints 0 to 0xf8 - const LowTypes = /*@__PURE__*/dec("88888888888888888888888888888888888666888888787833333333337888888000000000000000000000000008888880000000000000000000000000088888888888888888888888888888888888887866668888088888663380888308888800000000000000000000000800000000000000000000000000000008"); - // Character types for codepoints 0x600 to 0x6f9 - const ArabicTypes = /*@__PURE__*/dec("4444448826627288999999999992222222222222222222222222222222222222222222222229999999999999999999994444444444644222822222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222999999949999999229989999223333333333"); - const Brackets = /*@__PURE__*/Object.create(null), BracketStack = []; - // There's a lot more in - // https://www.unicode.org/Public/UCD/latest/ucd/BidiBrackets.txt, - // which are left out to keep code size down. - for (let p of ["()", "[]", "{}"]) { - let l = /*@__PURE__*/p.charCodeAt(0), r = /*@__PURE__*/p.charCodeAt(1); - Brackets[l] = r; - Brackets[r] = -l; - } - function charType(ch) { - return ch <= 0xf7 ? LowTypes[ch] : - 0x590 <= ch && ch <= 0x5f4 ? 2 /* R */ : - 0x600 <= ch && ch <= 0x6f9 ? ArabicTypes[ch - 0x600] : - 0x6ee <= ch && ch <= 0x8ac ? 4 /* AL */ : - 0x2000 <= ch && ch <= 0x200b ? 256 /* NI */ : - ch == 0x200c ? 256 /* NI */ : 1 /* L */; - } - const BidiRE = /[\u0590-\u05f4\u0600-\u06ff\u0700-\u08ac]/; - /** - Represents a contiguous range of text that has a single direction - (as in left-to-right or right-to-left). - */ - class BidiSpan { - /** - @internal - */ - constructor( - /** - The start of the span (relative to the start of the line). - */ - from, - /** - The end of the span. - */ - to, - /** - The ["bidi - level"](https://unicode.org/reports/tr9/#Basic_Display_Algorithm) - of the span (in this context, 0 means - left-to-right, 1 means right-to-left, 2 means left-to-right - number inside right-to-left text). - */ - level) { - this.from = from; - this.to = to; - this.level = level; - } - /** - The direction of this span. - */ - get dir() { return this.level % 2 ? RTL : LTR; } - /** - @internal - */ - side(end, dir) { return (this.dir == dir) == end ? this.to : this.from; } - /** - @internal - */ - static find(order, index, level, assoc) { - let maybe = -1; - for (let i = 0; i < order.length; i++) { - let span = order[i]; - if (span.from <= index && span.to >= index) { - if (span.level == level) - return i; - // When multiple spans match, if assoc != 0, take the one that - // covers that side, otherwise take the one with the minimum - // level. - if (maybe < 0 || (assoc != 0 ? (assoc < 0 ? span.from < index : span.to > index) : order[maybe].level > span.level)) - maybe = i; - } - } - if (maybe < 0) - throw new RangeError("Index out of range"); - return maybe; - } - } - // Reused array of character types - const types = []; - function computeOrder(line, direction) { - let len = line.length, outerType = direction == LTR ? 1 /* L */ : 2 /* R */, oppositeType = direction == LTR ? 2 /* R */ : 1 /* L */; - if (!line || outerType == 1 /* L */ && !BidiRE.test(line)) - return trivialOrder(len); - // 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. - // 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. - // (Left after this: L, R, EN, AN, ET, CS, NI) - for (let i = 0, prev = outerType, prevStrong = outerType; i < len; i++) { - let type = charType(line.charCodeAt(i)); - if (type == 512 /* NSM */) - type = prev; - else if (type == 8 /* EN */ && prevStrong == 4 /* AL */) - type = 16 /* AN */; - types[i] = type == 4 /* AL */ ? 2 /* R */ : type; - if (type & 7 /* Strong */) - prevStrong = type; - prev = type; - } - // W5. A sequence of European terminators adjacent to European - // numbers changes to all European numbers. - // W6. Otherwise, separators and terminators change to Other - // Neutral. - // 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. - // (Left after this: L, R, EN+AN, NI) - for (let i = 0, prev = outerType, prevStrong = outerType; i < len; i++) { - let type = types[i]; - if (type == 128 /* CS */) { - if (i < len - 1 && prev == types[i + 1] && (prev & 24 /* Num */)) - type = types[i] = prev; - else - types[i] = 256 /* NI */; - } - else if (type == 64 /* ET */) { - let end = i + 1; - while (end < len && types[end] == 64 /* ET */) - end++; - let replace = (i && prev == 8 /* EN */) || (end < len && types[end] == 8 /* EN */) ? (prevStrong == 1 /* L */ ? 1 /* L */ : 8 /* EN */) : 256 /* NI */; - for (let j = i; j < end; j++) - types[j] = replace; - i = end - 1; - } - else if (type == 8 /* EN */ && prevStrong == 1 /* L */) { - types[i] = 1 /* L */; - } - prev = type; - if (type & 7 /* Strong */) - prevStrong = type; - } - // N0. Process bracket pairs in an isolating run sequence - // sequentially in the logical order of the text positions of the - // opening paired brackets using the logic given below. Within this - // scope, bidirectional types EN and AN are treated as R. - for (let i = 0, sI = 0, context = 0, ch, br, type; i < len; i++) { - // Keeps [startIndex, type, strongSeen] triples for each open - // bracket on BracketStack. - if (br = Brackets[ch = line.charCodeAt(i)]) { - if (br < 0) { // Closing bracket - for (let sJ = sI - 3; sJ >= 0; sJ -= 3) { - if (BracketStack[sJ + 1] == -br) { - let flags = BracketStack[sJ + 2]; - let type = (flags & 2 /* EmbedInside */) ? outerType : - !(flags & 4 /* OppositeInside */) ? 0 : - (flags & 1 /* OppositeBefore */) ? oppositeType : outerType; - if (type) - types[i] = types[BracketStack[sJ]] = type; - sI = sJ; - break; - } - } - } - else if (BracketStack.length == 189 /* MaxDepth */) { - break; - } - else { - BracketStack[sI++] = i; - BracketStack[sI++] = ch; - BracketStack[sI++] = context; - } - } - else if ((type = types[i]) == 2 /* R */ || type == 1 /* L */) { - let embed = type == outerType; - context = embed ? 0 : 1 /* OppositeBefore */; - for (let sJ = sI - 3; sJ >= 0; sJ -= 3) { - let cur = BracketStack[sJ + 2]; - if (cur & 2 /* EmbedInside */) - break; - if (embed) { - BracketStack[sJ + 2] |= 2 /* EmbedInside */; - } - else { - if (cur & 4 /* OppositeInside */) - break; - BracketStack[sJ + 2] |= 4 /* OppositeInside */; - } - } - } - } - // 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. - // (Left after this: L, R, EN+AN) - for (let i = 0; i < len; i++) { - if (types[i] == 256 /* NI */) { - let end = i + 1; - while (end < len && types[end] == 256 /* NI */) - end++; - let beforeL = (i ? types[i - 1] : outerType) == 1 /* L */; - let afterL = (end < len ? types[end] : outerType) == 1 /* L */; - let replace = beforeL == afterL ? (beforeL ? 1 /* L */ : 2 /* R */) : outerType; - for (let j = i; j < end; j++) - types[j] = replace; - i = end - 1; - } - } - // Here we depart from the documented algorithm, in order to avoid - // building up an actual levels array. Since there are only three - // levels (0, 1, 2) in an implementation that doesn't take - // explicit embedding into account, we can build up the order on - // the fly, without following the level-based algorithm. - let order = []; - if (outerType == 1 /* L */) { - for (let i = 0; i < len;) { - let start = i, rtl = types[i++] != 1 /* L */; - while (i < len && rtl == (types[i] != 1 /* L */)) - i++; - if (rtl) { - for (let j = i; j > start;) { - let end = j, l = types[--j] != 2 /* R */; - while (j > start && l == (types[j - 1] != 2 /* R */)) - j--; - order.push(new BidiSpan(j, end, l ? 2 : 1)); - } - } - else { - order.push(new BidiSpan(start, i, 0)); - } - } - } - else { - for (let i = 0; i < len;) { - let start = i, rtl = types[i++] == 2 /* R */; - while (i < len && rtl == (types[i] == 2 /* R */)) - i++; - order.push(new BidiSpan(start, i, rtl ? 1 : 2)); - } - } - return order; - } - function trivialOrder(length) { - return [new BidiSpan(0, length, 0)]; - } - let movedOver = ""; - function moveVisually(line, order, dir, start, forward) { - var _a; - let startIndex = start.head - line.from, spanI = -1; - if (startIndex == 0) { - if (!forward || !line.length) - return null; - if (order[0].level != dir) { - startIndex = order[0].side(false, dir); - spanI = 0; - } - } - else if (startIndex == line.length) { - if (forward) - return null; - let last = order[order.length - 1]; - if (last.level != dir) { - startIndex = last.side(true, dir); - spanI = order.length - 1; - } - } - if (spanI < 0) - spanI = BidiSpan.find(order, startIndex, (_a = start.bidiLevel) !== null && _a !== void 0 ? _a : -1, start.assoc); - let span = order[spanI]; - // End of span. (But not end of line--that was checked for above.) - if (startIndex == span.side(forward, dir)) { - span = order[spanI += forward ? 1 : -1]; - startIndex = span.side(!forward, dir); - } - let indexForward = forward == (span.dir == dir); - let nextIndex = findClusterBreak(line.text, startIndex, indexForward); - movedOver = line.text.slice(Math.min(startIndex, nextIndex), Math.max(startIndex, nextIndex)); - if (nextIndex != span.side(forward, dir)) - return EditorSelection.cursor(nextIndex + line.from, indexForward ? -1 : 1, span.level); - let nextSpan = spanI == (forward ? order.length - 1 : 0) ? null : order[spanI + (forward ? 1 : -1)]; - if (!nextSpan && span.level != dir) - return EditorSelection.cursor(forward ? line.to : line.from, forward ? -1 : 1, dir); - if (nextSpan && nextSpan.level < span.level) - return EditorSelection.cursor(nextSpan.side(!forward, dir) + line.from, forward ? 1 : -1, nextSpan.level); - return EditorSelection.cursor(nextIndex + line.from, forward ? -1 : 1, span.level); - } - - const LineBreakPlaceholder = "\uffff"; - class DOMReader { - constructor(points, state) { - this.points = points; - this.text = ""; - this.lineSeparator = state.facet(EditorState.lineSeparator); - } - append(text) { - this.text += text; - } - lineBreak() { - this.text += LineBreakPlaceholder; - } - readRange(start, end) { - if (!start) - return this; - let parent = start.parentNode; - for (let cur = start;;) { - this.findPointBefore(parent, cur); - this.readNode(cur); - let next = cur.nextSibling; - if (next == end) - break; - let view = ContentView.get(cur), nextView = ContentView.get(next); - if (view && nextView ? view.breakAfter : - (view ? view.breakAfter : isBlockElement(cur)) || - (isBlockElement(next) && (cur.nodeName != "BR" || cur.cmIgnore))) - this.lineBreak(); - cur = next; - } - this.findPointBefore(parent, end); - return this; - } - readTextNode(node) { - let text = node.nodeValue; - for (let point of this.points) - if (point.node == node) - point.pos = this.text.length + Math.min(point.offset, text.length); - for (let off = 0, re = this.lineSeparator ? null : /\r\n?|\n/g;;) { - let nextBreak = -1, breakSize = 1, m; - if (this.lineSeparator) { - nextBreak = text.indexOf(this.lineSeparator, off); - breakSize = this.lineSeparator.length; - } - else if (m = re.exec(text)) { - nextBreak = m.index; - breakSize = m[0].length; - } - this.append(text.slice(off, nextBreak < 0 ? text.length : nextBreak)); - if (nextBreak < 0) - break; - this.lineBreak(); - if (breakSize > 1) - for (let point of this.points) - if (point.node == node && point.pos > this.text.length) - point.pos -= breakSize - 1; - off = nextBreak + breakSize; - } - } - readNode(node) { - if (node.cmIgnore) - return; - let view = ContentView.get(node); - let fromView = view && view.overrideDOMText; - if (fromView != null) { - this.findPointInside(node, fromView.length); - for (let i = fromView.iter(); !i.next().done;) { - if (i.lineBreak) - this.lineBreak(); - else - this.append(i.value); - } - } - else if (node.nodeType == 3) { - this.readTextNode(node); - } - else if (node.nodeName == "BR") { - if (node.nextSibling) - this.lineBreak(); - } - else if (node.nodeType == 1) { - this.readRange(node.firstChild, null); - } - } - findPointBefore(node, next) { - for (let point of this.points) - if (point.node == node && node.childNodes[point.offset] == next) - point.pos = this.text.length; - } - findPointInside(node, maxLen) { - for (let point of this.points) - if (node.nodeType == 3 ? point.node == node : node.contains(point.node)) - point.pos = this.text.length + Math.min(maxLen, point.offset); - } - } - function isBlockElement(node) { - return node.nodeType == 1 && /^(DIV|P|LI|UL|OL|BLOCKQUOTE|DD|DT|H\d|SECTION|PRE)$/.test(node.nodeName); - } - class DOMPoint { - constructor(node, offset) { - this.node = node; - this.offset = offset; - this.pos = -1; - } - } - - class DocView extends ContentView { - constructor(view) { - super(); - this.view = view; - this.compositionDeco = Decoration.none; - this.decorations = []; - this.pluginDecorationLength = 0; - // Track a minimum width for the editor. When measuring sizes in - // measureVisibleLineHeights, this is updated to point at the width - // of a given element and its extent in the document. When a change - // happens in that range, these are reset. That way, once we've seen - // a line/element of a given length, we keep the editor wide enough - // to fit at least that element, until it is changed, at which point - // we forget it again. - this.minWidth = 0; - this.minWidthFrom = 0; - this.minWidthTo = 0; - // Track whether the DOM selection was set in a lossy way, so that - // we don't mess it up when reading it back it - this.impreciseAnchor = null; - this.impreciseHead = null; - this.forceSelection = false; - // Used by the resize observer to ignore resizes that we caused - // ourselves - this.lastUpdate = Date.now(); - this.setDOM(view.contentDOM); - this.children = [new LineView]; - this.children[0].setParent(this); - this.updateDeco(); - this.updateInner([new ChangedRange(0, 0, 0, view.state.doc.length)], 0); - } - get root() { return this.view.root; } - get editorView() { return this.view; } - get length() { return this.view.state.doc.length; } - // Update the document view to a given state. scrollIntoView can be - // used as a hint to compute a new viewport that includes that - // position, if we know the editor is going to scroll that position - // into view. - update(update) { - let changedRanges = update.changedRanges; - if (this.minWidth > 0 && changedRanges.length) { - if (!changedRanges.every(({ fromA, toA }) => toA < this.minWidthFrom || fromA > this.minWidthTo)) { - this.minWidth = this.minWidthFrom = this.minWidthTo = 0; - } - else { - this.minWidthFrom = update.changes.mapPos(this.minWidthFrom, 1); - this.minWidthTo = update.changes.mapPos(this.minWidthTo, 1); - } - } - if (this.view.inputState.composing < 0) - this.compositionDeco = Decoration.none; - else if (update.transactions.length || this.dirty) - this.compositionDeco = computeCompositionDeco(this.view, update.changes); - // When the DOM nodes around the selection are moved to another - // parent, Chrome sometimes reports a different selection through - // getSelection than the one that it actually shows to the user. - // This forces a selection update when lines are joined to work - // around that. Issue #54 - if ((browser.ie || browser.chrome) && !this.compositionDeco.size && update && - update.state.doc.lines != update.startState.doc.lines) - this.forceSelection = true; - let prevDeco = this.decorations, deco = this.updateDeco(); - let decoDiff = findChangedDeco(prevDeco, deco, update.changes); - changedRanges = ChangedRange.extendWithRanges(changedRanges, decoDiff); - if (this.dirty == 0 /* Not */ && changedRanges.length == 0) { - return false; - } - else { - this.updateInner(changedRanges, update.startState.doc.length); - if (update.transactions.length) - this.lastUpdate = Date.now(); - return true; - } - } - // Used by update and the constructor do perform the actual DOM - // update - updateInner(changes, oldLength) { - this.view.viewState.mustMeasureContent = true; - this.updateChildren(changes, oldLength); - let { observer } = this.view; - observer.ignore(() => { - // Lock the height during redrawing, since Chrome sometimes - // messes with the scroll position during DOM mutation (though - // no relayout is triggered and I cannot imagine how it can - // recompute the scroll position without a layout) - this.dom.style.height = this.view.viewState.contentHeight + "px"; - this.dom.style.minWidth = this.minWidth ? this.minWidth + "px" : ""; - // Chrome will sometimes, when DOM mutations occur directly - // around the selection, get confused and report a different - // selection from the one it displays (issue #218). This tries - // to detect that situation. - let track = browser.chrome || browser.ios ? { node: observer.selectionRange.focusNode, written: false } : undefined; - this.sync(track); - this.dirty = 0 /* Not */; - if (track && (track.written || observer.selectionRange.focusNode != track.node)) - this.forceSelection = true; - this.dom.style.height = ""; - }); - let gaps = []; - if (this.view.viewport.from || this.view.viewport.to < this.view.state.doc.length) - for (let child of this.children) - if (child instanceof BlockWidgetView && child.widget instanceof BlockGapWidget) - gaps.push(child.dom); - observer.updateGaps(gaps); - } - updateChildren(changes, oldLength) { - let cursor = this.childCursor(oldLength); - for (let i = changes.length - 1;; i--) { - let next = i >= 0 ? changes[i] : null; - if (!next) - break; - let { fromA, toA, fromB, toB } = next; - let { content, breakAtStart, openStart, openEnd } = ContentBuilder.build(this.view.state.doc, fromB, toB, this.decorations, this.pluginDecorationLength); - let { i: toI, off: toOff } = cursor.findPos(toA, 1); - let { i: fromI, off: fromOff } = cursor.findPos(fromA, -1); - replaceRange(this, fromI, fromOff, toI, toOff, content, breakAtStart, openStart, openEnd); - } - } - // Sync the DOM selection to this.state.selection - updateSelection(mustRead = false, fromPointer = false) { - if (mustRead) - this.view.observer.readSelectionRange(); - if (!(fromPointer || this.mayControlSelection()) || - browser.ios && this.view.inputState.rapidCompositionStart) - return; - let force = this.forceSelection; - this.forceSelection = false; - let main = this.view.state.selection.main; - // FIXME need to handle the case where the selection falls inside a block range - let anchor = this.domAtPos(main.anchor); - let head = main.empty ? anchor : this.domAtPos(main.head); - // Always reset on Firefox when next to an uneditable node to - // avoid invisible cursor bugs (#111) - if (browser.gecko && main.empty && betweenUneditable(anchor)) { - let dummy = document.createTextNode(""); - this.view.observer.ignore(() => anchor.node.insertBefore(dummy, anchor.node.childNodes[anchor.offset] || null)); - anchor = head = new DOMPos(dummy, 0); - force = true; - } - let domSel = this.view.observer.selectionRange; - // If the selection is already here, or in an equivalent position, don't touch it - if (force || !domSel.focusNode || - !isEquivalentPosition(anchor.node, anchor.offset, domSel.anchorNode, domSel.anchorOffset) || - !isEquivalentPosition(head.node, head.offset, domSel.focusNode, domSel.focusOffset)) { - this.view.observer.ignore(() => { - // Chrome Android will hide the virtual keyboard when tapping - // inside an uneditable node, and not bring it back when we - // move the cursor to its proper position. This tries to - // restore the keyboard by cycling focus. - if (browser.android && browser.chrome && this.dom.contains(domSel.focusNode) && - inUneditable(domSel.focusNode, this.dom)) { - this.dom.blur(); - this.dom.focus({ preventScroll: true }); - } - let rawSel = getSelection(this.root); - if (main.empty) { - // Work around https://bugzilla.mozilla.org/show_bug.cgi?id=1612076 - if (browser.gecko) { - let nextTo = nextToUneditable(anchor.node, anchor.offset); - if (nextTo && nextTo != (1 /* Before */ | 2 /* After */)) { - let text = nearbyTextNode(anchor.node, anchor.offset, nextTo == 1 /* Before */ ? 1 : -1); - if (text) - anchor = new DOMPos(text, nextTo == 1 /* Before */ ? 0 : text.nodeValue.length); - } - } - rawSel.collapse(anchor.node, anchor.offset); - if (main.bidiLevel != null && domSel.cursorBidiLevel != null) - domSel.cursorBidiLevel = main.bidiLevel; - } - else if (rawSel.extend) { - // Selection.extend can be used to create an 'inverted' selection - // (one where the focus is before the anchor), but not all - // browsers support it yet. - rawSel.collapse(anchor.node, anchor.offset); - rawSel.extend(head.node, head.offset); - } - else { - // Primitive (IE) way - let range = document.createRange(); - if (main.anchor > main.head) - [anchor, head] = [head, anchor]; - range.setEnd(head.node, head.offset); - range.setStart(anchor.node, anchor.offset); - rawSel.removeAllRanges(); - rawSel.addRange(range); - } - }); - this.view.observer.setSelectionRange(anchor, head); - } - this.impreciseAnchor = anchor.precise ? null : new DOMPos(domSel.anchorNode, domSel.anchorOffset); - this.impreciseHead = head.precise ? null : new DOMPos(domSel.focusNode, domSel.focusOffset); - } - enforceCursorAssoc() { - if (this.compositionDeco.size) - return; - let cursor = this.view.state.selection.main; - let sel = getSelection(this.root); - if (!cursor.empty || !cursor.assoc || !sel.modify) - return; - let line = LineView.find(this, cursor.head); - if (!line) - return; - let lineStart = line.posAtStart; - if (cursor.head == lineStart || cursor.head == lineStart + line.length) - return; - let before = this.coordsAt(cursor.head, -1), after = this.coordsAt(cursor.head, 1); - if (!before || !after || before.bottom > after.top) - return; - let dom = this.domAtPos(cursor.head + cursor.assoc); - sel.collapse(dom.node, dom.offset); - sel.modify("move", cursor.assoc < 0 ? "forward" : "backward", "lineboundary"); - } - mayControlSelection() { - return this.view.state.facet(editable) ? this.root.activeElement == this.dom - : hasSelection(this.dom, this.view.observer.selectionRange); - } - nearest(dom) { - for (let cur = dom; cur;) { - let domView = ContentView.get(cur); - if (domView && domView.rootView == this) - return domView; - cur = cur.parentNode; - } - return null; - } - posFromDOM(node, offset) { - let view = this.nearest(node); - if (!view) - throw new RangeError("Trying to find position for a DOM position outside of the document"); - return view.localPosFromDOM(node, offset) + view.posAtStart; - } - domAtPos(pos) { - let { i, off } = this.childCursor().findPos(pos, -1); - for (; i < this.children.length - 1;) { - let child = this.children[i]; - if (off < child.length || child instanceof LineView) - break; - i++; - off = 0; - } - return this.children[i].domAtPos(off); - } - coordsAt(pos, side) { - for (let off = this.length, i = this.children.length - 1;; i--) { - let child = this.children[i], start = off - child.breakAfter - child.length; - if (pos > start || - (pos == start && child.type != BlockType.WidgetBefore && child.type != BlockType.WidgetAfter && - (!i || side == 2 || this.children[i - 1].breakAfter || - (this.children[i - 1].type == BlockType.WidgetBefore && side > -2)))) - return child.coordsAt(pos - start, side); - off = start; - } - } - measureVisibleLineHeights() { - let result = [], { from, to } = this.view.viewState.viewport; - let contentWidth = this.view.contentDOM.clientWidth; - let isWider = contentWidth > Math.max(this.view.scrollDOM.clientWidth, this.minWidth) + 1; - let widest = -1; - for (let pos = 0, i = 0; i < this.children.length; i++) { - let child = this.children[i], end = pos + child.length; - if (end > to) - break; - if (pos >= from) { - let childRect = child.dom.getBoundingClientRect(); - result.push(childRect.height); - if (isWider) { - let last = child.dom.lastChild; - let rects = last ? clientRectsFor(last) : []; - if (rects.length) { - let rect = rects[rects.length - 1]; - let width = this.view.textDirection == Direction.LTR ? rect.right - childRect.left - : childRect.right - rect.left; - if (width > widest) { - widest = width; - this.minWidth = contentWidth; - this.minWidthFrom = pos; - this.minWidthTo = end; - } - } - } - } - pos = end + child.breakAfter; - } - return result; - } - measureTextSize() { - for (let child of this.children) { - if (child instanceof LineView) { - let measure = child.measureTextSize(); - if (measure) - return measure; - } - } - // If no workable line exists, force a layout of a measurable element - let dummy = document.createElement("div"), lineHeight, charWidth; - dummy.className = "cm-line"; - dummy.textContent = "abc def ghi jkl mno pqr stu"; - this.view.observer.ignore(() => { - this.dom.appendChild(dummy); - let rect = clientRectsFor(dummy.firstChild)[0]; - lineHeight = dummy.getBoundingClientRect().height; - charWidth = rect ? rect.width / 27 : 7; - dummy.remove(); - }); - return { lineHeight, charWidth }; - } - childCursor(pos = this.length) { - // Move back to start of last element when possible, so that - // `ChildCursor.findPos` doesn't have to deal with the edge case - // of being after the last element. - let i = this.children.length; - if (i) - pos -= this.children[--i].length; - return new ChildCursor(this.children, pos, i); - } - computeBlockGapDeco() { - let deco = [], vs = this.view.viewState; - for (let pos = 0, i = 0;; i++) { - let next = i == vs.viewports.length ? null : vs.viewports[i]; - let end = next ? next.from - 1 : this.length; - if (end > pos) { - let height = vs.lineBlockAt(end).bottom - vs.lineBlockAt(pos).top; - deco.push(Decoration.replace({ - widget: new BlockGapWidget(height), - block: true, - inclusive: true, - isBlockGap: true, - }).range(pos, end)); - } - if (!next) - break; - pos = next.to + 1; - } - return Decoration.set(deco); - } - updateDeco() { - let pluginDecorations = this.view.pluginField(PluginField.decorations); - this.pluginDecorationLength = pluginDecorations.length; - return this.decorations = [ - ...pluginDecorations, - ...this.view.state.facet(decorations), - this.compositionDeco, - this.computeBlockGapDeco(), - this.view.viewState.lineGapDeco - ]; - } - scrollIntoView(target) { - let { range } = target; - let rect = this.coordsAt(range.head, range.empty ? range.assoc : range.head > range.anchor ? -1 : 1), other; - if (!rect) - return; - if (!range.empty && (other = this.coordsAt(range.anchor, range.anchor > range.head ? -1 : 1))) - rect = { left: Math.min(rect.left, other.left), top: Math.min(rect.top, other.top), - right: Math.max(rect.right, other.right), bottom: Math.max(rect.bottom, other.bottom) }; - let mLeft = 0, mRight = 0, mTop = 0, mBottom = 0; - for (let margins of this.view.pluginField(PluginField.scrollMargins)) - if (margins) { - let { left, right, top, bottom } = margins; - if (left != null) - mLeft = Math.max(mLeft, left); - if (right != null) - mRight = Math.max(mRight, right); - if (top != null) - mTop = Math.max(mTop, top); - if (bottom != null) - mBottom = Math.max(mBottom, bottom); - } - let targetRect = { - left: rect.left - mLeft, top: rect.top - mTop, - right: rect.right + mRight, bottom: rect.bottom + mBottom - }; - scrollRectIntoView(this.view.scrollDOM, targetRect, range.head < range.anchor ? -1 : 1, target.x, target.y, target.xMargin, target.yMargin, this.view.textDirection == Direction.LTR); - } - } - function betweenUneditable(pos) { - return pos.node.nodeType == 1 && pos.node.firstChild && - (pos.offset == 0 || pos.node.childNodes[pos.offset - 1].contentEditable == "false") && - (pos.offset == pos.node.childNodes.length || pos.node.childNodes[pos.offset].contentEditable == "false"); - } - class BlockGapWidget extends WidgetType { - constructor(height) { - super(); - this.height = height; - } - toDOM() { - let elt = document.createElement("div"); - this.updateDOM(elt); - return elt; - } - eq(other) { return other.height == this.height; } - updateDOM(elt) { - elt.style.height = this.height + "px"; - return true; - } - get estimatedHeight() { return this.height; } - } - function compositionSurroundingNode(view) { - let sel = view.observer.selectionRange; - let textNode = sel.focusNode && nearbyTextNode(sel.focusNode, sel.focusOffset, 0); - if (!textNode) - return null; - let cView = view.docView.nearest(textNode); - if (!cView) - return null; - if (cView instanceof LineView) { - let topNode = textNode; - while (topNode.parentNode != cView.dom) - topNode = topNode.parentNode; - let prev = topNode.previousSibling; - while (prev && !ContentView.get(prev)) - prev = prev.previousSibling; - let pos = prev ? ContentView.get(prev).posAtEnd : cView.posAtStart; - return { from: pos, to: pos, node: topNode, text: textNode }; - } - else { - for (;;) { - let { parent } = cView; - if (!parent) - return null; - if (parent instanceof LineView) - break; - cView = parent; - } - let from = cView.posAtStart; - return { from, to: from + cView.length, node: cView.dom, text: textNode }; - } - } - function computeCompositionDeco(view, changes) { - let surrounding = compositionSurroundingNode(view); - if (!surrounding) - return Decoration.none; - let { from, to, node, text: textNode } = surrounding; - let newFrom = changes.mapPos(from, 1), newTo = Math.max(newFrom, changes.mapPos(to, -1)); - let { state } = view, text = node.nodeType == 3 ? node.nodeValue : - new DOMReader([], state).readRange(node.firstChild, null).text; - if (newTo - newFrom < text.length) { - if (state.doc.sliceString(newFrom, Math.min(state.doc.length, newFrom + text.length), LineBreakPlaceholder) == text) - newTo = newFrom + text.length; - else if (state.doc.sliceString(Math.max(0, newTo - text.length), newTo, LineBreakPlaceholder) == text) - newFrom = newTo - text.length; - else - return Decoration.none; - } - else if (state.doc.sliceString(newFrom, newTo, LineBreakPlaceholder) != text) { - return Decoration.none; - } - let topView = ContentView.get(node); - if (topView instanceof CompositionView) - topView = topView.widget.topView; - else if (topView) - topView.parent = null; - return Decoration.set(Decoration.replace({ widget: new CompositionWidget(node, textNode, topView) }).range(newFrom, newTo)); - } - class CompositionWidget extends WidgetType { - constructor(top, text, topView) { - super(); - this.top = top; - this.text = text; - this.topView = topView; - } - eq(other) { return this.top == other.top && this.text == other.text; } - toDOM() { return this.top; } - ignoreEvent() { return false; } - get customView() { return CompositionView; } - } - function nearbyTextNode(node, offset, side) { - for (;;) { - if (node.nodeType == 3) - return node; - if (node.nodeType == 1 && offset > 0 && side <= 0) { - node = node.childNodes[offset - 1]; - offset = maxOffset(node); - } - else if (node.nodeType == 1 && offset < node.childNodes.length && side >= 0) { - node = node.childNodes[offset]; - offset = 0; - } - else { - return null; - } - } - } - function nextToUneditable(node, offset) { - if (node.nodeType != 1) - return 0; - return (offset && node.childNodes[offset - 1].contentEditable == "false" ? 1 /* Before */ : 0) | - (offset < node.childNodes.length && node.childNodes[offset].contentEditable == "false" ? 2 /* After */ : 0); - } - class DecorationComparator$1 { - constructor() { - this.changes = []; - } - compareRange(from, to) { addRange(from, to, this.changes); } - comparePoint(from, to) { addRange(from, to, this.changes); } - } - function findChangedDeco(a, b, diff) { - let comp = new DecorationComparator$1; - RangeSet.compare(a, b, diff, comp); - return comp.changes; - } - function inUneditable(node, inside) { - for (let cur = node; cur && cur != inside; cur = cur.assignedSlot || cur.parentNode) { - if (cur.nodeType == 1 && cur.contentEditable == 'false') { - return true; - } - } - return false; - } - - function groupAt(state, pos, bias = 1) { - let categorize = state.charCategorizer(pos); - let line = state.doc.lineAt(pos), linePos = pos - line.from; - if (line.length == 0) - return EditorSelection.cursor(pos); - if (linePos == 0) - bias = 1; - else if (linePos == line.length) - bias = -1; - let from = linePos, to = linePos; - if (bias < 0) - from = findClusterBreak(line.text, linePos, false); - else - to = findClusterBreak(line.text, linePos); - let cat = categorize(line.text.slice(from, to)); - while (from > 0) { - let prev = findClusterBreak(line.text, from, false); - if (categorize(line.text.slice(prev, from)) != cat) - break; - from = prev; - } - while (to < line.length) { - let next = findClusterBreak(line.text, to); - if (categorize(line.text.slice(to, next)) != cat) - break; - to = next; - } - return EditorSelection.range(from + line.from, to + line.from); - } - // Search the DOM for the {node, offset} position closest to the given - // coordinates. Very inefficient and crude, but can usually be avoided - // by calling caret(Position|Range)FromPoint instead. - function getdx(x, rect) { - return rect.left > x ? rect.left - x : Math.max(0, x - rect.right); - } - function getdy(y, rect) { - return rect.top > y ? rect.top - y : Math.max(0, y - rect.bottom); - } - function yOverlap(a, b) { - return a.top < b.bottom - 1 && a.bottom > b.top + 1; - } - function upTop(rect, top) { - return top < rect.top ? { top, left: rect.left, right: rect.right, bottom: rect.bottom } : rect; - } - function upBot(rect, bottom) { - return bottom > rect.bottom ? { top: rect.top, left: rect.left, right: rect.right, bottom } : rect; - } - function domPosAtCoords(parent, x, y) { - let closest, closestRect, closestX, closestY; - let above, below, aboveRect, belowRect; - for (let child = parent.firstChild; child; child = child.nextSibling) { - let rects = clientRectsFor(child); - for (let i = 0; i < rects.length; i++) { - let rect = rects[i]; - if (closestRect && yOverlap(closestRect, rect)) - rect = upTop(upBot(rect, closestRect.bottom), closestRect.top); - let dx = getdx(x, rect), dy = getdy(y, rect); - if (dx == 0 && dy == 0) - return child.nodeType == 3 ? domPosInText(child, x, y) : domPosAtCoords(child, x, y); - if (!closest || closestY > dy || closestY == dy && closestX > dx) { - closest = child; - closestRect = rect; - closestX = dx; - closestY = dy; - } - if (dx == 0) { - if (y > rect.bottom && (!aboveRect || aboveRect.bottom < rect.bottom)) { - above = child; - aboveRect = rect; - } - else if (y < rect.top && (!belowRect || belowRect.top > rect.top)) { - below = child; - belowRect = rect; - } - } - else if (aboveRect && yOverlap(aboveRect, rect)) { - aboveRect = upBot(aboveRect, rect.bottom); - } - else if (belowRect && yOverlap(belowRect, rect)) { - belowRect = upTop(belowRect, rect.top); - } - } - } - if (aboveRect && aboveRect.bottom >= y) { - closest = above; - closestRect = aboveRect; - } - else if (belowRect && belowRect.top <= y) { - closest = below; - closestRect = belowRect; - } - if (!closest) - return { node: parent, offset: 0 }; - let clipX = Math.max(closestRect.left, Math.min(closestRect.right, x)); - if (closest.nodeType == 3) - return domPosInText(closest, clipX, y); - if (!closestX && closest.contentEditable == "true") - return domPosAtCoords(closest, clipX, y); - let offset = Array.prototype.indexOf.call(parent.childNodes, closest) + - (x >= (closestRect.left + closestRect.right) / 2 ? 1 : 0); - return { node: parent, offset }; - } - function domPosInText(node, x, y) { - let len = node.nodeValue.length; - let closestOffset = -1, closestDY = 1e9, generalSide = 0; - for (let i = 0; i < len; i++) { - let rects = textRange(node, i, i + 1).getClientRects(); - for (let j = 0; j < rects.length; j++) { - let rect = rects[j]; - if (rect.top == rect.bottom) - continue; - if (!generalSide) - generalSide = x - rect.left; - let dy = (rect.top > y ? rect.top - y : y - rect.bottom) - 1; - if (rect.left - 1 <= x && rect.right + 1 >= x && dy < closestDY) { - let right = x >= (rect.left + rect.right) / 2, after = right; - if (browser.chrome || browser.gecko) { - // Check for RTL on browsers that support getting client - // rects for empty ranges. - let rectBefore = textRange(node, i).getBoundingClientRect(); - if (rectBefore.left == rect.right) - after = !right; - } - if (dy <= 0) - return { node, offset: i + (after ? 1 : 0) }; - closestOffset = i + (after ? 1 : 0); - closestDY = dy; - } - } - } - return { node, offset: closestOffset > -1 ? closestOffset : generalSide > 0 ? node.nodeValue.length : 0 }; - } - function posAtCoords(view, { x, y }, precise, bias = -1) { - var _a; - let content = view.contentDOM.getBoundingClientRect(), docTop = content.top + view.viewState.paddingTop; - let block, { docHeight } = view.viewState; - let yOffset = y - docTop; - if (yOffset < 0) - return 0; - if (yOffset > docHeight) - return view.state.doc.length; - // Scan for a text block near the queried y position - for (let halfLine = view.defaultLineHeight / 2, bounced = false;;) { - block = view.elementAtHeight(yOffset); - if (block.type == BlockType.Text) - break; - for (;;) { - // Move the y position out of this block - yOffset = bias > 0 ? block.bottom + halfLine : block.top - halfLine; - if (yOffset >= 0 && yOffset <= docHeight) - break; - // If the document consists entirely of replaced widgets, we - // won't find a text block, so return 0 - if (bounced) - return precise ? null : 0; - bounced = true; - bias = -bias; - } - } - y = docTop + yOffset; - let lineStart = block.from; - // If this is outside of the rendered viewport, we can't determine a position - if (lineStart < view.viewport.from) - return view.viewport.from == 0 ? 0 : precise ? null : posAtCoordsImprecise(view, content, block, x, y); - if (lineStart > view.viewport.to) - return view.viewport.to == view.state.doc.length ? view.state.doc.length : - precise ? null : posAtCoordsImprecise(view, content, block, x, y); - // Prefer ShadowRootOrDocument.elementFromPoint if present, fall back to document if not - let doc = view.dom.ownerDocument; - let root = view.root.elementFromPoint ? view.root : doc; - let element = root.elementFromPoint(x, y); - if (element && !view.contentDOM.contains(element)) - element = null; - // If the element is unexpected, clip x at the sides of the content area and try again - if (!element) { - x = Math.max(content.left + 1, Math.min(content.right - 1, x)); - element = root.elementFromPoint(x, y); - if (element && !view.contentDOM.contains(element)) - element = null; - } - // There's visible editor content under the point, so we can try - // using caret(Position|Range)FromPoint as a shortcut - let node, offset = -1; - if (element && ((_a = view.docView.nearest(element)) === null || _a === void 0 ? void 0 : _a.isEditable) != false) { - if (doc.caretPositionFromPoint) { - let pos = doc.caretPositionFromPoint(x, y); - if (pos) - ({ offsetNode: node, offset } = pos); - } - else if (doc.caretRangeFromPoint) { - let range = doc.caretRangeFromPoint(x, y); - if (range) { - ({ startContainer: node, startOffset: offset } = range); - if (browser.safari && isSuspiciousCaretResult(node, offset, x)) - node = undefined; - } - } - } - // No luck, do our own (potentially expensive) search - if (!node || !view.docView.dom.contains(node)) { - let line = LineView.find(view.docView, lineStart); - if (!line) - return yOffset > block.top + block.height / 2 ? block.to : block.from; - ({ node, offset } = domPosAtCoords(line.dom, x, y)); - } - return view.docView.posFromDOM(node, offset); - } - function posAtCoordsImprecise(view, contentRect, block, x, y) { - let into = Math.round((x - contentRect.left) * view.defaultCharacterWidth); - if (view.lineWrapping && block.height > view.defaultLineHeight * 1.5) { - let line = Math.floor((y - block.top) / view.defaultLineHeight); - into += line * view.viewState.heightOracle.lineLength; - } - let content = view.state.sliceDoc(block.from, block.to); - return block.from + findColumn(content, into, view.state.tabSize); - } - // In case of a high line height, Safari's caretRangeFromPoint treats - // the space between lines as belonging to the last character of the - // line before. This is used to detect such a result so that it can be - // ignored (issue #401). - function isSuspiciousCaretResult(node, offset, x) { - let len; - if (node.nodeType != 3 || offset != (len = node.nodeValue.length)) - return false; - for (let next = node.nextSibling; next; next = next.nextSibling) - if (next.nodeType != 1 || next.nodeName != "BR") - return false; - return textRange(node, len - 1, len).getBoundingClientRect().left > x; - } - function moveToLineBoundary(view, start, forward, includeWrap) { - let line = view.state.doc.lineAt(start.head); - let coords = !includeWrap || !view.lineWrapping ? null - : view.coordsAtPos(start.assoc < 0 && start.head > line.from ? start.head - 1 : start.head); - if (coords) { - let editorRect = view.dom.getBoundingClientRect(); - let pos = view.posAtCoords({ x: forward == (view.textDirection == Direction.LTR) ? editorRect.right - 1 : editorRect.left + 1, - y: (coords.top + coords.bottom) / 2 }); - if (pos != null) - return EditorSelection.cursor(pos, forward ? -1 : 1); - } - let lineView = LineView.find(view.docView, start.head); - let end = lineView ? (forward ? lineView.posAtEnd : lineView.posAtStart) : (forward ? line.to : line.from); - return EditorSelection.cursor(end, forward ? -1 : 1); - } - function moveByChar(view, start, forward, by) { - let line = view.state.doc.lineAt(start.head), spans = view.bidiSpans(line); - for (let cur = start, check = null;;) { - let next = moveVisually(line, spans, view.textDirection, cur, forward), char = movedOver; - if (!next) { - if (line.number == (forward ? view.state.doc.lines : 1)) - return cur; - char = "\n"; - line = view.state.doc.line(line.number + (forward ? 1 : -1)); - spans = view.bidiSpans(line); - next = EditorSelection.cursor(forward ? line.from : line.to); - } - if (!check) { - if (!by) - return next; - check = by(char); - } - else if (!check(char)) { - return cur; - } - cur = next; - } - } - function byGroup(view, pos, start) { - let categorize = view.state.charCategorizer(pos); - let cat = categorize(start); - return (next) => { - let nextCat = categorize(next); - if (cat == CharCategory.Space) - cat = nextCat; - return cat == nextCat; - }; - } - function moveVertically(view, start, forward, distance) { - let startPos = start.head, dir = forward ? 1 : -1; - if (startPos == (forward ? view.state.doc.length : 0)) - return EditorSelection.cursor(startPos, start.assoc); - let goal = start.goalColumn, startY; - let rect = view.contentDOM.getBoundingClientRect(); - let startCoords = view.coordsAtPos(startPos), docTop = view.documentTop; - if (startCoords) { - if (goal == null) - goal = startCoords.left - rect.left; - startY = dir < 0 ? startCoords.top : startCoords.bottom; - } - else { - let line = view.viewState.lineBlockAt(startPos - docTop); - if (goal == null) - goal = Math.min(rect.right - rect.left, view.defaultCharacterWidth * (startPos - line.from)); - startY = (dir < 0 ? line.top : line.bottom) + docTop; - } - let resolvedGoal = rect.left + goal; - let dist = distance !== null && distance !== void 0 ? distance : (view.defaultLineHeight >> 1); - for (let extra = 0;; extra += 10) { - let curY = startY + (dist + extra) * dir; - let pos = posAtCoords(view, { x: resolvedGoal, y: curY }, false, dir); - if (curY < rect.top || curY > rect.bottom || (dir < 0 ? pos < startPos : pos > startPos)) - return EditorSelection.cursor(pos, start.assoc, undefined, goal); - } - } - function skipAtoms(view, oldPos, pos) { - let atoms = view.pluginField(PluginField.atomicRanges); - for (;;) { - let moved = false; - for (let set of atoms) { - set.between(pos.from - 1, pos.from + 1, (from, to, value) => { - if (pos.from > from && pos.from < to) { - pos = oldPos.from > pos.from ? EditorSelection.cursor(from, 1) : EditorSelection.cursor(to, -1); - moved = true; - } - }); - } - if (!moved) - return pos; - } - } - - // This will also be where dragging info and such goes - class InputState { - constructor(view) { - this.lastKeyCode = 0; - this.lastKeyTime = 0; - // On iOS, some keys need to have their default behavior happen - // (after which we retroactively handle them and reset the DOM) to - // avoid messing up the virtual keyboard state. - this.pendingIOSKey = undefined; - this.lastSelectionOrigin = null; - this.lastSelectionTime = 0; - this.lastEscPress = 0; - this.lastContextMenu = 0; - this.scrollHandlers = []; - this.registeredEvents = []; - this.customHandlers = []; - // -1 means not in a composition. Otherwise, this counts the number - // of changes made during the composition. The count is used to - // avoid treating the start state of the composition, before any - // changes have been made, as part of the composition. - this.composing = -1; - // Tracks whether the next change should be marked as starting the - // composition (null means no composition, true means next is the - // first, false means first has already been marked for this - // composition) - this.compositionFirstChange = null; - this.compositionEndedAt = 0; - this.rapidCompositionStart = false; - this.mouseSelection = null; - for (let type in handlers) { - let handler = handlers[type]; - view.contentDOM.addEventListener(type, (event) => { - if (!eventBelongsToEditor(view, event) || this.ignoreDuringComposition(event)) - return; - if (type == "keydown" && this.keydown(view, event)) - return; - if (this.mustFlushObserver(event)) - view.observer.forceFlush(); - if (this.runCustomHandlers(type, view, event)) - event.preventDefault(); - else - handler(view, event); - }); - this.registeredEvents.push(type); - } - this.notifiedFocused = view.hasFocus; - this.ensureHandlers(view); - // On Safari adding an input event handler somehow prevents an - // issue where the composition vanishes when you press enter. - if (browser.safari) - view.contentDOM.addEventListener("input", () => null); - } - setSelectionOrigin(origin) { - this.lastSelectionOrigin = origin; - this.lastSelectionTime = Date.now(); - } - ensureHandlers(view) { - let handlers = this.customHandlers = view.pluginField(domEventHandlers); - for (let set of handlers) { - for (let type in set.handlers) - if (this.registeredEvents.indexOf(type) < 0 && type != "scroll") { - this.registeredEvents.push(type); - view.contentDOM.addEventListener(type, (event) => { - if (!eventBelongsToEditor(view, event)) - return; - if (this.runCustomHandlers(type, view, event)) - event.preventDefault(); - }); - } - } - } - runCustomHandlers(type, view, event) { - for (let set of this.customHandlers) { - let handler = set.handlers[type]; - if (handler) { - try { - if (handler.call(set.plugin, event, view) || event.defaultPrevented) - return true; - } - catch (e) { - logException(view.state, e); - } - } - } - return false; - } - runScrollHandlers(view, event) { - for (let set of this.customHandlers) { - let handler = set.handlers.scroll; - if (handler) { - try { - handler.call(set.plugin, event, view); - } - catch (e) { - logException(view.state, e); - } - } - } - } - keydown(view, event) { - // Must always run, even if a custom handler handled the event - this.lastKeyCode = event.keyCode; - this.lastKeyTime = Date.now(); - if (event.keyCode == 9 && Date.now() < this.lastEscPress + 2000) - return true; - // Chrome for Android usually doesn't fire proper key events, but - // occasionally does, usually surrounded by a bunch of complicated - // composition changes. When an enter or backspace key event is - // seen, hold off on handling DOM events for a bit, and then - // dispatch it. - if (browser.android && browser.chrome && !event.synthetic && - (event.keyCode == 13 || event.keyCode == 8)) { - view.observer.delayAndroidKey(event.key, event.keyCode); - return true; - } - // Prevent the default behavior of Enter on iOS makes the - // virtual keyboard get stuck in the wrong (lowercase) - // state. So we let it go through, and then, in - // applyDOMChange, notify key handlers of it and reset to - // the state they produce. - let pending; - if (browser.ios && (pending = PendingKeys.find(key => key.keyCode == event.keyCode)) && - !(event.ctrlKey || event.altKey || event.metaKey) && !event.synthetic) { - this.pendingIOSKey = pending; - setTimeout(() => this.flushIOSKey(view), 250); - return true; - } - return false; - } - flushIOSKey(view) { - let key = this.pendingIOSKey; - if (!key) - return false; - this.pendingIOSKey = undefined; - return dispatchKey(view.contentDOM, key.key, key.keyCode); - } - ignoreDuringComposition(event) { - if (!/^key/.test(event.type)) - return false; - if (this.composing > 0) - return true; - // See https://www.stum.de/2016/06/24/handling-ime-events-in-javascript/. - // On some input method editors (IMEs), the Enter key is used to - // confirm character selection. On Safari, when Enter is pressed, - // compositionend and keydown events are sometimes emitted in the - // wrong order. The key event should still be ignored, even when - // it happens after the compositionend event. - if (browser.safari && Date.now() - this.compositionEndedAt < 500) { - this.compositionEndedAt = 0; - return true; - } - return false; - } - mustFlushObserver(event) { - return (event.type == "keydown" && event.keyCode != 229) || - event.type == "compositionend" && !browser.ios; - } - startMouseSelection(mouseSelection) { - if (this.mouseSelection) - this.mouseSelection.destroy(); - this.mouseSelection = mouseSelection; - } - update(update) { - if (this.mouseSelection) - this.mouseSelection.update(update); - if (update.transactions.length) - this.lastKeyCode = this.lastSelectionTime = 0; - } - destroy() { - if (this.mouseSelection) - this.mouseSelection.destroy(); - } - } - const PendingKeys = [ - { key: "Backspace", keyCode: 8, inputType: "deleteContentBackward" }, - { key: "Enter", keyCode: 13, inputType: "insertParagraph" }, - { key: "Delete", keyCode: 46, inputType: "deleteContentForward" } - ]; - // Key codes for modifier keys - const modifierCodes = [16, 17, 18, 20, 91, 92, 224, 225]; - class MouseSelection { - constructor(view, startEvent, style, mustSelect) { - this.view = view; - this.style = style; - this.mustSelect = mustSelect; - this.lastEvent = startEvent; - let doc = view.contentDOM.ownerDocument; - doc.addEventListener("mousemove", this.move = this.move.bind(this)); - doc.addEventListener("mouseup", this.up = this.up.bind(this)); - this.extend = startEvent.shiftKey; - this.multiple = view.state.facet(EditorState.allowMultipleSelections) && addsSelectionRange(view, startEvent); - this.dragMove = dragMovesSelection(view, startEvent); - this.dragging = isInPrimarySelection(view, startEvent) && getClickType(startEvent) == 1 ? null : false; - // When clicking outside of the selection, immediately apply the - // effect of starting the selection - if (this.dragging === false) { - startEvent.preventDefault(); - this.select(startEvent); - } - } - move(event) { - if (event.buttons == 0) - return this.destroy(); - if (this.dragging !== false) - return; - this.select(this.lastEvent = event); - } - up(event) { - if (this.dragging == null) - this.select(this.lastEvent); - if (!this.dragging) - event.preventDefault(); - this.destroy(); - } - destroy() { - let doc = this.view.contentDOM.ownerDocument; - doc.removeEventListener("mousemove", this.move); - doc.removeEventListener("mouseup", this.up); - this.view.inputState.mouseSelection = null; - } - select(event) { - let selection = this.style.get(event, this.extend, this.multiple); - if (this.mustSelect || !selection.eq(this.view.state.selection) || - selection.main.assoc != this.view.state.selection.main.assoc) - this.view.dispatch({ - selection, - userEvent: "select.pointer", - scrollIntoView: true - }); - this.mustSelect = false; - } - update(update) { - if (update.docChanged && this.dragging) - this.dragging = this.dragging.map(update.changes); - if (this.style.update(update)) - setTimeout(() => this.select(this.lastEvent), 20); - } - } - function addsSelectionRange(view, event) { - let facet = view.state.facet(clickAddsSelectionRange); - return facet.length ? facet[0](event) : browser.mac ? event.metaKey : event.ctrlKey; - } - function dragMovesSelection(view, event) { - let facet = view.state.facet(dragMovesSelection$1); - return facet.length ? facet[0](event) : browser.mac ? !event.altKey : !event.ctrlKey; - } - function isInPrimarySelection(view, event) { - let { main } = view.state.selection; - if (main.empty) - return false; - // On boundary clicks, check whether the coordinates are inside the - // selection's client rectangles - let sel = getSelection(view.root); - if (sel.rangeCount == 0) - return true; - let rects = sel.getRangeAt(0).getClientRects(); - for (let i = 0; i < rects.length; i++) { - let rect = rects[i]; - if (rect.left <= event.clientX && rect.right >= event.clientX && - rect.top <= event.clientY && rect.bottom >= event.clientY) - return true; - } - return false; - } - function eventBelongsToEditor(view, event) { - if (!event.bubbles) - return true; - if (event.defaultPrevented) - return false; - for (let node = event.target, cView; node != view.contentDOM; node = node.parentNode) - if (!node || node.nodeType == 11 || ((cView = ContentView.get(node)) && cView.ignoreEvent(event))) - return false; - return true; - } - const handlers = /*@__PURE__*/Object.create(null); - // This is very crude, but unfortunately both these browsers _pretend_ - // that they have a clipboard API—all the objects and methods are - // there, they just don't work, and they are hard to test. - const brokenClipboardAPI = (browser.ie && browser.ie_version < 15) || - (browser.ios && browser.webkit_version < 604); - function capturePaste(view) { - let parent = view.dom.parentNode; - if (!parent) - return; - let target = parent.appendChild(document.createElement("textarea")); - target.style.cssText = "position: fixed; left: -10000px; top: 10px"; - target.focus(); - setTimeout(() => { - view.focus(); - target.remove(); - doPaste(view, target.value); - }, 50); - } - function doPaste(view, input) { - let { state } = view, changes, i = 1, text = state.toText(input); - let byLine = text.lines == state.selection.ranges.length; - let linewise = lastLinewiseCopy != null && state.selection.ranges.every(r => r.empty) && lastLinewiseCopy == text.toString(); - if (linewise) { - let lastLine = -1; - changes = state.changeByRange(range => { - let line = state.doc.lineAt(range.from); - if (line.from == lastLine) - return { range }; - lastLine = line.from; - let insert = state.toText((byLine ? text.line(i++).text : input) + state.lineBreak); - return { changes: { from: line.from, insert }, - range: EditorSelection.cursor(range.from + insert.length) }; - }); - } - else if (byLine) { - changes = state.changeByRange(range => { - let line = text.line(i++); - return { changes: { from: range.from, to: range.to, insert: line.text }, - range: EditorSelection.cursor(range.from + line.length) }; - }); - } - else { - changes = state.replaceSelection(text); - } - view.dispatch(changes, { - userEvent: "input.paste", - scrollIntoView: true - }); - } - handlers.keydown = (view, event) => { - view.inputState.setSelectionOrigin("select"); - if (event.keyCode == 27) - view.inputState.lastEscPress = Date.now(); - else if (modifierCodes.indexOf(event.keyCode) < 0) - view.inputState.lastEscPress = 0; - }; - let lastTouch = 0; - handlers.touchstart = (view, e) => { - lastTouch = Date.now(); - view.inputState.setSelectionOrigin("select.pointer"); - }; - handlers.touchmove = view => { - view.inputState.setSelectionOrigin("select.pointer"); - }; - handlers.mousedown = (view, event) => { - view.observer.flush(); - if (lastTouch > Date.now() - 2000 && getClickType(event) == 1) - return; // Ignore touch interaction - let style = null; - for (let makeStyle of view.state.facet(mouseSelectionStyle)) { - style = makeStyle(view, event); - if (style) - break; - } - if (!style && event.button == 0) - style = basicMouseSelection(view, event); - if (style) { - let mustFocus = view.root.activeElement != view.contentDOM; - if (mustFocus) - view.observer.ignore(() => focusPreventScroll(view.contentDOM)); - view.inputState.startMouseSelection(new MouseSelection(view, event, style, mustFocus)); - } - }; - function rangeForClick(view, pos, bias, type) { - if (type == 1) { // Single click - return EditorSelection.cursor(pos, bias); - } - else if (type == 2) { // Double click - return groupAt(view.state, pos, bias); - } - else { // Triple click - let visual = LineView.find(view.docView, pos), line = view.state.doc.lineAt(visual ? visual.posAtEnd : pos); - let from = visual ? visual.posAtStart : line.from, to = visual ? visual.posAtEnd : line.to; - if (to < view.state.doc.length && to == line.to) - to++; - return EditorSelection.range(from, to); - } - } - let insideY = (y, rect) => y >= rect.top && y <= rect.bottom; - let inside = (x, y, rect) => insideY(y, rect) && x >= rect.left && x <= rect.right; - // Try to determine, for the given coordinates, associated with the - // given position, whether they are related to the element before or - // the element after the position. - function findPositionSide(view, pos, x, y) { - let line = LineView.find(view.docView, pos); - if (!line) - return 1; - let off = pos - line.posAtStart; - // Line boundaries point into the line - if (off == 0) - return 1; - if (off == line.length) - return -1; - // Positions on top of an element point at that element - let before = line.coordsAt(off, -1); - if (before && inside(x, y, before)) - return -1; - let after = line.coordsAt(off, 1); - if (after && inside(x, y, after)) - return 1; - // This is probably a line wrap point. Pick before if the point is - // beside it. - return before && insideY(y, before) ? -1 : 1; - } - function queryPos(view, event) { - let pos = view.posAtCoords({ x: event.clientX, y: event.clientY }, false); - return { pos, bias: findPositionSide(view, pos, event.clientX, event.clientY) }; - } - const BadMouseDetail = browser.ie && browser.ie_version <= 11; - let lastMouseDown = null, lastMouseDownCount = 0, lastMouseDownTime = 0; - function getClickType(event) { - if (!BadMouseDetail) - return event.detail; - let last = lastMouseDown, lastTime = lastMouseDownTime; - lastMouseDown = event; - lastMouseDownTime = Date.now(); - return lastMouseDownCount = !last || (lastTime > Date.now() - 400 && Math.abs(last.clientX - event.clientX) < 2 && - Math.abs(last.clientY - event.clientY) < 2) ? (lastMouseDownCount + 1) % 3 : 1; - } - function basicMouseSelection(view, event) { - let start = queryPos(view, event), type = getClickType(event); - let startSel = view.state.selection; - let last = start, lastEvent = event; - return { - update(update) { - if (update.docChanged) { - if (start) - start.pos = update.changes.mapPos(start.pos); - startSel = startSel.map(update.changes); - lastEvent = null; - } - }, - get(event, extend, multiple) { - let cur; - if (lastEvent && event.clientX == lastEvent.clientX && event.clientY == lastEvent.clientY) - cur = last; - else { - cur = last = queryPos(view, event); - lastEvent = event; - } - if (!cur || !start) - return startSel; - let range = rangeForClick(view, cur.pos, cur.bias, type); - if (start.pos != cur.pos && !extend) { - let startRange = rangeForClick(view, start.pos, start.bias, type); - let from = Math.min(startRange.from, range.from), to = Math.max(startRange.to, range.to); - range = from < range.from ? EditorSelection.range(from, to) : EditorSelection.range(to, from); - } - if (extend) - return startSel.replaceRange(startSel.main.extend(range.from, range.to)); - else if (multiple) - return startSel.addRange(range); - else - return EditorSelection.create([range]); - } - }; - } - handlers.dragstart = (view, event) => { - let { selection: { main } } = view.state; - let { mouseSelection } = view.inputState; - if (mouseSelection) - mouseSelection.dragging = main; - if (event.dataTransfer) { - event.dataTransfer.setData("Text", view.state.sliceDoc(main.from, main.to)); - event.dataTransfer.effectAllowed = "copyMove"; - } - }; - function dropText(view, event, text, direct) { - if (!text) - return; - let dropPos = view.posAtCoords({ x: event.clientX, y: event.clientY }, false); - event.preventDefault(); - let { mouseSelection } = view.inputState; - let del = direct && mouseSelection && mouseSelection.dragging && mouseSelection.dragMove ? - { from: mouseSelection.dragging.from, to: mouseSelection.dragging.to } : null; - let ins = { from: dropPos, insert: text }; - let changes = view.state.changes(del ? [del, ins] : ins); - view.focus(); - view.dispatch({ - changes, - selection: { anchor: changes.mapPos(dropPos, -1), head: changes.mapPos(dropPos, 1) }, - userEvent: del ? "move.drop" : "input.drop" - }); - } - handlers.drop = (view, event) => { - if (!event.dataTransfer) - return; - if (view.state.readOnly) - return event.preventDefault(); - let files = event.dataTransfer.files; - if (files && files.length) { // For a file drop, read the file's text. - event.preventDefault(); - let text = Array(files.length), read = 0; - let finishFile = () => { - if (++read == files.length) - dropText(view, event, text.filter(s => s != null).join(view.state.lineBreak), false); - }; - for (let i = 0; i < files.length; i++) { - let reader = new FileReader; - reader.onerror = finishFile; - reader.onload = () => { - if (!/[\x00-\x08\x0e-\x1f]{2}/.test(reader.result)) - text[i] = reader.result; - finishFile(); - }; - reader.readAsText(files[i]); - } - } - else { - dropText(view, event, event.dataTransfer.getData("Text"), true); - } - }; - handlers.paste = (view, event) => { - if (view.state.readOnly) - return event.preventDefault(); - view.observer.flush(); - let data = brokenClipboardAPI ? null : event.clipboardData; - if (data) { - doPaste(view, data.getData("text/plain")); - event.preventDefault(); - } - else { - capturePaste(view); - } - }; - function captureCopy(view, text) { - // The extra wrapper is somehow necessary on IE/Edge to prevent the - // content from being mangled when it is put onto the clipboard - let parent = view.dom.parentNode; - if (!parent) - return; - let target = parent.appendChild(document.createElement("textarea")); - target.style.cssText = "position: fixed; left: -10000px; top: 10px"; - target.value = text; - target.focus(); - target.selectionEnd = text.length; - target.selectionStart = 0; - setTimeout(() => { - target.remove(); - view.focus(); - }, 50); - } - function copiedRange(state) { - let content = [], ranges = [], linewise = false; - for (let range of state.selection.ranges) - if (!range.empty) { - content.push(state.sliceDoc(range.from, range.to)); - ranges.push(range); - } - if (!content.length) { - // Nothing selected, do a line-wise copy - let upto = -1; - for (let { from } of state.selection.ranges) { - let line = state.doc.lineAt(from); - if (line.number > upto) { - content.push(line.text); - ranges.push({ from: line.from, to: Math.min(state.doc.length, line.to + 1) }); - } - upto = line.number; - } - linewise = true; - } - return { text: content.join(state.lineBreak), ranges, linewise }; - } - let lastLinewiseCopy = null; - handlers.copy = handlers.cut = (view, event) => { - let { text, ranges, linewise } = copiedRange(view.state); - if (!text && !linewise) - return; - lastLinewiseCopy = linewise ? text : null; - let data = brokenClipboardAPI ? null : event.clipboardData; - if (data) { - event.preventDefault(); - data.clearData(); - data.setData("text/plain", text); - } - else { - captureCopy(view, text); - } - if (event.type == "cut" && !view.state.readOnly) - view.dispatch({ - changes: ranges, - scrollIntoView: true, - userEvent: "delete.cut" - }); - }; - handlers.focus = handlers.blur = view => { - setTimeout(() => { - if (view.hasFocus != view.inputState.notifiedFocused) - view.update([]); - }, 10); - }; - function forceClearComposition(view, rapid) { - if (view.docView.compositionDeco.size) { - view.inputState.rapidCompositionStart = rapid; - try { - view.update([]); - } - finally { - view.inputState.rapidCompositionStart = false; - } - } - } - handlers.compositionstart = handlers.compositionupdate = view => { - if (view.inputState.compositionFirstChange == null) - view.inputState.compositionFirstChange = true; - if (view.inputState.composing < 0) { - // FIXME possibly set a timeout to clear it again on Android - view.inputState.composing = 0; - if (view.docView.compositionDeco.size) { - view.observer.flush(); - forceClearComposition(view, true); - } - } - }; - handlers.compositionend = view => { - view.inputState.composing = -1; - view.inputState.compositionEndedAt = Date.now(); - view.inputState.compositionFirstChange = null; - setTimeout(() => { - if (view.inputState.composing < 0) - forceClearComposition(view, false); - }, 50); - }; - handlers.contextmenu = view => { - view.inputState.lastContextMenu = Date.now(); - }; - handlers.beforeinput = (view, event) => { - var _a; - // Because Chrome Android doesn't fire useful key events, use - // beforeinput to detect backspace (and possibly enter and delete, - // but those usually don't even seem to fire beforeinput events at - // the moment) and fake a key event for it. - // - // (preventDefault on beforeinput, though supported in the spec, - // seems to do nothing at all on Chrome). - let pending; - if (browser.chrome && browser.android && (pending = PendingKeys.find(key => key.inputType == event.inputType))) { - view.observer.delayAndroidKey(pending.key, pending.keyCode); - if (pending.key == "Backspace" || pending.key == "Delete") { - let startViewHeight = ((_a = window.visualViewport) === null || _a === void 0 ? void 0 : _a.height) || 0; - setTimeout(() => { - var _a; - // Backspacing near uneditable nodes on Chrome Android sometimes - // closes the virtual keyboard. This tries to crudely detect - // that and refocus to get it back. - if ((((_a = window.visualViewport) === null || _a === void 0 ? void 0 : _a.height) || 0) > startViewHeight + 10 && view.hasFocus) { - view.contentDOM.blur(); - view.focus(); - } - }, 100); - } - } - }; - - const wrappingWhiteSpace = ["pre-wrap", "normal", "pre-line", "break-spaces"]; - class HeightOracle { - constructor() { - this.doc = Text.empty; - this.lineWrapping = false; - this.direction = Direction.LTR; - this.heightSamples = {}; - this.lineHeight = 14; - this.charWidth = 7; - this.lineLength = 30; - // Used to track, during updateHeight, if any actual heights changed - this.heightChanged = false; - } - heightForGap(from, to) { - let lines = this.doc.lineAt(to).number - this.doc.lineAt(from).number + 1; - if (this.lineWrapping) - lines += Math.ceil(((to - from) - (lines * this.lineLength * 0.5)) / this.lineLength); - return this.lineHeight * lines; - } - heightForLine(length) { - if (!this.lineWrapping) - return this.lineHeight; - let lines = 1 + Math.max(0, Math.ceil((length - this.lineLength) / (this.lineLength - 5))); - return lines * this.lineHeight; - } - setDoc(doc) { this.doc = doc; return this; } - mustRefreshForStyle(whiteSpace, direction) { - return (wrappingWhiteSpace.indexOf(whiteSpace) > -1) != this.lineWrapping || this.direction != direction; - } - mustRefreshForHeights(lineHeights) { - let newHeight = false; - for (let i = 0; i < lineHeights.length; i++) { - let h = lineHeights[i]; - if (h < 0) { - i++; - } - else if (!this.heightSamples[Math.floor(h * 10)]) { // Round to .1 pixels - newHeight = true; - this.heightSamples[Math.floor(h * 10)] = true; - } - } - return newHeight; - } - refresh(whiteSpace, direction, lineHeight, charWidth, lineLength, knownHeights) { - let lineWrapping = wrappingWhiteSpace.indexOf(whiteSpace) > -1; - let changed = Math.round(lineHeight) != Math.round(this.lineHeight) || - this.lineWrapping != lineWrapping || - this.direction != direction; - this.lineWrapping = lineWrapping; - this.direction = direction; - this.lineHeight = lineHeight; - this.charWidth = charWidth; - this.lineLength = lineLength; - if (changed) { - this.heightSamples = {}; - for (let i = 0; i < knownHeights.length; i++) { - let h = knownHeights[i]; - if (h < 0) - i++; - else - this.heightSamples[Math.floor(h * 10)] = true; - } - } - return changed; - } - } - // This object is used by `updateHeight` to make DOM measurements - // arrive at the right nides. The `heights` array is a sequence of - // block heights, starting from position `from`. - class MeasuredHeights { - constructor(from, heights) { - this.from = from; - this.heights = heights; - this.index = 0; - } - get more() { return this.index < this.heights.length; } - } - /** - Record used to represent information about a block-level element - in the editor view. - */ - class BlockInfo { - /** - @internal - */ - constructor( - /** - The start of the element in the document. - */ - from, - /** - The length of the element. - */ - length, - /** - The top position of the element (relative to the top of the - document). - */ - top, - /** - Its height. - */ - height, - /** - The type of element this is. When querying lines, this may be - an array of all the blocks that make up the line. - */ - type) { - this.from = from; - this.length = length; - this.top = top; - this.height = height; - this.type = type; - } - /** - The end of the element as a document position. - */ - get to() { return this.from + this.length; } - /** - The bottom position of the element. - */ - get bottom() { return this.top + this.height; } - /** - @internal - */ - join(other) { - let detail = (Array.isArray(this.type) ? this.type : [this]) - .concat(Array.isArray(other.type) ? other.type : [other]); - return new BlockInfo(this.from, this.length + other.length, this.top, this.height + other.height, detail); - } - /** - FIXME remove on next breaking release @internal - */ - moveY(offset) { - return !offset ? this : new BlockInfo(this.from, this.length, this.top + offset, this.height, Array.isArray(this.type) ? this.type.map(b => b.moveY(offset)) : this.type); - } - } - var QueryType$1 = /*@__PURE__*/(function (QueryType) { - QueryType[QueryType["ByPos"] = 0] = "ByPos"; - QueryType[QueryType["ByHeight"] = 1] = "ByHeight"; - QueryType[QueryType["ByPosNoHeight"] = 2] = "ByPosNoHeight"; - return QueryType})(QueryType$1 || (QueryType$1 = {})); - const Epsilon = 1e-3; - class HeightMap { - constructor(length, // The number of characters covered - height, // Height of this part of the document - flags = 2 /* Outdated */) { - this.length = length; - this.height = height; - this.flags = flags; - } - get outdated() { return (this.flags & 2 /* Outdated */) > 0; } - set outdated(value) { this.flags = (value ? 2 /* Outdated */ : 0) | (this.flags & ~2 /* Outdated */); } - setHeight(oracle, height) { - if (this.height != height) { - if (Math.abs(this.height - height) > Epsilon) - oracle.heightChanged = true; - this.height = height; - } - } - // Base case is to replace a leaf node, which simply builds a tree - // from the new nodes and returns that (HeightMapBranch and - // HeightMapGap override this to actually use from/to) - replace(_from, _to, nodes) { - return HeightMap.of(nodes); - } - // Again, these are base cases, and are overridden for branch and gap nodes. - decomposeLeft(_to, result) { result.push(this); } - decomposeRight(_from, result) { result.push(this); } - applyChanges(decorations, oldDoc, oracle, changes) { - let me = this; - for (let i = changes.length - 1; i >= 0; i--) { - let { fromA, toA, fromB, toB } = changes[i]; - let start = me.lineAt(fromA, QueryType$1.ByPosNoHeight, oldDoc, 0, 0); - let end = start.to >= toA ? start : me.lineAt(toA, QueryType$1.ByPosNoHeight, oldDoc, 0, 0); - toB += end.to - toA; - toA = end.to; - while (i > 0 && start.from <= changes[i - 1].toA) { - fromA = changes[i - 1].fromA; - fromB = changes[i - 1].fromB; - i--; - if (fromA < start.from) - start = me.lineAt(fromA, QueryType$1.ByPosNoHeight, oldDoc, 0, 0); - } - fromB += start.from - fromA; - fromA = start.from; - let nodes = NodeBuilder.build(oracle, decorations, fromB, toB); - me = me.replace(fromA, toA, nodes); - } - return me.updateHeight(oracle, 0); - } - static empty() { return new HeightMapText(0, 0); } - // nodes uses null values to indicate the position of line breaks. - // There are never line breaks at the start or end of the array, or - // two line breaks next to each other, and the array isn't allowed - // to be empty (same restrictions as return value from the builder). - static of(nodes) { - if (nodes.length == 1) - return nodes[0]; - let i = 0, j = nodes.length, before = 0, after = 0; - for (;;) { - if (i == j) { - if (before > after * 2) { - let split = nodes[i - 1]; - if (split.break) - nodes.splice(--i, 1, split.left, null, split.right); - else - nodes.splice(--i, 1, split.left, split.right); - j += 1 + split.break; - before -= split.size; - } - else if (after > before * 2) { - let split = nodes[j]; - if (split.break) - nodes.splice(j, 1, split.left, null, split.right); - else - nodes.splice(j, 1, split.left, split.right); - j += 2 + split.break; - after -= split.size; - } - else { - break; - } - } - else if (before < after) { - let next = nodes[i++]; - if (next) - before += next.size; - } - else { - let next = nodes[--j]; - if (next) - after += next.size; - } - } - let brk = 0; - if (nodes[i - 1] == null) { - brk = 1; - i--; - } - else if (nodes[i] == null) { - brk = 1; - j++; - } - return new HeightMapBranch(HeightMap.of(nodes.slice(0, i)), brk, HeightMap.of(nodes.slice(j))); - } - } - HeightMap.prototype.size = 1; - class HeightMapBlock extends HeightMap { - constructor(length, height, type) { - super(length, height); - this.type = type; - } - blockAt(_height, _doc, top, offset) { - return new BlockInfo(offset, this.length, top, this.height, this.type); - } - lineAt(_value, _type, doc, top, offset) { - return this.blockAt(0, doc, top, offset); - } - forEachLine(_from, _to, doc, top, offset, f) { - f(this.blockAt(0, doc, top, offset)); - } - updateHeight(oracle, offset = 0, _force = false, measured) { - if (measured && measured.from <= offset && measured.more) - this.setHeight(oracle, measured.heights[measured.index++]); - this.outdated = false; - return this; - } - toString() { return `block(${this.length})`; } - } - class HeightMapText extends HeightMapBlock { - constructor(length, height) { - super(length, height, BlockType.Text); - this.collapsed = 0; // Amount of collapsed content in the line - this.widgetHeight = 0; // Maximum inline widget height - } - replace(_from, _to, nodes) { - let node = nodes[0]; - if (nodes.length == 1 && (node instanceof HeightMapText || node instanceof HeightMapGap && (node.flags & 4 /* SingleLine */)) && - Math.abs(this.length - node.length) < 10) { - if (node instanceof HeightMapGap) - node = new HeightMapText(node.length, this.height); - else - node.height = this.height; - if (!this.outdated) - node.outdated = false; - return node; - } - else { - return HeightMap.of(nodes); - } - } - updateHeight(oracle, offset = 0, force = false, measured) { - if (measured && measured.from <= offset && measured.more) - this.setHeight(oracle, measured.heights[measured.index++]); - else if (force || this.outdated) - this.setHeight(oracle, Math.max(this.widgetHeight, oracle.heightForLine(this.length - this.collapsed))); - this.outdated = false; - return this; - } - toString() { - return `line(${this.length}${this.collapsed ? -this.collapsed : ""}${this.widgetHeight ? ":" + this.widgetHeight : ""})`; - } - } - class HeightMapGap extends HeightMap { - constructor(length) { super(length, 0); } - lines(doc, offset) { - let firstLine = doc.lineAt(offset).number, lastLine = doc.lineAt(offset + this.length).number; - return { firstLine, lastLine, lineHeight: this.height / (lastLine - firstLine + 1) }; - } - blockAt(height, doc, top, offset) { - let { firstLine, lastLine, lineHeight } = this.lines(doc, offset); - let line = Math.max(0, Math.min(lastLine - firstLine, Math.floor((height - top) / lineHeight))); - let { from, length } = doc.line(firstLine + line); - return new BlockInfo(from, length, top + lineHeight * line, lineHeight, BlockType.Text); - } - lineAt(value, type, doc, top, offset) { - if (type == QueryType$1.ByHeight) - return this.blockAt(value, doc, top, offset); - if (type == QueryType$1.ByPosNoHeight) { - let { from, to } = doc.lineAt(value); - return new BlockInfo(from, to - from, 0, 0, BlockType.Text); - } - let { firstLine, lineHeight } = this.lines(doc, offset); - let { from, length, number } = doc.lineAt(value); - return new BlockInfo(from, length, top + lineHeight * (number - firstLine), lineHeight, BlockType.Text); - } - forEachLine(from, to, doc, top, offset, f) { - let { firstLine, lineHeight } = this.lines(doc, offset); - for (let pos = Math.max(from, offset), end = Math.min(offset + this.length, to); pos <= end;) { - let line = doc.lineAt(pos); - if (pos == from) - top += lineHeight * (line.number - firstLine); - f(new BlockInfo(line.from, line.length, top, lineHeight, BlockType.Text)); - top += lineHeight; - pos = line.to + 1; - } - } - replace(from, to, nodes) { - let after = this.length - to; - if (after > 0) { - let last = nodes[nodes.length - 1]; - if (last instanceof HeightMapGap) - nodes[nodes.length - 1] = new HeightMapGap(last.length + after); - else - nodes.push(null, new HeightMapGap(after - 1)); - } - if (from > 0) { - let first = nodes[0]; - if (first instanceof HeightMapGap) - nodes[0] = new HeightMapGap(from + first.length); - else - nodes.unshift(new HeightMapGap(from - 1), null); - } - return HeightMap.of(nodes); - } - decomposeLeft(to, result) { - result.push(new HeightMapGap(to - 1), null); - } - decomposeRight(from, result) { - result.push(null, new HeightMapGap(this.length - from - 1)); - } - updateHeight(oracle, offset = 0, force = false, measured) { - let end = offset + this.length; - if (measured && measured.from <= offset + this.length && measured.more) { - // Fill in part of this gap with measured lines. We know there - // can't be widgets or collapsed ranges in those lines, because - // they would already have been added to the heightmap (gaps - // only contain plain text). - let nodes = [], pos = Math.max(offset, measured.from), singleHeight = -1; - let wasChanged = oracle.heightChanged; - if (measured.from > offset) - nodes.push(new HeightMapGap(measured.from - offset - 1).updateHeight(oracle, offset)); - while (pos <= end && measured.more) { - let len = oracle.doc.lineAt(pos).length; - if (nodes.length) - nodes.push(null); - let height = measured.heights[measured.index++]; - if (singleHeight == -1) - singleHeight = height; - else if (Math.abs(height - singleHeight) >= Epsilon) - singleHeight = -2; - let line = new HeightMapText(len, height); - line.outdated = false; - nodes.push(line); - pos += len + 1; - } - if (pos <= end) - nodes.push(null, new HeightMapGap(end - pos).updateHeight(oracle, pos)); - let result = HeightMap.of(nodes); - oracle.heightChanged = wasChanged || singleHeight < 0 || Math.abs(result.height - this.height) >= Epsilon || - Math.abs(singleHeight - this.lines(oracle.doc, offset).lineHeight) >= Epsilon; - return result; - } - else if (force || this.outdated) { - this.setHeight(oracle, oracle.heightForGap(offset, offset + this.length)); - this.outdated = false; - } - return this; - } - toString() { return `gap(${this.length})`; } - } - class HeightMapBranch extends HeightMap { - constructor(left, brk, right) { - super(left.length + brk + right.length, left.height + right.height, brk | (left.outdated || right.outdated ? 2 /* Outdated */ : 0)); - this.left = left; - this.right = right; - this.size = left.size + right.size; - } - get break() { return this.flags & 1 /* Break */; } - blockAt(height, doc, top, offset) { - let mid = top + this.left.height; - return height < mid ? this.left.blockAt(height, doc, top, offset) - : this.right.blockAt(height, doc, mid, offset + this.left.length + this.break); - } - lineAt(value, type, doc, top, offset) { - let rightTop = top + this.left.height, rightOffset = offset + this.left.length + this.break; - let left = type == QueryType$1.ByHeight ? value < rightTop : value < rightOffset; - let base = left ? this.left.lineAt(value, type, doc, top, offset) - : this.right.lineAt(value, type, doc, rightTop, rightOffset); - if (this.break || (left ? base.to < rightOffset : base.from > rightOffset)) - return base; - let subQuery = type == QueryType$1.ByPosNoHeight ? QueryType$1.ByPosNoHeight : QueryType$1.ByPos; - if (left) - return base.join(this.right.lineAt(rightOffset, subQuery, doc, rightTop, rightOffset)); - else - return this.left.lineAt(rightOffset, subQuery, doc, top, offset).join(base); - } - forEachLine(from, to, doc, top, offset, f) { - let rightTop = top + this.left.height, rightOffset = offset + this.left.length + this.break; - if (this.break) { - if (from < rightOffset) - this.left.forEachLine(from, to, doc, top, offset, f); - if (to >= rightOffset) - this.right.forEachLine(from, to, doc, rightTop, rightOffset, f); - } - else { - let mid = this.lineAt(rightOffset, QueryType$1.ByPos, doc, top, offset); - if (from < mid.from) - this.left.forEachLine(from, mid.from - 1, doc, top, offset, f); - if (mid.to >= from && mid.from <= to) - f(mid); - if (to > mid.to) - this.right.forEachLine(mid.to + 1, to, doc, rightTop, rightOffset, f); - } - } - replace(from, to, nodes) { - let rightStart = this.left.length + this.break; - if (to < rightStart) - return this.balanced(this.left.replace(from, to, nodes), this.right); - if (from > this.left.length) - return this.balanced(this.left, this.right.replace(from - rightStart, to - rightStart, nodes)); - let result = []; - if (from > 0) - this.decomposeLeft(from, result); - let left = result.length; - for (let node of nodes) - result.push(node); - if (from > 0) - mergeGaps(result, left - 1); - if (to < this.length) { - let right = result.length; - this.decomposeRight(to, result); - mergeGaps(result, right); - } - return HeightMap.of(result); - } - decomposeLeft(to, result) { - let left = this.left.length; - if (to <= left) - return this.left.decomposeLeft(to, result); - result.push(this.left); - if (this.break) { - left++; - if (to >= left) - result.push(null); - } - if (to > left) - this.right.decomposeLeft(to - left, result); - } - decomposeRight(from, result) { - let left = this.left.length, right = left + this.break; - if (from >= right) - return this.right.decomposeRight(from - right, result); - if (from < left) - this.left.decomposeRight(from, result); - if (this.break && from < right) - result.push(null); - result.push(this.right); - } - balanced(left, right) { - if (left.size > 2 * right.size || right.size > 2 * left.size) - return HeightMap.of(this.break ? [left, null, right] : [left, right]); - this.left = left; - this.right = right; - this.height = left.height + right.height; - this.outdated = left.outdated || right.outdated; - this.size = left.size + right.size; - this.length = left.length + this.break + right.length; - return this; - } - updateHeight(oracle, offset = 0, force = false, measured) { - let { left, right } = this, rightStart = offset + left.length + this.break, rebalance = null; - if (measured && measured.from <= offset + left.length && measured.more) - rebalance = left = left.updateHeight(oracle, offset, force, measured); - else - left.updateHeight(oracle, offset, force); - if (measured && measured.from <= rightStart + right.length && measured.more) - rebalance = right = right.updateHeight(oracle, rightStart, force, measured); - else - right.updateHeight(oracle, rightStart, force); - if (rebalance) - return this.balanced(left, right); - this.height = this.left.height + this.right.height; - this.outdated = false; - return this; - } - toString() { return this.left + (this.break ? " " : "-") + this.right; } - } - function mergeGaps(nodes, around) { - let before, after; - if (nodes[around] == null && - (before = nodes[around - 1]) instanceof HeightMapGap && - (after = nodes[around + 1]) instanceof HeightMapGap) - nodes.splice(around - 1, 3, new HeightMapGap(before.length + 1 + after.length)); - } - const relevantWidgetHeight = 5; - class NodeBuilder { - constructor(pos, oracle) { - this.pos = pos; - this.oracle = oracle; - this.nodes = []; - this.lineStart = -1; - this.lineEnd = -1; - this.covering = null; - this.writtenTo = pos; - } - get isCovered() { - return this.covering && this.nodes[this.nodes.length - 1] == this.covering; - } - span(_from, to) { - if (this.lineStart > -1) { - let end = Math.min(to, this.lineEnd), last = this.nodes[this.nodes.length - 1]; - if (last instanceof HeightMapText) - last.length += end - this.pos; - else if (end > this.pos || !this.isCovered) - this.nodes.push(new HeightMapText(end - this.pos, -1)); - this.writtenTo = end; - if (to > end) { - this.nodes.push(null); - this.writtenTo++; - this.lineStart = -1; - } - } - this.pos = to; - } - point(from, to, deco) { - if (from < to || deco.heightRelevant) { - let height = deco.widget ? deco.widget.estimatedHeight : 0; - if (height < 0) - height = this.oracle.lineHeight; - let len = to - from; - if (deco.block) { - this.addBlock(new HeightMapBlock(len, height, deco.type)); - } - else if (len || height >= relevantWidgetHeight) { - this.addLineDeco(height, len); - } - } - else if (to > from) { - this.span(from, to); - } - if (this.lineEnd > -1 && this.lineEnd < this.pos) - this.lineEnd = this.oracle.doc.lineAt(this.pos).to; - } - enterLine() { - if (this.lineStart > -1) - return; - let { from, to } = this.oracle.doc.lineAt(this.pos); - this.lineStart = from; - this.lineEnd = to; - if (this.writtenTo < from) { - if (this.writtenTo < from - 1 || this.nodes[this.nodes.length - 1] == null) - this.nodes.push(this.blankContent(this.writtenTo, from - 1)); - this.nodes.push(null); - } - if (this.pos > from) - this.nodes.push(new HeightMapText(this.pos - from, -1)); - this.writtenTo = this.pos; - } - blankContent(from, to) { - let gap = new HeightMapGap(to - from); - if (this.oracle.doc.lineAt(from).to == to) - gap.flags |= 4 /* SingleLine */; - return gap; - } - ensureLine() { - this.enterLine(); - let last = this.nodes.length ? this.nodes[this.nodes.length - 1] : null; - if (last instanceof HeightMapText) - return last; - let line = new HeightMapText(0, -1); - this.nodes.push(line); - return line; - } - addBlock(block) { - this.enterLine(); - if (block.type == BlockType.WidgetAfter && !this.isCovered) - this.ensureLine(); - this.nodes.push(block); - this.writtenTo = this.pos = this.pos + block.length; - if (block.type != BlockType.WidgetBefore) - this.covering = block; - } - addLineDeco(height, length) { - let line = this.ensureLine(); - line.length += length; - line.collapsed += length; - line.widgetHeight = Math.max(line.widgetHeight, height); - this.writtenTo = this.pos = this.pos + length; - } - finish(from) { - let last = this.nodes.length == 0 ? null : this.nodes[this.nodes.length - 1]; - if (this.lineStart > -1 && !(last instanceof HeightMapText) && !this.isCovered) - this.nodes.push(new HeightMapText(0, -1)); - else if (this.writtenTo < this.pos || last == null) - this.nodes.push(this.blankContent(this.writtenTo, this.pos)); - let pos = from; - for (let node of this.nodes) { - if (node instanceof HeightMapText) - node.updateHeight(this.oracle, pos); - pos += node ? node.length : 1; - } - return this.nodes; - } - // Always called with a region that on both sides either stretches - // to a line break or the end of the document. - // The returned array uses null to indicate line breaks, but never - // starts or ends in a line break, or has multiple line breaks next - // to each other. - static build(oracle, decorations, from, to) { - let builder = new NodeBuilder(from, oracle); - RangeSet.spans(decorations, from, to, builder, 0); - return builder.finish(from); - } - } - function heightRelevantDecoChanges(a, b, diff) { - let comp = new DecorationComparator; - RangeSet.compare(a, b, diff, comp, 0); - return comp.changes; - } - class DecorationComparator { - constructor() { - this.changes = []; - } - compareRange() { } - comparePoint(from, to, a, b) { - if (from < to || a && a.heightRelevant || b && b.heightRelevant) - addRange(from, to, this.changes, 5); - } - } - - function visiblePixelRange(dom, paddingTop) { - let rect = dom.getBoundingClientRect(); - let left = Math.max(0, rect.left), right = Math.min(innerWidth, rect.right); - let top = Math.max(0, rect.top), bottom = Math.min(innerHeight, rect.bottom); - let body = dom.ownerDocument.body; - for (let parent = dom.parentNode; parent && parent != body;) { - if (parent.nodeType == 1) { - let elt = parent; - let style = window.getComputedStyle(elt); - if ((elt.scrollHeight > elt.clientHeight || elt.scrollWidth > elt.clientWidth) && - style.overflow != "visible") { - let parentRect = elt.getBoundingClientRect(); - left = Math.max(left, parentRect.left); - right = Math.min(right, parentRect.right); - top = Math.max(top, parentRect.top); - bottom = Math.min(bottom, parentRect.bottom); - } - parent = style.position == "absolute" || style.position == "fixed" ? elt.offsetParent : elt.parentNode; - } - else if (parent.nodeType == 11) { // Shadow root - parent = parent.host; - } - else { - break; - } - } - return { left: left - rect.left, right: Math.max(left, right) - rect.left, - top: top - (rect.top + paddingTop), bottom: Math.max(top, bottom) - (rect.top + paddingTop) }; - } - function fullPixelRange(dom, paddingTop) { - let rect = dom.getBoundingClientRect(); - return { left: 0, right: rect.right - rect.left, - top: paddingTop, bottom: rect.bottom - (rect.top + paddingTop) }; - } - // Line gaps are placeholder widgets used to hide pieces of overlong - // lines within the viewport, as a kludge to keep the editor - // responsive when a ridiculously long line is loaded into it. - class LineGap { - constructor(from, to, size) { - this.from = from; - this.to = to; - this.size = size; - } - static same(a, b) { - if (a.length != b.length) - return false; - for (let i = 0; i < a.length; i++) { - let gA = a[i], gB = b[i]; - if (gA.from != gB.from || gA.to != gB.to || gA.size != gB.size) - return false; - } - return true; - } - draw(wrapping) { - return Decoration.replace({ widget: new LineGapWidget(this.size, wrapping) }).range(this.from, this.to); - } - } - class LineGapWidget extends WidgetType { - constructor(size, vertical) { - super(); - this.size = size; - this.vertical = vertical; - } - eq(other) { return other.size == this.size && other.vertical == this.vertical; } - toDOM() { - let elt = document.createElement("div"); - if (this.vertical) { - elt.style.height = this.size + "px"; - } - else { - elt.style.width = this.size + "px"; - elt.style.height = "2px"; - elt.style.display = "inline-block"; - } - return elt; - } - get estimatedHeight() { return this.vertical ? this.size : -1; } - } - class ViewState { - constructor(state) { - this.state = state; - // These are contentDOM-local coordinates - this.pixelViewport = { left: 0, right: window.innerWidth, top: 0, bottom: 0 }; - this.inView = true; - this.paddingTop = 0; - this.paddingBottom = 0; - this.contentDOMWidth = 0; - this.contentDOMHeight = 0; - this.editorHeight = 0; - this.editorWidth = 0; - this.heightOracle = new HeightOracle; - // See VP.MaxDOMHeight - this.scaler = IdScaler; - this.scrollTarget = null; - // Briefly set to true when printing, to disable viewport limiting - this.printing = false; - // Flag set when editor content was redrawn, so that the next - // measure stage knows it must read DOM layout - this.mustMeasureContent = true; - this.visibleRanges = []; - // Cursor 'assoc' is only significant when the cursor is on a line - // wrap point, where it must stick to the character that it is - // associated with. Since browsers don't provide a reasonable - // interface to set or query this, when a selection is set that - // might cause this to be significant, this flag is set. The next - // measure phase will check whether the cursor is on a line-wrapping - // boundary and, if so, reset it to make sure it is positioned in - // the right place. - this.mustEnforceCursorAssoc = false; - this.heightMap = HeightMap.empty().applyChanges(state.facet(decorations), Text.empty, this.heightOracle.setDoc(state.doc), [new ChangedRange(0, 0, 0, state.doc.length)]); - this.viewport = this.getViewport(0, null); - this.updateViewportLines(); - this.updateForViewport(); - this.lineGaps = this.ensureLineGaps([]); - this.lineGapDeco = Decoration.set(this.lineGaps.map(gap => gap.draw(false))); - this.computeVisibleRanges(); - } - updateForViewport() { - let viewports = [this.viewport], { main } = this.state.selection; - for (let i = 0; i <= 1; i++) { - let pos = i ? main.head : main.anchor; - if (!viewports.some(({ from, to }) => pos >= from && pos <= to)) { - let { from, to } = this.lineBlockAt(pos); - viewports.push(new Viewport(from, to)); - } - } - this.viewports = viewports.sort((a, b) => a.from - b.from); - this.scaler = this.heightMap.height <= 7000000 /* MaxDOMHeight */ ? IdScaler : - new BigScaler(this.heightOracle.doc, this.heightMap, this.viewports); - } - updateViewportLines() { - this.viewportLines = []; - this.heightMap.forEachLine(this.viewport.from, this.viewport.to, this.state.doc, 0, 0, block => { - this.viewportLines.push(this.scaler.scale == 1 ? block : scaleBlock(block, this.scaler)); - }); - } - update(update, scrollTarget = null) { - let prev = this.state; - this.state = update.state; - let newDeco = this.state.facet(decorations); - let contentChanges = update.changedRanges; - let heightChanges = ChangedRange.extendWithRanges(contentChanges, heightRelevantDecoChanges(update.startState.facet(decorations), newDeco, update ? update.changes : ChangeSet.empty(this.state.doc.length))); - let prevHeight = this.heightMap.height; - this.heightMap = this.heightMap.applyChanges(newDeco, prev.doc, this.heightOracle.setDoc(this.state.doc), heightChanges); - if (this.heightMap.height != prevHeight) - update.flags |= 2 /* Height */; - let viewport = heightChanges.length ? this.mapViewport(this.viewport, update.changes) : this.viewport; - if (scrollTarget && (scrollTarget.range.head < viewport.from || scrollTarget.range.head > viewport.to) || - !this.viewportIsAppropriate(viewport)) - viewport = this.getViewport(0, scrollTarget); - let updateLines = !update.changes.empty || (update.flags & 2 /* Height */) || - viewport.from != this.viewport.from || viewport.to != this.viewport.to; - this.viewport = viewport; - this.updateForViewport(); - if (updateLines) - this.updateViewportLines(); - if (this.lineGaps.length || this.viewport.to - this.viewport.from > 4000 /* DoubleMargin */) - this.updateLineGaps(this.ensureLineGaps(this.mapLineGaps(this.lineGaps, update.changes))); - update.flags |= this.computeVisibleRanges(); - if (scrollTarget) - this.scrollTarget = scrollTarget; - if (!this.mustEnforceCursorAssoc && update.selectionSet && update.view.lineWrapping && - update.state.selection.main.empty && update.state.selection.main.assoc) - this.mustEnforceCursorAssoc = true; - } - measure(view) { - let dom = view.contentDOM, style = window.getComputedStyle(dom); - let oracle = this.heightOracle; - let whiteSpace = style.whiteSpace, direction = style.direction == "rtl" ? Direction.RTL : Direction.LTR; - let refresh = this.heightOracle.mustRefreshForStyle(whiteSpace, direction); - let measureContent = refresh || this.mustMeasureContent || this.contentDOMHeight != dom.clientHeight; - let result = 0, bias = 0; - if (this.editorWidth != view.scrollDOM.clientWidth) { - if (oracle.lineWrapping) - measureContent = true; - this.editorWidth = view.scrollDOM.clientWidth; - result |= 8 /* Geometry */; - } - if (measureContent) { - this.mustMeasureContent = false; - this.contentDOMHeight = dom.clientHeight; - // Vertical padding - let paddingTop = parseInt(style.paddingTop) || 0, paddingBottom = parseInt(style.paddingBottom) || 0; - if (this.paddingTop != paddingTop || this.paddingBottom != paddingBottom) { - result |= 8 /* Geometry */; - this.paddingTop = paddingTop; - this.paddingBottom = paddingBottom; - } - } - // Pixel viewport - let pixelViewport = (this.printing ? fullPixelRange : visiblePixelRange)(dom, this.paddingTop); - let dTop = pixelViewport.top - this.pixelViewport.top, dBottom = pixelViewport.bottom - this.pixelViewport.bottom; - this.pixelViewport = pixelViewport; - let inView = this.pixelViewport.bottom > this.pixelViewport.top && this.pixelViewport.right > this.pixelViewport.left; - if (inView != this.inView) { - this.inView = inView; - if (inView) - measureContent = true; - } - if (!this.inView) - return 0; - let contentWidth = dom.clientWidth; - if (this.contentDOMWidth != contentWidth || this.editorHeight != view.scrollDOM.clientHeight) { - this.contentDOMWidth = contentWidth; - this.editorHeight = view.scrollDOM.clientHeight; - result |= 8 /* Geometry */; - } - if (measureContent) { - let lineHeights = view.docView.measureVisibleLineHeights(); - if (oracle.mustRefreshForHeights(lineHeights)) - refresh = true; - if (refresh || oracle.lineWrapping && Math.abs(contentWidth - this.contentDOMWidth) > oracle.charWidth) { - let { lineHeight, charWidth } = view.docView.measureTextSize(); - refresh = oracle.refresh(whiteSpace, direction, lineHeight, charWidth, contentWidth / charWidth, lineHeights); - if (refresh) { - view.docView.minWidth = 0; - result |= 8 /* Geometry */; - } - } - if (dTop > 0 && dBottom > 0) - bias = Math.max(dTop, dBottom); - else if (dTop < 0 && dBottom < 0) - bias = Math.min(dTop, dBottom); - oracle.heightChanged = false; - this.heightMap = this.heightMap.updateHeight(oracle, 0, refresh, new MeasuredHeights(this.viewport.from, lineHeights)); - if (oracle.heightChanged) - result |= 2 /* Height */; - } - let viewportChange = !this.viewportIsAppropriate(this.viewport, bias) || - this.scrollTarget && (this.scrollTarget.range.head < this.viewport.from || this.scrollTarget.range.head > this.viewport.to); - if (viewportChange) - this.viewport = this.getViewport(bias, this.scrollTarget); - this.updateForViewport(); - if ((result & 2 /* Height */) || viewportChange) - this.updateViewportLines(); - if (this.lineGaps.length || this.viewport.to - this.viewport.from > 4000 /* DoubleMargin */) - this.updateLineGaps(this.ensureLineGaps(refresh ? [] : this.lineGaps)); - result |= this.computeVisibleRanges(); - if (this.mustEnforceCursorAssoc) { - this.mustEnforceCursorAssoc = false; - // This is done in the read stage, because moving the selection - // to a line end is going to trigger a layout anyway, so it - // can't be a pure write. It should be rare that it does any - // writing. - view.docView.enforceCursorAssoc(); - } - return result; - } - get visibleTop() { return this.scaler.fromDOM(this.pixelViewport.top); } - get visibleBottom() { return this.scaler.fromDOM(this.pixelViewport.bottom); } - getViewport(bias, scrollTarget) { - // This will divide VP.Margin between the top and the - // bottom, depending on the bias (the change in viewport position - // since the last update). It'll hold a number between 0 and 1 - let marginTop = 0.5 - Math.max(-0.5, Math.min(0.5, bias / 1000 /* Margin */ / 2)); - let map = this.heightMap, doc = this.state.doc, { visibleTop, visibleBottom } = this; - let viewport = new Viewport(map.lineAt(visibleTop - marginTop * 1000 /* Margin */, QueryType$1.ByHeight, doc, 0, 0).from, map.lineAt(visibleBottom + (1 - marginTop) * 1000 /* Margin */, QueryType$1.ByHeight, doc, 0, 0).to); - // If scrollTarget is given, make sure the viewport includes that position - if (scrollTarget) { - let { head } = scrollTarget.range; - if (head < viewport.from || head > viewport.to) { - let viewHeight = Math.min(this.editorHeight, this.pixelViewport.bottom - this.pixelViewport.top); - let block = map.lineAt(head, QueryType$1.ByPos, doc, 0, 0), topPos; - if (scrollTarget.y == "center") - topPos = (block.top + block.bottom) / 2 - viewHeight / 2; - else if (scrollTarget.y == "start" || scrollTarget.y == "nearest" && head < viewport.from) - topPos = block.top; - else - topPos = block.bottom - viewHeight; - viewport = new Viewport(map.lineAt(topPos - 1000 /* Margin */ / 2, QueryType$1.ByHeight, doc, 0, 0).from, map.lineAt(topPos + viewHeight + 1000 /* Margin */ / 2, QueryType$1.ByHeight, doc, 0, 0).to); - } - } - return viewport; - } - mapViewport(viewport, changes) { - let from = changes.mapPos(viewport.from, -1), to = changes.mapPos(viewport.to, 1); - return new Viewport(this.heightMap.lineAt(from, QueryType$1.ByPos, this.state.doc, 0, 0).from, this.heightMap.lineAt(to, QueryType$1.ByPos, this.state.doc, 0, 0).to); - } - // Checks if a given viewport covers the visible part of the - // document and not too much beyond that. - viewportIsAppropriate({ from, to }, bias = 0) { - if (!this.inView) - return true; - let { top } = this.heightMap.lineAt(from, QueryType$1.ByPos, this.state.doc, 0, 0); - let { bottom } = this.heightMap.lineAt(to, QueryType$1.ByPos, this.state.doc, 0, 0); - let { visibleTop, visibleBottom } = this; - return (from == 0 || top <= visibleTop - Math.max(10 /* MinCoverMargin */, Math.min(-bias, 250 /* MaxCoverMargin */))) && - (to == this.state.doc.length || - bottom >= visibleBottom + Math.max(10 /* MinCoverMargin */, Math.min(bias, 250 /* MaxCoverMargin */))) && - (top > visibleTop - 2 * 1000 /* Margin */ && bottom < visibleBottom + 2 * 1000 /* Margin */); - } - mapLineGaps(gaps, changes) { - if (!gaps.length || changes.empty) - return gaps; - let mapped = []; - for (let gap of gaps) - if (!changes.touchesRange(gap.from, gap.to)) - mapped.push(new LineGap(changes.mapPos(gap.from), changes.mapPos(gap.to), gap.size)); - return mapped; - } - // Computes positions in the viewport where the start or end of a - // line should be hidden, trying to reuse existing line gaps when - // appropriate to avoid unneccesary redraws. - // Uses crude character-counting for the positioning and sizing, - // since actual DOM coordinates aren't always available and - // predictable. Relies on generous margins (see LG.Margin) to hide - // the artifacts this might produce from the user. - ensureLineGaps(current) { - let gaps = []; - // This won't work at all in predominantly right-to-left text. - if (this.heightOracle.direction != Direction.LTR) - return gaps; - for (let line of this.viewportLines) { - if (line.length < 4000 /* DoubleMargin */) - continue; - let structure = lineStructure(line.from, line.to, this.state); - if (structure.total < 4000 /* DoubleMargin */) - continue; - let viewFrom, viewTo; - if (this.heightOracle.lineWrapping) { - let marginHeight = (2000 /* Margin */ / this.heightOracle.lineLength) * this.heightOracle.lineHeight; - viewFrom = findPosition(structure, (this.visibleTop - line.top - marginHeight) / line.height); - viewTo = findPosition(structure, (this.visibleBottom - line.top + marginHeight) / line.height); - } - else { - let totalWidth = structure.total * this.heightOracle.charWidth; - let marginWidth = 2000 /* Margin */ * this.heightOracle.charWidth; - viewFrom = findPosition(structure, (this.pixelViewport.left - marginWidth) / totalWidth); - viewTo = findPosition(structure, (this.pixelViewport.right + marginWidth) / totalWidth); - } - let outside = []; - if (viewFrom > line.from) - outside.push({ from: line.from, to: viewFrom }); - if (viewTo < line.to) - outside.push({ from: viewTo, to: line.to }); - let sel = this.state.selection.main; - // Make sure the gaps don't cover a selection end - if (sel.from >= line.from && sel.from <= line.to) - cutRange(outside, sel.from - 10 /* SelectionMargin */, sel.from + 10 /* SelectionMargin */); - if (!sel.empty && sel.to >= line.from && sel.to <= line.to) - cutRange(outside, sel.to - 10 /* SelectionMargin */, sel.to + 10 /* SelectionMargin */); - for (let { from, to } of outside) - if (to - from > 1000 /* HalfMargin */) { - gaps.push(find(current, gap => gap.from >= line.from && gap.to <= line.to && - Math.abs(gap.from - from) < 1000 /* HalfMargin */ && Math.abs(gap.to - to) < 1000 /* HalfMargin */) || - new LineGap(from, to, this.gapSize(line, from, to, structure))); - } - } - return gaps; - } - gapSize(line, from, to, structure) { - let fraction = findFraction(structure, to) - findFraction(structure, from); - if (this.heightOracle.lineWrapping) { - return line.height * fraction; - } - else { - return structure.total * this.heightOracle.charWidth * fraction; - } - } - updateLineGaps(gaps) { - if (!LineGap.same(gaps, this.lineGaps)) { - this.lineGaps = gaps; - this.lineGapDeco = Decoration.set(gaps.map(gap => gap.draw(this.heightOracle.lineWrapping))); - } - } - computeVisibleRanges() { - let deco = this.state.facet(decorations); - if (this.lineGaps.length) - deco = deco.concat(this.lineGapDeco); - let ranges = []; - RangeSet.spans(deco, this.viewport.from, this.viewport.to, { - span(from, to) { ranges.push({ from, to }); }, - point() { } - }, 20); - let changed = ranges.length != this.visibleRanges.length || - this.visibleRanges.some((r, i) => r.from != ranges[i].from || r.to != ranges[i].to); - this.visibleRanges = ranges; - return changed ? 4 /* Viewport */ : 0; - } - lineBlockAt(pos) { - return (pos >= this.viewport.from && pos <= this.viewport.to && this.viewportLines.find(b => b.from <= pos && b.to >= pos)) || - scaleBlock(this.heightMap.lineAt(pos, QueryType$1.ByPos, this.state.doc, 0, 0), this.scaler); - } - lineBlockAtHeight(height) { - return scaleBlock(this.heightMap.lineAt(this.scaler.fromDOM(height), QueryType$1.ByHeight, this.state.doc, 0, 0), this.scaler); - } - elementAtHeight(height) { - return scaleBlock(this.heightMap.blockAt(this.scaler.fromDOM(height), this.state.doc, 0, 0), this.scaler); - } - get docHeight() { - return this.scaler.toDOM(this.heightMap.height); - } - get contentHeight() { - return this.docHeight + this.paddingTop + this.paddingBottom; - } - } - class Viewport { - constructor(from, to) { - this.from = from; - this.to = to; - } - } - function lineStructure(from, to, state) { - let ranges = [], pos = from, total = 0; - RangeSet.spans(state.facet(decorations), from, to, { - span() { }, - point(from, to) { - if (from > pos) { - ranges.push({ from: pos, to: from }); - total += from - pos; - } - pos = to; - } - }, 20); // We're only interested in collapsed ranges of a significant size - if (pos < to) { - ranges.push({ from: pos, to }); - total += to - pos; - } - return { total, ranges }; - } - function findPosition({ total, ranges }, ratio) { - if (ratio <= 0) - return ranges[0].from; - if (ratio >= 1) - return ranges[ranges.length - 1].to; - let dist = Math.floor(total * ratio); - for (let i = 0;; i++) { - let { from, to } = ranges[i], size = to - from; - if (dist <= size) - return from + dist; - dist -= size; - } - } - function findFraction(structure, pos) { - let counted = 0; - for (let { from, to } of structure.ranges) { - if (pos <= to) { - counted += pos - from; - break; - } - counted += to - from; - } - return counted / structure.total; - } - function cutRange(ranges, from, to) { - for (let i = 0; i < ranges.length; i++) { - let r = ranges[i]; - if (r.from < to && r.to > from) { - let pieces = []; - if (r.from < from) - pieces.push({ from: r.from, to: from }); - if (r.to > to) - pieces.push({ from: to, to: r.to }); - ranges.splice(i, 1, ...pieces); - i += pieces.length - 1; - } - } - } - function find(array, f) { - for (let val of array) - if (f(val)) - return val; - return undefined; - } - // Don't scale when the document height is within the range of what - // the DOM can handle. - const IdScaler = { - toDOM(n) { return n; }, - fromDOM(n) { return n; }, - scale: 1 - }; - // When the height is too big (> VP.MaxDOMHeight), scale down the - // regions outside the viewports so that the total height is - // VP.MaxDOMHeight. - class BigScaler { - constructor(doc, heightMap, viewports) { - let vpHeight = 0, base = 0, domBase = 0; - this.viewports = viewports.map(({ from, to }) => { - let top = heightMap.lineAt(from, QueryType$1.ByPos, doc, 0, 0).top; - let bottom = heightMap.lineAt(to, QueryType$1.ByPos, doc, 0, 0).bottom; - vpHeight += bottom - top; - return { from, to, top, bottom, domTop: 0, domBottom: 0 }; - }); - this.scale = (7000000 /* MaxDOMHeight */ - vpHeight) / (heightMap.height - vpHeight); - for (let obj of this.viewports) { - obj.domTop = domBase + (obj.top - base) * this.scale; - domBase = obj.domBottom = obj.domTop + (obj.bottom - obj.top); - base = obj.bottom; - } - } - toDOM(n) { - for (let i = 0, base = 0, domBase = 0;; i++) { - let vp = i < this.viewports.length ? this.viewports[i] : null; - if (!vp || n < vp.top) - return domBase + (n - base) * this.scale; - if (n <= vp.bottom) - return vp.domTop + (n - vp.top); - base = vp.bottom; - domBase = vp.domBottom; - } - } - fromDOM(n) { - for (let i = 0, base = 0, domBase = 0;; i++) { - let vp = i < this.viewports.length ? this.viewports[i] : null; - if (!vp || n < vp.domTop) - return base + (n - domBase) / this.scale; - if (n <= vp.domBottom) - return vp.top + (n - vp.domTop); - base = vp.bottom; - domBase = vp.domBottom; - } - } - } - function scaleBlock(block, scaler) { - if (scaler.scale == 1) - return block; - let bTop = scaler.toDOM(block.top), bBottom = scaler.toDOM(block.bottom); - return new BlockInfo(block.from, block.length, bTop, bBottom - bTop, Array.isArray(block.type) ? block.type.map(b => scaleBlock(b, scaler)) : block.type); - } - - const theme = /*@__PURE__*/Facet.define({ combine: strs => strs.join(" ") }); - const darkTheme = /*@__PURE__*/Facet.define({ combine: values => values.indexOf(true) > -1 }); - const baseThemeID = /*@__PURE__*/StyleModule.newName(), baseLightID = /*@__PURE__*/StyleModule.newName(), baseDarkID = /*@__PURE__*/StyleModule.newName(); - const lightDarkIDs = { "&light": "." + baseLightID, "&dark": "." + baseDarkID }; - function buildTheme(main, spec, scopes) { - return new StyleModule(spec, { - finish(sel) { - return /&/.test(sel) ? sel.replace(/&\w*/, m => { - if (m == "&") - return main; - if (!scopes || !scopes[m]) - throw new RangeError(`Unsupported selector: ${m}`); - return scopes[m]; - }) : main + " " + sel; - } - }); - } - const baseTheme$8 = /*@__PURE__*/buildTheme("." + baseThemeID, { - "&.cm-editor": { - position: "relative !important", - boxSizing: "border-box", - "&.cm-focused": { - // Provide a simple default outline to make sure a focused - // editor is visually distinct. Can't leave the default behavior - // because that will apply to the content element, which is - // inside the scrollable container and doesn't include the - // gutters. We also can't use an 'auto' outline, since those - // are, for some reason, drawn behind the element content, which - // will cause things like the active line background to cover - // the outline (#297). - 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, - minHeight: "100%", - display: "block", - whiteSpace: "pre", - wordWrap: "normal", - boxSizing: "border-box", - 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" - }, - "&light .cm-content": { caretColor: "black" }, - "&dark .cm-content": { caretColor: "white" }, - ".cm-line": { - display: "block", - padding: "0 2px 0 4px" - }, - ".cm-selectionLayer": { - zIndex: -1, - contain: "size style" - }, - ".cm-selectionBackground": { - position: "absolute", - }, - "&light .cm-selectionBackground": { - background: "#d9d9d9" - }, - "&dark .cm-selectionBackground": { - background: "#222" - }, - "&light.cm-focused .cm-selectionBackground": { - background: "#d7d4f0" - }, - "&dark.cm-focused .cm-selectionBackground": { - background: "#233" - }, - ".cm-cursorLayer": { - zIndex: 100, - contain: "size style", - pointerEvents: "none" - }, - "&.cm-focused .cm-cursorLayer": { - animation: "steps(1) cm-blink 1.2s infinite" - }, - // Two animations defined so that we can switch between them to - // restart the animation without forcing another style - // recomputation. - "@keyframes cm-blink": { "0%": {}, "50%": { visibility: "hidden" }, "100%": {} }, - "@keyframes cm-blink2": { "0%": {}, "50%": { visibility: "hidden" }, "100%": {} }, - ".cm-cursor, .cm-dropCursor": { - position: "absolute", - borderLeft: "1.2px solid black", - marginLeft: "-0.6px", - pointerEvents: "none", - }, - ".cm-cursor": { - display: "none" - }, - "&dark .cm-cursor": { - borderLeftColor: "#444" - }, - "&.cm-focused .cm-cursor": { - display: "block" - }, - "&light .cm-activeLine": { backgroundColor: "#f3f9ff" }, - "&dark .cm-activeLine": { backgroundColor: "#223039" }, - "&light .cm-specialChar": { color: "red" }, - "&dark .cm-specialChar": { color: "#f78" }, - ".cm-tab": { - display: "inline-block", - overflow: "hidden", - verticalAlign: "bottom" - }, - ".cm-widgetBuffer": { - verticalAlign: "text-top", - height: "1em", - display: "inline" - }, - ".cm-placeholder": { - color: "#888", - display: "inline-block", - verticalAlign: "top", - }, - ".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" - } - }, lightDarkIDs); - - const observeOptions = { - childList: true, - characterData: true, - subtree: true, - attributes: true, - characterDataOldValue: true - }; - // IE11 has very broken mutation observers, so we also listen to - // DOMCharacterDataModified there - const useCharData = browser.ie && browser.ie_version <= 11; - class DOMObserver { - constructor(view, onChange, onScrollChanged) { - this.view = view; - this.onChange = onChange; - this.onScrollChanged = onScrollChanged; - this.active = false; - // The known selection. Kept in our own object, as opposed to just - // directly accessing the selection because: - // - Safari doesn't report the right selection in shadow DOM - // - Reading from the selection forces a DOM layout - // - This way, we can ignore selectionchange events if we have - // already seen the 'new' selection - this.selectionRange = new DOMSelectionState; - // Set when a selection change is detected, cleared on flush - this.selectionChanged = false; - this.delayedFlush = -1; - this.resizeTimeout = -1; - this.queue = []; - this.delayedAndroidKey = null; - this.scrollTargets = []; - this.intersection = null; - this.resize = null; - this.intersecting = false; - this.gapIntersection = null; - this.gaps = []; - // Timeout for scheduling check of the parents that need scroll handlers - this.parentCheck = -1; - this.dom = view.contentDOM; - this.observer = new MutationObserver(mutations => { - for (let mut of mutations) - this.queue.push(mut); - // IE11 will sometimes (on typing over a selection or - // backspacing out a single character text node) call the - // observer callback before actually updating the DOM. - // - // Unrelatedly, iOS Safari will, when ending a composition, - // sometimes first clear it, deliver the mutations, and then - // reinsert the finished text. CodeMirror's handling of the - // deletion will prevent the reinsertion from happening, - // breaking composition. - if ((browser.ie && browser.ie_version <= 11 || browser.ios && view.composing) && - mutations.some(m => m.type == "childList" && m.removedNodes.length || - m.type == "characterData" && m.oldValue.length > m.target.nodeValue.length)) - this.flushSoon(); - else - this.flush(); - }); - if (useCharData) - this.onCharData = (event) => { - this.queue.push({ target: event.target, - type: "characterData", - oldValue: event.prevValue }); - this.flushSoon(); - }; - this.onSelectionChange = this.onSelectionChange.bind(this); - window.addEventListener("resize", this.onResize = this.onResize.bind(this)); - if (typeof ResizeObserver == "function") { - this.resize = new ResizeObserver(() => { - if (this.view.docView.lastUpdate < Date.now() - 75) - this.onResize(); - }); - this.resize.observe(view.scrollDOM); - } - window.addEventListener("beforeprint", this.onPrint = this.onPrint.bind(this)); - this.start(); - window.addEventListener("scroll", this.onScroll = this.onScroll.bind(this)); - if (typeof IntersectionObserver == "function") { - this.intersection = new IntersectionObserver(entries => { - if (this.parentCheck < 0) - this.parentCheck = setTimeout(this.listenForScroll.bind(this), 1000); - if (entries.length > 0 && (entries[entries.length - 1].intersectionRatio > 0) != this.intersecting) { - this.intersecting = !this.intersecting; - if (this.intersecting != this.view.inView) - this.onScrollChanged(document.createEvent("Event")); - } - }, {}); - this.intersection.observe(this.dom); - this.gapIntersection = new IntersectionObserver(entries => { - if (entries.length > 0 && entries[entries.length - 1].intersectionRatio > 0) - this.onScrollChanged(document.createEvent("Event")); - }, {}); - } - this.listenForScroll(); - this.readSelectionRange(); - this.dom.ownerDocument.addEventListener("selectionchange", this.onSelectionChange); - } - onScroll(e) { - if (this.intersecting) - this.flush(false); - this.onScrollChanged(e); - } - onResize() { - if (this.resizeTimeout < 0) - this.resizeTimeout = setTimeout(() => { - this.resizeTimeout = -1; - this.view.requestMeasure(); - }, 50); - } - onPrint() { - this.view.viewState.printing = true; - this.view.measure(); - setTimeout(() => { - this.view.viewState.printing = false; - this.view.requestMeasure(); - }, 500); - } - updateGaps(gaps) { - if (this.gapIntersection && (gaps.length != this.gaps.length || this.gaps.some((g, i) => g != gaps[i]))) { - this.gapIntersection.disconnect(); - for (let gap of gaps) - this.gapIntersection.observe(gap); - this.gaps = gaps; - } - } - onSelectionChange(event) { - if (!this.readSelectionRange() || this.delayedAndroidKey) - return; - let { view } = this, sel = this.selectionRange; - if (view.state.facet(editable) ? view.root.activeElement != this.dom : !hasSelection(view.dom, sel)) - return; - let context = sel.anchorNode && view.docView.nearest(sel.anchorNode); - if (context && context.ignoreEvent(event)) - return; - // Deletions on IE11 fire their events in the wrong order, giving - // us a selection change event before the DOM changes are - // reported. - // Chrome Android has a similar issue when backspacing out a - // selection (#645). - if ((browser.ie && browser.ie_version <= 11 || browser.android && browser.chrome) && !view.state.selection.main.empty && - // (Selection.isCollapsed isn't reliable on IE) - sel.focusNode && isEquivalentPosition(sel.focusNode, sel.focusOffset, sel.anchorNode, sel.anchorOffset)) - this.flushSoon(); - else - this.flush(false); - } - readSelectionRange() { - let { root } = this.view, domSel = getSelection(root); - // The Selection object is broken in shadow roots in Safari. See - // https://github.com/codemirror/codemirror.next/issues/414 - let range = browser.safari && root.nodeType == 11 && deepActiveElement() == this.view.contentDOM && - safariSelectionRangeHack(this.view) || domSel; - if (this.selectionRange.eq(range)) - return false; - this.selectionRange.setRange(range); - return this.selectionChanged = true; - } - setSelectionRange(anchor, head) { - this.selectionRange.set(anchor.node, anchor.offset, head.node, head.offset); - this.selectionChanged = false; - } - listenForScroll() { - this.parentCheck = -1; - let i = 0, changed = null; - for (let dom = this.dom; dom;) { - if (dom.nodeType == 1) { - if (!changed && i < this.scrollTargets.length && this.scrollTargets[i] == dom) - i++; - else if (!changed) - changed = this.scrollTargets.slice(0, i); - if (changed) - changed.push(dom); - dom = dom.assignedSlot || dom.parentNode; - } - else if (dom.nodeType == 11) { // Shadow root - dom = dom.host; - } - else { - break; - } - } - if (i < this.scrollTargets.length && !changed) - changed = this.scrollTargets.slice(0, i); - if (changed) { - for (let dom of this.scrollTargets) - dom.removeEventListener("scroll", this.onScroll); - for (let dom of this.scrollTargets = changed) - dom.addEventListener("scroll", this.onScroll); - } - } - ignore(f) { - if (!this.active) - return f(); - try { - this.stop(); - return f(); - } - finally { - this.start(); - this.clear(); - } - } - start() { - if (this.active) - return; - this.observer.observe(this.dom, observeOptions); - if (useCharData) - this.dom.addEventListener("DOMCharacterDataModified", this.onCharData); - this.active = true; - } - stop() { - if (!this.active) - return; - this.active = false; - this.observer.disconnect(); - if (useCharData) - this.dom.removeEventListener("DOMCharacterDataModified", this.onCharData); - } - // Throw away any pending changes - clear() { - this.processRecords(); - this.queue.length = 0; - this.selectionChanged = false; - } - // Chrome Android, especially in combination with GBoard, not only - // doesn't reliably fire regular key events, but also often - // surrounds the effect of enter or backspace with a bunch of - // composition events that, when interrupted, cause text duplication - // or other kinds of corruption. This hack makes the editor back off - // from handling DOM changes for a moment when such a key is - // detected (via beforeinput or keydown), and then dispatches the - // key event, throwing away the DOM changes if it gets handled. - delayAndroidKey(key, keyCode) { - if (!this.delayedAndroidKey) - requestAnimationFrame(() => { - let key = this.delayedAndroidKey; - this.delayedAndroidKey = null; - let startState = this.view.state; - if (dispatchKey(this.view.contentDOM, key.key, key.keyCode)) - this.processRecords(); - else - this.flush(); - if (this.view.state == startState) - this.view.update([]); - }); - // Since backspace beforeinput is sometimes signalled spuriously, - // Enter always takes precedence. - if (!this.delayedAndroidKey || key == "Enter") - this.delayedAndroidKey = { key, keyCode }; - } - flushSoon() { - if (this.delayedFlush < 0) - this.delayedFlush = window.setTimeout(() => { this.delayedFlush = -1; this.flush(); }, 20); - } - forceFlush() { - if (this.delayedFlush >= 0) { - window.clearTimeout(this.delayedFlush); - this.delayedFlush = -1; - this.flush(); - } - } - processRecords() { - let records = this.queue; - for (let mut of this.observer.takeRecords()) - records.push(mut); - if (records.length) - this.queue = []; - let from = -1, to = -1, typeOver = false; - for (let record of records) { - let range = this.readMutation(record); - if (!range) - continue; - if (range.typeOver) - typeOver = true; - if (from == -1) { - ({ from, to } = range); - } - else { - from = Math.min(range.from, from); - to = Math.max(range.to, to); - } - } - return { from, to, typeOver }; - } - // Apply pending changes, if any - flush(readSelection = true) { - // Completely hold off flushing when pending keys are set—the code - // managing those will make sure processRecords is called and the - // view is resynchronized after - if (this.delayedFlush >= 0 || this.delayedAndroidKey) - return; - if (readSelection) - this.readSelectionRange(); - let { from, to, typeOver } = this.processRecords(); - let newSel = this.selectionChanged && hasSelection(this.dom, this.selectionRange); - if (from < 0 && !newSel) - return; - this.selectionChanged = false; - let startState = this.view.state; - this.onChange(from, to, typeOver); - // The view wasn't updated - if (this.view.state == startState) - this.view.update([]); - } - readMutation(rec) { - let cView = this.view.docView.nearest(rec.target); - if (!cView || cView.ignoreMutation(rec)) - return null; - cView.markDirty(rec.type == "attributes"); - if (rec.type == "attributes") - cView.dirty |= 4 /* Attrs */; - if (rec.type == "childList") { - let childBefore = findChild(cView, rec.previousSibling || rec.target.previousSibling, -1); - let childAfter = findChild(cView, rec.nextSibling || rec.target.nextSibling, 1); - return { from: childBefore ? cView.posAfter(childBefore) : cView.posAtStart, - to: childAfter ? cView.posBefore(childAfter) : cView.posAtEnd, typeOver: false }; - } - else if (rec.type == "characterData") { - return { from: cView.posAtStart, to: cView.posAtEnd, typeOver: rec.target.nodeValue == rec.oldValue }; - } - else { - return null; - } - } - destroy() { - var _a, _b, _c; - this.stop(); - (_a = this.intersection) === null || _a === void 0 ? void 0 : _a.disconnect(); - (_b = this.gapIntersection) === null || _b === void 0 ? void 0 : _b.disconnect(); - (_c = this.resize) === null || _c === void 0 ? void 0 : _c.disconnect(); - for (let dom of this.scrollTargets) - dom.removeEventListener("scroll", this.onScroll); - window.removeEventListener("scroll", this.onScroll); - window.removeEventListener("resize", this.onResize); - window.removeEventListener("beforeprint", this.onPrint); - this.dom.ownerDocument.removeEventListener("selectionchange", this.onSelectionChange); - clearTimeout(this.parentCheck); - clearTimeout(this.resizeTimeout); - } - } - function findChild(cView, dom, dir) { - while (dom) { - let curView = ContentView.get(dom); - if (curView && curView.parent == cView) - return curView; - let parent = dom.parentNode; - dom = parent != cView.dom ? parent : dir > 0 ? dom.nextSibling : dom.previousSibling; - } - return null; - } - // Used to work around a Safari Selection/shadow DOM bug (#414) - function safariSelectionRangeHack(view) { - let found = null; - // Because Safari (at least in 2018-2021) doesn't provide regular - // access to the selection inside a shadowroot, we have to perform a - // ridiculous hack to get at it—using `execCommand` to trigger a - // `beforeInput` event so that we can read the target range from the - // event. - function read(event) { - event.preventDefault(); - event.stopImmediatePropagation(); - found = event.getTargetRanges()[0]; - } - view.contentDOM.addEventListener("beforeinput", read, true); - document.execCommand("indent"); - view.contentDOM.removeEventListener("beforeinput", read, true); - if (!found) - return null; - let anchorNode = found.startContainer, anchorOffset = found.startOffset; - let focusNode = found.endContainer, focusOffset = found.endOffset; - let curAnchor = view.docView.domAtPos(view.state.selection.main.anchor); - // Since such a range doesn't distinguish between anchor and head, - // use a heuristic that flips it around if its end matches the - // current anchor. - if (isEquivalentPosition(curAnchor.node, curAnchor.offset, focusNode, focusOffset)) - [anchorNode, anchorOffset, focusNode, focusOffset] = [focusNode, focusOffset, anchorNode, anchorOffset]; - return { anchorNode, anchorOffset, focusNode, focusOffset }; - } - - function applyDOMChange(view, start, end, typeOver) { - let change, newSel; - let sel = view.state.selection.main; - if (start > -1) { - let bounds = view.docView.domBoundsAround(start, end, 0); - if (!bounds || view.state.readOnly) - return; - let { from, to } = bounds; - let selPoints = view.docView.impreciseHead || view.docView.impreciseAnchor ? [] : selectionPoints(view); - let reader = new DOMReader(selPoints, view.state); - reader.readRange(bounds.startDOM, bounds.endDOM); - let preferredPos = sel.from, preferredSide = null; - // Prefer anchoring to end when Backspace is pressed (or, on - // Android, when something was deleted) - if (view.inputState.lastKeyCode === 8 && view.inputState.lastKeyTime > Date.now() - 100 || - browser.android && reader.text.length < to - from) { - preferredPos = sel.to; - preferredSide = "end"; - } - let diff = findDiff(view.state.doc.sliceString(from, to, LineBreakPlaceholder), reader.text, preferredPos - from, preferredSide); - if (diff) { - // Chrome inserts two newlines when pressing shift-enter at the - // end of a line. This drops one of those. - if (browser.chrome && view.inputState.lastKeyCode == 13 && - diff.toB == diff.from + 2 && reader.text.slice(diff.from, diff.toB) == LineBreakPlaceholder + LineBreakPlaceholder) - diff.toB--; - change = { from: from + diff.from, to: from + diff.toA, - insert: Text.of(reader.text.slice(diff.from, diff.toB).split(LineBreakPlaceholder)) }; - } - newSel = selectionFromPoints(selPoints, from); - } - else if (view.hasFocus || !view.state.facet(editable)) { - let domSel = view.observer.selectionRange; - let { impreciseHead: iHead, impreciseAnchor: iAnchor } = view.docView; - let head = iHead && iHead.node == domSel.focusNode && iHead.offset == domSel.focusOffset || - !contains(view.contentDOM, domSel.focusNode) - ? view.state.selection.main.head - : view.docView.posFromDOM(domSel.focusNode, domSel.focusOffset); - let anchor = iAnchor && iAnchor.node == domSel.anchorNode && iAnchor.offset == domSel.anchorOffset || - !contains(view.contentDOM, domSel.anchorNode) - ? view.state.selection.main.anchor - : view.docView.posFromDOM(domSel.anchorNode, domSel.anchorOffset); - if (head != sel.head || anchor != sel.anchor) - newSel = EditorSelection.single(anchor, head); - } - if (!change && !newSel) - return; - // Heuristic to notice typing over a selected character - if (!change && typeOver && !sel.empty && newSel && newSel.main.empty) - change = { from: sel.from, to: sel.to, insert: view.state.doc.slice(sel.from, sel.to) }; - // If the change is inside the selection and covers most of it, - // assume it is a selection replace (with identical characters at - // the start/end not included in the diff) - else if (change && change.from >= sel.from && change.to <= sel.to && - (change.from != sel.from || change.to != sel.to) && - (sel.to - sel.from) - (change.to - change.from) <= 4) - change = { - from: sel.from, to: sel.to, - insert: view.state.doc.slice(sel.from, change.from).append(change.insert).append(view.state.doc.slice(change.to, sel.to)) - }; - if (change) { - let startState = view.state; - if (browser.ios && view.inputState.flushIOSKey(view)) - return; - // Android browsers don't fire reasonable key events for enter, - // backspace, or delete. So this detects changes that look like - // they're caused by those keys, and reinterprets them as key - // events. (Some of these keys are also handled by beforeinput - // events and the pendingAndroidKey mechanism, but that's not - // reliable in all situations.) - if (browser.android && - ((change.from == sel.from && change.to == sel.to && - change.insert.length == 1 && change.insert.lines == 2 && - dispatchKey(view.contentDOM, "Enter", 13)) || - (change.from == sel.from - 1 && change.to == sel.to && change.insert.length == 0 && - dispatchKey(view.contentDOM, "Backspace", 8)) || - (change.from == sel.from && change.to == sel.to + 1 && change.insert.length == 0 && - dispatchKey(view.contentDOM, "Delete", 46)))) - return; - let text = change.insert.toString(); - if (view.state.facet(inputHandler$1).some(h => h(view, change.from, change.to, text))) - return; - if (view.inputState.composing >= 0) - view.inputState.composing++; - let tr; - if (change.from >= sel.from && change.to <= sel.to && change.to - change.from >= (sel.to - sel.from) / 3 && - (!newSel || newSel.main.empty && newSel.main.from == change.from + change.insert.length) && - view.inputState.composing < 0) { - let before = sel.from < change.from ? startState.sliceDoc(sel.from, change.from) : ""; - let after = sel.to > change.to ? startState.sliceDoc(change.to, sel.to) : ""; - tr = startState.replaceSelection(view.state.toText(before + change.insert.sliceString(0, undefined, view.state.lineBreak) + after)); - } - else { - let changes = startState.changes(change); - let mainSel = newSel && !startState.selection.main.eq(newSel.main) && newSel.main.to <= changes.newLength - ? newSel.main : undefined; - // Try to apply a composition change to all cursors - if (startState.selection.ranges.length > 1 && view.inputState.composing >= 0 && - change.to <= sel.to && change.to >= sel.to - 10) { - let replaced = view.state.sliceDoc(change.from, change.to); - let compositionRange = compositionSurroundingNode(view) || view.state.doc.lineAt(sel.head); - let offset = sel.to - change.to, size = sel.to - sel.from; - tr = startState.changeByRange(range => { - if (range.from == sel.from && range.to == sel.to) - return { changes, range: mainSel || range.map(changes) }; - let to = range.to - offset, from = to - replaced.length; - if (range.to - range.from != size || view.state.sliceDoc(from, to) != replaced || - // Unfortunately, there's no way to make multiple - // changes in the same node work without aborting - // composition, so cursors in the composition range are - // ignored. - compositionRange && range.to >= compositionRange.from && range.from <= compositionRange.to) - return { range }; - let rangeChanges = startState.changes({ from, to, insert: change.insert }), selOff = range.to - sel.to; - return { - changes: rangeChanges, - range: !mainSel ? range.map(rangeChanges) : - EditorSelection.range(Math.max(0, mainSel.anchor + selOff), Math.max(0, mainSel.head + selOff)) - }; - }); - } - else { - tr = { - changes, - selection: mainSel && startState.selection.replaceRange(mainSel) - }; - } - } - let userEvent = "input.type"; - if (view.composing) { - userEvent += ".compose"; - if (view.inputState.compositionFirstChange) { - userEvent += ".start"; - view.inputState.compositionFirstChange = false; - } - } - view.dispatch(tr, { scrollIntoView: true, userEvent }); - } - else if (newSel && !newSel.main.eq(sel)) { - let scrollIntoView = false, userEvent = "select"; - if (view.inputState.lastSelectionTime > Date.now() - 50) { - if (view.inputState.lastSelectionOrigin == "select") - scrollIntoView = true; - userEvent = view.inputState.lastSelectionOrigin; - } - view.dispatch({ selection: newSel, scrollIntoView, userEvent }); - } - } - function findDiff(a, b, preferredPos, preferredSide) { - let minLen = Math.min(a.length, b.length); - let from = 0; - while (from < minLen && a.charCodeAt(from) == b.charCodeAt(from)) - from++; - if (from == minLen && a.length == b.length) - return null; - let toA = a.length, toB = b.length; - while (toA > 0 && toB > 0 && a.charCodeAt(toA - 1) == b.charCodeAt(toB - 1)) { - toA--; - toB--; - } - if (preferredSide == "end") { - let adjust = Math.max(0, from - Math.min(toA, toB)); - preferredPos -= toA + adjust - from; - } - if (toA < from && a.length < b.length) { - let move = preferredPos <= from && preferredPos >= toA ? from - preferredPos : 0; - from -= move; - toB = from + (toB - toA); - toA = from; - } - else if (toB < from) { - let move = preferredPos <= from && preferredPos >= toB ? from - preferredPos : 0; - from -= move; - toA = from + (toA - toB); - toB = from; - } - return { from, toA, toB }; - } - function selectionPoints(view) { - let result = []; - if (view.root.activeElement != view.contentDOM) - return result; - let { anchorNode, anchorOffset, focusNode, focusOffset } = view.observer.selectionRange; - if (anchorNode) { - result.push(new DOMPoint(anchorNode, anchorOffset)); - if (focusNode != anchorNode || focusOffset != anchorOffset) - result.push(new DOMPoint(focusNode, focusOffset)); - } - return result; - } - function selectionFromPoints(points, base) { - if (points.length == 0) - return null; - let anchor = points[0].pos, head = points.length == 2 ? points[1].pos : anchor; - return anchor > -1 && head > -1 ? EditorSelection.single(anchor + base, head + base) : null; - } - - // The editor's update state machine looks something like this: - // - // Idle → Updating ⇆ Idle (unchecked) → Measuring → Idle - // ↑ ↓ - // Updating (measure) - // - // The difference between 'Idle' and 'Idle (unchecked)' lies in - // whether a layout check has been scheduled. A regular update through - // the `update` method updates the DOM in a write-only fashion, and - // relies on a check (scheduled with `requestAnimationFrame`) to make - // sure everything is where it should be and the viewport covers the - // visible code. That check continues to measure and then optionally - // update until it reaches a coherent state. - /** - An editor view represents the editor's user interface. It holds - the editable DOM surface, and possibly other elements such as the - line number gutter. It handles events and dispatches state - transactions for editing actions. - */ - class EditorView { - /** - Construct a new view. You'll usually want to put `view.dom` into - your document after creating a view, so that the user can see - it. - */ - constructor( - /** - Initialization options. - */ - config = {}) { - this.plugins = []; - this.pluginMap = new Map; - this.editorAttrs = {}; - this.contentAttrs = {}; - this.bidiCache = []; - this.destroyed = false; - /** - @internal - */ - this.updateState = 2 /* Updating */; - /** - @internal - */ - this.measureScheduled = -1; - /** - @internal - */ - 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.style.cssText = "position: absolute; top: -10000px"; - this.announceDOM.setAttribute("aria-live", "polite"); - this.dom = document.createElement("div"); - this.dom.appendChild(this.announceDOM); - this.dom.appendChild(this.scrollDOM); - this._dispatch = config.dispatch || ((tr) => this.update([tr])); - this.dispatch = this.dispatch.bind(this); - this.root = (config.root || getRoot(config.parent) || document); - this.viewState = new ViewState(config.state || EditorState.create()); - this.plugins = this.state.facet(viewPlugin).map(spec => new PluginInstance(spec)); - for (let plugin of this.plugins) - plugin.update(this); - this.observer = new DOMObserver(this, (from, to, typeOver) => { - applyDOMChange(this, from, to, typeOver); - }, event => { - this.inputState.runScrollHandlers(this, event); - if (this.observer.intersecting) - this.measure(); - }); - this.inputState = new InputState(this); - this.docView = new DocView(this); - this.mountStyles(); - this.updateAttrs(); - this.updateState = 0 /* Idle */; - this.requestMeasure(); - if (config.parent) - config.parent.appendChild(this.dom); - } - /** - The current editor state. - */ - get state() { return this.viewState.state; } - /** - To be able to display large documents without consuming too much - memory or overloading the browser, CodeMirror only draws the - code that is visible (plus a margin around it) to the DOM. This - property tells you the extent of the current drawn viewport, in - document positions. - */ - get viewport() { return this.viewState.viewport; } - /** - When there are, for example, large collapsed ranges in the - viewport, its size can be a lot bigger than the actual visible - content. Thus, if you are doing something like styling the - content in the viewport, it is preferable to only do so for - these ranges, which are the subset of the viewport that is - actually drawn. - */ - get visibleRanges() { return this.viewState.visibleRanges; } - /** - Returns false when the editor is entirely scrolled out of view - or otherwise hidden. - */ - get inView() { return this.viewState.inView; } - /** - Indicates whether the user is currently composing text via - [IME](https://en.wikipedia.org/wiki/Input_method), and at least - one change has been made in the current composition. - */ - get composing() { return this.inputState.composing > 0; } - /** - Indicates whether the user is currently in composing state. Note - that on some platforms, like Android, this will be the case a - lot, since just putting the cursor on a word starts a - composition there. - */ - get compositionStarted() { return this.inputState.composing >= 0; } - dispatch(...input) { - this._dispatch(input.length == 1 && input[0] instanceof Transaction ? input[0] - : this.state.update(...input)); - } - /** - Update the view for the given array of transactions. This will - update the visible document and selection to match the state - produced by the transactions, and notify view plugins of the - change. You should usually call - [`dispatch`](https://codemirror.net/6/docs/ref/#view.EditorView.dispatch) instead, which uses this - as a primitive. - */ - update(transactions) { - if (this.updateState != 0 /* Idle */) - throw new Error("Calls to EditorView.update are not allowed while an update is in progress"); - let redrawn = false, update; - let state = this.state; - for (let tr of transactions) { - if (tr.startState != state) - throw new RangeError("Trying to update state with a transaction that doesn't start from the previous state."); - state = tr.state; - } - if (this.destroyed) { - this.viewState.state = state; - return; - } - // When the phrases change, redraw the editor - if (state.facet(EditorState.phrases) != this.state.facet(EditorState.phrases)) - return this.setState(state); - update = new ViewUpdate(this, state, transactions); - let scrollTarget = this.viewState.scrollTarget; - try { - this.updateState = 2 /* Updating */; - for (let tr of transactions) { - if (scrollTarget) - scrollTarget = scrollTarget.map(tr.changes); - if (tr.scrollIntoView) { - let { main } = tr.state.selection; - scrollTarget = new ScrollTarget(main.empty ? main : EditorSelection.cursor(main.head, main.head > main.anchor ? -1 : 1)); - } - for (let e of tr.effects) { - if (e.is(scrollTo)) - scrollTarget = new ScrollTarget(e.value); - else if (e.is(centerOn)) - scrollTarget = new ScrollTarget(e.value, "center"); - else if (e.is(scrollIntoView$1)) - scrollTarget = e.value; - } - } - this.viewState.update(update, scrollTarget); - this.bidiCache = CachedOrder.update(this.bidiCache, update.changes); - if (!update.empty) { - this.updatePlugins(update); - this.inputState.update(update); - } - redrawn = this.docView.update(update); - if (this.state.facet(styleModule) != this.styleModules) - this.mountStyles(); - this.updateAttrs(); - this.showAnnouncements(transactions); - this.docView.updateSelection(redrawn, transactions.some(tr => tr.isUserEvent("select.pointer"))); - } - finally { - this.updateState = 0 /* Idle */; - } - if (update.startState.facet(theme) != update.state.facet(theme)) - this.viewState.mustMeasureContent = true; - if (redrawn || scrollTarget || this.viewState.mustEnforceCursorAssoc || this.viewState.mustMeasureContent) - this.requestMeasure(); - if (!update.empty) - for (let listener of this.state.facet(updateListener)) - listener(update); - } - /** - Reset the view to the given state. (This will cause the entire - document to be redrawn and all view plugins to be reinitialized, - so you should probably only use it when the new state isn't - derived from the old state. Otherwise, use - [`dispatch`](https://codemirror.net/6/docs/ref/#view.EditorView.dispatch) instead.) - */ - setState(newState) { - if (this.updateState != 0 /* Idle */) - throw new Error("Calls to EditorView.setState are not allowed while an update is in progress"); - if (this.destroyed) { - this.viewState.state = newState; - return; - } - this.updateState = 2 /* Updating */; - let hadFocus = this.hasFocus; - try { - for (let plugin of this.plugins) - plugin.destroy(this); - this.viewState = new ViewState(newState); - this.plugins = newState.facet(viewPlugin).map(spec => new PluginInstance(spec)); - this.pluginMap.clear(); - for (let plugin of this.plugins) - plugin.update(this); - this.docView = new DocView(this); - this.inputState.ensureHandlers(this); - this.mountStyles(); - this.updateAttrs(); - this.bidiCache = []; - } - finally { - this.updateState = 0 /* Idle */; - } - if (hadFocus) - this.focus(); - this.requestMeasure(); - } - updatePlugins(update) { - let prevSpecs = update.startState.facet(viewPlugin), specs = update.state.facet(viewPlugin); - if (prevSpecs != specs) { - let newPlugins = []; - for (let spec of specs) { - let found = prevSpecs.indexOf(spec); - if (found < 0) { - newPlugins.push(new PluginInstance(spec)); - } - else { - let plugin = this.plugins[found]; - plugin.mustUpdate = update; - newPlugins.push(plugin); - } - } - for (let plugin of this.plugins) - if (plugin.mustUpdate != update) - plugin.destroy(this); - this.plugins = newPlugins; - this.pluginMap.clear(); - this.inputState.ensureHandlers(this); - } - else { - for (let p of this.plugins) - p.mustUpdate = update; - } - for (let i = 0; i < this.plugins.length; i++) - this.plugins[i].update(this); - } - /** - @internal - */ - measure(flush = true) { - if (this.destroyed) - return; - if (this.measureScheduled > -1) - cancelAnimationFrame(this.measureScheduled); - this.measureScheduled = 0; // Prevent requestMeasure calls from scheduling another animation frame - if (flush) - this.observer.flush(); - let updated = null; - try { - for (let i = 0;; i++) { - this.updateState = 1 /* Measuring */; - let oldViewport = this.viewport; - let changed = this.viewState.measure(this); - if (!changed && !this.measureRequests.length && this.viewState.scrollTarget == null) - break; - if (i > 5) { - console.warn(this.measureRequests.length - ? "Measure loop restarted more than 5 times" - : "Viewport failed to stabilize"); - break; - } - let measuring = []; - // Only run measure requests in this cycle when the viewport didn't change - if (!(changed & 4 /* Viewport */)) - [this.measureRequests, measuring] = [measuring, this.measureRequests]; - let measured = measuring.map(m => { - try { - return m.read(this); - } - catch (e) { - logException(this.state, e); - return BadMeasure; - } - }); - let update = new ViewUpdate(this, this.state), redrawn = false, scrolled = false; - update.flags |= changed; - if (!updated) - updated = update; - else - updated.flags |= changed; - this.updateState = 2 /* Updating */; - if (!update.empty) { - this.updatePlugins(update); - this.inputState.update(update); - this.updateAttrs(); - redrawn = this.docView.update(update); - } - for (let i = 0; i < measuring.length; i++) - if (measured[i] != BadMeasure) { - try { - let m = measuring[i]; - if (m.write) - m.write(measured[i], this); - } - catch (e) { - logException(this.state, e); - } - } - if (this.viewState.scrollTarget) { - this.docView.scrollIntoView(this.viewState.scrollTarget); - this.viewState.scrollTarget = null; - scrolled = true; - } - if (redrawn) - this.docView.updateSelection(true); - if (this.viewport.from == oldViewport.from && this.viewport.to == oldViewport.to && - !scrolled && this.measureRequests.length == 0) - break; - } - } - finally { - this.updateState = 0 /* Idle */; - this.measureScheduled = -1; - } - if (updated && !updated.empty) - for (let listener of this.state.facet(updateListener)) - listener(updated); - } - /** - Get the CSS classes for the currently active editor themes. - */ - get themeClasses() { - return baseThemeID + " " + - (this.state.facet(darkTheme) ? baseDarkID : baseLightID) + " " + - this.state.facet(theme); - } - updateAttrs() { - let editorAttrs = attrsFromFacet(this, editorAttributes, { - class: "cm-editor" + (this.hasFocus ? " cm-focused " : " ") + this.themeClasses - }); - let contentAttrs = { - spellcheck: "false", - autocorrect: "off", - autocapitalize: "off", - translate: "no", - contenteditable: !this.state.facet(editable) ? "false" : "true", - class: "cm-content", - style: `${browser.tabSize}: ${this.state.tabSize}`, - role: "textbox", - "aria-multiline": "true" - }; - if (this.state.readOnly) - contentAttrs["aria-readonly"] = "true"; - attrsFromFacet(this, contentAttributes, contentAttrs); - this.observer.ignore(() => { - updateAttrs(this.contentDOM, this.contentAttrs, contentAttrs); - updateAttrs(this.dom, this.editorAttrs, editorAttrs); - }); - this.editorAttrs = editorAttrs; - this.contentAttrs = contentAttrs; - } - showAnnouncements(trs) { - let first = true; - for (let tr of trs) - for (let effect of tr.effects) - if (effect.is(EditorView.announce)) { - if (first) - this.announceDOM.textContent = ""; - first = false; - let div = this.announceDOM.appendChild(document.createElement("div")); - div.textContent = effect.value; - } - } - mountStyles() { - this.styleModules = this.state.facet(styleModule); - StyleModule.mount(this.root, this.styleModules.concat(baseTheme$8).reverse()); - } - readMeasured() { - if (this.updateState == 2 /* Updating */) - throw new Error("Reading the editor layout isn't allowed during an update"); - if (this.updateState == 0 /* Idle */ && this.measureScheduled > -1) - this.measure(false); - } - /** - Schedule a layout measurement, optionally providing callbacks to - do custom DOM measuring followed by a DOM write phase. Using - this is preferable reading DOM layout directly from, for - example, an event handler, because it'll make sure measuring and - drawing done by other components is synchronized, avoiding - unnecessary DOM layout computations. - */ - requestMeasure(request) { - if (this.measureScheduled < 0) - this.measureScheduled = requestAnimationFrame(() => this.measure()); - if (request) { - if (request.key != null) - for (let i = 0; i < this.measureRequests.length; i++) { - if (this.measureRequests[i].key === request.key) { - this.measureRequests[i] = request; - return; - } - } - this.measureRequests.push(request); - } - } - /** - Collect all values provided by the active plugins for a given - field. - */ - pluginField(field) { - let result = []; - for (let plugin of this.plugins) - plugin.update(this).takeField(field, result); - return result; - } - /** - Get the value of a specific plugin, if present. Note that - plugins that crash can be dropped from a view, so even when you - know you registered a given plugin, it is recommended to check - the return value of this method. - */ - plugin(plugin) { - let known = this.pluginMap.get(plugin); - if (known === undefined || known && known.spec != plugin) - this.pluginMap.set(plugin, known = this.plugins.find(p => p.spec == plugin) || null); - return known && known.update(this).value; - } - /** - The top position of the document, in screen coordinates. This - may be negative when the editor is scrolled down. Points - directly to the top of the first line, not above the padding. - */ - get documentTop() { - return this.contentDOM.getBoundingClientRect().top + this.viewState.paddingTop; - } - /** - Reports the padding above and below the document. - */ - get documentPadding() { - return { top: this.viewState.paddingTop, bottom: this.viewState.paddingBottom }; - } - /** - Find the line or block widget at the given vertical position. - - By default, this position is interpreted as a screen position, - meaning `docTop` is set to the DOM top position of the editor - content (forcing a layout). You can pass a different `docTop` - value—for example 0 to interpret `height` as a document-relative - position, or a precomputed document top - (`view.contentDOM.getBoundingClientRect().top`) to limit layout - queries. - - *Deprecated: use `elementAtHeight` instead.* - */ - blockAtHeight(height, docTop) { - let top = ensureTop(docTop, this); - return this.elementAtHeight(height - top).moveY(top); - } - /** - Find the text line or block widget at the given vertical - position (which is interpreted as relative to the [top of the - document](https://codemirror.net/6/docs/ref/#view.EditorView.documentTop) - */ - elementAtHeight(height) { - this.readMeasured(); - return this.viewState.elementAtHeight(height); - } - /** - Find information for the visual line (see - [`visualLineAt`](https://codemirror.net/6/docs/ref/#view.EditorView.visualLineAt)) at the given - vertical position. The resulting block info might hold another - array of block info structs in its `type` field if this line - consists of more than one block. - - Defaults to treating `height` as a screen position. See - [`blockAtHeight`](https://codemirror.net/6/docs/ref/#view.EditorView.blockAtHeight) for the - interpretation of the `docTop` parameter. - - *Deprecated: use `lineBlockAtHeight` instead.* - */ - visualLineAtHeight(height, docTop) { - let top = ensureTop(docTop, this); - return this.lineBlockAtHeight(height - top).moveY(top); - } - /** - Find the line block (see - [`lineBlockAt`](https://codemirror.net/6/docs/ref/#view.EditorView.lineBlockAt) at the given - height. - */ - lineBlockAtHeight(height) { - this.readMeasured(); - return this.viewState.lineBlockAtHeight(height); - } - /** - Iterate over the height information of the visual lines in the - viewport. The heights of lines are reported relative to the - given document top, which defaults to the screen position of the - document (forcing a layout). - - *Deprecated: use `viewportLineBlocks` instead.* - */ - viewportLines(f, docTop) { - let top = ensureTop(docTop, this); - for (let line of this.viewportLineBlocks) - f(line.moveY(top)); - } - /** - Get the extent and vertical position of all [line - blocks](https://codemirror.net/6/docs/ref/#view.EditorView.lineBlockAt) in the viewport. Positions - are relative to the [top of the - document](https://codemirror.net/6/docs/ref/#view.EditorView.documentTop); - */ - get viewportLineBlocks() { - return this.viewState.viewportLines; - } - /** - Find the extent and height of the visual line (a range delimited - on both sides by either non-[hidden](https://codemirror.net/6/docs/ref/#view.Decoration^range) - line breaks, or the start/end of the document) at the given position. - - Vertical positions are computed relative to the `docTop` - argument, which defaults to 0 for this method. You can pass - `view.contentDOM.getBoundingClientRect().top` here to get screen - coordinates. - - *Deprecated: use `lineBlockAt` instead.* - */ - visualLineAt(pos, docTop = 0) { - return this.lineBlockAt(pos).moveY(docTop + this.viewState.paddingTop); - } - /** - Find the line block around the given document position. A line - block is a range delimited on both sides by either a - non-[hidden](https://codemirror.net/6/docs/ref/#view.Decoration^range) line breaks, or the - start/end of the document. It will usually just hold a line of - text, but may be broken into multiple textblocks by block - widgets. - */ - lineBlockAt(pos) { - return this.viewState.lineBlockAt(pos); - } - /** - The editor's total content height. - */ - get contentHeight() { - return this.viewState.contentHeight; - } - /** - Move a cursor position by [grapheme - cluster](https://codemirror.net/6/docs/ref/#text.findClusterBreak). `forward` determines whether - the motion is away from the line start, or towards it. Motion in - bidirectional text is in visual order, in the editor's [text - direction](https://codemirror.net/6/docs/ref/#view.EditorView.textDirection). When the start - position was the last one on the line, the returned position - will be across the line break. If there is no further line, the - original position is returned. - - By default, this method moves over a single cluster. The - optional `by` argument can be used to move across more. It will - be called with the first cluster as argument, and should return - a predicate that determines, for each subsequent cluster, - whether it should also be moved over. - */ - moveByChar(start, forward, by) { - return skipAtoms(this, start, moveByChar(this, start, forward, by)); - } - /** - Move a cursor position across the next group of either - [letters](https://codemirror.net/6/docs/ref/#state.EditorState.charCategorizer) or non-letter - non-whitespace characters. - */ - moveByGroup(start, forward) { - return skipAtoms(this, start, moveByChar(this, start, forward, initial => byGroup(this, start.head, initial))); - } - /** - Move to the next line boundary in the given direction. If - `includeWrap` is true, line wrapping is on, and there is a - further wrap point on the current line, the wrap point will be - returned. Otherwise this function will return the start or end - of the line. - */ - moveToLineBoundary(start, forward, includeWrap = true) { - return moveToLineBoundary(this, start, forward, includeWrap); - } - /** - Move a cursor position vertically. When `distance` isn't given, - it defaults to moving to the next line (including wrapped - lines). Otherwise, `distance` should provide a positive distance - in pixels. - - When `start` has a - [`goalColumn`](https://codemirror.net/6/docs/ref/#state.SelectionRange.goalColumn), the vertical - motion will use that as a target horizontal position. Otherwise, - the cursor's own horizontal position is used. The returned - cursor will have its goal column set to whichever column was - used. - */ - moveVertically(start, forward, distance) { - return skipAtoms(this, start, moveVertically(this, start, forward, distance)); - } - // FIXME remove on next major version - scrollPosIntoView(pos) { - this.dispatch({ effects: scrollTo.of(EditorSelection.cursor(pos)) }); - } - /** - Find the DOM parent node and offset (child offset if `node` is - an element, character offset when it is a text node) at the - given document position. - - Note that for positions that aren't currently in - `visibleRanges`, the resulting DOM position isn't necessarily - meaningful (it may just point before or after a placeholder - element). - */ - domAtPos(pos) { - return this.docView.domAtPos(pos); - } - /** - Find the document position at the given DOM node. Can be useful - for associating positions with DOM events. Will raise an error - when `node` isn't part of the editor content. - */ - posAtDOM(node, offset = 0) { - return this.docView.posFromDOM(node, offset); - } - posAtCoords(coords, precise = true) { - this.readMeasured(); - return posAtCoords(this, coords, precise); - } - /** - Get the screen coordinates at the given document position. - `side` determines whether the coordinates are based on the - element before (-1) or after (1) the position (if no element is - available on the given side, the method will transparently use - another strategy to get reasonable coordinates). - */ - coordsAtPos(pos, side = 1) { - this.readMeasured(); - let rect = this.docView.coordsAt(pos, side); - if (!rect || rect.left == rect.right) - return rect; - let line = this.state.doc.lineAt(pos), order = this.bidiSpans(line); - let span = order[BidiSpan.find(order, pos - line.from, -1, side)]; - return flattenRect(rect, (span.dir == Direction.LTR) == (side > 0)); - } - /** - The default width of a character in the editor. May not - accurately reflect the width of all characters (given variable - width fonts or styling of invididual ranges). - */ - get defaultCharacterWidth() { return this.viewState.heightOracle.charWidth; } - /** - The default height of a line in the editor. May not be accurate - for all lines. - */ - get defaultLineHeight() { return this.viewState.heightOracle.lineHeight; } - /** - The text direction - ([`direction`](https://developer.mozilla.org/en-US/docs/Web/CSS/direction) - CSS property) of the editor. - */ - get textDirection() { return this.viewState.heightOracle.direction; } - /** - Whether this editor [wraps lines](https://codemirror.net/6/docs/ref/#view.EditorView.lineWrapping) - (as determined by the - [`white-space`](https://developer.mozilla.org/en-US/docs/Web/CSS/white-space) - CSS property of its content element). - */ - get lineWrapping() { return this.viewState.heightOracle.lineWrapping; } - /** - Returns the bidirectional text structure of the given line - (which should be in the current document) as an array of span - objects. The order of these spans matches the [text - direction](https://codemirror.net/6/docs/ref/#view.EditorView.textDirection)—if that is - left-to-right, the leftmost spans come first, otherwise the - rightmost spans come first. - */ - bidiSpans(line) { - if (line.length > MaxBidiLine) - return trivialOrder(line.length); - let dir = this.textDirection; - for (let entry of this.bidiCache) - if (entry.from == line.from && entry.dir == dir) - return entry.order; - let order = computeOrder(line.text, this.textDirection); - this.bidiCache.push(new CachedOrder(line.from, line.to, dir, order)); - return order; - } - /** - Check whether the editor has focus. - */ - get hasFocus() { - var _a; - // Safari return false for hasFocus when the context menu is open - // or closing, which leads us to ignore selection changes from the - // context menu because it looks like the editor isn't focused. - // This kludges around that. - return (document.hasFocus() || browser.safari && ((_a = this.inputState) === null || _a === void 0 ? void 0 : _a.lastContextMenu) > Date.now() - 3e4) && - this.root.activeElement == this.contentDOM; - } - /** - Put focus on the editor. - */ - focus() { - this.observer.ignore(() => { - focusPreventScroll(this.contentDOM); - this.docView.updateSelection(); - }); - } - /** - Clean up this editor view, removing its element from the - document, unregistering event handlers, and notifying - plugins. The view instance can no longer be used after - calling this. - */ - destroy() { - for (let plugin of this.plugins) - plugin.destroy(this); - this.plugins = []; - this.inputState.destroy(); - this.dom.remove(); - this.observer.destroy(); - if (this.measureScheduled > -1) - cancelAnimationFrame(this.measureScheduled); - this.destroyed = true; - } - /** - Returns an effect that can be - [added](https://codemirror.net/6/docs/ref/#state.TransactionSpec.effects) to a transaction to - cause it to scroll the given position or range into view. - */ - static scrollIntoView(pos, options = {}) { - return scrollIntoView$1.of(new ScrollTarget(typeof pos == "number" ? EditorSelection.cursor(pos) : pos, options.y, options.x, options.yMargin, options.xMargin)); - } - /** - Facet that can be used to add DOM event handlers. The value - should be an object mapping event names to handler functions. The - first such function to return true will be assumed to have handled - that event, and no other handlers or built-in behavior will be - activated for it. - These are registered on the [content - element](https://codemirror.net/6/docs/ref/#view.EditorView.contentDOM), except for `scroll` - handlers, which will be called any time the editor's [scroll - element](https://codemirror.net/6/docs/ref/#view.EditorView.scrollDOM) or one of its parent nodes - is scrolled. - */ - static domEventHandlers(handlers) { - return ViewPlugin.define(() => ({}), { eventHandlers: handlers }); - } - /** - Create a theme extension. The first argument can be a - [`style-mod`](https://github.com/marijnh/style-mod#documentation) - style spec providing the styles for the theme. These will be - prefixed with a generated class for the style. - - Because the selectors will be prefixed with a scope class, rule - that directly match the editor's [wrapper - element](https://codemirror.net/6/docs/ref/#view.EditorView.dom)—to which the scope class will be - added—need to be explicitly differentiated by adding an `&` to - the selector for that element—for example - `&.cm-focused`. - - When `dark` is set to true, the theme will be marked as dark, - which will cause the `&dark` rules from [base - themes](https://codemirror.net/6/docs/ref/#view.EditorView^baseTheme) to be used (as opposed to - `&light` when a light theme is active). - */ - static theme(spec, options) { - let prefix = StyleModule.newName(); - let result = [theme.of(prefix), styleModule.of(buildTheme(`.${prefix}`, spec))]; - if (options && options.dark) - result.push(darkTheme.of(true)); - return result; - } - /** - Create an extension that adds styles to the base theme. Like - with [`theme`](https://codemirror.net/6/docs/ref/#view.EditorView^theme), use `&` to indicate the - place of the editor wrapper element when directly targeting - that. You can also use `&dark` or `&light` instead to only - target editors with a dark or light theme. - */ - static baseTheme(spec) { - return Prec.lowest(styleModule.of(buildTheme("." + baseThemeID, spec, lightDarkIDs))); - } - } - /** - Effect that can be [added](https://codemirror.net/6/docs/ref/#state.TransactionSpec.effects) to a - transaction to make it scroll the given range into view. - - *Deprecated*. Use [`scrollIntoView`](https://codemirror.net/6/docs/ref/#view.EditorView^scrollIntoView) instead. - */ - EditorView.scrollTo = scrollTo; - /** - Effect that makes the editor scroll the given range to the - center of the visible view. - - *Deprecated*. Use [`scrollIntoView`](https://codemirror.net/6/docs/ref/#view.EditorView^scrollIntoView) instead. - */ - EditorView.centerOn = centerOn; - /** - Facet to add a [style - module](https://github.com/marijnh/style-mod#documentation) to - an editor view. The view will ensure that the module is - mounted in its [document - root](https://codemirror.net/6/docs/ref/#view.EditorView.constructor^config.root). - */ - EditorView.styleModule = styleModule; - /** - An input handler can override the way changes to the editable - DOM content are handled. Handlers are passed the document - positions between which the change was found, and the new - content. When one returns true, no further input handlers are - called and the default behavior is prevented. - */ - EditorView.inputHandler = inputHandler$1; - /** - Allows you to provide a function that should be called when the - library catches an exception from an extension (mostly from view - plugins, but may be used by other extensions to route exceptions - from user-code-provided callbacks). This is mostly useful for - debugging and logging. See [`logException`](https://codemirror.net/6/docs/ref/#view.logException). - */ - EditorView.exceptionSink = exceptionSink; - /** - A facet that can be used to register a function to be called - every time the view updates. - */ - EditorView.updateListener = updateListener; - /** - Facet that controls whether the editor content DOM is editable. - When its highest-precedence value is `false`, the element will - not longer have its `contenteditable` attribute set. (Note that - this doesn't affect API calls that change the editor content, - even when those are bound to keys or buttons. See the - [`readOnly`](https://codemirror.net/6/docs/ref/#state.EditorState.readOnly) facet for that.) - */ - EditorView.editable = editable; - /** - Allows you to influence the way mouse selection happens. The - functions in this facet will be called for a `mousedown` event - on the editor, and can return an object that overrides the way a - selection is computed from that mouse click or drag. - */ - EditorView.mouseSelectionStyle = mouseSelectionStyle; - /** - Facet used to configure whether a given selection drag event - should move or copy the selection. The given predicate will be - called with the `mousedown` event, and can return `true` when - the drag should move the content. - */ - EditorView.dragMovesSelection = dragMovesSelection$1; - /** - Facet used to configure whether a given selecting click adds - a new range to the existing selection or replaces it entirely. - */ - EditorView.clickAddsSelectionRange = clickAddsSelectionRange; - /** - A facet that determines which [decorations](https://codemirror.net/6/docs/ref/#view.Decoration) - are shown in the view. See also [view - plugins](https://codemirror.net/6/docs/ref/#view.EditorView^decorations), which have a separate - mechanism for providing decorations. - */ - EditorView.decorations = decorations; - /** - This facet records whether a dark theme is active. The extension - returned by [`theme`](https://codemirror.net/6/docs/ref/#view.EditorView^theme) automatically - includes an instance of this when the `dark` option is set to - true. - */ - EditorView.darkTheme = darkTheme; - /** - Facet that provides additional DOM attributes for the editor's - editable DOM element. - */ - EditorView.contentAttributes = contentAttributes; - /** - Facet that provides DOM attributes for the editor's outer - element. - */ - EditorView.editorAttributes = editorAttributes; - /** - An extension that enables line wrapping in the editor (by - setting CSS `white-space` to `pre-wrap` in the content). - */ - EditorView.lineWrapping = /*@__PURE__*/EditorView.contentAttributes.of({ "class": "cm-lineWrapping" }); - /** - State effect used to include screen reader announcements in a - transaction. These will be added to the DOM in a visually hidden - element with `aria-live="polite"` set, and should be used to - describe effects that are visually obvious but may not be - noticed by screen reader users (such as moving to the next - search match). - */ - EditorView.announce = /*@__PURE__*/StateEffect.define(); - // Maximum line length for which we compute accurate bidi info - const MaxBidiLine = 4096; - // FIXME remove this and its callers on next breaking release - function ensureTop(given, view) { - return (given == null ? view.contentDOM.getBoundingClientRect().top : given) + view.viewState.paddingTop; - } - const BadMeasure = {}; - class CachedOrder { - constructor(from, to, dir, order) { - this.from = from; - this.to = to; - this.dir = dir; - this.order = order; - } - static update(cache, changes) { - if (changes.empty) - return cache; - let result = [], lastDir = cache.length ? cache[cache.length - 1].dir : Direction.LTR; - for (let i = Math.max(0, cache.length - 10); i < cache.length; i++) { - let entry = cache[i]; - if (entry.dir == lastDir && !changes.touchesRange(entry.from, entry.to)) - result.push(new CachedOrder(changes.mapPos(entry.from, 1), changes.mapPos(entry.to, -1), entry.dir, entry.order)); - } - return result; - } - } - function attrsFromFacet(view, facet, base) { - for (let sources = view.state.facet(facet), i = sources.length - 1; i >= 0; i--) { - let source = sources[i], value = typeof source == "function" ? source(view) : source; - if (value) - combineAttrs(value, base); - } - return base; - } - - const currentPlatform = browser.mac ? "mac" : browser.windows ? "win" : browser.linux ? "linux" : "key"; - function normalizeKeyName(name, platform) { - const parts = name.split(/-(?!$)/); - let result = parts[parts.length - 1]; - if (result == "Space") - result = " "; - let alt, ctrl, shift, meta; - for (let i = 0; i < parts.length - 1; ++i) { - const mod = parts[i]; - if (/^(cmd|meta|m)$/i.test(mod)) - meta = 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 if (/^mod$/i.test(mod)) { - if (platform == "mac") - meta = true; - else - ctrl = true; - } - else - throw new Error("Unrecognized modifier name: " + mod); - } - if (alt) - result = "Alt-" + result; - if (ctrl) - result = "Ctrl-" + result; - if (meta) - result = "Meta-" + result; - if (shift) - result = "Shift-" + result; - return result; - } - function modifiers(name, event, shift) { - if (event.altKey) - name = "Alt-" + name; - if (event.ctrlKey) - name = "Ctrl-" + name; - if (event.metaKey) - name = "Meta-" + name; - if (shift !== false && event.shiftKey) - name = "Shift-" + name; - return name; - } - const handleKeyEvents = /*@__PURE__*/EditorView.domEventHandlers({ - keydown(event, view) { - return runHandlers(getKeymap(view.state), event, view, "editor"); - } - }); - /** - Facet used for registering keymaps. - - You can add multiple keymaps to an editor. Their priorities - determine their precedence (the ones specified early or with high - priority get checked first). When a handler has returned `true` - for a given key, no further handlers are called. - */ - const keymap = /*@__PURE__*/Facet.define({ enables: handleKeyEvents }); - const Keymaps = /*@__PURE__*/new WeakMap(); - // This is hidden behind an indirection, rather than directly computed - // by the facet, to keep internal types out of the facet's type. - function getKeymap(state) { - let bindings = state.facet(keymap); - let map = Keymaps.get(bindings); - if (!map) - Keymaps.set(bindings, map = buildKeymap(bindings.reduce((a, b) => a.concat(b), []))); - return map; - } - /** - Run the key handlers registered for a given scope. The event - object should be `"keydown"` event. Returns true if any of the - handlers handled it. - */ - function runScopeHandlers(view, event, scope) { - return runHandlers(getKeymap(view.state), event, view, scope); - } - let storedPrefix = null; - const PrefixTimeout = 4000; - function buildKeymap(bindings, platform = currentPlatform) { - let bound = Object.create(null); - let isPrefix = Object.create(null); - let checkPrefix = (name, is) => { - let current = isPrefix[name]; - if (current == null) - isPrefix[name] = is; - else if (current != is) - throw new Error("Key binding " + name + " is used both as a regular binding and as a multi-stroke prefix"); - }; - let add = (scope, key, command, preventDefault) => { - let scopeObj = bound[scope] || (bound[scope] = Object.create(null)); - let parts = key.split(/ (?!$)/).map(k => normalizeKeyName(k, platform)); - for (let i = 1; i < parts.length; i++) { - let prefix = parts.slice(0, i).join(" "); - checkPrefix(prefix, true); - if (!scopeObj[prefix]) - scopeObj[prefix] = { - preventDefault: true, - commands: [(view) => { - let ourObj = storedPrefix = { view, prefix, scope }; - setTimeout(() => { if (storedPrefix == ourObj) - storedPrefix = null; }, PrefixTimeout); - return true; - }] - }; - } - let full = parts.join(" "); - checkPrefix(full, false); - let binding = scopeObj[full] || (scopeObj[full] = { preventDefault: false, commands: [] }); - binding.commands.push(command); - if (preventDefault) - binding.preventDefault = true; - }; - for (let b of bindings) { - let name = b[platform] || b.key; - if (!name) - continue; - for (let scope of b.scope ? b.scope.split(" ") : ["editor"]) { - add(scope, name, b.run, b.preventDefault); - if (b.shift) - add(scope, "Shift-" + name, b.shift, b.preventDefault); - } - } - return bound; - } - function runHandlers(map, event, view, scope) { - let name = keyName(event), isChar = name.length == 1 && name != " "; - let prefix = "", fallthrough = false; - if (storedPrefix && storedPrefix.view == view && storedPrefix.scope == scope) { - prefix = storedPrefix.prefix + " "; - if (fallthrough = modifierCodes.indexOf(event.keyCode) < 0) - storedPrefix = null; - } - let runFor = (binding) => { - if (binding) { - for (let cmd of binding.commands) - if (cmd(view)) - return true; - if (binding.preventDefault) - fallthrough = true; - } - return false; - }; - let scopeObj = map[scope], baseName; - if (scopeObj) { - if (runFor(scopeObj[prefix + modifiers(name, event, !isChar)])) - return true; - if (isChar && (event.shiftKey || event.altKey || event.metaKey) && - (baseName = base[event.keyCode]) && baseName != name) { - if (runFor(scopeObj[prefix + modifiers(baseName, event, true)])) - return true; - } - else if (isChar && event.shiftKey) { - if (runFor(scopeObj[prefix + modifiers(name, event, true)])) - return true; - } - } - return fallthrough; - } - - const CanHidePrimary = !browser.ios; // FIXME test IE - const selectionConfig = /*@__PURE__*/Facet.define({ - combine(configs) { - return combineConfig(configs, { - cursorBlinkRate: 1200, - drawRangeCursor: true - }, { - cursorBlinkRate: (a, b) => Math.min(a, b), - drawRangeCursor: (a, b) => a || b - }); - } - }); - /** - Returns an extension that hides the browser's native selection and - cursor, replacing the selection with a background behind the text - (with the `cm-selectionBackground` class), and the - cursors with elements overlaid over the code (using - `cm-cursor-primary` and `cm-cursor-secondary`). - - This allows the editor to display secondary selection ranges, and - tends to produce a type of selection more in line with that users - expect in a text editor (the native selection styling will often - leave gaps between lines and won't fill the horizontal space after - a line when the selection continues past it). - - It does have a performance cost, in that it requires an extra DOM - layout cycle for many updates (the selection is drawn based on DOM - layout information that's only available after laying out the - content). - */ - function drawSelection(config = {}) { - return [ - selectionConfig.of(config), - drawSelectionPlugin, - hideNativeSelection - ]; - } - class Piece { - constructor(left, top, width, height, className) { - this.left = left; - this.top = top; - this.width = width; - this.height = height; - this.className = className; - } - draw() { - let elt = document.createElement("div"); - elt.className = this.className; - this.adjust(elt); - return elt; - } - adjust(elt) { - elt.style.left = this.left + "px"; - elt.style.top = this.top + "px"; - if (this.width >= 0) - elt.style.width = this.width + "px"; - elt.style.height = this.height + "px"; - } - eq(p) { - return this.left == p.left && this.top == p.top && this.width == p.width && this.height == p.height && - this.className == p.className; - } - } - const drawSelectionPlugin = /*@__PURE__*/ViewPlugin.fromClass(class { - constructor(view) { - this.view = view; - this.rangePieces = []; - this.cursors = []; - this.measureReq = { read: this.readPos.bind(this), write: this.drawSel.bind(this) }; - this.selectionLayer = view.scrollDOM.appendChild(document.createElement("div")); - this.selectionLayer.className = "cm-selectionLayer"; - this.selectionLayer.setAttribute("aria-hidden", "true"); - this.cursorLayer = view.scrollDOM.appendChild(document.createElement("div")); - this.cursorLayer.className = "cm-cursorLayer"; - this.cursorLayer.setAttribute("aria-hidden", "true"); - view.requestMeasure(this.measureReq); - this.setBlinkRate(); - } - setBlinkRate() { - this.cursorLayer.style.animationDuration = this.view.state.facet(selectionConfig).cursorBlinkRate + "ms"; - } - update(update) { - let confChanged = update.startState.facet(selectionConfig) != update.state.facet(selectionConfig); - if (confChanged || update.selectionSet || update.geometryChanged || update.viewportChanged) - this.view.requestMeasure(this.measureReq); - if (update.transactions.some(tr => tr.scrollIntoView)) - this.cursorLayer.style.animationName = this.cursorLayer.style.animationName == "cm-blink" ? "cm-blink2" : "cm-blink"; - if (confChanged) - this.setBlinkRate(); - } - readPos() { - let { state } = this.view, conf = state.facet(selectionConfig); - let rangePieces = state.selection.ranges.map(r => r.empty ? [] : measureRange(this.view, r)).reduce((a, b) => a.concat(b)); - let cursors = []; - for (let r of state.selection.ranges) { - let prim = r == state.selection.main; - if (r.empty ? !prim || CanHidePrimary : conf.drawRangeCursor) { - let piece = measureCursor(this.view, r, prim); - if (piece) - cursors.push(piece); - } - } - return { rangePieces, cursors }; - } - drawSel({ rangePieces, cursors }) { - if (rangePieces.length != this.rangePieces.length || rangePieces.some((p, i) => !p.eq(this.rangePieces[i]))) { - this.selectionLayer.textContent = ""; - for (let p of rangePieces) - this.selectionLayer.appendChild(p.draw()); - this.rangePieces = rangePieces; - } - if (cursors.length != this.cursors.length || cursors.some((c, i) => !c.eq(this.cursors[i]))) { - let oldCursors = this.cursorLayer.children; - if (oldCursors.length !== cursors.length) { - this.cursorLayer.textContent = ""; - for (const c of cursors) - this.cursorLayer.appendChild(c.draw()); - } - else { - cursors.forEach((c, idx) => c.adjust(oldCursors[idx])); - } - this.cursors = cursors; - } - } - destroy() { - this.selectionLayer.remove(); - this.cursorLayer.remove(); - } - }); - const themeSpec = { - ".cm-line": { - "& ::selection": { backgroundColor: "transparent !important" }, - "&::selection": { backgroundColor: "transparent !important" } - } - }; - if (CanHidePrimary) - themeSpec[".cm-line"].caretColor = "transparent !important"; - const hideNativeSelection = /*@__PURE__*/Prec.highest(/*@__PURE__*/EditorView.theme(themeSpec)); - function getBase(view) { - let rect = view.scrollDOM.getBoundingClientRect(); - let left = view.textDirection == Direction.LTR ? rect.left : rect.right - view.scrollDOM.clientWidth; - return { left: left - view.scrollDOM.scrollLeft, top: rect.top - view.scrollDOM.scrollTop }; - } - function wrappedLine(view, pos, inside) { - let range = EditorSelection.cursor(pos); - return { from: Math.max(inside.from, view.moveToLineBoundary(range, false, true).from), - to: Math.min(inside.to, view.moveToLineBoundary(range, true, true).from), - type: BlockType.Text }; - } - function blockAt(view, pos) { - let line = view.lineBlockAt(pos); - if (Array.isArray(line.type)) - for (let l of line.type) { - if (l.to > pos || l.to == pos && (l.to == line.to || l.type == BlockType.Text)) - return l; - } - return line; - } - function measureRange(view, range) { - if (range.to <= view.viewport.from || range.from >= view.viewport.to) - return []; - let from = Math.max(range.from, view.viewport.from), to = Math.min(range.to, view.viewport.to); - let ltr = view.textDirection == Direction.LTR; - let content = view.contentDOM, contentRect = content.getBoundingClientRect(), base = getBase(view); - let lineStyle = window.getComputedStyle(content.firstChild); - let leftSide = contentRect.left + parseInt(lineStyle.paddingLeft) + Math.min(0, parseInt(lineStyle.textIndent)); - let rightSide = contentRect.right - parseInt(lineStyle.paddingRight); - let startBlock = blockAt(view, from), endBlock = blockAt(view, to); - let visualStart = startBlock.type == BlockType.Text ? startBlock : null; - let visualEnd = endBlock.type == BlockType.Text ? endBlock : null; - if (view.lineWrapping) { - if (visualStart) - visualStart = wrappedLine(view, from, visualStart); - if (visualEnd) - visualEnd = wrappedLine(view, to, visualEnd); - } - if (visualStart && visualEnd && visualStart.from == visualEnd.from) { - return pieces(drawForLine(range.from, range.to, visualStart)); - } - else { - let top = visualStart ? drawForLine(range.from, null, visualStart) : drawForWidget(startBlock, false); - let bottom = visualEnd ? drawForLine(null, range.to, visualEnd) : drawForWidget(endBlock, true); - let between = []; - if ((visualStart || startBlock).to < (visualEnd || endBlock).from - 1) - between.push(piece(leftSide, top.bottom, rightSide, bottom.top)); - else if (top.bottom < bottom.top && view.elementAtHeight((top.bottom + bottom.top) / 2).type == BlockType.Text) - top.bottom = bottom.top = (top.bottom + bottom.top) / 2; - return pieces(top).concat(between).concat(pieces(bottom)); - } - function piece(left, top, right, bottom) { - return new Piece(left - base.left, top - base.top - 0.01 /* Epsilon */, right - left, bottom - top + 0.01 /* Epsilon */, "cm-selectionBackground"); - } - function pieces({ top, bottom, horizontal }) { - let pieces = []; - for (let i = 0; i < horizontal.length; i += 2) - pieces.push(piece(horizontal[i], top, horizontal[i + 1], bottom)); - return pieces; - } - // Gets passed from/to in line-local positions - function drawForLine(from, to, line) { - let top = 1e9, bottom = -1e9, horizontal = []; - function addSpan(from, fromOpen, to, toOpen, dir) { - // Passing 2/-2 is a kludge to force the view to return - // coordinates on the proper side of block widgets, since - // normalizing the side there, though appropriate for most - // coordsAtPos queries, would break selection drawing. - let fromCoords = view.coordsAtPos(from, (from == line.to ? -2 : 2)); - let toCoords = view.coordsAtPos(to, (to == line.from ? 2 : -2)); - top = Math.min(fromCoords.top, toCoords.top, top); - bottom = Math.max(fromCoords.bottom, toCoords.bottom, bottom); - if (dir == Direction.LTR) - horizontal.push(ltr && fromOpen ? leftSide : fromCoords.left, ltr && toOpen ? rightSide : toCoords.right); - else - horizontal.push(!ltr && toOpen ? leftSide : toCoords.left, !ltr && fromOpen ? rightSide : fromCoords.right); - } - let start = from !== null && from !== void 0 ? from : line.from, end = to !== null && to !== void 0 ? to : line.to; - // Split the range by visible range and document line - for (let r of view.visibleRanges) - if (r.to > start && r.from < end) { - for (let pos = Math.max(r.from, start), endPos = Math.min(r.to, end);;) { - let docLine = view.state.doc.lineAt(pos); - for (let span of view.bidiSpans(docLine)) { - let spanFrom = span.from + docLine.from, spanTo = span.to + docLine.from; - if (spanFrom >= endPos) - break; - if (spanTo > pos) - addSpan(Math.max(spanFrom, pos), from == null && spanFrom <= start, Math.min(spanTo, endPos), to == null && spanTo >= end, span.dir); - } - pos = docLine.to + 1; - if (pos >= endPos) - break; - } - } - if (horizontal.length == 0) - addSpan(start, from == null, end, to == null, view.textDirection); - return { top, bottom, horizontal }; - } - function drawForWidget(block, top) { - let y = contentRect.top + (top ? block.top : block.bottom); - return { top: y, bottom: y, horizontal: [] }; - } - } - function measureCursor(view, cursor, primary) { - let pos = view.coordsAtPos(cursor.head, cursor.assoc || 1); - if (!pos) - return null; - let base = getBase(view); - return new Piece(pos.left - base.left, pos.top - base.top, -1, pos.bottom - pos.top, primary ? "cm-cursor cm-cursor-primary" : "cm-cursor cm-cursor-secondary"); - } - - const setDropCursorPos = /*@__PURE__*/StateEffect.define({ - map(pos, mapping) { return pos == null ? null : mapping.mapPos(pos); } - }); - const dropCursorPos = /*@__PURE__*/StateField.define({ - create() { return null; }, - update(pos, tr) { - if (pos != null) - pos = tr.changes.mapPos(pos); - return tr.effects.reduce((pos, e) => e.is(setDropCursorPos) ? e.value : pos, pos); - } - }); - const drawDropCursor = /*@__PURE__*/ViewPlugin.fromClass(class { - constructor(view) { - this.view = view; - this.cursor = null; - this.measureReq = { read: this.readPos.bind(this), write: this.drawCursor.bind(this) }; - } - update(update) { - var _a; - let cursorPos = update.state.field(dropCursorPos); - if (cursorPos == null) { - if (this.cursor != null) { - (_a = this.cursor) === null || _a === void 0 ? void 0 : _a.remove(); - this.cursor = null; - } - } - else { - if (!this.cursor) { - this.cursor = this.view.scrollDOM.appendChild(document.createElement("div")); - this.cursor.className = "cm-dropCursor"; - } - if (update.startState.field(dropCursorPos) != cursorPos || update.docChanged || update.geometryChanged) - this.view.requestMeasure(this.measureReq); - } - } - readPos() { - let pos = this.view.state.field(dropCursorPos); - let rect = pos != null && this.view.coordsAtPos(pos); - if (!rect) - return null; - let outer = this.view.scrollDOM.getBoundingClientRect(); - return { - left: rect.left - outer.left + this.view.scrollDOM.scrollLeft, - top: rect.top - outer.top + this.view.scrollDOM.scrollTop, - height: rect.bottom - rect.top - }; - } - drawCursor(pos) { - if (this.cursor) { - if (pos) { - this.cursor.style.left = pos.left + "px"; - this.cursor.style.top = pos.top + "px"; - this.cursor.style.height = pos.height + "px"; - } - else { - this.cursor.style.left = "-100000px"; - } - } - } - destroy() { - if (this.cursor) - this.cursor.remove(); - } - setDropPos(pos) { - if (this.view.state.field(dropCursorPos) != pos) - this.view.dispatch({ effects: setDropCursorPos.of(pos) }); - } - }, { - eventHandlers: { - dragover(event) { - this.setDropPos(this.view.posAtCoords({ x: event.clientX, y: event.clientY })); - }, - dragleave(event) { - if (event.target == this.view.contentDOM || !this.view.contentDOM.contains(event.relatedTarget)) - this.setDropPos(null); - }, - dragend() { - this.setDropPos(null); - }, - drop() { - this.setDropPos(null); - } - } - }); - /** - Draws a cursor at the current drop position when something is - dragged over the editor. - */ - function dropCursor() { - return [dropCursorPos, drawDropCursor]; - } - - function iterMatches(doc, re, from, to, f) { - re.lastIndex = 0; - for (let cursor = doc.iterRange(from, to), pos = from, m; !cursor.next().done; pos += cursor.value.length) { - if (!cursor.lineBreak) - while (m = re.exec(cursor.value)) - f(pos + m.index, pos + m.index + m[0].length, m); - } - } - function matchRanges(view, maxLength) { - let visible = view.visibleRanges; - if (visible.length == 1 && visible[0].from == view.viewport.from && - visible[0].to == view.viewport.to) - return visible; - let result = []; - for (let { from, to } of visible) { - from = Math.max(view.state.doc.lineAt(from).from, from - maxLength); - to = Math.min(view.state.doc.lineAt(to).to, to + maxLength); - if (result.length && result[result.length - 1].to >= from) - result[result.length - 1].to = to; - else - result.push({ from, to }); - } - return result; - } - /** - Helper class used to make it easier to maintain decorations on - visible code that matches a given regular expression. To be used - in a [view plugin](https://codemirror.net/6/docs/ref/#view.ViewPlugin). Instances of this object - represent a matching configuration. - */ - class MatchDecorator { - /** - Create a decorator. - */ - constructor(config) { - let { regexp, decoration, boundary, maxLength = 1000 } = config; - if (!regexp.global) - throw new RangeError("The regular expression given to MatchDecorator should have its 'g' flag set"); - this.regexp = regexp; - this.getDeco = typeof decoration == "function" ? decoration : () => decoration; - this.boundary = boundary; - this.maxLength = maxLength; - } - /** - Compute the full set of decorations for matches in the given - view's viewport. You'll want to call this when initializing your - plugin. - */ - createDeco(view) { - let build = new RangeSetBuilder(); - for (let { from, to } of matchRanges(view, this.maxLength)) - iterMatches(view.state.doc, this.regexp, from, to, (a, b, m) => build.add(a, b, this.getDeco(m, view, a))); - return build.finish(); - } - /** - Update a set of decorations for a view update. `deco` _must_ be - the set of decorations produced by _this_ `MatchDecorator` for - the view state before the update. - */ - updateDeco(update, deco) { - let changeFrom = 1e9, changeTo = -1; - if (update.docChanged) - update.changes.iterChanges((_f, _t, from, to) => { - if (to > update.view.viewport.from && from < update.view.viewport.to) { - changeFrom = Math.min(from, changeFrom); - changeTo = Math.max(to, changeTo); - } - }); - if (update.viewportChanged || changeTo - changeFrom > 1000) - return this.createDeco(update.view); - if (changeTo > -1) - return this.updateRange(update.view, deco.map(update.changes), changeFrom, changeTo); - return deco; - } - updateRange(view, deco, updateFrom, updateTo) { - for (let r of view.visibleRanges) { - let from = Math.max(r.from, updateFrom), to = Math.min(r.to, updateTo); - if (to > from) { - let fromLine = view.state.doc.lineAt(from), toLine = fromLine.to < to ? view.state.doc.lineAt(to) : fromLine; - let start = Math.max(r.from, fromLine.from), end = Math.min(r.to, toLine.to); - if (this.boundary) { - for (; from > fromLine.from; from--) - if (this.boundary.test(fromLine.text[from - 1 - fromLine.from])) { - start = from; - break; - } - for (; to < toLine.to; to++) - if (this.boundary.test(toLine.text[to - toLine.from])) { - end = to; - break; - } - } - let ranges = [], m; - if (fromLine == toLine) { - this.regexp.lastIndex = start - fromLine.from; - while ((m = this.regexp.exec(fromLine.text)) && m.index < end - fromLine.from) { - let pos = m.index + fromLine.from; - ranges.push(this.getDeco(m, view, pos).range(pos, pos + m[0].length)); - } - } - else { - iterMatches(view.state.doc, this.regexp, start, end, (from, to, m) => ranges.push(this.getDeco(m, view, from).range(from, to))); - } - deco = deco.update({ filterFrom: start, filterTo: end, filter: (from, to) => from < start || to > end, add: ranges }); - } - } - return deco; - } - } - - const UnicodeRegexpSupport = /x/.unicode != null ? "gu" : "g"; - const Specials = /*@__PURE__*/new RegExp("[\u0000-\u0008\u000a-\u001f\u007f-\u009f\u00ad\u061c\u200b\u200e\u200f\u2028\u2029\u202d\u202e\ufeff\ufff9-\ufffc]", UnicodeRegexpSupport); - const Names = { - 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", - 8233: "paragraph separator", - 65279: "zero width no-break space", - 65532: "object replacement" - }; - let _supportsTabSize = null; - function supportsTabSize() { - var _a; - if (_supportsTabSize == null && typeof document != "undefined" && document.body) { - let styles = document.body.style; - _supportsTabSize = ((_a = styles.tabSize) !== null && _a !== void 0 ? _a : styles.MozTabSize) != null; - } - return _supportsTabSize || false; - } - const specialCharConfig = /*@__PURE__*/Facet.define({ - combine(configs) { - let config = combineConfig(configs, { - render: null, - specialChars: Specials, - addSpecialChars: null - }); - if (config.replaceTabs = !supportsTabSize()) - config.specialChars = new RegExp("\t|" + config.specialChars.source, UnicodeRegexpSupport); - if (config.addSpecialChars) - config.specialChars = new RegExp(config.specialChars.source + "|" + config.addSpecialChars.source, UnicodeRegexpSupport); - return config; - } - }); - /** - Returns an extension that installs highlighting of special - characters. - */ - function highlightSpecialChars( - /** - Configuration options. - */ - config = {}) { - return [specialCharConfig.of(config), specialCharPlugin()]; - } - let _plugin = null; - function specialCharPlugin() { - return _plugin || (_plugin = ViewPlugin.fromClass(class { - constructor(view) { - this.view = view; - this.decorations = Decoration.none; - this.decorationCache = Object.create(null); - this.decorator = this.makeDecorator(view.state.facet(specialCharConfig)); - this.decorations = this.decorator.createDeco(view); - } - makeDecorator(conf) { - return new MatchDecorator({ - regexp: conf.specialChars, - decoration: (m, view, pos) => { - let { doc } = view.state; - let code = codePointAt(m[0], 0); - if (code == 9) { - let line = doc.lineAt(pos); - let size = view.state.tabSize, col = countColumn(line.text, size, pos - line.from); - return Decoration.replace({ widget: new TabWidget((size - (col % size)) * this.view.defaultCharacterWidth) }); - } - return this.decorationCache[code] || - (this.decorationCache[code] = Decoration.replace({ widget: new SpecialCharWidget(conf, code) })); - }, - boundary: conf.replaceTabs ? undefined : /[^]/ - }); - } - update(update) { - let conf = update.state.facet(specialCharConfig); - if (update.startState.facet(specialCharConfig) != conf) { - this.decorator = this.makeDecorator(conf); - this.decorations = this.decorator.createDeco(update.view); - } - else { - this.decorations = this.decorator.updateDeco(update, this.decorations); - } - } - }, { - decorations: v => v.decorations - })); - } - const DefaultPlaceholder = "\u2022"; - // Assigns placeholder characters from the Control Pictures block to - // ASCII control characters - function placeholder$1(code) { - if (code >= 32) - return DefaultPlaceholder; - if (code == 10) - return "\u2424"; - return String.fromCharCode(9216 + code); - } - class SpecialCharWidget extends WidgetType { - constructor(options, code) { - super(); - this.options = options; - this.code = code; - } - eq(other) { return other.code == this.code; } - toDOM(view) { - let ph = placeholder$1(this.code); - let desc = view.state.phrase("Control character") + " " + (Names[this.code] || "0x" + this.code.toString(16)); - let custom = this.options.render && this.options.render(this.code, desc, ph); - if (custom) - return custom; - let span = document.createElement("span"); - span.textContent = ph; - span.title = desc; - span.setAttribute("aria-label", desc); - span.className = "cm-specialChar"; - return span; - } - ignoreEvent() { return false; } - } - class TabWidget extends WidgetType { - constructor(width) { - super(); - this.width = width; - } - eq(other) { return other.width == this.width; } - toDOM() { - let span = document.createElement("span"); - span.textContent = "\t"; - span.className = "cm-tab"; - span.style.width = this.width + "px"; - return span; - } - ignoreEvent() { return false; } - } - - /** - Mark lines that have a cursor on them with the `"cm-activeLine"` - DOM class. - */ - function highlightActiveLine() { - return activeLineHighlighter; - } - const lineDeco = /*@__PURE__*/Decoration.line({ class: "cm-activeLine" }); - const activeLineHighlighter = /*@__PURE__*/ViewPlugin.fromClass(class { - constructor(view) { - this.decorations = this.getDeco(view); - } - update(update) { - if (update.docChanged || update.selectionSet) - this.decorations = this.getDeco(update.view); - } - getDeco(view) { - let lastLineStart = -1, deco = []; - for (let r of view.state.selection.ranges) { - if (!r.empty) - return Decoration.none; - let line = view.lineBlockAt(r.head); - if (line.from > lastLineStart) { - deco.push(lineDeco.range(line.from)); - lastLineStart = line.from; - } - } - return Decoration.set(deco); - } - }, { - decorations: v => v.decorations - }); - - const fromHistory = /*@__PURE__*/Annotation.define(); - /** - Transaction annotation that will prevent that transaction from - being combined with other transactions in the undo history. Given - `"before"`, it'll prevent merging with previous transactions. With - `"after"`, subsequent transactions won't be combined with this - one. With `"full"`, the transaction is isolated on both sides. - */ - const isolateHistory = /*@__PURE__*/Annotation.define(); - /** - This facet provides a way to register functions that, given a - transaction, provide a set of effects that the history should - store when inverting the transaction. This can be used to - integrate some kinds of effects in the history, so that they can - be undone (and redone again). - */ - const invertedEffects = /*@__PURE__*/Facet.define(); - const historyConfig = /*@__PURE__*/Facet.define({ - combine(configs) { - return combineConfig(configs, { - minDepth: 100, - newGroupDelay: 500 - }, { minDepth: Math.max, newGroupDelay: Math.min }); - } - }); - function changeEnd(changes) { - let end = 0; - changes.iterChangedRanges((_, to) => end = to); - return end; - } - const historyField_ = /*@__PURE__*/StateField.define({ - create() { - return HistoryState.empty; - }, - update(state, tr) { - let config = tr.state.facet(historyConfig); - let fromHist = tr.annotation(fromHistory); - if (fromHist) { - let selection = tr.docChanged ? EditorSelection.single(changeEnd(tr.changes)) : undefined; - let item = HistEvent.fromTransaction(tr, selection), from = fromHist.side; - let other = from == 0 /* Done */ ? state.undone : state.done; - if (item) - other = updateBranch(other, other.length, config.minDepth, item); - else - other = addSelection(other, tr.startState.selection); - return new HistoryState(from == 0 /* Done */ ? fromHist.rest : other, from == 0 /* Done */ ? other : fromHist.rest); - } - let isolate = tr.annotation(isolateHistory); - if (isolate == "full" || isolate == "before") - state = state.isolate(); - if (tr.annotation(Transaction.addToHistory) === false) - return !tr.changes.empty ? state.addMapping(tr.changes.desc) : state; - let event = HistEvent.fromTransaction(tr); - let time = tr.annotation(Transaction.time), userEvent = tr.annotation(Transaction.userEvent); - if (event) - state = state.addChanges(event, time, userEvent, config.newGroupDelay, config.minDepth); - else if (tr.selection) - state = state.addSelection(tr.startState.selection, time, userEvent, config.newGroupDelay); - if (isolate == "full" || isolate == "after") - state = state.isolate(); - return state; - }, - toJSON(value) { - return { done: value.done.map(e => e.toJSON()), undone: value.undone.map(e => e.toJSON()) }; - }, - fromJSON(json) { - return new HistoryState(json.done.map(HistEvent.fromJSON), json.undone.map(HistEvent.fromJSON)); - } - }); - /** - Create a history extension with the given configuration. - */ - function history(config = {}) { - return [ - historyField_, - historyConfig.of(config), - EditorView.domEventHandlers({ - beforeinput(e, view) { - let command = e.inputType == "historyUndo" ? undo : e.inputType == "historyRedo" ? redo : null; - if (!command) - return false; - e.preventDefault(); - return command(view); - } - }) - ]; - } - function cmd(side, selection) { - return function ({ state, dispatch }) { - if (!selection && state.readOnly) - return false; - let historyState = state.field(historyField_, false); - if (!historyState) - return false; - let tr = historyState.pop(side, state, selection); - if (!tr) - return false; - dispatch(tr); - return true; - }; - } - /** - Undo a single group of history events. Returns false if no group - was available. - */ - const undo = /*@__PURE__*/cmd(0 /* Done */, false); - /** - Redo a group of history events. Returns false if no group was - available. - */ - const redo = /*@__PURE__*/cmd(1 /* Undone */, false); - /** - Undo a selection change. - */ - const undoSelection = /*@__PURE__*/cmd(0 /* Done */, true); - /** - Redo a selection change. - */ - const redoSelection = /*@__PURE__*/cmd(1 /* Undone */, true); - // History events store groups of changes or effects that need to be - // undone/redone together. - class HistEvent { - constructor( - // The changes in this event. Normal events hold at least one - // change or effect. But it may be necessary to store selection - // events before the first change, in which case a special type of - // instance is created which doesn't hold any changes, with - // changes == startSelection == undefined - changes, - // The effects associated with this event - effects, mapped, - // The selection before this event - startSelection, - // Stores selection changes after this event, to be used for - // selection undo/redo. - selectionsAfter) { - this.changes = changes; - this.effects = effects; - this.mapped = mapped; - this.startSelection = startSelection; - this.selectionsAfter = selectionsAfter; - } - setSelAfter(after) { - return new HistEvent(this.changes, this.effects, this.mapped, this.startSelection, after); - } - toJSON() { - var _a, _b, _c; - return { - changes: (_a = this.changes) === null || _a === void 0 ? void 0 : _a.toJSON(), - mapped: (_b = this.mapped) === null || _b === void 0 ? void 0 : _b.toJSON(), - startSelection: (_c = this.startSelection) === null || _c === void 0 ? void 0 : _c.toJSON(), - selectionsAfter: this.selectionsAfter.map(s => s.toJSON()) - }; - } - static fromJSON(json) { - return new HistEvent(json.changes && ChangeSet.fromJSON(json.changes), [], json.mapped && ChangeDesc.fromJSON(json.mapped), json.startSelection && EditorSelection.fromJSON(json.startSelection), json.selectionsAfter.map(EditorSelection.fromJSON)); - } - // This does not check `addToHistory` and such, it assumes the - // transaction needs to be converted to an item. Returns null when - // there are no changes or effects in the transaction. - static fromTransaction(tr, selection) { - let effects = none$1; - for (let invert of tr.startState.facet(invertedEffects)) { - let result = invert(tr); - if (result.length) - effects = effects.concat(result); - } - if (!effects.length && tr.changes.empty) - return null; - return new HistEvent(tr.changes.invert(tr.startState.doc), effects, undefined, selection || tr.startState.selection, none$1); - } - static selection(selections) { - return new HistEvent(undefined, none$1, undefined, undefined, selections); - } - } - function updateBranch(branch, to, maxLen, newEvent) { - let start = to + 1 > maxLen + 20 ? to - maxLen - 1 : 0; - let newBranch = branch.slice(start, to); - newBranch.push(newEvent); - return newBranch; - } - function isAdjacent(a, b) { - let ranges = [], isAdjacent = false; - a.iterChangedRanges((f, t) => ranges.push(f, t)); - b.iterChangedRanges((_f, _t, f, t) => { - for (let i = 0; i < ranges.length;) { - let from = ranges[i++], to = ranges[i++]; - if (t >= from && f <= to) - isAdjacent = true; - } - }); - return isAdjacent; - } - function eqSelectionShape(a, b) { - return a.ranges.length == b.ranges.length && - a.ranges.filter((r, i) => r.empty != b.ranges[i].empty).length === 0; - } - function conc(a, b) { - return !a.length ? b : !b.length ? a : a.concat(b); - } - const none$1 = []; - const MaxSelectionsPerEvent = 200; - function addSelection(branch, selection) { - if (!branch.length) { - return [HistEvent.selection([selection])]; - } - else { - let lastEvent = branch[branch.length - 1]; - let sels = lastEvent.selectionsAfter.slice(Math.max(0, lastEvent.selectionsAfter.length - MaxSelectionsPerEvent)); - if (sels.length && sels[sels.length - 1].eq(selection)) - return branch; - sels.push(selection); - return updateBranch(branch, branch.length - 1, 1e9, lastEvent.setSelAfter(sels)); - } - } - // Assumes the top item has one or more selectionAfter values - function popSelection(branch) { - let last = branch[branch.length - 1]; - let newBranch = branch.slice(); - newBranch[branch.length - 1] = last.setSelAfter(last.selectionsAfter.slice(0, last.selectionsAfter.length - 1)); - return newBranch; - } - // Add a mapping to the top event in the given branch. If this maps - // away all the changes and effects in that item, drop it and - // propagate the mapping to the next item. - function addMappingToBranch(branch, mapping) { - if (!branch.length) - return branch; - let length = branch.length, selections = none$1; - while (length) { - let event = mapEvent(branch[length - 1], mapping, selections); - if (event.changes && !event.changes.empty || event.effects.length) { // Event survived mapping - let result = branch.slice(0, length); - result[length - 1] = event; - return result; - } - else { // Drop this event, since there's no changes or effects left - mapping = event.mapped; - length--; - selections = event.selectionsAfter; - } - } - return selections.length ? [HistEvent.selection(selections)] : none$1; - } - function mapEvent(event, mapping, extraSelections) { - let selections = conc(event.selectionsAfter.length ? event.selectionsAfter.map(s => s.map(mapping)) : none$1, extraSelections); - // Change-less events don't store mappings (they are always the last event in a branch) - if (!event.changes) - return HistEvent.selection(selections); - let mappedChanges = event.changes.map(mapping), before = mapping.mapDesc(event.changes, true); - let fullMapping = event.mapped ? event.mapped.composeDesc(before) : before; - return new HistEvent(mappedChanges, StateEffect.mapEffects(event.effects, mapping), fullMapping, event.startSelection.map(before), selections); - } - const joinableUserEvent = /^(input\.type|delete)($|\.)/; - class HistoryState { - constructor(done, undone, prevTime = 0, prevUserEvent = undefined) { - this.done = done; - this.undone = undone; - this.prevTime = prevTime; - this.prevUserEvent = prevUserEvent; - } - isolate() { - return this.prevTime ? new HistoryState(this.done, this.undone) : this; - } - addChanges(event, time, userEvent, newGroupDelay, maxLen) { - let done = this.done, lastEvent = done[done.length - 1]; - if (lastEvent && lastEvent.changes && !lastEvent.changes.empty && event.changes && - (!userEvent || joinableUserEvent.test(userEvent)) && - ((!lastEvent.selectionsAfter.length && - time - this.prevTime < newGroupDelay && - isAdjacent(lastEvent.changes, event.changes)) || - // For compose (but not compose.start) events, always join with previous event - userEvent == "input.type.compose")) { - done = updateBranch(done, done.length - 1, maxLen, new HistEvent(event.changes.compose(lastEvent.changes), conc(event.effects, lastEvent.effects), lastEvent.mapped, lastEvent.startSelection, none$1)); - } - else { - done = updateBranch(done, done.length, maxLen, event); - } - return new HistoryState(done, none$1, time, userEvent); - } - addSelection(selection, time, userEvent, newGroupDelay) { - let last = this.done.length ? this.done[this.done.length - 1].selectionsAfter : none$1; - if (last.length > 0 && - time - this.prevTime < newGroupDelay && - userEvent == this.prevUserEvent && userEvent && /^select($|\.)/.test(userEvent) && - eqSelectionShape(last[last.length - 1], selection)) - return this; - return new HistoryState(addSelection(this.done, selection), this.undone, time, userEvent); - } - addMapping(mapping) { - return new HistoryState(addMappingToBranch(this.done, mapping), addMappingToBranch(this.undone, mapping), this.prevTime, this.prevUserEvent); - } - pop(side, state, selection) { - let branch = side == 0 /* Done */ ? this.done : this.undone; - if (branch.length == 0) - return null; - let event = branch[branch.length - 1]; - if (selection && event.selectionsAfter.length) { - return state.update({ - selection: event.selectionsAfter[event.selectionsAfter.length - 1], - annotations: fromHistory.of({ side, rest: popSelection(branch) }), - userEvent: side == 0 /* Done */ ? "select.undo" : "select.redo", - scrollIntoView: true - }); - } - else if (!event.changes) { - return null; - } - else { - let rest = branch.length == 1 ? none$1 : branch.slice(0, branch.length - 1); - if (event.mapped) - rest = addMappingToBranch(rest, event.mapped); - return state.update({ - changes: event.changes, - selection: event.startSelection, - effects: event.effects, - annotations: fromHistory.of({ side, rest }), - filter: false, - userEvent: side == 0 /* Done */ ? "undo" : "redo", - scrollIntoView: true - }); - } - } - } - HistoryState.empty = /*@__PURE__*/new HistoryState(none$1, none$1); - /** - Default key bindings for the undo history. - - - Mod-z: [`undo`](https://codemirror.net/6/docs/ref/#history.undo). - - Mod-y (Mod-Shift-z on macOS): [`redo`](https://codemirror.net/6/docs/ref/#history.redo). - - Mod-u: [`undoSelection`](https://codemirror.net/6/docs/ref/#history.undoSelection). - - Alt-u (Mod-Shift-u on macOS): [`redoSelection`](https://codemirror.net/6/docs/ref/#history.redoSelection). - */ - const historyKeymap = [ - { key: "Mod-z", run: undo, preventDefault: true }, - { key: "Mod-y", mac: "Mod-Shift-z", run: redo, preventDefault: true }, - { key: "Mod-u", run: undoSelection, preventDefault: true }, - { key: "Alt-u", mac: "Mod-Shift-u", run: redoSelection, preventDefault: true } - ]; - - // FIXME profile adding a per-Tree TreeNode cache, validating it by - // parent pointer - /// The default maximum length of a `TreeBuffer` node (1024). - const DefaultBufferLength = 1024; - let nextPropID = 0; - class Range { - constructor(from, to) { - this.from = from; - this.to = to; - } - } - /// Each [node type](#common.NodeType) or [individual tree](#common.Tree) - /// can have metadata associated with it in props. Instances of this - /// class represent prop names. - class NodeProp { - /// Create a new node prop type. - constructor(config = {}) { - this.id = nextPropID++; - this.perNode = !!config.perNode; - this.deserialize = config.deserialize || (() => { - throw new Error("This node type doesn't define a deserialize function"); - }); - } - /// This is meant to be used with - /// [`NodeSet.extend`](#common.NodeSet.extend) or - /// [`LRParser.configure`](#lr.ParserConfig.props) to compute - /// prop values for each node type in the set. Takes a [match - /// object](#common.NodeType^match) or function that returns undefined - /// if the node type doesn't get this prop, and the prop's value if - /// it does. - add(match) { - if (this.perNode) - throw new RangeError("Can't add per-node props to node types"); - if (typeof match != "function") - match = NodeType.match(match); - return (type) => { - let result = match(type); - return result === undefined ? null : [this, result]; - }; - } - } - /// Prop that is used to describe matching delimiters. For opening - /// delimiters, this holds an array of node names (written as a - /// space-separated string when declaring this prop in a grammar) - /// for the node types of closing delimiters that match it. - NodeProp.closedBy = new NodeProp({ deserialize: str => str.split(" ") }); - /// The inverse of [`closedBy`](#common.NodeProp^closedBy). This is - /// attached to closing delimiters, holding an array of node names - /// of types of matching opening delimiters. - NodeProp.openedBy = new NodeProp({ deserialize: str => str.split(" ") }); - /// Used to assign node types to groups (for example, all node - /// types that represent an expression could be tagged with an - /// `"Expression"` group). - NodeProp.group = new NodeProp({ deserialize: str => str.split(" ") }); - /// The hash of the [context](#lr.ContextTracker.constructor) - /// that the node was parsed in, if any. Used to limit reuse of - /// contextual nodes. - NodeProp.contextHash = new NodeProp({ perNode: true }); - /// The distance beyond the end of the node that the tokenizer - /// looked ahead for any of the tokens inside the node. (The LR - /// parser only stores this when it is larger than 25, for - /// efficiency reasons.) - NodeProp.lookAhead = new NodeProp({ perNode: true }); - /// This per-node prop is used to replace a given node, or part of a - /// node, with another tree. This is useful to include trees from - /// different languages. - NodeProp.mounted = new NodeProp({ perNode: true }); - const noProps = Object.create(null); - /// Each node in a syntax tree has a node type associated with it. - class NodeType { - /// @internal - constructor( - /// The name of the node type. Not necessarily unique, but if the - /// grammar was written properly, different node types with the - /// same name within a node set should play the same semantic - /// role. - name, - /// @internal - props, - /// The id of this node in its set. Corresponds to the term ids - /// used in the parser. - id, - /// @internal - flags = 0) { - this.name = name; - this.props = props; - this.id = id; - this.flags = flags; - } - static define(spec) { - let props = spec.props && spec.props.length ? Object.create(null) : noProps; - let flags = (spec.top ? 1 /* Top */ : 0) | (spec.skipped ? 2 /* Skipped */ : 0) | - (spec.error ? 4 /* Error */ : 0) | (spec.name == null ? 8 /* Anonymous */ : 0); - let type = new NodeType(spec.name || "", props, spec.id, flags); - if (spec.props) - for (let src of spec.props) { - if (!Array.isArray(src)) - src = src(type); - if (src) { - if (src[0].perNode) - throw new RangeError("Can't store a per-node prop on a node type"); - props[src[0].id] = src[1]; - } - } - return type; - } - /// Retrieves a node prop for this type. Will return `undefined` if - /// the prop isn't present on this node. - prop(prop) { return this.props[prop.id]; } - /// True when this is the top node of a grammar. - get isTop() { return (this.flags & 1 /* Top */) > 0; } - /// True when this node is produced by a skip rule. - get isSkipped() { return (this.flags & 2 /* Skipped */) > 0; } - /// Indicates whether this is an error node. - get isError() { return (this.flags & 4 /* Error */) > 0; } - /// When true, this node type doesn't correspond to a user-declared - /// named node, for example because it is used to cache repetition. - get isAnonymous() { return (this.flags & 8 /* Anonymous */) > 0; } - /// Returns true when this node's name or one of its - /// [groups](#common.NodeProp^group) matches the given string. - is(name) { - if (typeof name == 'string') { - if (this.name == name) - return true; - let group = this.prop(NodeProp.group); - return group ? group.indexOf(name) > -1 : false; - } - return this.id == name; - } - /// Create a function from node types to arbitrary values by - /// specifying an object whose property names are node or - /// [group](#common.NodeProp^group) names. Often useful with - /// [`NodeProp.add`](#common.NodeProp.add). You can put multiple - /// names, separated by spaces, in a single property name to map - /// multiple node names to a single value. - static match(map) { - let direct = Object.create(null); - for (let prop in map) - for (let name of prop.split(" ")) - direct[name] = map[prop]; - return (node) => { - for (let groups = node.prop(NodeProp.group), i = -1; i < (groups ? groups.length : 0); i++) { - let found = direct[i < 0 ? node.name : groups[i]]; - if (found) - return found; - } - }; - } - } - /// An empty dummy node type to use when no actual type is available. - NodeType.none = new NodeType("", Object.create(null), 0, 8 /* Anonymous */); - /// A node set holds a collection of node types. It is used to - /// compactly represent trees by storing their type ids, rather than a - /// full pointer to the type object, in a numeric array. Each parser - /// [has](#lr.LRParser.nodeSet) a node set, and [tree - /// buffers](#common.TreeBuffer) can only store collections of nodes - /// from the same set. A set can have a maximum of 2**16 (65536) node - /// types in it, so that the ids fit into 16-bit typed array slots. - class NodeSet { - /// Create a set with the given types. The `id` property of each - /// type should correspond to its position within the array. - constructor( - /// The node types in this set, by id. - types) { - this.types = types; - for (let i = 0; i < types.length; i++) - if (types[i].id != i) - throw new RangeError("Node type ids should correspond to array positions when creating a node set"); - } - /// Create a copy of this set with some node properties added. The - /// arguments to this method should be created with - /// [`NodeProp.add`](#common.NodeProp.add). - extend(...props) { - let newTypes = []; - for (let type of this.types) { - let newProps = null; - for (let source of props) { - let add = source(type); - if (add) { - if (!newProps) - newProps = Object.assign({}, type.props); - newProps[add[0].id] = add[1]; - } - } - newTypes.push(newProps ? new NodeType(type.name, newProps, type.id, type.flags) : type); - } - return new NodeSet(newTypes); - } - } - const CachedNode = new WeakMap(), CachedInnerNode = new WeakMap(); - /// A piece of syntax tree. There are two ways to approach these - /// trees: the way they are actually stored in memory, and the - /// convenient way. - /// - /// Syntax trees are stored as a tree of `Tree` and `TreeBuffer` - /// objects. By packing detail information into `TreeBuffer` leaf - /// nodes, the representation is made a lot more memory-efficient. - /// - /// However, when you want to actually work with tree nodes, this - /// representation is very awkward, so most client code will want to - /// use the [`TreeCursor`](#common.TreeCursor) or - /// [`SyntaxNode`](#common.SyntaxNode) interface instead, which provides - /// a view on some part of this data structure, and can be used to - /// move around to adjacent nodes. - class Tree { - /// Construct a new tree. See also [`Tree.build`](#common.Tree^build). - constructor( - /// The type of the top node. - type, - /// This node's child nodes. - children, - /// The positions (offsets relative to the start of this tree) of - /// the children. - positions, - /// The total length of this tree - length, - /// Per-node [node props](#common.NodeProp) to associate with this node. - props) { - this.type = type; - this.children = children; - this.positions = positions; - this.length = length; - /// @internal - this.props = null; - if (props && props.length) { - this.props = Object.create(null); - for (let [prop, value] of props) - this.props[typeof prop == "number" ? prop : prop.id] = value; - } - } - /// @internal - toString() { - let mounted = this.prop(NodeProp.mounted); - if (mounted && !mounted.overlay) - return mounted.tree.toString(); - let children = ""; - for (let ch of this.children) { - let str = ch.toString(); - if (str) { - if (children) - children += ","; - children += str; - } - } - return !this.type.name ? children : - (/\W/.test(this.type.name) && !this.type.isError ? JSON.stringify(this.type.name) : this.type.name) + - (children.length ? "(" + children + ")" : ""); - } - /// Get a [tree cursor](#common.TreeCursor) rooted at this tree. When - /// `pos` is given, the cursor is [moved](#common.TreeCursor.moveTo) - /// to the given position and side. - cursor(pos, side = 0) { - let scope = (pos != null && CachedNode.get(this)) || this.topNode; - let cursor = new TreeCursor(scope); - if (pos != null) { - cursor.moveTo(pos, side); - CachedNode.set(this, cursor._tree); - } - return cursor; - } - /// Get a [tree cursor](#common.TreeCursor) that, unlike regular - /// cursors, doesn't skip through - /// [anonymous](#common.NodeType.isAnonymous) nodes and doesn't - /// automatically enter mounted nodes. - fullCursor() { - return new TreeCursor(this.topNode, 1 /* Full */); - } - /// Get a [syntax node](#common.SyntaxNode) object for the top of the - /// tree. - get topNode() { - return new TreeNode(this, 0, 0, null); - } - /// Get the [syntax node](#common.SyntaxNode) at the given position. - /// If `side` is -1, this will move into nodes that end at the - /// position. If 1, it'll move into nodes that start at the - /// position. With 0, it'll only enter nodes that cover the position - /// from both sides. - resolve(pos, side = 0) { - let node = resolveNode(CachedNode.get(this) || this.topNode, pos, side, false); - CachedNode.set(this, node); - return node; - } - /// Like [`resolve`](#common.Tree.resolve), but will enter - /// [overlaid](#common.MountedTree.overlay) nodes, producing a syntax node - /// pointing into the innermost overlaid tree at the given position - /// (with parent links going through all parent structure, including - /// the host trees). - resolveInner(pos, side = 0) { - let node = resolveNode(CachedInnerNode.get(this) || this.topNode, pos, side, true); - CachedInnerNode.set(this, node); - return node; - } - /// Iterate over the tree and its children, calling `enter` for any - /// node that touches the `from`/`to` region (if given) before - /// running over such a node's children, and `leave` (if given) when - /// leaving the node. When `enter` returns `false`, that node will - /// not have its children iterated over (or `leave` called). - iterate(spec) { - let { enter, leave, from = 0, to = this.length } = spec; - for (let c = this.cursor(), get = () => c.node;;) { - let mustLeave = false; - if (c.from <= to && c.to >= from && (c.type.isAnonymous || enter(c.type, c.from, c.to, get) !== false)) { - if (c.firstChild()) - continue; - if (!c.type.isAnonymous) - mustLeave = true; - } - for (;;) { - if (mustLeave && leave) - leave(c.type, c.from, c.to, get); - mustLeave = c.type.isAnonymous; - if (c.nextSibling()) - break; - if (!c.parent()) - return; - mustLeave = true; - } - } - } - /// Get the value of the given [node prop](#common.NodeProp) for this - /// node. Works with both per-node and per-type props. - prop(prop) { - return !prop.perNode ? this.type.prop(prop) : this.props ? this.props[prop.id] : undefined; - } - /// Returns the node's [per-node props](#common.NodeProp.perNode) in a - /// format that can be passed to the [`Tree`](#common.Tree) - /// constructor. - get propValues() { - let result = []; - if (this.props) - for (let id in this.props) - result.push([+id, this.props[id]]); - return result; - } - /// Balance the direct children of this tree, producing a copy of - /// which may have children grouped into subtrees with type - /// [`NodeType.none`](#common.NodeType^none). - balance(config = {}) { - return this.children.length <= 8 /* BranchFactor */ ? this : - balanceRange(NodeType.none, this.children, this.positions, 0, this.children.length, 0, this.length, (children, positions, length) => new Tree(this.type, children, positions, length, this.propValues), config.makeTree || ((children, positions, length) => new Tree(NodeType.none, children, positions, length))); - } - /// Build a tree from a postfix-ordered buffer of node information, - /// or a cursor over such a buffer. - static build(data) { return buildTree(data); } - } - /// The empty tree - Tree.empty = new Tree(NodeType.none, [], [], 0); - class FlatBufferCursor { - constructor(buffer, index) { - this.buffer = buffer; - this.index = index; - } - 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 FlatBufferCursor(this.buffer, this.index); } - } - /// Tree buffers contain (type, start, end, endIndex) quads for each - /// node. In such a buffer, nodes are stored in prefix order (parents - /// before children, with the endIndex of the parent indicating which - /// children belong to it) - class TreeBuffer { - /// Create a tree buffer. - constructor( - /// The buffer's content. - buffer, - /// The total length of the group of nodes in the buffer. - length, - /// The node set used in this buffer. - set) { - this.buffer = buffer; - this.length = length; - this.set = set; - } - /// @internal - get type() { return NodeType.none; } - /// @internal - toString() { - let result = []; - for (let index = 0; index < this.buffer.length;) { - result.push(this.childString(index)); - index = this.buffer[index + 3]; - } - return result.join(","); - } - /// @internal - childString(index) { - let id = this.buffer[index], endIndex = this.buffer[index + 3]; - let type = this.set.types[id], result = type.name; - if (/\W/.test(result) && !type.isError) - result = JSON.stringify(result); - index += 4; - if (endIndex == index) - return result; - let children = []; - while (index < endIndex) { - children.push(this.childString(index)); - index = this.buffer[index + 3]; - } - return result + "(" + children.join(",") + ")"; - } - /// @internal - findChild(startIndex, endIndex, dir, pos, side) { - let { buffer } = this, pick = -1; - for (let i = startIndex; i != endIndex; i = buffer[i + 3]) { - if (checkSide(side, pos, buffer[i + 1], buffer[i + 2])) { - pick = i; - if (dir > 0) - break; - } - } - return pick; - } - /// @internal - slice(startI, endI, from, to) { - let b = this.buffer; - let copy = new Uint16Array(endI - startI); - for (let i = startI, j = 0; i < endI;) { - copy[j++] = b[i++]; - copy[j++] = b[i++] - from; - copy[j++] = b[i++] - from; - copy[j++] = b[i++] - startI; - } - return new TreeBuffer(copy, to - from, this.set); - } - } - function checkSide(side, pos, from, to) { - switch (side) { - case -2 /* Before */: return from < pos; - case -1 /* AtOrBefore */: return to >= pos && from < pos; - case 0 /* Around */: return from < pos && to > pos; - case 1 /* AtOrAfter */: return from <= pos && to > pos; - case 2 /* After */: return to > pos; - case 4 /* DontCare */: return true; - } - } - function enterUnfinishedNodesBefore(node, pos) { - let scan = node.childBefore(pos); - while (scan) { - let last = scan.lastChild; - if (!last || last.to != scan.to) - break; - if (last.type.isError && last.from == last.to) { - node = scan; - scan = last.prevSibling; - } - else { - scan = last; - } - } - return node; - } - function resolveNode(node, pos, side, overlays) { - var _a; - // Move up to a node that actually holds the position, if possible - while (node.from == node.to || - (side < 1 ? node.from >= pos : node.from > pos) || - (side > -1 ? node.to <= pos : node.to < pos)) { - let parent = !overlays && node instanceof TreeNode && node.index < 0 ? null : node.parent; - if (!parent) - return node; - node = parent; - } - // Must go up out of overlays when those do not overlap with pos - if (overlays) - for (let scan = node, parent = scan.parent; parent; scan = parent, parent = scan.parent) { - if (scan instanceof TreeNode && scan.index < 0 && ((_a = parent.enter(pos, side, true)) === null || _a === void 0 ? void 0 : _a.from) != scan.from) - node = parent; - } - for (;;) { - let inner = node.enter(pos, side, overlays); - if (!inner) - return node; - node = inner; - } - } - class TreeNode { - constructor(node, _from, - // Index in parent node, set to -1 if the node is not a direct child of _parent.node (overlay) - index, _parent) { - this.node = node; - this._from = _from; - this.index = index; - this._parent = _parent; - } - get type() { return this.node.type; } - get name() { return this.node.type.name; } - get from() { return this._from; } - get to() { return this._from + this.node.length; } - nextChild(i, dir, pos, side, mode = 0) { - for (let parent = this;;) { - for (let { children, positions } = parent.node, e = dir > 0 ? children.length : -1; i != e; i += dir) { - let next = children[i], start = positions[i] + parent._from; - if (!checkSide(side, pos, start, start + next.length)) - continue; - if (next instanceof TreeBuffer) { - if (mode & 2 /* NoEnterBuffer */) - continue; - let index = next.findChild(0, next.buffer.length, dir, pos - start, side); - if (index > -1) - return new BufferNode(new BufferContext(parent, next, i, start), null, index); - } - else if ((mode & 1 /* Full */) || (!next.type.isAnonymous || hasChild(next))) { - let mounted; - if (!(mode & 1 /* Full */) && next.props && (mounted = next.prop(NodeProp.mounted)) && !mounted.overlay) - return new TreeNode(mounted.tree, start, i, parent); - let inner = new TreeNode(next, start, i, parent); - return (mode & 1 /* Full */) || !inner.type.isAnonymous ? inner - : inner.nextChild(dir < 0 ? next.children.length - 1 : 0, dir, pos, side); - } - } - if ((mode & 1 /* Full */) || !parent.type.isAnonymous) - return null; - if (parent.index >= 0) - i = parent.index + dir; - else - i = dir < 0 ? -1 : parent._parent.node.children.length; - parent = parent._parent; - if (!parent) - return null; - } - } - get firstChild() { return this.nextChild(0, 1, 0, 4 /* DontCare */); } - get lastChild() { return this.nextChild(this.node.children.length - 1, -1, 0, 4 /* DontCare */); } - childAfter(pos) { return this.nextChild(0, 1, pos, 2 /* After */); } - childBefore(pos) { return this.nextChild(this.node.children.length - 1, -1, pos, -2 /* Before */); } - enter(pos, side, overlays = true, buffers = true) { - let mounted; - if (overlays && (mounted = this.node.prop(NodeProp.mounted)) && mounted.overlay) { - let rPos = pos - this.from; - for (let { from, to } of mounted.overlay) { - if ((side > 0 ? from <= rPos : from < rPos) && - (side < 0 ? to >= rPos : to > rPos)) - return new TreeNode(mounted.tree, mounted.overlay[0].from + this.from, -1, this); - } - } - return this.nextChild(0, 1, pos, side, buffers ? 0 : 2 /* NoEnterBuffer */); - } - nextSignificantParent() { - let val = this; - while (val.type.isAnonymous && val._parent) - val = val._parent; - return val; - } - 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 /* DontCare */) : null; - } - get prevSibling() { - return this._parent && this.index >= 0 ? this._parent.nextChild(this.index - 1, -1, 0, 4 /* DontCare */) : null; - } - get cursor() { return new TreeCursor(this); } - get tree() { return this.node; } - toTree() { return this.node; } - resolve(pos, side = 0) { - return resolveNode(this, pos, side, false); - } - resolveInner(pos, side = 0) { - return resolveNode(this, pos, side, true); - } - enterUnfinishedNodesBefore(pos) { return enterUnfinishedNodesBefore(this, pos); } - getChild(type, before = null, after = null) { - let r = getChildren(this, type, before, after); - return r.length ? r[0] : null; - } - getChildren(type, before = null, after = null) { - return getChildren(this, type, before, after); - } - /// @internal - toString() { return this.node.toString(); } - } - function getChildren(node, type, before, after) { - let cur = node.cursor, result = []; - if (!cur.firstChild()) - return result; - if (before != null) - while (!cur.type.is(before)) - if (!cur.nextSibling()) - return result; - for (;;) { - if (after != null && cur.type.is(after)) - return result; - if (cur.type.is(type)) - result.push(cur.node); - if (!cur.nextSibling()) - return after == null ? result : []; - } - } - class BufferContext { - constructor(parent, buffer, index, start) { - this.parent = parent; - this.buffer = buffer; - this.index = index; - this.start = start; - } - } - class BufferNode { - constructor(context, _parent, index) { - this.context = context; - this._parent = _parent; - this.index = index; - this.type = context.buffer.set.types[context.buffer.buffer[index]]; - } - 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]; } - child(dir, pos, side) { - let { buffer } = this.context; - let index = buffer.findChild(this.index + 4, buffer.buffer[this.index + 3], dir, pos - this.context.start, side); - return index < 0 ? null : new BufferNode(this.context, this, index); - } - get firstChild() { return this.child(1, 0, 4 /* DontCare */); } - get lastChild() { return this.child(-1, 0, 4 /* DontCare */); } - childAfter(pos) { return this.child(1, pos, 2 /* After */); } - childBefore(pos) { return this.child(-1, pos, -2 /* Before */); } - enter(pos, side, overlays, buffers = true) { - if (!buffers) - return null; - let { buffer } = this.context; - let index = buffer.findChild(this.index + 4, buffer.buffer[this.index + 3], side > 0 ? 1 : -1, pos - this.context.start, side); - return index < 0 ? null : new BufferNode(this.context, this, index); - } - get parent() { - return this._parent || this.context.parent.nextSignificantParent(); - } - externalSibling(dir) { - return this._parent ? null : this.context.parent.nextChild(this.context.index + dir, dir, 0, 4 /* DontCare */); - } - get nextSibling() { - let { buffer } = this.context; - let after = buffer.buffer[this.index + 3]; - if (after < (this._parent ? buffer.buffer[this._parent.index + 3] : buffer.buffer.length)) - return new BufferNode(this.context, this._parent, after); - return this.externalSibling(1); - } - get prevSibling() { - let { buffer } = this.context; - let parentStart = this._parent ? this._parent.index + 4 : 0; - if (this.index == parentStart) - return this.externalSibling(-1); - return new BufferNode(this.context, this._parent, buffer.findChild(parentStart, this.index, -1, 0, 4 /* DontCare */)); - } - get cursor() { return new TreeCursor(this); } - get tree() { return null; } - toTree() { - let children = [], positions = []; - let { buffer } = this.context; - let startI = this.index + 4, endI = buffer.buffer[this.index + 3]; - if (endI > startI) { - let from = buffer.buffer[this.index + 1], to = buffer.buffer[this.index + 2]; - children.push(buffer.slice(startI, endI, from, to)); - positions.push(0); - } - return new Tree(this.type, children, positions, this.to - this.from); - } - resolve(pos, side = 0) { - return resolveNode(this, pos, side, false); - } - resolveInner(pos, side = 0) { - return resolveNode(this, pos, side, true); - } - enterUnfinishedNodesBefore(pos) { return enterUnfinishedNodesBefore(this, pos); } - /// @internal - toString() { return this.context.buffer.childString(this.index); } - getChild(type, before = null, after = null) { - let r = getChildren(this, type, before, after); - return r.length ? r[0] : null; - } - getChildren(type, before = null, after = null) { - return getChildren(this, type, before, after); - } - } - /// A tree cursor object focuses on a given node in a syntax tree, and - /// allows you to move to adjacent nodes. - class TreeCursor { - /// @internal - constructor(node, - /// @internal - mode = 0) { - this.mode = mode; - this.buffer = null; - this.stack = []; - this.index = 0; - this.bufferNode = null; - if (node instanceof TreeNode) { - this.yieldNode(node); - } - else { - this._tree = node.context.parent; - this.buffer = node.context; - for (let n = node._parent; n; n = n._parent) - this.stack.unshift(n.index); - this.bufferNode = node; - this.yieldBuf(node.index); - } - } - /// Shorthand for `.type.name`. - get name() { return this.type.name; } - yieldNode(node) { - if (!node) - return false; - this._tree = node; - this.type = node.type; - this.from = node.from; - this.to = node.to; - return true; - } - yieldBuf(index, type) { - this.index = index; - let { start, buffer } = this.buffer; - this.type = type || buffer.set.types[buffer.buffer[index]]; - this.from = start + buffer.buffer[index + 1]; - this.to = start + buffer.buffer[index + 2]; - return true; - } - yield(node) { - if (!node) - return false; - if (node instanceof TreeNode) { - this.buffer = null; - return this.yieldNode(node); - } - this.buffer = node.context; - return this.yieldBuf(node.index, node.type); - } - /// @internal - toString() { - return this.buffer ? this.buffer.buffer.childString(this.index) : this._tree.toString(); - } - /// @internal - enterChild(dir, pos, side) { - if (!this.buffer) - return this.yield(this._tree.nextChild(dir < 0 ? this._tree.node.children.length - 1 : 0, dir, pos, side, this.mode)); - let { buffer } = this.buffer; - let index = buffer.findChild(this.index + 4, buffer.buffer[this.index + 3], dir, pos - this.buffer.start, side); - if (index < 0) - return false; - this.stack.push(this.index); - return this.yieldBuf(index); - } - /// Move the cursor to this node's first child. When this returns - /// false, the node has no child, and the cursor has not been moved. - firstChild() { return this.enterChild(1, 0, 4 /* DontCare */); } - /// Move the cursor to this node's last child. - lastChild() { return this.enterChild(-1, 0, 4 /* DontCare */); } - /// Move the cursor to the first child that ends after `pos`. - childAfter(pos) { return this.enterChild(1, pos, 2 /* After */); } - /// Move to the last child that starts before `pos`. - childBefore(pos) { return this.enterChild(-1, pos, -2 /* Before */); } - /// Move the cursor to the child around `pos`. If side is -1 the - /// child may end at that position, when 1 it may start there. This - /// will also enter [overlaid](#common.MountedTree.overlay) - /// [mounted](#common.NodeProp^mounted) trees unless `overlays` is - /// set to false. - enter(pos, side, overlays = true, buffers = true) { - if (!this.buffer) - return this.yield(this._tree.enter(pos, side, overlays && !(this.mode & 1 /* Full */), buffers)); - return buffers ? this.enterChild(1, pos, side) : false; - } - /// Move to the node's parent node, if this isn't the top node. - parent() { - if (!this.buffer) - return this.yieldNode((this.mode & 1 /* Full */) ? this._tree._parent : this._tree.parent); - if (this.stack.length) - return this.yieldBuf(this.stack.pop()); - let parent = (this.mode & 1 /* Full */) ? this.buffer.parent : this.buffer.parent.nextSignificantParent(); - this.buffer = null; - return this.yieldNode(parent); - } - /// @internal - sibling(dir) { - if (!this.buffer) - return !this._tree._parent ? false - : this.yield(this._tree.index < 0 ? null - : this._tree._parent.nextChild(this._tree.index + dir, dir, 0, 4 /* DontCare */, this.mode)); - let { buffer } = this.buffer, d = this.stack.length - 1; - if (dir < 0) { - let parentStart = d < 0 ? 0 : this.stack[d] + 4; - if (this.index != parentStart) - return this.yieldBuf(buffer.findChild(parentStart, this.index, -1, 0, 4 /* DontCare */)); - } - else { - let after = buffer.buffer[this.index + 3]; - if (after < (d < 0 ? buffer.buffer.length : buffer.buffer[this.stack[d] + 3])) - return this.yieldBuf(after); - } - return d < 0 ? this.yield(this.buffer.parent.nextChild(this.buffer.index + dir, dir, 0, 4 /* DontCare */, this.mode)) : false; - } - /// Move to this node's next sibling, if any. - nextSibling() { return this.sibling(1); } - /// Move to this node's previous sibling, if any. - prevSibling() { return this.sibling(-1); } - atLastNode(dir) { - let index, parent, { buffer } = this; - if (buffer) { - if (dir > 0) { - if (this.index < buffer.buffer.buffer.length) - return false; - } - else { - for (let i = 0; i < this.index; i++) - if (buffer.buffer.buffer[i + 3] < this.index) - return false; - } - ({ index, parent } = buffer); - } - else { - ({ index, _parent: parent } = this._tree); - } - for (; parent; { index, _parent: parent } = parent) { - if (index > -1) - for (let i = index + dir, e = dir < 0 ? -1 : parent.node.children.length; i != e; i += dir) { - let child = parent.node.children[i]; - if ((this.mode & 1 /* Full */) || child instanceof TreeBuffer || !child.type.isAnonymous || hasChild(child)) - return false; - } - } - return true; - } - move(dir, enter) { - if (enter && this.enterChild(dir, 0, 4 /* DontCare */)) - return true; - for (;;) { - if (this.sibling(dir)) - return true; - if (this.atLastNode(dir) || !this.parent()) - return false; - } - } - /// Move to the next node in a - /// [pre-order](https://en.wikipedia.org/wiki/Tree_traversal#Pre-order_(NLR)) - /// traversal, going from a node to its first child or, if the - /// current node is empty or `enter` is false, its next sibling or - /// the next sibling of the first parent node that has one. - next(enter = true) { return this.move(1, enter); } - /// Move to the next node in a last-to-first pre-order traveral. A - /// node is followed by its last child or, if it has none, its - /// previous sibling or the previous sibling of the first parent - /// node that has one. - prev(enter = true) { return this.move(-1, enter); } - /// Move the cursor to the innermost node that covers `pos`. If - /// `side` is -1, it will enter nodes that end at `pos`. If it is 1, - /// it will enter nodes that start at `pos`. - moveTo(pos, side = 0) { - // Move up to a node that actually holds the position, if possible - while (this.from == this.to || - (side < 1 ? this.from >= pos : this.from > pos) || - (side > -1 ? this.to <= pos : this.to < pos)) - if (!this.parent()) - break; - // Then scan down into child nodes as far as possible - while (this.enterChild(1, pos, side)) { } - return this; - } - /// Get a [syntax node](#common.SyntaxNode) at the cursor's current - /// position. - get node() { - if (!this.buffer) - return this._tree; - let cache = this.bufferNode, result = null, depth = 0; - if (cache && cache.context == this.buffer) { - scan: for (let index = this.index, d = this.stack.length; d >= 0;) { - for (let c = cache; c; c = c._parent) - if (c.index == index) { - if (index == this.index) - return c; - result = c; - depth = d + 1; - break scan; - } - index = this.stack[--d]; - } - } - for (let i = depth; i < this.stack.length; i++) - result = new BufferNode(this.buffer, result, this.stack[i]); - return this.bufferNode = new BufferNode(this.buffer, result, this.index); - } - /// Get the [tree](#common.Tree) that represents the current node, if - /// any. Will return null when the node is in a [tree - /// buffer](#common.TreeBuffer). - get tree() { - return this.buffer ? null : this._tree.node; - } - } - function hasChild(tree) { - return tree.children.some(ch => ch instanceof TreeBuffer || !ch.type.isAnonymous || hasChild(ch)); - } - function buildTree(data) { - var _a; - let { buffer, nodeSet, maxBufferLength = DefaultBufferLength, reused = [], minRepeatType = nodeSet.types.length } = data; - let cursor = Array.isArray(buffer) ? new FlatBufferCursor(buffer, buffer.length) : buffer; - let types = nodeSet.types; - let contextHash = 0, lookAhead = 0; - function takeNode(parentStart, minPos, children, positions, inRepeat) { - let { id, start, end, size } = cursor; - let lookAheadAtStart = lookAhead; - while (size < 0) { - cursor.next(); - if (size == -1 /* Reuse */) { - let node = reused[id]; - children.push(node); - positions.push(start - parentStart); - return; - } - else if (size == -3 /* ContextChange */) { // Context change - contextHash = id; - return; - } - else if (size == -4 /* LookAhead */) { - lookAhead = id; - return; - } - else { - throw new RangeError(`Unrecognized record size: ${size}`); - } - } - let type = types[id], node, buffer; - let startPos = start - parentStart; - if (end - start <= maxBufferLength && (buffer = findBufferSize(cursor.pos - minPos, inRepeat))) { - // Small enough for a buffer, and no reused nodes inside - let data = new Uint16Array(buffer.size - buffer.skip); - let endPos = cursor.pos - buffer.size, index = data.length; - while (cursor.pos > endPos) - index = copyToBuffer(buffer.start, data, index); - node = new TreeBuffer(data, end - buffer.start, nodeSet); - startPos = buffer.start - parentStart; - } - else { // Make it a node - let endPos = cursor.pos - size; - cursor.next(); - let localChildren = [], localPositions = []; - let localInRepeat = id >= minRepeatType ? id : -1; - let lastGroup = 0, lastEnd = end; - while (cursor.pos > endPos) { - if (localInRepeat >= 0 && cursor.id == localInRepeat && cursor.size >= 0) { - if (cursor.end <= lastEnd - maxBufferLength) { - makeRepeatLeaf(localChildren, localPositions, start, lastGroup, cursor.end, lastEnd, localInRepeat, lookAheadAtStart); - lastGroup = localChildren.length; - lastEnd = cursor.end; - } - cursor.next(); - } - else { - takeNode(start, endPos, localChildren, localPositions, localInRepeat); - } - } - if (localInRepeat >= 0 && lastGroup > 0 && lastGroup < localChildren.length) - makeRepeatLeaf(localChildren, localPositions, start, lastGroup, start, lastEnd, localInRepeat, lookAheadAtStart); - localChildren.reverse(); - localPositions.reverse(); - if (localInRepeat > -1 && lastGroup > 0) { - let make = makeBalanced(type); - node = balanceRange(type, localChildren, localPositions, 0, localChildren.length, 0, end - start, make, make); - } - else { - node = makeTree(type, localChildren, localPositions, end - start, lookAheadAtStart - end); - } - } - children.push(node); - positions.push(startPos); - } - function makeBalanced(type) { - return (children, positions, length) => { - let lookAhead = 0, lastI = children.length - 1, last, lookAheadProp; - if (lastI >= 0 && (last = children[lastI]) instanceof Tree) { - if (!lastI && last.type == type && last.length == length) - return last; - if (lookAheadProp = last.prop(NodeProp.lookAhead)) - lookAhead = positions[lastI] + last.length + lookAheadProp; - } - return makeTree(type, children, positions, length, lookAhead); - }; - } - function makeRepeatLeaf(children, positions, base, i, from, to, type, lookAhead) { - let localChildren = [], localPositions = []; - while (children.length > i) { - localChildren.push(children.pop()); - localPositions.push(positions.pop() + base - from); - } - children.push(makeTree(nodeSet.types[type], localChildren, localPositions, to - from, lookAhead - to)); - positions.push(from - base); - } - function makeTree(type, children, positions, length, lookAhead = 0, props) { - if (contextHash) { - let pair = [NodeProp.contextHash, contextHash]; - props = props ? [pair].concat(props) : [pair]; - } - if (lookAhead > 25) { - let pair = [NodeProp.lookAhead, lookAhead]; - props = props ? [pair].concat(props) : [pair]; - } - return new Tree(type, children, positions, length, props); - } - function findBufferSize(maxSize, inRepeat) { - // Scan through the buffer to find previous siblings that fit - // together in a TreeBuffer, and don't contain any reused nodes - // (which can't be stored in a buffer). - // If `inRepeat` is > -1, ignore node boundaries of that type for - // nesting, but make sure the end falls either at the start - // (`maxSize`) or before such a node. - let fork = cursor.fork(); - let size = 0, start = 0, skip = 0, minStart = fork.end - maxBufferLength; - let result = { size: 0, start: 0, skip: 0 }; - scan: for (let minPos = fork.pos - maxSize; fork.pos > minPos;) { - let nodeSize = fork.size; - // Pretend nested repeat nodes of the same type don't exist - if (fork.id == inRepeat && nodeSize >= 0) { - // Except that we store the current state as a valid return - // value. - result.size = size; - result.start = start; - result.skip = skip; - skip += 4; - size += 4; - fork.next(); - continue; - } - let startPos = fork.pos - nodeSize; - if (nodeSize < 0 || startPos < minPos || fork.start < minStart) - break; - let localSkipped = fork.id >= minRepeatType ? 4 : 0; - let nodeStart = fork.start; - fork.next(); - while (fork.pos > startPos) { - if (fork.size < 0) { - if (fork.size == -3 /* ContextChange */) - localSkipped += 4; - else - break scan; - } - else if (fork.id >= minRepeatType) { - localSkipped += 4; - } - fork.next(); - } - start = nodeStart; - size += nodeSize; - skip += localSkipped; - } - if (inRepeat < 0 || size == maxSize) { - result.size = size; - result.start = start; - result.skip = skip; - } - return result.size > 4 ? result : undefined; - } - function copyToBuffer(bufferStart, buffer, index) { - let { id, start, end, size } = cursor; - cursor.next(); - if (size >= 0 && id < minRepeatType) { - let startIndex = index; - if (size > 4) { - let endPos = cursor.pos - (size - 4); - while (cursor.pos > endPos) - index = copyToBuffer(bufferStart, buffer, index); - } - buffer[--index] = startIndex; - buffer[--index] = end - bufferStart; - buffer[--index] = start - bufferStart; - buffer[--index] = id; - } - else if (size == -3 /* ContextChange */) { - contextHash = id; - } - else if (size == -4 /* LookAhead */) { - lookAhead = id; - } - return index; - } - let children = [], positions = []; - while (cursor.pos > 0) - takeNode(data.start || 0, data.bufferStart || 0, children, positions, -1); - let length = (_a = data.length) !== null && _a !== void 0 ? _a : (children.length ? positions[0] + children[0].length : 0); - return new Tree(types[data.topID], children.reverse(), positions.reverse(), length); - } - const nodeSizeCache = new WeakMap; - function nodeSize(balanceType, node) { - if (!balanceType.isAnonymous || node instanceof TreeBuffer || node.type != balanceType) - return 1; - let size = nodeSizeCache.get(node); - if (size == null) { - size = 1; - for (let child of node.children) { - if (child.type != balanceType || !(child instanceof Tree)) { - size = 1; - break; - } - size += nodeSize(balanceType, child); - } - nodeSizeCache.set(node, size); - } - return size; - } - function balanceRange( - // The type the balanced tree's inner nodes. - balanceType, - // The direct children and their positions - children, positions, - // The index range in children/positions to use - from, to, - // The start position of the nodes, relative to their parent. - start, - // Length of the outer node - length, - // Function to build the top node of the balanced tree - mkTop, - // Function to build internal nodes for the balanced tree - mkTree) { - let total = 0; - for (let i = from; i < to; i++) - total += nodeSize(balanceType, children[i]); - let maxChild = Math.ceil((total * 1.5) / 8 /* BranchFactor */); - let localChildren = [], localPositions = []; - function divide(children, positions, from, to, offset) { - for (let i = from; i < to;) { - let groupFrom = i, groupStart = positions[i], groupSize = nodeSize(balanceType, children[i]); - i++; - for (; i < to; i++) { - let nextSize = nodeSize(balanceType, children[i]); - if (groupSize + nextSize >= maxChild) - break; - groupSize += nextSize; - } - if (i == groupFrom + 1) { - if (groupSize > maxChild) { - let only = children[groupFrom]; // Only trees can have a size > 1 - divide(only.children, only.positions, 0, only.children.length, positions[groupFrom] + offset); - continue; - } - localChildren.push(children[groupFrom]); - } - else { - let length = positions[i - 1] + children[i - 1].length - groupStart; - localChildren.push(balanceRange(balanceType, children, positions, groupFrom, i, groupStart, length, null, mkTree)); - } - localPositions.push(groupStart + offset - start); - } - } - divide(children, positions, from, to, 0); - return (mkTop || mkTree)(localChildren, localPositions, length); - } - - /// Tree fragments are used during [incremental - /// parsing](#common.Parser.startParse) to track parts of old trees - /// that can be reused in a new parse. An array of fragments is used - /// to track regions of an old tree whose nodes might be reused in new - /// parses. Use the static - /// [`applyChanges`](#common.TreeFragment^applyChanges) method to - /// update fragments for document changes. - class TreeFragment { - /// Construct a tree fragment. - constructor( - /// The start of the unchanged range pointed to by this fragment. - /// This refers to an offset in the _updated_ document (as opposed - /// to the original tree). - from, - /// The end of the unchanged range. - to, - /// The tree that this fragment is based on. - tree, - /// The offset between the fragment's tree and the document that - /// this fragment can be used against. Add this when going from - /// document to tree positions, subtract it to go from tree to - /// document positions. - offset, openStart = false, openEnd = false) { - this.from = from; - this.to = to; - this.tree = tree; - this.offset = offset; - this.open = (openStart ? 1 /* Start */ : 0) | (openEnd ? 2 /* End */ : 0); - } - /// Whether the start of the fragment represents the start of a - /// parse, or the end of a change. (In the second case, it may not - /// be safe to reuse some nodes at the start, depending on the - /// parsing algorithm.) - get openStart() { return (this.open & 1 /* Start */) > 0; } - /// Whether the end of the fragment represents the end of a - /// full-document parse, or the start of a change. - get openEnd() { return (this.open & 2 /* End */) > 0; } - /// Create a set of fragments from a freshly parsed tree, or update - /// an existing set of fragments by replacing the ones that overlap - /// with a tree with content from the new tree. When `partial` is - /// true, the parse is treated as incomplete, and the resulting - /// fragment has [`openEnd`](#common.TreeFragment.openEnd) set to - /// true. - static addTree(tree, fragments = [], partial = false) { - let result = [new TreeFragment(0, tree.length, tree, 0, false, partial)]; - for (let f of fragments) - if (f.to > tree.length) - result.push(f); - return result; - } - /// Apply a set of edits to an array of fragments, removing or - /// splitting fragments as necessary to remove edited ranges, and - /// adjusting offsets for fragments that moved. - static applyChanges(fragments, changes, minGap = 128) { - if (!changes.length) - return fragments; - let result = []; - let fI = 1, nextF = fragments.length ? fragments[0] : null; - for (let cI = 0, pos = 0, off = 0;; cI++) { - let nextC = cI < changes.length ? changes[cI] : null; - let nextPos = nextC ? nextC.fromA : 1e9; - if (nextPos - pos >= minGap) - while (nextF && nextF.from < nextPos) { - let cut = nextF; - if (pos >= cut.from || nextPos <= cut.to || off) { - let fFrom = Math.max(cut.from, pos) - off, fTo = Math.min(cut.to, nextPos) - off; - cut = fFrom >= fTo ? null : new TreeFragment(fFrom, fTo, cut.tree, cut.offset + off, cI > 0, !!nextC); - } - if (cut) - result.push(cut); - if (nextF.to > nextPos) - break; - nextF = fI < fragments.length ? fragments[fI++] : null; - } - if (!nextC) - break; - pos = nextC.toA; - off = nextC.toA - nextC.toB; - } - return result; - } - } - /// A superclass that parsers should extend. - class Parser { - /// Start a parse, returning a [partial parse](#common.PartialParse) - /// object. [`fragments`](#common.TreeFragment) can be passed in to - /// make the parse incremental. - /// - /// By default, the entire input is parsed. You can pass `ranges`, - /// which should be a sorted array of non-empty, non-overlapping - /// ranges, to parse only those ranges. The tree returned in that - /// case will start at `ranges[0].from`. - startParse(input, fragments, ranges) { - if (typeof input == "string") - input = new StringInput(input); - ranges = !ranges ? [new Range(0, input.length)] : ranges.length ? ranges.map(r => new Range(r.from, r.to)) : [new Range(0, 0)]; - return this.createParse(input, fragments || [], ranges); - } - /// Run a full parse, returning the resulting tree. - parse(input, fragments, ranges) { - let parse = this.startParse(input, fragments, ranges); - for (;;) { - let done = parse.advance(); - if (done) - return done; - } - } - } - class StringInput { - constructor(string) { - this.string = string; - } - get length() { return this.string.length; } - chunk(from) { return this.string.slice(from); } - get lineChunks() { return false; } - read(from, to) { return this.string.slice(from, to); } - } - new NodeProp({ perNode: true }); - - var _a; - /** - Node prop stored in a grammar's top syntax node to provide the - facet that stores language data for that language. - */ - const languageDataProp = /*@__PURE__*/new NodeProp(); - /** - Helper function to define a facet (to be added to the top syntax - node(s) for a language via - [`languageDataProp`](https://codemirror.net/6/docs/ref/#language.languageDataProp)), that will be - used to associate language data with the language. You - probably only need this when subclassing - [`Language`](https://codemirror.net/6/docs/ref/#language.Language). - */ - function defineLanguageFacet(baseData) { - return Facet.define({ - combine: baseData ? values => values.concat(baseData) : undefined - }); - } - /** - A language object manages parsing and per-language - [metadata](https://codemirror.net/6/docs/ref/#state.EditorState.languageDataAt). Parse data is - managed as a [Lezer](https://lezer.codemirror.net) tree. You'll - want to subclass this class for custom parsers, or use the - [`LRLanguage`](https://codemirror.net/6/docs/ref/#language.LRLanguage) or - [`StreamLanguage`](https://codemirror.net/6/docs/ref/#stream-parser.StreamLanguage) abstractions for - [Lezer](https://lezer.codemirror.net/) or stream parsers. - */ - class Language { - /** - Construct a language object. You usually don't need to invoke - this directly. But when you do, make sure you use - [`defineLanguageFacet`](https://codemirror.net/6/docs/ref/#language.defineLanguageFacet) to create - the first argument. - */ - constructor( - /** - The [language data](https://codemirror.net/6/docs/ref/#state.EditorState.languageDataAt) data - facet used for this language. - */ - data, parser, - /** - The node type of the top node of trees produced by this parser. - */ - topNode, extraExtensions = []) { - this.data = data; - this.topNode = topNode; - // Kludge to define EditorState.tree as a debugging helper, - // without the EditorState package actually knowing about - // languages and lezer trees. - if (!EditorState.prototype.hasOwnProperty("tree")) - Object.defineProperty(EditorState.prototype, "tree", { get() { return syntaxTree(this); } }); - this.parser = parser; - this.extension = [ - language.of(this), - EditorState.languageData.of((state, pos, side) => state.facet(languageDataFacetAt(state, pos, side))) - ].concat(extraExtensions); - } - /** - Query whether this language is active at the given position. - */ - isActiveAt(state, pos, side = -1) { - return languageDataFacetAt(state, pos, side) == this.data; - } - /** - Find the document regions that were parsed using this language. - The returned regions will _include_ any nested languages rooted - in this language, when those exist. - */ - findRegions(state) { - let lang = state.facet(language); - if ((lang === null || lang === void 0 ? void 0 : lang.data) == this.data) - return [{ from: 0, to: state.doc.length }]; - if (!lang || !lang.allowsNesting) - return []; - let result = []; - let explore = (tree, from) => { - if (tree.prop(languageDataProp) == this.data) { - result.push({ from, to: from + tree.length }); - return; - } - let mount = tree.prop(NodeProp.mounted); - if (mount) { - if (mount.tree.prop(languageDataProp) == this.data) { - if (mount.overlay) - for (let r of mount.overlay) - result.push({ from: r.from + from, to: r.to + from }); - else - result.push({ from: from, to: from + tree.length }); - return; - } - else if (mount.overlay) { - let size = result.length; - explore(mount.tree, mount.overlay[0].from + from); - if (result.length > size) - return; - } - } - for (let i = 0; i < tree.children.length; i++) { - let ch = tree.children[i]; - if (ch instanceof Tree) - explore(ch, tree.positions[i] + from); - } - }; - explore(syntaxTree(state), 0); - return result; - } - /** - Indicates whether this language allows nested languages. The - default implementation returns true. - */ - get allowsNesting() { return true; } - } - /** - @internal - */ - Language.setState = /*@__PURE__*/StateEffect.define(); - function languageDataFacetAt(state, pos, side) { - let topLang = state.facet(language); - if (!topLang) - return null; - let facet = topLang.data; - if (topLang.allowsNesting) { - for (let node = syntaxTree(state).topNode; node; node = node.enter(pos, side, true, false)) - facet = node.type.prop(languageDataProp) || facet; - } - return facet; - } - /** - A subclass of [`Language`](https://codemirror.net/6/docs/ref/#language.Language) for use with Lezer - [LR parsers](https://lezer.codemirror.net/docs/ref#lr.LRParser) - parsers. - */ - class LRLanguage extends Language { - constructor(data, parser) { - super(data, parser, parser.topNode); - this.parser = parser; - } - /** - Define a language from a parser. - */ - static define(spec) { - let data = defineLanguageFacet(spec.languageData); - return new LRLanguage(data, spec.parser.configure({ - props: [languageDataProp.add(type => type.isTop ? data : undefined)] - })); - } - /** - Create a new instance of this language with a reconfigured - version of its parser. - */ - configure(options) { - return new LRLanguage(this.data, this.parser.configure(options)); - } - get allowsNesting() { return this.parser.wrappers.length > 0; } // FIXME - } - /** - Get the syntax tree for a state, which is the current (possibly - incomplete) parse tree of active [language](https://codemirror.net/6/docs/ref/#language.Language), - or the empty tree if there is no language available. - */ - function syntaxTree(state) { - let field = state.field(Language.state, false); - return field ? field.tree : Tree.empty; - } - // Lezer-style Input object for a Text document. - class DocInput { - constructor(doc, length = doc.length) { - this.doc = doc; - this.length = length; - this.cursorPos = 0; - this.string = ""; - this.cursor = doc.iter(); - } - syncTo(pos) { - this.string = this.cursor.next(pos - this.cursorPos).value; - this.cursorPos = pos + this.string.length; - return this.cursorPos - this.string.length; - } - chunk(pos) { - this.syncTo(pos); - return this.string; - } - get lineChunks() { return true; } - read(from, to) { - let stringStart = this.cursorPos - this.string.length; - if (from < stringStart || to >= this.cursorPos) - return this.doc.sliceString(from, to); - else - return this.string.slice(from - stringStart, to - stringStart); - } - } - let currentContext = null; - /** - A parse context provided to parsers working on the editor content. - */ - class ParseContext { - /** - @internal - */ - constructor(parser, - /** - The current editor state. - */ - state, - /** - Tree fragments that can be reused by incremental re-parses. - */ - fragments = [], - /** - @internal - */ - tree, treeLen, - /** - The current editor viewport (or some overapproximation - thereof). Intended to be used for opportunistically avoiding - work (in which case - [`skipUntilInView`](https://codemirror.net/6/docs/ref/#language.ParseContext.skipUntilInView) - should be called to make sure the parser is restarted when the - skipped region becomes visible). - */ - viewport, - /** - @internal - */ - skipped, - /** - This is where skipping parsers can register a promise that, - when resolved, will schedule a new parse. It is cleared when - the parse worker picks up the promise. @internal - */ - scheduleOn) { - this.parser = parser; - this.state = state; - this.fragments = fragments; - this.tree = tree; - this.treeLen = treeLen; - this.viewport = viewport; - this.skipped = skipped; - this.scheduleOn = scheduleOn; - this.parse = null; - /** - @internal - */ - this.tempSkipped = []; - } - startParse() { - return this.parser.startParse(new DocInput(this.state.doc), this.fragments); - } - /** - @internal - */ - work(until, upto) { - if (upto != null && upto >= this.state.doc.length) - upto = undefined; - if (this.tree != Tree.empty && this.isDone(upto !== null && upto !== void 0 ? upto : this.state.doc.length)) { - this.takeTree(); - return true; - } - return this.withContext(() => { - var _a; - if (typeof until == "number") { - let endTime = Date.now() + until; - until = () => Date.now() > endTime; - } - if (!this.parse) - this.parse = this.startParse(); - if (upto != null && (this.parse.stoppedAt == null || this.parse.stoppedAt > upto) && - upto < this.state.doc.length) - this.parse.stopAt(upto); - for (;;) { - let done = this.parse.advance(); - if (done) { - this.fragments = this.withoutTempSkipped(TreeFragment.addTree(done, this.fragments, this.parse.stoppedAt != null)); - this.treeLen = (_a = this.parse.stoppedAt) !== null && _a !== void 0 ? _a : this.state.doc.length; - this.tree = done; - this.parse = null; - if (this.treeLen < (upto !== null && upto !== void 0 ? upto : this.state.doc.length)) - this.parse = this.startParse(); - else - return true; - } - if (until()) - return false; - } - }); - } - /** - @internal - */ - takeTree() { - let pos, tree; - if (this.parse && (pos = this.parse.parsedPos) >= this.treeLen) { - if (this.parse.stoppedAt == null || this.parse.stoppedAt > pos) - this.parse.stopAt(pos); - this.withContext(() => { while (!(tree = this.parse.advance())) { } }); - this.treeLen = pos; - this.tree = tree; - this.fragments = this.withoutTempSkipped(TreeFragment.addTree(this.tree, this.fragments, true)); - this.parse = null; - } - } - withContext(f) { - let prev = currentContext; - currentContext = this; - try { - return f(); - } - finally { - currentContext = prev; - } - } - withoutTempSkipped(fragments) { - for (let r; r = this.tempSkipped.pop();) - fragments = cutFragments(fragments, r.from, r.to); - return fragments; - } - /** - @internal - */ - changes(changes, newState) { - let { fragments, tree, treeLen, viewport, skipped } = this; - this.takeTree(); - if (!changes.empty) { - let ranges = []; - changes.iterChangedRanges((fromA, toA, fromB, toB) => ranges.push({ fromA, toA, fromB, toB })); - fragments = TreeFragment.applyChanges(fragments, ranges); - tree = Tree.empty; - treeLen = 0; - viewport = { from: changes.mapPos(viewport.from, -1), to: changes.mapPos(viewport.to, 1) }; - if (this.skipped.length) { - skipped = []; - for (let r of this.skipped) { - let from = changes.mapPos(r.from, 1), to = changes.mapPos(r.to, -1); - if (from < to) - skipped.push({ from, to }); - } - } - } - return new ParseContext(this.parser, newState, fragments, tree, treeLen, viewport, skipped, this.scheduleOn); - } - /** - @internal - */ - updateViewport(viewport) { - if (this.viewport.from == viewport.from && this.viewport.to == viewport.to) - return false; - this.viewport = viewport; - let startLen = this.skipped.length; - for (let i = 0; i < this.skipped.length; i++) { - let { from, to } = this.skipped[i]; - if (from < viewport.to && to > viewport.from) { - this.fragments = cutFragments(this.fragments, from, to); - this.skipped.splice(i--, 1); - } - } - if (this.skipped.length >= startLen) - return false; - this.reset(); - return true; - } - /** - @internal - */ - reset() { - if (this.parse) { - this.takeTree(); - this.parse = null; - } - } - /** - Notify the parse scheduler that the given region was skipped - because it wasn't in view, and the parse should be restarted - when it comes into view. - */ - skipUntilInView(from, to) { - this.skipped.push({ from, to }); - } - /** - Returns a parser intended to be used as placeholder when - asynchronously loading a nested parser. It'll skip its input and - mark it as not-really-parsed, so that the next update will parse - it again. - - When `until` is given, a reparse will be scheduled when that - promise resolves. - */ - static getSkippingParser(until) { - return new class extends Parser { - createParse(input, fragments, ranges) { - let from = ranges[0].from, to = ranges[ranges.length - 1].to; - let parser = { - parsedPos: from, - advance() { - let cx = currentContext; - if (cx) { - for (let r of ranges) - cx.tempSkipped.push(r); - if (until) - cx.scheduleOn = cx.scheduleOn ? Promise.all([cx.scheduleOn, until]) : until; - } - this.parsedPos = to; - return new Tree(NodeType.none, [], [], to - from); - }, - stoppedAt: null, - stopAt() { } - }; - return parser; - } - }; - } - /** - @internal - */ - isDone(upto) { - upto = Math.min(upto, this.state.doc.length); - let frags = this.fragments; - return this.treeLen >= upto && frags.length && frags[0].from == 0 && frags[0].to >= upto; - } - /** - Get the context for the current parse, or `null` if no editor - parse is in progress. - */ - static get() { return currentContext; } - } - function cutFragments(fragments, from, to) { - return TreeFragment.applyChanges(fragments, [{ fromA: from, toA: to, fromB: from, toB: to }]); - } - class LanguageState { - constructor( - // A mutable parse state that is used to preserve work done during - // the lifetime of a state when moving to the next state. - context) { - this.context = context; - this.tree = context.tree; - } - apply(tr) { - if (!tr.docChanged && this.tree == this.context.tree) - return this; - let newCx = this.context.changes(tr.changes, tr.state); - // If the previous parse wasn't done, go forward only up to its - // end position or the end of the viewport, to avoid slowing down - // state updates with parse work beyond the viewport. - let upto = this.context.treeLen == tr.startState.doc.length ? undefined - : Math.max(tr.changes.mapPos(this.context.treeLen), newCx.viewport.to); - if (!newCx.work(20 /* Apply */, upto)) - newCx.takeTree(); - return new LanguageState(newCx); - } - static init(state) { - let vpTo = Math.min(3000 /* InitViewport */, state.doc.length); - let parseState = new ParseContext(state.facet(language).parser, state, [], Tree.empty, 0, { from: 0, to: vpTo }, [], null); - if (!parseState.work(20 /* Apply */, vpTo)) - parseState.takeTree(); - return new LanguageState(parseState); - } - } - Language.state = /*@__PURE__*/StateField.define({ - create: LanguageState.init, - update(value, tr) { - for (let e of tr.effects) - if (e.is(Language.setState)) - return e.value; - if (tr.startState.facet(language) != tr.state.facet(language)) - return LanguageState.init(tr.state); - return value.apply(tr); - } - }); - let requestIdle = (callback) => { - let timeout = setTimeout(() => callback(), 500 /* MaxPause */); - return () => clearTimeout(timeout); - }; - if (typeof requestIdleCallback != "undefined") - requestIdle = (callback) => { - let idle = -1, timeout = setTimeout(() => { - idle = requestIdleCallback(callback, { timeout: 500 /* MaxPause */ - 100 /* MinPause */ }); - }, 100 /* MinPause */); - return () => idle < 0 ? clearTimeout(timeout) : cancelIdleCallback(idle); - }; - const isInputPending = typeof navigator != "undefined" && ((_a = navigator.scheduling) === null || _a === void 0 ? void 0 : _a.isInputPending) - ? () => navigator.scheduling.isInputPending() : null; - const parseWorker = /*@__PURE__*/ViewPlugin.fromClass(class ParseWorker { - constructor(view) { - this.view = view; - this.working = null; - this.workScheduled = 0; - // End of the current time chunk - this.chunkEnd = -1; - // Milliseconds of budget left for this chunk - this.chunkBudget = -1; - this.work = this.work.bind(this); - this.scheduleWork(); - } - update(update) { - let cx = this.view.state.field(Language.state).context; - if (cx.updateViewport(update.view.viewport) || this.view.viewport.to > cx.treeLen) - this.scheduleWork(); - if (update.docChanged) { - if (this.view.hasFocus) - this.chunkBudget += 50 /* ChangeBonus */; - this.scheduleWork(); - } - this.checkAsyncSchedule(cx); - } - scheduleWork() { - if (this.working) - return; - let { state } = this.view, field = state.field(Language.state); - if (field.tree != field.context.tree || !field.context.isDone(state.doc.length)) - this.working = requestIdle(this.work); - } - work(deadline) { - this.working = null; - let now = Date.now(); - if (this.chunkEnd < now && (this.chunkEnd < 0 || this.view.hasFocus)) { // Start a new chunk - this.chunkEnd = now + 30000 /* ChunkTime */; - this.chunkBudget = 3000 /* ChunkBudget */; - } - if (this.chunkBudget <= 0) - return; // No more budget - let { state, viewport: { to: vpTo } } = this.view, field = state.field(Language.state); - if (field.tree == field.context.tree && field.context.isDone(vpTo + 100000 /* MaxParseAhead */)) - return; - let endTime = Date.now() + Math.min(this.chunkBudget, 100 /* Slice */, deadline && !isInputPending ? Math.max(25 /* MinSlice */, deadline.timeRemaining() - 5) : 1e9); - let viewportFirst = field.context.treeLen < vpTo && state.doc.length > vpTo + 1000; - let done = field.context.work(() => { - return isInputPending && isInputPending() || Date.now() > endTime; - }, vpTo + (viewportFirst ? 0 : 100000 /* MaxParseAhead */)); - this.chunkBudget -= Date.now() - now; - if (done || this.chunkBudget <= 0) { - field.context.takeTree(); - this.view.dispatch({ effects: Language.setState.of(new LanguageState(field.context)) }); - } - if (this.chunkBudget > 0 && !(done && !viewportFirst)) - this.scheduleWork(); - this.checkAsyncSchedule(field.context); - } - checkAsyncSchedule(cx) { - if (cx.scheduleOn) { - this.workScheduled++; - cx.scheduleOn - .then(() => this.scheduleWork()) - .catch(err => logException(this.view.state, err)) - .then(() => this.workScheduled--); - cx.scheduleOn = null; - } - } - destroy() { - if (this.working) - this.working(); - } - isWorking() { - return !!(this.working || this.workScheduled > 0); - } - }, { - eventHandlers: { focus() { this.scheduleWork(); } } - }); - /** - The facet used to associate a language with an editor state. - */ - const language = /*@__PURE__*/Facet.define({ - combine(languages) { return languages.length ? languages[0] : null; }, - enables: [Language.state, parseWorker] - }); - /** - This class bundles a [language object](https://codemirror.net/6/docs/ref/#language.Language) with an - optional set of supporting extensions. Language packages are - encouraged to export a function that optionally takes a - configuration object and returns a `LanguageSupport` instance, as - the main way for client code to use the package. - */ - class LanguageSupport { - /** - Create a support object. - */ - constructor( - /** - The language object. - */ - language, - /** - An optional set of supporting extensions. When nesting a - language in another language, the outer language is encouraged - to include the supporting extensions for its inner languages - in its own set of support extensions. - */ - support = []) { - this.language = language; - this.support = support; - this.extension = [language, support]; - } - } - - /** - Facet that defines a way to provide a function that computes the - appropriate indentation depth at the start of a given line, or - `null` to indicate no appropriate indentation could be determined. - */ - const indentService = /*@__PURE__*/Facet.define(); - /** - Facet for overriding the unit by which indentation happens. - Should be a string consisting either entirely of spaces or - entirely of tabs. When not set, this defaults to 2 spaces. - */ - const indentUnit = /*@__PURE__*/Facet.define({ - combine: values => { - if (!values.length) - return " "; - if (!/^(?: +|\t+)$/.test(values[0])) - throw new Error("Invalid indent unit: " + JSON.stringify(values[0])); - return values[0]; - } - }); - /** - Return the _column width_ of an indent unit in the state. - Determined by the [`indentUnit`](https://codemirror.net/6/docs/ref/#language.indentUnit) - facet, and [`tabSize`](https://codemirror.net/6/docs/ref/#state.EditorState^tabSize) when that - contains tabs. - */ - function getIndentUnit(state) { - let unit = state.facet(indentUnit); - return unit.charCodeAt(0) == 9 ? state.tabSize * unit.length : unit.length; - } - /** - Create an indentation string that covers columns 0 to `cols`. - Will use tabs for as much of the columns as possible when the - [`indentUnit`](https://codemirror.net/6/docs/ref/#language.indentUnit) facet contains - tabs. - */ - function indentString(state, cols) { - let result = "", ts = state.tabSize; - if (state.facet(indentUnit).charCodeAt(0) == 9) - while (cols >= ts) { - result += "\t"; - cols -= ts; - } - for (let i = 0; i < cols; i++) - result += " "; - return result; - } - /** - Get the indentation at the given position. Will first consult any - [indent services](https://codemirror.net/6/docs/ref/#language.indentService) that are registered, - and if none of those return an indentation, this will check the - syntax tree for the [indent node prop](https://codemirror.net/6/docs/ref/#language.indentNodeProp) - and use that if found. Returns a number when an indentation could - be determined, and null otherwise. - */ - function getIndentation(context, pos) { - if (context instanceof EditorState) - context = new IndentContext(context); - for (let service of context.state.facet(indentService)) { - let result = service(context, pos); - if (result != null) - return result; - } - let tree = syntaxTree(context.state); - return tree ? syntaxIndentation(context, tree, pos) : null; - } - /** - Indentation contexts are used when calling [indentation - services](https://codemirror.net/6/docs/ref/#language.indentService). They provide helper utilities - useful in indentation logic, and can selectively override the - indentation reported for some lines. - */ - class IndentContext { - /** - Create an indent context. - */ - constructor( - /** - The editor state. - */ - state, - /** - @internal - */ - options = {}) { - this.state = state; - this.options = options; - this.unit = getIndentUnit(state); - } - /** - Get a description of the line at the given position, taking - [simulated line - breaks](https://codemirror.net/6/docs/ref/#language.IndentContext.constructor^options.simulateBreak) - into account. If there is such a break at `pos`, the `bias` - argument determines whether the part of the line line before or - after the break is used. - */ - lineAt(pos, bias = 1) { - let line = this.state.doc.lineAt(pos); - let { simulateBreak, simulateDoubleBreak } = this.options; - if (simulateBreak != null && simulateBreak >= line.from && simulateBreak <= line.to) { - if (simulateDoubleBreak && simulateBreak == pos) - return { text: "", from: pos }; - else if (bias < 0 ? simulateBreak < pos : simulateBreak <= pos) - return { text: line.text.slice(simulateBreak - line.from), from: simulateBreak }; - else - return { text: line.text.slice(0, simulateBreak - line.from), from: line.from }; - } - return line; - } - /** - Get the text directly after `pos`, either the entire line - or the next 100 characters, whichever is shorter. - */ - textAfterPos(pos, bias = 1) { - if (this.options.simulateDoubleBreak && pos == this.options.simulateBreak) - return ""; - let { text, from } = this.lineAt(pos, bias); - return text.slice(pos - from, Math.min(text.length, pos + 100 - from)); - } - /** - Find the column for the given position. - */ - column(pos, bias = 1) { - let { text, from } = this.lineAt(pos, bias); - let result = this.countColumn(text, pos - from); - let override = this.options.overrideIndentation ? this.options.overrideIndentation(from) : -1; - if (override > -1) - result += override - this.countColumn(text, text.search(/\S|$/)); - return result; - } - /** - Find the column position (taking tabs into account) of the given - position in the given string. - */ - countColumn(line, pos = line.length) { - return countColumn(line, this.state.tabSize, pos); - } - /** - Find the indentation column of the line at the given point. - */ - lineIndent(pos, bias = 1) { - let { text, from } = this.lineAt(pos, bias); - let override = this.options.overrideIndentation; - if (override) { - let overriden = override(from); - if (overriden > -1) - return overriden; - } - return this.countColumn(text, text.search(/\S|$/)); - } - /** - Returns the [simulated line - break](https://codemirror.net/6/docs/ref/#language.IndentContext.constructor^options.simulateBreak) - for this context, if any. - */ - get simulatedBreak() { - return this.options.simulateBreak || null; - } - } - /** - A syntax tree node prop used to associate indentation strategies - with node types. Such a strategy is a function from an indentation - context to a column number or null, where null indicates that no - definitive indentation can be determined. - */ - const indentNodeProp = /*@__PURE__*/new NodeProp(); - // Compute the indentation for a given position from the syntax tree. - function syntaxIndentation(cx, ast, pos) { - return indentFrom(ast.resolveInner(pos).enterUnfinishedNodesBefore(pos), pos, cx); - } - function ignoreClosed(cx) { - return cx.pos == cx.options.simulateBreak && cx.options.simulateDoubleBreak; - } - function indentStrategy(tree) { - let strategy = tree.type.prop(indentNodeProp); - if (strategy) - return strategy; - let first = tree.firstChild, close; - if (first && (close = first.type.prop(NodeProp.closedBy))) { - let last = tree.lastChild, closed = last && close.indexOf(last.name) > -1; - return cx => delimitedStrategy(cx, true, 1, undefined, closed && !ignoreClosed(cx) ? last.from : undefined); - } - return tree.parent == null ? topIndent$1 : null; - } - function indentFrom(node, pos, base) { - for (; node; node = node.parent) { - let strategy = indentStrategy(node); - if (strategy) - return strategy(new TreeIndentContext(base, pos, node)); - } - return null; - } - function topIndent$1() { return 0; } - /** - Objects of this type provide context information and helper - methods to indentation functions. - */ - class TreeIndentContext extends IndentContext { - /** - @internal - */ - constructor(base, - /** - The position at which indentation is being computed. - */ - pos, - /** - The syntax tree node to which the indentation strategy - applies. - */ - node) { - super(base.state, base.options); - this.base = base; - this.pos = pos; - this.node = node; - } - /** - Get the text directly after `this.pos`, either the entire line - or the next 100 characters, whichever is shorter. - */ - get textAfter() { - return this.textAfterPos(this.pos); - } - /** - Get the indentation at the reference line for `this.node`, which - is the line on which it starts, unless there is a node that is - _not_ a parent of this node covering the start of that line. If - so, the line at the start of that node is tried, again skipping - on if it is covered by another such node. - */ - get baseIndent() { - let line = this.state.doc.lineAt(this.node.from); - // Skip line starts that are covered by a sibling (or cousin, etc) - for (;;) { - let atBreak = this.node.resolve(line.from); - while (atBreak.parent && atBreak.parent.from == atBreak.from) - atBreak = atBreak.parent; - if (isParent(atBreak, this.node)) - break; - line = this.state.doc.lineAt(atBreak.from); - } - return this.lineIndent(line.from); - } - /** - Continue looking for indentations in the node's parent nodes, - and return the result of that. - */ - continue() { - let parent = this.node.parent; - return parent ? indentFrom(parent, this.pos, this.base) : 0; - } - } - function isParent(parent, of) { - for (let cur = of; cur; cur = cur.parent) - if (parent == cur) - return true; - return false; - } - // Check whether a delimited node is aligned (meaning there are - // non-skipped nodes on the same line as the opening delimiter). And - // if so, return the opening token. - function bracketedAligned(context) { - let tree = context.node; - let openToken = tree.childAfter(tree.from), last = tree.lastChild; - if (!openToken) - return null; - let sim = context.options.simulateBreak; - let openLine = context.state.doc.lineAt(openToken.from); - let lineEnd = sim == null || sim <= openLine.from ? openLine.to : Math.min(openLine.to, sim); - for (let pos = openToken.to;;) { - let next = tree.childAfter(pos); - if (!next || next == last) - return null; - if (!next.type.isSkipped) - return next.from < lineEnd ? openToken : null; - pos = next.to; - } - } - /** - An indentation strategy for delimited (usually bracketed) nodes. - Will, by default, indent one unit more than the parent's base - indent unless the line starts with a closing token. When `align` - is true and there are non-skipped nodes on the node's opening - line, the content of the node will be aligned with the end of the - opening node, like this: - - foo(bar, - baz) - */ - function delimitedIndent({ closing, align = true, units = 1 }) { - return (context) => delimitedStrategy(context, align, units, closing); - } - function delimitedStrategy(context, align, units, closing, closedAt) { - let after = context.textAfter, space = after.match(/^\s*/)[0].length; - let closed = closing && after.slice(space, space + closing.length) == closing || closedAt == context.pos + space; - let aligned = align ? bracketedAligned(context) : null; - if (aligned) - return closed ? context.column(aligned.from) : context.column(aligned.to); - return context.baseIndent + (closed ? 0 : context.unit * units); - } - const DontIndentBeyond = 200; - /** - Enables reindentation on input. When a language defines an - `indentOnInput` field in its [language - data](https://codemirror.net/6/docs/ref/#state.EditorState.languageDataAt), which must hold a regular - expression, the line at the cursor will be reindented whenever new - text is typed and the input from the start of the line up to the - cursor matches that regexp. - - To avoid unneccesary reindents, it is recommended to start the - regexp with `^` (usually followed by `\s*`), and end it with `$`. - For example, `/^\s*\}$/` will reindent when a closing brace is - added at the start of a line. - */ - function indentOnInput() { - return EditorState.transactionFilter.of(tr => { - if (!tr.docChanged || !tr.isUserEvent("input.type") && !tr.isUserEvent("input.complete")) - return tr; - let rules = tr.startState.languageDataAt("indentOnInput", tr.startState.selection.main.head); - if (!rules.length) - return tr; - let doc = tr.newDoc, { head } = tr.newSelection.main, line = doc.lineAt(head); - if (head > line.from + DontIndentBeyond) - return tr; - let lineStart = doc.sliceString(line.from, head); - if (!rules.some(r => r.test(lineStart))) - return tr; - let { state } = tr, last = -1, changes = []; - for (let { head } of state.selection.ranges) { - let line = state.doc.lineAt(head); - if (line.from == last) - continue; - last = line.from; - let indent = getIndentation(state, line.from); - if (indent == null) - continue; - let cur = /^\s*/.exec(line.text)[0]; - let norm = indentString(state, indent); - if (cur != norm) - changes.push({ from: line.from, to: line.from + cur.length, insert: norm }); - } - return changes.length ? [tr, { changes, sequential: true }] : tr; - }); - } - - /** - A facet that registers a code folding service. When called with - the extent of a line, such a function should return a foldable - range that starts on that line (but continues beyond it), if one - can be found. - */ - const foldService = /*@__PURE__*/Facet.define(); - /** - This node prop is used to associate folding information with - syntax node types. Given a syntax node, it should check whether - that tree is foldable and return the range that can be collapsed - when it is. - */ - const foldNodeProp = /*@__PURE__*/new NodeProp(); - /** - [Fold](https://codemirror.net/6/docs/ref/#language.foldNodeProp) function that folds everything but - the first and the last child of a syntax node. Useful for nodes - that start and end with delimiters. - */ - function foldInside$1(node) { - let first = node.firstChild, last = node.lastChild; - return first && first.to < last.from ? { from: first.to, to: last.type.isError ? node.to : last.from } : null; - } - function syntaxFolding(state, start, end) { - let tree = syntaxTree(state); - if (tree.length == 0) - return null; - let inner = tree.resolveInner(end); - let found = null; - for (let cur = inner; cur; cur = cur.parent) { - if (cur.to <= end || cur.from > end) - continue; - if (found && cur.from < start) - break; - let prop = cur.type.prop(foldNodeProp); - if (prop && (cur.to < tree.length - 50 || tree.length == state.doc.length || !isUnfinished(cur))) { - let value = prop(cur, state); - if (value && value.from <= end && value.from >= start && value.to > end) - found = value; - } - } - return found; - } - function isUnfinished(node) { - let ch = node.lastChild; - return ch && ch.to == node.to && ch.type.isError; - } - /** - Check whether the given line is foldable. First asks any fold - services registered through - [`foldService`](https://codemirror.net/6/docs/ref/#language.foldService), and if none of them return - a result, tries to query the [fold node - prop](https://codemirror.net/6/docs/ref/#language.foldNodeProp) of syntax nodes that cover the end - of the line. - */ - function foldable(state, lineStart, lineEnd) { - for (let service of state.facet(foldService)) { - let result = service(state, lineStart, lineEnd); - if (result) - return result; - } - return syntaxFolding(state, lineStart, lineEnd); - } - - /** - A gutter marker represents a bit of information attached to a line - in a specific gutter. Your own custom markers have to extend this - class. - */ - class GutterMarker extends RangeValue { - /** - @internal - */ - compare(other) { - return this == other || this.constructor == other.constructor && this.eq(other); - } - /** - Compare this marker to another marker of the same type. - */ - eq(other) { return false; } - /** - Called if the marker has a `toDOM` method and its representation - was removed from a gutter. - */ - destroy(dom) { } - } - GutterMarker.prototype.elementClass = ""; - GutterMarker.prototype.toDOM = undefined; - GutterMarker.prototype.mapMode = MapMode.TrackBefore; - GutterMarker.prototype.startSide = GutterMarker.prototype.endSide = -1; - GutterMarker.prototype.point = true; - /** - Facet used to add a class to all gutter elements for a given line. - Markers given to this facet should _only_ define an - [`elementclass`](https://codemirror.net/6/docs/ref/#gutter.GutterMarker.elementClass), not a - [`toDOM`](https://codemirror.net/6/docs/ref/#gutter.GutterMarker.toDOM) (or the marker will appear - in all gutters for the line). - */ - const gutterLineClass = /*@__PURE__*/Facet.define(); - const defaults$1 = { - class: "", - renderEmptyElements: false, - elementStyle: "", - markers: () => RangeSet.empty, - lineMarker: () => null, - lineMarkerChange: null, - initialSpacer: null, - updateSpacer: null, - domEventHandlers: {} - }; - const activeGutters = /*@__PURE__*/Facet.define(); - /** - Define an editor gutter. The order in which the gutters appear is - determined by their extension priority. - */ - function gutter(config) { - return [gutters(), activeGutters.of(Object.assign(Object.assign({}, defaults$1), config))]; - } - const baseTheme$7 = /*@__PURE__*/EditorView.baseTheme({ - ".cm-gutters": { - display: "flex", - height: "100%", - boxSizing: "border-box", - left: 0, - zIndex: 200 - }, - "&light .cm-gutters": { - backgroundColor: "#f5f5f5", - color: "#999", - 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" - } - }); - const unfixGutters = /*@__PURE__*/Facet.define({ - combine: values => values.some(x => x) - }); - /** - The gutter-drawing plugin is automatically enabled when you add a - gutter, but you can use this function to explicitly configure it. - - Unless `fixed` is explicitly set to `false`, the gutters are - fixed, meaning they don't scroll along with the content - horizontally (except on Internet Explorer, which doesn't support - CSS [`position: - sticky`](https://developer.mozilla.org/en-US/docs/Web/CSS/position#sticky)). - */ - function gutters(config) { - let result = [ - gutterView, - baseTheme$7 - ]; - if (config && config.fixed === false) - result.push(unfixGutters.of(true)); - return result; - } - const gutterView = /*@__PURE__*/ViewPlugin.fromClass(class { - constructor(view) { - this.view = view; - this.prevViewport = view.viewport; - this.dom = document.createElement("div"); - this.dom.className = "cm-gutters"; - this.dom.setAttribute("aria-hidden", "true"); - this.dom.style.minHeight = this.view.contentHeight + "px"; - this.gutters = view.state.facet(activeGutters).map(conf => new SingleGutterView(view, conf)); - for (let gutter of this.gutters) - this.dom.appendChild(gutter.dom); - this.fixed = !view.state.facet(unfixGutters); - if (this.fixed) { - // FIXME IE11 fallback, which doesn't support position: sticky, - // by using position: relative + event handlers that realign the - // gutter (or just force fixed=false on IE11?) - this.dom.style.position = "sticky"; - } - this.syncGutters(false); - view.scrollDOM.insertBefore(this.dom, view.contentDOM); - } - update(update) { - if (this.updateGutters(update)) { - // Detach during sync when the viewport changed significantly - // (such as during scrolling), since for large updates that is - // faster. - let vpA = this.prevViewport, vpB = update.view.viewport; - let vpOverlap = Math.min(vpA.to, vpB.to) - Math.max(vpA.from, vpB.from); - this.syncGutters(vpOverlap < (vpB.to - vpB.from) * 0.8); - } - if (update.geometryChanged) - this.dom.style.minHeight = this.view.contentHeight + "px"; - if (this.view.state.facet(unfixGutters) != !this.fixed) { - this.fixed = !this.fixed; - this.dom.style.position = this.fixed ? "sticky" : ""; - } - this.prevViewport = update.view.viewport; - } - syncGutters(detach) { - let after = this.dom.nextSibling; - if (detach) - this.dom.remove(); - let lineClasses = RangeSet.iter(this.view.state.facet(gutterLineClass), this.view.viewport.from); - let classSet = []; - let contexts = this.gutters.map(gutter => new UpdateContext(gutter, this.view.viewport, -this.view.documentPadding.top)); - for (let line of this.view.viewportLineBlocks) { - let text; - if (Array.isArray(line.type)) { - for (let b of line.type) - if (b.type == BlockType.Text) { - text = b; - break; - } - } - else { - text = line.type == BlockType.Text ? line : undefined; - } - if (!text) - continue; - if (classSet.length) - classSet = []; - advanceCursor(lineClasses, classSet, line.from); - for (let cx of contexts) - cx.line(this.view, text, classSet); - } - for (let cx of contexts) - cx.finish(); - if (detach) - this.view.scrollDOM.insertBefore(this.dom, after); - } - updateGutters(update) { - let prev = update.startState.facet(activeGutters), cur = update.state.facet(activeGutters); - let change = update.docChanged || update.heightChanged || update.viewportChanged || - !RangeSet.eq(update.startState.facet(gutterLineClass), update.state.facet(gutterLineClass), update.view.viewport.from, update.view.viewport.to); - if (prev == cur) { - for (let gutter of this.gutters) - if (gutter.update(update)) - change = true; - } - else { - change = true; - let gutters = []; - for (let conf of cur) { - let known = prev.indexOf(conf); - if (known < 0) { - gutters.push(new SingleGutterView(this.view, conf)); - } - else { - this.gutters[known].update(update); - gutters.push(this.gutters[known]); - } - } - for (let g of this.gutters) { - g.dom.remove(); - if (gutters.indexOf(g) < 0) - g.destroy(); - } - for (let g of gutters) - this.dom.appendChild(g.dom); - this.gutters = gutters; - } - return change; - } - destroy() { - for (let view of this.gutters) - view.destroy(); - this.dom.remove(); - } - }, { - provide: /*@__PURE__*/PluginField.scrollMargins.from(value => { - if (value.gutters.length == 0 || !value.fixed) - return null; - return value.view.textDirection == Direction.LTR ? { left: value.dom.offsetWidth } : { right: value.dom.offsetWidth }; - }) - }); - function asArray(val) { return (Array.isArray(val) ? val : [val]); } - function advanceCursor(cursor, collect, pos) { - while (cursor.value && cursor.from <= pos) { - if (cursor.from == pos) - collect.push(cursor.value); - cursor.next(); - } - } - class UpdateContext { - constructor(gutter, viewport, height) { - this.gutter = gutter; - this.height = height; - this.localMarkers = []; - this.i = 0; - this.cursor = RangeSet.iter(gutter.markers, viewport.from); - } - line(view, line, extraMarkers) { - if (this.localMarkers.length) - this.localMarkers = []; - advanceCursor(this.cursor, this.localMarkers, line.from); - let localMarkers = extraMarkers.length ? this.localMarkers.concat(extraMarkers) : this.localMarkers; - let forLine = this.gutter.config.lineMarker(view, line, localMarkers); - if (forLine) - localMarkers.unshift(forLine); - let gutter = this.gutter; - if (localMarkers.length == 0 && !gutter.config.renderEmptyElements) - return; - let above = line.top - this.height; - if (this.i == gutter.elements.length) { - let newElt = new GutterElement(view, line.height, above, localMarkers); - gutter.elements.push(newElt); - gutter.dom.appendChild(newElt.dom); - } - else { - gutter.elements[this.i].update(view, line.height, above, localMarkers); - } - this.height = line.bottom; - this.i++; - } - finish() { - let gutter = this.gutter; - while (gutter.elements.length > this.i) { - let last = gutter.elements.pop(); - gutter.dom.removeChild(last.dom); - last.destroy(); - } - } - } - class SingleGutterView { - constructor(view, config) { - this.view = view; - this.config = config; - this.elements = []; - this.spacer = null; - this.dom = document.createElement("div"); - this.dom.className = "cm-gutter" + (this.config.class ? " " + this.config.class : ""); - for (let prop in config.domEventHandlers) { - this.dom.addEventListener(prop, (event) => { - let line = view.lineBlockAtHeight(event.clientY - view.documentTop); - if (config.domEventHandlers[prop](view, line, event)) - event.preventDefault(); - }); - } - this.markers = asArray(config.markers(view)); - if (config.initialSpacer) { - this.spacer = new GutterElement(view, 0, 0, [config.initialSpacer(view)]); - this.dom.appendChild(this.spacer.dom); - this.spacer.dom.style.cssText += "visibility: hidden; pointer-events: none"; - } - } - update(update) { - let prevMarkers = this.markers; - this.markers = asArray(this.config.markers(update.view)); - if (this.spacer && this.config.updateSpacer) { - let updated = this.config.updateSpacer(this.spacer.markers[0], update); - if (updated != this.spacer.markers[0]) - this.spacer.update(update.view, 0, 0, [updated]); - } - let vp = update.view.viewport; - return !RangeSet.eq(this.markers, prevMarkers, vp.from, vp.to) || - (this.config.lineMarkerChange ? this.config.lineMarkerChange(update) : false); - } - destroy() { - for (let elt of this.elements) - elt.destroy(); - } - } - class GutterElement { - constructor(view, height, above, markers) { - this.height = -1; - this.above = 0; - this.markers = []; - this.dom = document.createElement("div"); - this.update(view, height, above, markers); - } - update(view, height, above, markers) { - if (this.height != height) - this.dom.style.height = (this.height = height) + "px"; - if (this.above != above) - this.dom.style.marginTop = (this.above = above) ? above + "px" : ""; - if (!sameMarkers(this.markers, markers)) - this.setMarkers(view, markers); - } - setMarkers(view, markers) { - let cls = "cm-gutterElement", domPos = this.dom.firstChild; - for (let iNew = 0, iOld = 0;;) { - let skipTo = iOld, marker = iNew < markers.length ? markers[iNew++] : null, matched = false; - if (marker) { - let c = marker.elementClass; - if (c) - cls += " " + c; - for (let i = iOld; i < this.markers.length; i++) - if (this.markers[i].compare(marker)) { - skipTo = i; - matched = true; - break; - } - } - else { - skipTo = this.markers.length; - } - while (iOld < skipTo) { - let next = this.markers[iOld++]; - if (next.toDOM) { - next.destroy(domPos); - let after = domPos.nextSibling; - domPos.remove(); - domPos = after; - } - } - if (!marker) - break; - if (marker.toDOM) { - if (matched) - domPos = domPos.nextSibling; - else - this.dom.insertBefore(marker.toDOM(view), domPos); - } - if (matched) - iOld++; - } - this.dom.className = cls; - this.markers = markers; - } - destroy() { - this.setMarkers(null, []); // First argument not used unless creating markers - } - } - function sameMarkers(a, b) { - if (a.length != b.length) - return false; - for (let i = 0; i < a.length; i++) - if (!a[i].compare(b[i])) - return false; - return true; - } - /** - Facet used to provide markers to the line number gutter. - */ - const lineNumberMarkers = /*@__PURE__*/Facet.define(); - const lineNumberConfig = /*@__PURE__*/Facet.define({ - combine(values) { - return combineConfig(values, { formatNumber: String, domEventHandlers: {} }, { - domEventHandlers(a, b) { - let result = Object.assign({}, a); - for (let event in b) { - let exists = result[event], add = b[event]; - result[event] = exists ? (view, line, event) => exists(view, line, event) || add(view, line, event) : add; - } - return result; - } - }); - } - }); - class NumberMarker extends GutterMarker { - constructor(number) { - super(); - this.number = number; - } - eq(other) { return this.number == other.number; } - toDOM() { return document.createTextNode(this.number); } - } - function formatNumber(view, number) { - return view.state.facet(lineNumberConfig).formatNumber(number, view.state); - } - const lineNumberGutter = /*@__PURE__*/activeGutters.compute([lineNumberConfig], state => ({ - class: "cm-lineNumbers", - renderEmptyElements: false, - markers(view) { return view.state.facet(lineNumberMarkers); }, - lineMarker(view, line, others) { - if (others.some(m => m.toDOM)) - return null; - return new NumberMarker(formatNumber(view, view.state.doc.lineAt(line.from).number)); - }, - lineMarkerChange: update => update.startState.facet(lineNumberConfig) != update.state.facet(lineNumberConfig), - initialSpacer(view) { - return new NumberMarker(formatNumber(view, maxLineNumber(view.state.doc.lines))); - }, - updateSpacer(spacer, update) { - let max = formatNumber(update.view, maxLineNumber(update.view.state.doc.lines)); - return max == spacer.number ? spacer : new NumberMarker(max); - }, - domEventHandlers: state.facet(lineNumberConfig).domEventHandlers - })); - /** - Create a line number gutter extension. - */ - function lineNumbers(config = {}) { - return [ - lineNumberConfig.of(config), - gutters(), - lineNumberGutter - ]; - } - function maxLineNumber(lines) { - let last = 9; - while (last < lines) - last = last * 10 + 9; - return last; - } - const activeLineGutterMarker = /*@__PURE__*/new class extends GutterMarker { - constructor() { - super(...arguments); - this.elementClass = "cm-activeLineGutter"; - } - }; - const activeLineGutterHighlighter = /*@__PURE__*/gutterLineClass.compute(["selection"], state => { - let marks = [], last = -1; - for (let range of state.selection.ranges) - if (range.empty) { - let linePos = state.doc.lineAt(range.head).from; - if (linePos > last) { - last = linePos; - marks.push(activeLineGutterMarker.range(linePos)); - } - } - return RangeSet.of(marks); - }); - /** - Returns an extension that adds a `cm-activeLineGutter` class to - all gutter elements on the [active - line](https://codemirror.net/6/docs/ref/#view.highlightActiveLine). - */ - function highlightActiveLineGutter() { - return activeLineGutterHighlighter; - } - - function mapRange(range, mapping) { - let from = mapping.mapPos(range.from, 1), to = mapping.mapPos(range.to, -1); - return from >= to ? undefined : { from, to }; - } - /** - State effect that can be attached to a transaction to fold the - given range. (You probably only need this in exceptional - circumstances—usually you'll just want to let - [`foldCode`](https://codemirror.net/6/docs/ref/#fold.foldCode) and the [fold - gutter](https://codemirror.net/6/docs/ref/#fold.foldGutter) create the transactions.) - */ - const foldEffect = /*@__PURE__*/StateEffect.define({ map: mapRange }); - /** - State effect that unfolds the given range (if it was folded). - */ - const unfoldEffect = /*@__PURE__*/StateEffect.define({ map: mapRange }); - function selectedLines(view) { - let lines = []; - for (let { head } of view.state.selection.ranges) { - if (lines.some(l => l.from <= head && l.to >= head)) - continue; - lines.push(view.lineBlockAt(head)); - } - return lines; - } - const foldState = /*@__PURE__*/StateField.define({ - create() { - return Decoration.none; - }, - update(folded, tr) { - folded = folded.map(tr.changes); - for (let e of tr.effects) { - if (e.is(foldEffect) && !foldExists(folded, e.value.from, e.value.to)) - folded = folded.update({ add: [foldWidget.range(e.value.from, e.value.to)] }); - else if (e.is(unfoldEffect)) - folded = folded.update({ filter: (from, to) => e.value.from != from || e.value.to != to, - filterFrom: e.value.from, filterTo: e.value.to }); - } - // Clear folded ranges that cover the selection head - if (tr.selection) { - let onSelection = false, { head } = tr.selection.main; - folded.between(head, head, (a, b) => { if (a < head && b > head) - onSelection = true; }); - if (onSelection) - folded = folded.update({ - filterFrom: head, - filterTo: head, - filter: (a, b) => b <= head || a >= head - }); - } - return folded; - }, - provide: f => EditorView.decorations.from(f) - }); - function foldInside(state, from, to) { - var _a; - let found = null; - (_a = state.field(foldState, false)) === null || _a === void 0 ? void 0 : _a.between(from, to, (from, to) => { - if (!found || found.from > from) - found = { from, to }; - }); - return found; - } - function foldExists(folded, from, to) { - let found = false; - folded.between(from, from, (a, b) => { if (a == from && b == to) - found = true; }); - return found; - } - function maybeEnable(state, other) { - return state.field(foldState, false) ? other : other.concat(StateEffect.appendConfig.of(codeFolding())); - } - /** - Fold the lines that are selected, if possible. - */ - const foldCode = view => { - for (let line of selectedLines(view)) { - let range = foldable(view.state, line.from, line.to); - if (range) { - view.dispatch({ effects: maybeEnable(view.state, [foldEffect.of(range), announceFold(view, range)]) }); - return true; - } - } - return false; - }; - /** - Unfold folded ranges on selected lines. - */ - const unfoldCode = view => { - if (!view.state.field(foldState, false)) - return false; - let effects = []; - for (let line of selectedLines(view)) { - let folded = foldInside(view.state, line.from, line.to); - if (folded) - effects.push(unfoldEffect.of(folded), announceFold(view, folded, false)); - } - if (effects.length) - view.dispatch({ effects }); - return effects.length > 0; - }; - function announceFold(view, range, fold = true) { - let lineFrom = view.state.doc.lineAt(range.from).number, lineTo = view.state.doc.lineAt(range.to).number; - return EditorView.announce.of(`${view.state.phrase(fold ? "Folded lines" : "Unfolded lines")} ${lineFrom} ${view.state.phrase("to")} ${lineTo}.`); - } - /** - Fold all top-level foldable ranges. - */ - const foldAll = view => { - let { state } = view, effects = []; - for (let pos = 0; pos < state.doc.length;) { - let line = view.lineBlockAt(pos), range = foldable(state, line.from, line.to); - if (range) - effects.push(foldEffect.of(range)); - pos = (range ? view.lineBlockAt(range.to) : line).to + 1; - } - if (effects.length) - view.dispatch({ effects: maybeEnable(view.state, effects) }); - return !!effects.length; - }; - /** - Unfold all folded code. - */ - const unfoldAll = view => { - let field = view.state.field(foldState, false); - if (!field || !field.size) - return false; - let effects = []; - field.between(0, view.state.doc.length, (from, to) => { effects.push(unfoldEffect.of({ from, to })); }); - view.dispatch({ effects }); - return true; - }; - /** - Default fold-related key bindings. - - - Ctrl-Shift-[ (Cmd-Alt-[ on macOS): [`foldCode`](https://codemirror.net/6/docs/ref/#fold.foldCode). - - Ctrl-Shift-] (Cmd-Alt-] on macOS): [`unfoldCode`](https://codemirror.net/6/docs/ref/#fold.unfoldCode). - - Ctrl-Alt-[: [`foldAll`](https://codemirror.net/6/docs/ref/#fold.foldAll). - - Ctrl-Alt-]: [`unfoldAll`](https://codemirror.net/6/docs/ref/#fold.unfoldAll). - */ - const foldKeymap = [ - { key: "Ctrl-Shift-[", mac: "Cmd-Alt-[", run: foldCode }, - { key: "Ctrl-Shift-]", mac: "Cmd-Alt-]", run: unfoldCode }, - { key: "Ctrl-Alt-[", run: foldAll }, - { key: "Ctrl-Alt-]", run: unfoldAll } - ]; - const defaultConfig = { - placeholderDOM: null, - placeholderText: "…" - }; - const foldConfig = /*@__PURE__*/Facet.define({ - combine(values) { return combineConfig(values, defaultConfig); } - }); - /** - Create an extension that configures code folding. - */ - function codeFolding(config) { - let result = [foldState, baseTheme$6]; - if (config) - result.push(foldConfig.of(config)); - return result; - } - const foldWidget = /*@__PURE__*/Decoration.replace({ widget: /*@__PURE__*/new class extends WidgetType { - toDOM(view) { - let { state } = view, conf = state.facet(foldConfig); - let onclick = (event) => { - let line = view.lineBlockAt(view.posAtDOM(event.target)); - let folded = foldInside(view.state, line.from, line.to); - if (folded) - view.dispatch({ effects: unfoldEffect.of(folded) }); - event.preventDefault(); - }; - if (conf.placeholderDOM) - return conf.placeholderDOM(view, onclick); - let element = document.createElement("span"); - element.textContent = conf.placeholderText; - element.setAttribute("aria-label", state.phrase("folded code")); - element.title = state.phrase("unfold"); - element.className = "cm-foldPlaceholder"; - element.onclick = onclick; - return element; - } - } }); - const foldGutterDefaults = { - openText: "⌄", - closedText: "›", - markerDOM: null, - domEventHandlers: {}, - }; - class FoldMarker extends GutterMarker { - constructor(config, open) { - super(); - this.config = config; - this.open = open; - } - eq(other) { return this.config == other.config && this.open == other.open; } - toDOM(view) { - if (this.config.markerDOM) - return this.config.markerDOM(this.open); - let span = document.createElement("span"); - span.textContent = this.open ? this.config.openText : this.config.closedText; - span.title = view.state.phrase(this.open ? "Fold line" : "Unfold line"); - return span; - } - } - /** - Create an extension that registers a fold gutter, which shows a - fold status indicator before foldable lines (which can be clicked - to fold or unfold the line). - */ - function foldGutter(config = {}) { - let fullConfig = Object.assign(Object.assign({}, foldGutterDefaults), config); - let canFold = new FoldMarker(fullConfig, true), canUnfold = new FoldMarker(fullConfig, false); - let markers = ViewPlugin.fromClass(class { - constructor(view) { - this.from = view.viewport.from; - this.markers = this.buildMarkers(view); - } - update(update) { - if (update.docChanged || update.viewportChanged || - update.startState.facet(language) != update.state.facet(language) || - update.startState.field(foldState, false) != update.state.field(foldState, false) || - syntaxTree(update.startState) != syntaxTree(update.state)) - this.markers = this.buildMarkers(update.view); - } - buildMarkers(view) { - let builder = new RangeSetBuilder(); - for (let line of view.viewportLineBlocks) { - let mark = foldInside(view.state, line.from, line.to) ? canUnfold - : foldable(view.state, line.from, line.to) ? canFold : null; - if (mark) - builder.add(line.from, line.from, mark); - } - return builder.finish(); - } - }); - let { domEventHandlers } = fullConfig; - return [ - markers, - gutter({ - class: "cm-foldGutter", - markers(view) { var _a; return ((_a = view.plugin(markers)) === null || _a === void 0 ? void 0 : _a.markers) || RangeSet.empty; }, - initialSpacer() { - return new FoldMarker(fullConfig, false); - }, - domEventHandlers: Object.assign(Object.assign({}, domEventHandlers), { click: (view, line, event) => { - if (domEventHandlers.click && domEventHandlers.click(view, line, event)) - return true; - let folded = foldInside(view.state, line.from, line.to); - if (folded) { - view.dispatch({ effects: unfoldEffect.of(folded) }); - return true; - } - let range = foldable(view.state, line.from, line.to); - if (range) { - view.dispatch({ effects: foldEffect.of(range) }); - return true; - } - return false; - } }) - }), - codeFolding() - ]; - } - const baseTheme$6 = /*@__PURE__*/EditorView.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" - } - }); - - const baseTheme$5 = /*@__PURE__*/EditorView.baseTheme({ - "&.cm-focused .cm-matchingBracket": { backgroundColor: "#328c8252" }, - "&.cm-focused .cm-nonmatchingBracket": { backgroundColor: "#bb555544" } - }); - const DefaultScanDist = 10000, DefaultBrackets = "()[]{}"; - const bracketMatchingConfig = /*@__PURE__*/Facet.define({ - combine(configs) { - return combineConfig(configs, { - afterCursor: true, - brackets: DefaultBrackets, - maxScanDistance: DefaultScanDist - }); - } - }); - const matchingMark = /*@__PURE__*/Decoration.mark({ class: "cm-matchingBracket" }), nonmatchingMark = /*@__PURE__*/Decoration.mark({ class: "cm-nonmatchingBracket" }); - const bracketMatchingState = /*@__PURE__*/StateField.define({ - create() { return Decoration.none; }, - update(deco, tr) { - if (!tr.docChanged && !tr.selection) - return deco; - let decorations = []; - let config = tr.state.facet(bracketMatchingConfig); - for (let range of tr.state.selection.ranges) { - if (!range.empty) - continue; - let match = matchBrackets(tr.state, range.head, -1, config) - || (range.head > 0 && matchBrackets(tr.state, range.head - 1, 1, config)) - || (config.afterCursor && - (matchBrackets(tr.state, range.head, 1, config) || - (range.head < tr.state.doc.length && matchBrackets(tr.state, range.head + 1, -1, config)))); - if (!match) - continue; - let mark = match.matched ? matchingMark : nonmatchingMark; - decorations.push(mark.range(match.start.from, match.start.to)); - if (match.end) - decorations.push(mark.range(match.end.from, match.end.to)); - } - return Decoration.set(decorations, true); - }, - provide: f => EditorView.decorations.from(f) - }); - const bracketMatchingUnique = [ - bracketMatchingState, - baseTheme$5 - ]; - /** - Create an extension that enables bracket matching. Whenever the - cursor is next to a bracket, that bracket and the one it matches - are highlighted. Or, when no matching bracket is found, another - highlighting style is used to indicate this. - */ - function bracketMatching(config = {}) { - return [bracketMatchingConfig.of(config), bracketMatchingUnique]; - } - function matchingNodes(node, dir, brackets) { - let byProp = node.prop(dir < 0 ? NodeProp.openedBy : NodeProp.closedBy); - if (byProp) - return byProp; - if (node.name.length == 1) { - let index = brackets.indexOf(node.name); - if (index > -1 && index % 2 == (dir < 0 ? 1 : 0)) - return [brackets[index + dir]]; - } - return null; - } - /** - Find the matching bracket for the token at `pos`, scanning - direction `dir`. Only the `brackets` and `maxScanDistance` - properties are used from `config`, if given. Returns null if no - bracket was found at `pos`, or a match result otherwise. - */ - function matchBrackets(state, pos, dir, config = {}) { - let maxScanDistance = config.maxScanDistance || DefaultScanDist, brackets = config.brackets || DefaultBrackets; - let tree = syntaxTree(state), node = tree.resolveInner(pos, dir); - for (let cur = node; cur; cur = cur.parent) { - let matches = matchingNodes(cur.type, dir, brackets); - if (matches && cur.from < cur.to) - return matchMarkedBrackets(state, pos, dir, cur, matches, brackets); - } - return matchPlainBrackets(state, pos, dir, tree, node.type, maxScanDistance, brackets); - } - function matchMarkedBrackets(_state, _pos, dir, token, matching, brackets) { - let parent = token.parent, firstToken = { from: token.from, to: token.to }; - let depth = 0, cursor = parent === null || parent === void 0 ? void 0 : parent.cursor; - if (cursor && (dir < 0 ? cursor.childBefore(token.from) : cursor.childAfter(token.to))) - do { - if (dir < 0 ? cursor.to <= token.from : cursor.from >= token.to) { - if (depth == 0 && matching.indexOf(cursor.type.name) > -1 && cursor.from < cursor.to) { - return { start: firstToken, end: { from: cursor.from, to: cursor.to }, matched: true }; - } - else if (matchingNodes(cursor.type, dir, brackets)) { - depth++; - } - else if (matchingNodes(cursor.type, -dir, brackets)) { - depth--; - if (depth == 0) - return { - start: firstToken, - end: cursor.from == cursor.to ? undefined : { from: cursor.from, to: cursor.to }, - matched: false - }; - } - } - } while (dir < 0 ? cursor.prevSibling() : cursor.nextSibling()); - return { start: firstToken, matched: false }; - } - function matchPlainBrackets(state, pos, dir, tree, tokenType, maxScanDistance, brackets) { - let startCh = dir < 0 ? state.sliceDoc(pos - 1, pos) : state.sliceDoc(pos, pos + 1); - let bracket = brackets.indexOf(startCh); - if (bracket < 0 || (bracket % 2 == 0) != (dir > 0)) - return null; - let startToken = { from: dir < 0 ? pos - 1 : pos, to: dir > 0 ? pos + 1 : pos }; - let iter = state.doc.iterRange(pos, dir > 0 ? state.doc.length : 0), depth = 0; - for (let distance = 0; !(iter.next()).done && distance <= maxScanDistance;) { - let text = iter.value; - if (dir < 0) - distance += text.length; - let basePos = pos + distance * dir; - for (let pos = dir > 0 ? 0 : text.length - 1, end = dir > 0 ? text.length : -1; pos != end; pos += dir) { - let found = brackets.indexOf(text[pos]); - if (found < 0 || tree.resolve(basePos + pos, 1).type != tokenType) - continue; - if ((found % 2 == 0) == (dir > 0)) { - depth++; - } - else if (depth == 1) { // Closing - return { start: startToken, end: { from: basePos + pos, to: basePos + pos + 1 }, matched: (found >> 1) == (bracket >> 1) }; - } - else { - depth--; - } - } - if (dir > 0) - distance += text.length; - } - return iter.done ? { start: startToken, matched: false } : null; - } - - function updateSel(sel, by) { - return EditorSelection.create(sel.ranges.map(by), sel.mainIndex); - } - function setSel(state, selection) { - return state.update({ selection, scrollIntoView: true, userEvent: "select" }); - } - function moveSel({ state, dispatch }, how) { - let selection = updateSel(state.selection, how); - if (selection.eq(state.selection)) - return false; - dispatch(setSel(state, selection)); - return true; - } - function rangeEnd(range, forward) { - return EditorSelection.cursor(forward ? range.to : range.from); - } - function cursorByChar(view, forward) { - return moveSel(view, range => range.empty ? view.moveByChar(range, forward) : rangeEnd(range, forward)); - } - /** - Move the selection one character to the left (which is backward in - left-to-right text, forward in right-to-left text). - */ - const cursorCharLeft = view => cursorByChar(view, view.textDirection != Direction.LTR); - /** - Move the selection one character to the right. - */ - const cursorCharRight = view => cursorByChar(view, view.textDirection == Direction.LTR); - function cursorByGroup(view, forward) { - return moveSel(view, range => range.empty ? view.moveByGroup(range, forward) : rangeEnd(range, forward)); - } - /** - Move the selection to the left across one group of word or - non-word (but also non-space) characters. - */ - const cursorGroupLeft = view => cursorByGroup(view, view.textDirection != Direction.LTR); - /** - Move the selection one group to the right. - */ - const cursorGroupRight = view => cursorByGroup(view, view.textDirection == Direction.LTR); - function interestingNode(state, node, bracketProp) { - if (node.type.prop(bracketProp)) - return true; - let len = node.to - node.from; - return len && (len > 2 || /[^\s,.;:]/.test(state.sliceDoc(node.from, node.to))) || node.firstChild; - } - function moveBySyntax(state, start, forward) { - let pos = syntaxTree(state).resolveInner(start.head); - let bracketProp = forward ? NodeProp.closedBy : NodeProp.openedBy; - // Scan forward through child nodes to see if there's an interesting - // node ahead. - for (let at = start.head;;) { - let next = forward ? pos.childAfter(at) : pos.childBefore(at); - if (!next) - break; - if (interestingNode(state, next, bracketProp)) - pos = next; - else - at = forward ? next.to : next.from; - } - let bracket = pos.type.prop(bracketProp), match, newPos; - if (bracket && (match = forward ? matchBrackets(state, pos.from, 1) : matchBrackets(state, pos.to, -1)) && match.matched) - newPos = forward ? match.end.to : match.end.from; - else - newPos = forward ? pos.to : pos.from; - return EditorSelection.cursor(newPos, forward ? -1 : 1); - } - /** - Move the cursor over the next syntactic element to the left. - */ - const cursorSyntaxLeft = view => moveSel(view, range => moveBySyntax(view.state, range, view.textDirection != Direction.LTR)); - /** - Move the cursor over the next syntactic element to the right. - */ - const cursorSyntaxRight = view => moveSel(view, range => moveBySyntax(view.state, range, view.textDirection == Direction.LTR)); - function cursorByLine(view, forward) { - return moveSel(view, range => { - if (!range.empty) - return rangeEnd(range, forward); - let moved = view.moveVertically(range, forward); - return moved.head != range.head ? moved : view.moveToLineBoundary(range, forward); - }); - } - /** - Move the selection one line up. - */ - const cursorLineUp = view => cursorByLine(view, false); - /** - Move the selection one line down. - */ - const cursorLineDown = view => cursorByLine(view, true); - function cursorByPage(view, forward) { - let { state } = view, selection = updateSel(state.selection, range => { - return range.empty ? view.moveVertically(range, forward, view.dom.clientHeight) : rangeEnd(range, forward); - }); - if (selection.eq(state.selection)) - return false; - let startPos = view.coordsAtPos(state.selection.main.head); - let scrollRect = view.scrollDOM.getBoundingClientRect(); - view.dispatch(setSel(state, selection), { - effects: startPos && startPos.top > scrollRect.top && startPos.bottom < scrollRect.bottom - ? EditorView.scrollIntoView(selection.main.head, { y: "start", yMargin: startPos.top - scrollRect.top }) - : undefined - }); - return true; - } - /** - Move the selection one page up. - */ - const cursorPageUp = view => cursorByPage(view, false); - /** - Move the selection one page down. - */ - const cursorPageDown = view => cursorByPage(view, true); - function moveByLineBoundary(view, start, forward) { - let line = view.lineBlockAt(start.head), moved = view.moveToLineBoundary(start, forward); - if (moved.head == start.head && moved.head != (forward ? line.to : line.from)) - moved = view.moveToLineBoundary(start, forward, false); - if (!forward && moved.head == line.from && line.length) { - let space = /^\s*/.exec(view.state.sliceDoc(line.from, Math.min(line.from + 100, line.to)))[0].length; - if (space && start.head != line.from + space) - moved = EditorSelection.cursor(line.from + space); - } - return moved; - } - /** - Move the selection to the next line wrap point, or to the end of - the line if there isn't one left on this line. - */ - const cursorLineBoundaryForward = view => moveSel(view, range => moveByLineBoundary(view, range, true)); - /** - Move the selection to previous line wrap point, or failing that to - the start of the line. If the line is indented, and the cursor - isn't already at the end of the indentation, this will move to the - end of the indentation instead of the start of the line. - */ - const cursorLineBoundaryBackward = view => moveSel(view, range => moveByLineBoundary(view, range, false)); - /** - Move the selection to the start of the line. - */ - const cursorLineStart = view => moveSel(view, range => EditorSelection.cursor(view.lineBlockAt(range.head).from, 1)); - /** - Move the selection to the end of the line. - */ - const cursorLineEnd = view => moveSel(view, range => EditorSelection.cursor(view.lineBlockAt(range.head).to, -1)); - function toMatchingBracket(state, dispatch, extend) { - let found = false, selection = updateSel(state.selection, range => { - let matching = matchBrackets(state, range.head, -1) - || matchBrackets(state, range.head, 1) - || (range.head > 0 && matchBrackets(state, range.head - 1, 1)) - || (range.head < state.doc.length && matchBrackets(state, range.head + 1, -1)); - if (!matching || !matching.end) - return range; - found = true; - let head = matching.start.from == range.head ? matching.end.to : matching.end.from; - return extend ? EditorSelection.range(range.anchor, head) : EditorSelection.cursor(head); - }); - if (!found) - return false; - dispatch(setSel(state, selection)); - return true; - } - /** - Move the selection to the bracket matching the one it is currently - on, if any. - */ - const cursorMatchingBracket = ({ state, dispatch }) => toMatchingBracket(state, dispatch, false); - function extendSel(view, how) { - let selection = updateSel(view.state.selection, range => { - let head = how(range); - return EditorSelection.range(range.anchor, head.head, head.goalColumn); - }); - if (selection.eq(view.state.selection)) - return false; - view.dispatch(setSel(view.state, selection)); - return true; - } - function selectByChar(view, forward) { - return extendSel(view, range => view.moveByChar(range, forward)); - } - /** - Move the selection head one character to the left, while leaving - the anchor in place. - */ - const selectCharLeft = view => selectByChar(view, view.textDirection != Direction.LTR); - /** - Move the selection head one character to the right. - */ - const selectCharRight = view => selectByChar(view, view.textDirection == Direction.LTR); - function selectByGroup(view, forward) { - return extendSel(view, range => view.moveByGroup(range, forward)); - } - /** - Move the selection head one [group](https://codemirror.net/6/docs/ref/#commands.cursorGroupLeft) to - the left. - */ - const selectGroupLeft = view => selectByGroup(view, view.textDirection != Direction.LTR); - /** - Move the selection head one group to the right. - */ - const selectGroupRight = view => selectByGroup(view, view.textDirection == Direction.LTR); - /** - Move the selection head over the next syntactic element to the left. - */ - const selectSyntaxLeft = view => extendSel(view, range => moveBySyntax(view.state, range, view.textDirection != Direction.LTR)); - /** - Move the selection head over the next syntactic element to the right. - */ - const selectSyntaxRight = view => extendSel(view, range => moveBySyntax(view.state, range, view.textDirection == Direction.LTR)); - function selectByLine(view, forward) { - return extendSel(view, range => view.moveVertically(range, forward)); - } - /** - Move the selection head one line up. - */ - const selectLineUp = view => selectByLine(view, false); - /** - Move the selection head one line down. - */ - const selectLineDown = view => selectByLine(view, true); - function selectByPage(view, forward) { - return extendSel(view, range => view.moveVertically(range, forward, view.dom.clientHeight)); - } - /** - Move the selection head one page up. - */ - const selectPageUp = view => selectByPage(view, false); - /** - Move the selection head one page down. - */ - const selectPageDown = view => selectByPage(view, true); - /** - Move the selection head to the next line boundary. - */ - const selectLineBoundaryForward = view => extendSel(view, range => moveByLineBoundary(view, range, true)); - /** - Move the selection head to the previous line boundary. - */ - const selectLineBoundaryBackward = view => extendSel(view, range => moveByLineBoundary(view, range, false)); - /** - Move the selection head to the start of the line. - */ - const selectLineStart = view => extendSel(view, range => EditorSelection.cursor(view.lineBlockAt(range.head).from)); - /** - Move the selection head to the end of the line. - */ - const selectLineEnd = view => extendSel(view, range => EditorSelection.cursor(view.lineBlockAt(range.head).to)); - /** - Move the selection to the start of the document. - */ - const cursorDocStart = ({ state, dispatch }) => { - dispatch(setSel(state, { anchor: 0 })); - return true; - }; - /** - Move the selection to the end of the document. - */ - const cursorDocEnd = ({ state, dispatch }) => { - dispatch(setSel(state, { anchor: state.doc.length })); - return true; - }; - /** - Move the selection head to the start of the document. - */ - const selectDocStart = ({ state, dispatch }) => { - dispatch(setSel(state, { anchor: state.selection.main.anchor, head: 0 })); - return true; - }; - /** - Move the selection head to the end of the document. - */ - const selectDocEnd = ({ state, dispatch }) => { - dispatch(setSel(state, { anchor: state.selection.main.anchor, head: state.doc.length })); - return true; - }; - /** - Select the entire document. - */ - const selectAll = ({ state, dispatch }) => { - dispatch(state.update({ selection: { anchor: 0, head: state.doc.length }, userEvent: "select" })); - return true; - }; - /** - Expand the selection to cover entire lines. - */ - const selectLine = ({ state, dispatch }) => { - let ranges = selectedLineBlocks(state).map(({ from, to }) => EditorSelection.range(from, Math.min(to + 1, state.doc.length))); - dispatch(state.update({ selection: EditorSelection.create(ranges), userEvent: "select" })); - return true; - }; - /** - Select the next syntactic construct that is larger than the - selection. Note that this will only work insofar as the language - [provider](https://codemirror.net/6/docs/ref/#language.language) you use builds up a full - syntax tree. - */ - const selectParentSyntax = ({ state, dispatch }) => { - let selection = updateSel(state.selection, range => { - var _a; - let context = syntaxTree(state).resolveInner(range.head, 1); - while (!((context.from < range.from && context.to >= range.to) || - (context.to > range.to && context.from <= range.from) || - !((_a = context.parent) === null || _a === void 0 ? void 0 : _a.parent))) - context = context.parent; - return EditorSelection.range(context.to, context.from); - }); - dispatch(setSel(state, selection)); - return true; - }; - /** - Simplify the current selection. When multiple ranges are selected, - reduce it to its main range. Otherwise, if the selection is - non-empty, convert it to a cursor selection. - */ - const simplifySelection = ({ state, dispatch }) => { - let cur = state.selection, selection = null; - if (cur.ranges.length > 1) - selection = EditorSelection.create([cur.main]); - else if (!cur.main.empty) - selection = EditorSelection.create([EditorSelection.cursor(cur.main.head)]); - if (!selection) - return false; - dispatch(setSel(state, selection)); - return true; - }; - function deleteBy({ state, dispatch }, by) { - if (state.readOnly) - return false; - let event = "delete.selection"; - let changes = state.changeByRange(range => { - let { from, to } = range; - if (from == to) { - let towards = by(from); - if (towards < from) - event = "delete.backward"; - else if (towards > from) - event = "delete.forward"; - from = Math.min(from, towards); - to = Math.max(to, towards); - } - return from == to ? { range } : { changes: { from, to }, range: EditorSelection.cursor(from) }; - }); - if (changes.changes.empty) - return false; - dispatch(state.update(changes, { scrollIntoView: true, userEvent: event })); - return true; - } - function skipAtomic(target, pos, forward) { - if (target instanceof EditorView) - for (let ranges of target.pluginField(PluginField.atomicRanges)) - ranges.between(pos, pos, (from, to) => { - if (from < pos && to > pos) - pos = forward ? to : from; - }); - return pos; - } - const deleteByChar = (target, forward) => deleteBy(target, pos => { - let { state } = target, line = state.doc.lineAt(pos), before, targetPos; - if (!forward && pos > line.from && pos < line.from + 200 && - !/[^ \t]/.test(before = line.text.slice(0, pos - line.from))) { - if (before[before.length - 1] == "\t") - return pos - 1; - let col = countColumn(before, state.tabSize), drop = col % getIndentUnit(state) || getIndentUnit(state); - for (let i = 0; i < drop && before[before.length - 1 - i] == " "; i++) - pos--; - targetPos = pos; - } - else { - targetPos = findClusterBreak(line.text, pos - line.from, forward, forward) + line.from; - if (targetPos == pos && line.number != (forward ? state.doc.lines : 1)) - targetPos += forward ? 1 : -1; - } - return skipAtomic(target, targetPos, forward); - }); - /** - Delete the selection, or, for cursor selections, the character - before the cursor. - */ - const deleteCharBackward = view => deleteByChar(view, false); - /** - Delete the selection or the character after the cursor. - */ - const deleteCharForward = view => deleteByChar(view, true); - const deleteByGroup = (target, forward) => deleteBy(target, start => { - let pos = start, { state } = target, line = state.doc.lineAt(pos); - let categorize = state.charCategorizer(pos); - for (let cat = null;;) { - if (pos == (forward ? line.to : line.from)) { - if (pos == start && line.number != (forward ? state.doc.lines : 1)) - pos += forward ? 1 : -1; - break; - } - let next = findClusterBreak(line.text, pos - line.from, forward) + line.from; - let nextChar = line.text.slice(Math.min(pos, next) - line.from, Math.max(pos, next) - line.from); - let nextCat = categorize(nextChar); - if (cat != null && nextCat != cat) - break; - if (nextChar != " " || pos != start) - cat = nextCat; - pos = next; - } - return skipAtomic(target, pos, forward); - }); - /** - Delete the selection or backward until the end of the next - [group](https://codemirror.net/6/docs/ref/#view.EditorView.moveByGroup), only skipping groups of - whitespace when they consist of a single space. - */ - const deleteGroupBackward = target => deleteByGroup(target, false); - /** - Delete the selection or forward until the end of the next group. - */ - const deleteGroupForward = target => deleteByGroup(target, true); - /** - Delete the selection, or, if it is a cursor selection, delete to - the end of the line. If the cursor is directly at the end of the - line, delete the line break after it. - */ - const deleteToLineEnd = view => deleteBy(view, pos => { - let lineEnd = view.lineBlockAt(pos).to; - return skipAtomic(view, pos < lineEnd ? lineEnd : Math.min(view.state.doc.length, pos + 1), true); - }); - /** - Delete the selection, or, if it is a cursor selection, delete to - the start of the line. If the cursor is directly at the start of the - line, delete the line break before it. - */ - const deleteToLineStart = view => deleteBy(view, pos => { - let lineStart = view.lineBlockAt(pos).from; - return skipAtomic(view, pos > lineStart ? lineStart : Math.max(0, pos - 1), false); - }); - /** - Replace each selection range with a line break, leaving the cursor - on the line before the break. - */ - const splitLine = ({ state, dispatch }) => { - if (state.readOnly) - return false; - let changes = state.changeByRange(range => { - return { changes: { from: range.from, to: range.to, insert: Text.of(["", ""]) }, - range: EditorSelection.cursor(range.from) }; - }); - dispatch(state.update(changes, { scrollIntoView: true, userEvent: "input" })); - return true; - }; - /** - Flip the characters before and after the cursor(s). - */ - const transposeChars = ({ state, dispatch }) => { - if (state.readOnly) - return false; - let changes = state.changeByRange(range => { - if (!range.empty || range.from == 0 || range.from == state.doc.length) - return { range }; - let pos = range.from, line = state.doc.lineAt(pos); - let from = pos == line.from ? pos - 1 : findClusterBreak(line.text, pos - line.from, false) + line.from; - let to = pos == line.to ? pos + 1 : findClusterBreak(line.text, pos - line.from, true) + line.from; - return { changes: { from, to, insert: state.doc.slice(pos, to).append(state.doc.slice(from, pos)) }, - range: EditorSelection.cursor(to) }; - }); - if (changes.changes.empty) - return false; - dispatch(state.update(changes, { scrollIntoView: true, userEvent: "move.character" })); - return true; - }; - function selectedLineBlocks(state) { - let blocks = [], upto = -1; - for (let range of state.selection.ranges) { - let startLine = state.doc.lineAt(range.from), endLine = state.doc.lineAt(range.to); - if (!range.empty && range.to == endLine.from) - endLine = state.doc.lineAt(range.to - 1); - if (upto >= startLine.number) { - let prev = blocks[blocks.length - 1]; - prev.to = endLine.to; - prev.ranges.push(range); - } - else { - blocks.push({ from: startLine.from, to: endLine.to, ranges: [range] }); - } - upto = endLine.number + 1; - } - return blocks; - } - function moveLine(state, dispatch, forward) { - if (state.readOnly) - return false; - let changes = [], ranges = []; - for (let block of selectedLineBlocks(state)) { - if (forward ? block.to == state.doc.length : block.from == 0) - continue; - let nextLine = state.doc.lineAt(forward ? block.to + 1 : block.from - 1); - let size = nextLine.length + 1; - if (forward) { - changes.push({ from: block.to, to: nextLine.to }, { from: block.from, insert: nextLine.text + state.lineBreak }); - for (let r of block.ranges) - ranges.push(EditorSelection.range(Math.min(state.doc.length, r.anchor + size), Math.min(state.doc.length, r.head + size))); - } - else { - changes.push({ from: nextLine.from, to: block.from }, { from: block.to, insert: state.lineBreak + nextLine.text }); - for (let r of block.ranges) - ranges.push(EditorSelection.range(r.anchor - size, r.head - size)); - } - } - if (!changes.length) - return false; - dispatch(state.update({ - changes, - scrollIntoView: true, - selection: EditorSelection.create(ranges, state.selection.mainIndex), - userEvent: "move.line" - })); - return true; - } - /** - Move the selected lines up one line. - */ - const moveLineUp = ({ state, dispatch }) => moveLine(state, dispatch, false); - /** - Move the selected lines down one line. - */ - const moveLineDown = ({ state, dispatch }) => moveLine(state, dispatch, true); - function copyLine(state, dispatch, forward) { - if (state.readOnly) - return false; - let changes = []; - for (let block of selectedLineBlocks(state)) { - if (forward) - changes.push({ from: block.from, insert: state.doc.slice(block.from, block.to) + state.lineBreak }); - else - changes.push({ from: block.to, insert: state.lineBreak + state.doc.slice(block.from, block.to) }); - } - dispatch(state.update({ changes, scrollIntoView: true, userEvent: "input.copyline" })); - return true; - } - /** - Create a copy of the selected lines. Keep the selection in the top copy. - */ - const copyLineUp = ({ state, dispatch }) => copyLine(state, dispatch, false); - /** - Create a copy of the selected lines. Keep the selection in the bottom copy. - */ - const copyLineDown = ({ state, dispatch }) => copyLine(state, dispatch, true); - /** - Delete selected lines. - */ - const deleteLine = view => { - if (view.state.readOnly) - return false; - let { state } = view, changes = state.changes(selectedLineBlocks(state).map(({ from, to }) => { - if (from > 0) - from--; - else if (to < state.doc.length) - to++; - return { from, to }; - })); - let selection = updateSel(state.selection, range => view.moveVertically(range, true)).map(changes); - view.dispatch({ changes, selection, scrollIntoView: true, userEvent: "delete.line" }); - return true; - }; - function isBetweenBrackets(state, pos) { - if (/\(\)|\[\]|\{\}/.test(state.sliceDoc(pos - 1, pos + 1))) - return { from: pos, to: pos }; - let context = syntaxTree(state).resolveInner(pos); - let before = context.childBefore(pos), after = context.childAfter(pos), closedBy; - if (before && after && before.to <= pos && after.from >= pos && - (closedBy = before.type.prop(NodeProp.closedBy)) && closedBy.indexOf(after.name) > -1 && - state.doc.lineAt(before.to).from == state.doc.lineAt(after.from).from) - return { from: before.to, to: after.from }; - return null; - } - /** - Replace the selection with a newline and indent the newly created - line(s). If the current line consists only of whitespace, this - will also delete that whitespace. When the cursor is between - matching brackets, an additional newline will be inserted after - the cursor. - */ - const insertNewlineAndIndent = /*@__PURE__*/newlineAndIndent(false); - /** - Create a blank, indented line below the current line. - */ - const insertBlankLine = /*@__PURE__*/newlineAndIndent(true); - function newlineAndIndent(atEof) { - return ({ state, dispatch }) => { - if (state.readOnly) - return false; - let changes = state.changeByRange(range => { - let { from, to } = range, line = state.doc.lineAt(from); - let explode = !atEof && from == to && isBetweenBrackets(state, from); - if (atEof) - from = to = (to <= line.to ? line : state.doc.lineAt(to)).to; - let cx = new IndentContext(state, { simulateBreak: from, simulateDoubleBreak: !!explode }); - let indent = getIndentation(cx, from); - if (indent == null) - indent = /^\s*/.exec(state.doc.lineAt(from).text)[0].length; - while (to < line.to && /\s/.test(line.text[to - line.from])) - to++; - if (explode) - ({ from, to } = explode); - else if (from > line.from && from < line.from + 100 && !/\S/.test(line.text.slice(0, from))) - from = line.from; - let insert = ["", indentString(state, indent)]; - if (explode) - insert.push(indentString(state, cx.lineIndent(line.from, -1))); - return { changes: { from, to, insert: Text.of(insert) }, - range: EditorSelection.cursor(from + 1 + insert[1].length) }; - }); - dispatch(state.update(changes, { scrollIntoView: true, userEvent: "input" })); - return true; - }; - } - function changeBySelectedLine(state, f) { - let atLine = -1; - return state.changeByRange(range => { - let changes = []; - for (let pos = range.from; pos <= range.to;) { - let line = state.doc.lineAt(pos); - if (line.number > atLine && (range.empty || range.to > line.from)) { - f(line, changes, range); - atLine = line.number; - } - pos = line.to + 1; - } - let changeSet = state.changes(changes); - return { changes, - range: EditorSelection.range(changeSet.mapPos(range.anchor, 1), changeSet.mapPos(range.head, 1)) }; - }); - } - /** - Auto-indent the selected lines. This uses the [indentation service - facet](https://codemirror.net/6/docs/ref/#language.indentService) as source for auto-indent - information. - */ - const indentSelection = ({ state, dispatch }) => { - if (state.readOnly) - return false; - let updated = Object.create(null); - let context = new IndentContext(state, { overrideIndentation: start => { - let found = updated[start]; - return found == null ? -1 : found; - } }); - let changes = changeBySelectedLine(state, (line, changes, range) => { - let indent = getIndentation(context, line.from); - if (indent == null) - return; - if (!/\S/.test(line.text)) - indent = 0; - let cur = /^\s*/.exec(line.text)[0]; - let norm = indentString(state, indent); - if (cur != norm || range.from < line.from + cur.length) { - updated[line.from] = indent; - changes.push({ from: line.from, to: line.from + cur.length, insert: norm }); - } - }); - if (!changes.changes.empty) - dispatch(state.update(changes, { userEvent: "indent" })); - return true; - }; - /** - Add a [unit](https://codemirror.net/6/docs/ref/#language.indentUnit) of indentation to all selected - lines. - */ - const indentMore = ({ state, dispatch }) => { - if (state.readOnly) - return false; - dispatch(state.update(changeBySelectedLine(state, (line, changes) => { - changes.push({ from: line.from, insert: state.facet(indentUnit) }); - }), { userEvent: "input.indent" })); - return true; - }; - /** - Remove a [unit](https://codemirror.net/6/docs/ref/#language.indentUnit) of indentation from all - selected lines. - */ - const indentLess = ({ state, dispatch }) => { - if (state.readOnly) - return false; - dispatch(state.update(changeBySelectedLine(state, (line, changes) => { - let space = /^\s*/.exec(line.text)[0]; - if (!space) - return; - let col = countColumn(space, state.tabSize), keep = 0; - let insert = indentString(state, Math.max(0, col - getIndentUnit(state))); - while (keep < space.length && keep < insert.length && space.charCodeAt(keep) == insert.charCodeAt(keep)) - keep++; - changes.push({ from: line.from + keep, to: line.from + space.length, insert: insert.slice(keep) }); - }), { userEvent: "delete.dedent" })); - return true; - }; - /** - Array of key bindings containing the Emacs-style bindings that are - available on macOS by default. - - - Ctrl-b: [`cursorCharLeft`](https://codemirror.net/6/docs/ref/#commands.cursorCharLeft) ([`selectCharLeft`](https://codemirror.net/6/docs/ref/#commands.selectCharLeft) with Shift) - - Ctrl-f: [`cursorCharRight`](https://codemirror.net/6/docs/ref/#commands.cursorCharRight) ([`selectCharRight`](https://codemirror.net/6/docs/ref/#commands.selectCharRight) with Shift) - - Ctrl-p: [`cursorLineUp`](https://codemirror.net/6/docs/ref/#commands.cursorLineUp) ([`selectLineUp`](https://codemirror.net/6/docs/ref/#commands.selectLineUp) with Shift) - - Ctrl-n: [`cursorLineDown`](https://codemirror.net/6/docs/ref/#commands.cursorLineDown) ([`selectLineDown`](https://codemirror.net/6/docs/ref/#commands.selectLineDown) with Shift) - - Ctrl-a: [`cursorLineStart`](https://codemirror.net/6/docs/ref/#commands.cursorLineStart) ([`selectLineStart`](https://codemirror.net/6/docs/ref/#commands.selectLineStart) with Shift) - - Ctrl-e: [`cursorLineEnd`](https://codemirror.net/6/docs/ref/#commands.cursorLineEnd) ([`selectLineEnd`](https://codemirror.net/6/docs/ref/#commands.selectLineEnd) with Shift) - - Ctrl-d: [`deleteCharForward`](https://codemirror.net/6/docs/ref/#commands.deleteCharForward) - - Ctrl-h: [`deleteCharBackward`](https://codemirror.net/6/docs/ref/#commands.deleteCharBackward) - - Ctrl-k: [`deleteToLineEnd`](https://codemirror.net/6/docs/ref/#commands.deleteToLineEnd) - - Ctrl-Alt-h: [`deleteGroupBackward`](https://codemirror.net/6/docs/ref/#commands.deleteGroupBackward) - - Ctrl-o: [`splitLine`](https://codemirror.net/6/docs/ref/#commands.splitLine) - - Ctrl-t: [`transposeChars`](https://codemirror.net/6/docs/ref/#commands.transposeChars) - - Ctrl-v: [`cursorPageDown`](https://codemirror.net/6/docs/ref/#commands.cursorPageDown) - - Alt-v: [`cursorPageUp`](https://codemirror.net/6/docs/ref/#commands.cursorPageUp) - */ - const emacsStyleKeymap = [ - { key: "Ctrl-b", run: cursorCharLeft, shift: selectCharLeft, preventDefault: true }, - { key: "Ctrl-f", run: cursorCharRight, shift: selectCharRight }, - { key: "Ctrl-p", run: cursorLineUp, shift: selectLineUp }, - { key: "Ctrl-n", run: cursorLineDown, shift: selectLineDown }, - { key: "Ctrl-a", run: cursorLineStart, shift: selectLineStart }, - { key: "Ctrl-e", run: cursorLineEnd, shift: selectLineEnd }, - { key: "Ctrl-d", run: deleteCharForward }, - { key: "Ctrl-h", run: deleteCharBackward }, - { key: "Ctrl-k", run: deleteToLineEnd }, - { key: "Ctrl-Alt-h", run: deleteGroupBackward }, - { key: "Ctrl-o", run: splitLine }, - { key: "Ctrl-t", run: transposeChars }, - { key: "Ctrl-v", run: cursorPageDown }, - ]; - /** - An array of key bindings closely sticking to platform-standard or - widely used bindings. (This includes the bindings from - [`emacsStyleKeymap`](https://codemirror.net/6/docs/ref/#commands.emacsStyleKeymap), with their `key` - property changed to `mac`.) - - - ArrowLeft: [`cursorCharLeft`](https://codemirror.net/6/docs/ref/#commands.cursorCharLeft) ([`selectCharLeft`](https://codemirror.net/6/docs/ref/#commands.selectCharLeft) with Shift) - - ArrowRight: [`cursorCharRight`](https://codemirror.net/6/docs/ref/#commands.cursorCharRight) ([`selectCharRight`](https://codemirror.net/6/docs/ref/#commands.selectCharRight) with Shift) - - Ctrl-ArrowLeft (Alt-ArrowLeft on macOS): [`cursorGroupLeft`](https://codemirror.net/6/docs/ref/#commands.cursorGroupLeft) ([`selectGroupLeft`](https://codemirror.net/6/docs/ref/#commands.selectGroupLeft) with Shift) - - Ctrl-ArrowRight (Alt-ArrowRight on macOS): [`cursorGroupRight`](https://codemirror.net/6/docs/ref/#commands.cursorGroupRight) ([`selectGroupRight`](https://codemirror.net/6/docs/ref/#commands.selectGroupRight) with Shift) - - Cmd-ArrowLeft (on macOS): [`cursorLineStart`](https://codemirror.net/6/docs/ref/#commands.cursorLineStart) ([`selectLineStart`](https://codemirror.net/6/docs/ref/#commands.selectLineStart) with Shift) - - Cmd-ArrowRight (on macOS): [`cursorLineEnd`](https://codemirror.net/6/docs/ref/#commands.cursorLineEnd) ([`selectLineEnd`](https://codemirror.net/6/docs/ref/#commands.selectLineEnd) with Shift) - - ArrowUp: [`cursorLineUp`](https://codemirror.net/6/docs/ref/#commands.cursorLineUp) ([`selectLineUp`](https://codemirror.net/6/docs/ref/#commands.selectLineUp) with Shift) - - ArrowDown: [`cursorLineDown`](https://codemirror.net/6/docs/ref/#commands.cursorLineDown) ([`selectLineDown`](https://codemirror.net/6/docs/ref/#commands.selectLineDown) with Shift) - - Cmd-ArrowUp (on macOS): [`cursorDocStart`](https://codemirror.net/6/docs/ref/#commands.cursorDocStart) ([`selectDocStart`](https://codemirror.net/6/docs/ref/#commands.selectDocStart) with Shift) - - Cmd-ArrowDown (on macOS): [`cursorDocEnd`](https://codemirror.net/6/docs/ref/#commands.cursorDocEnd) ([`selectDocEnd`](https://codemirror.net/6/docs/ref/#commands.selectDocEnd) with Shift) - - Ctrl-ArrowUp (on macOS): [`cursorPageUp`](https://codemirror.net/6/docs/ref/#commands.cursorPageUp) ([`selectPageUp`](https://codemirror.net/6/docs/ref/#commands.selectPageUp) with Shift) - - Ctrl-ArrowDown (on macOS): [`cursorPageDown`](https://codemirror.net/6/docs/ref/#commands.cursorPageDown) ([`selectPageDown`](https://codemirror.net/6/docs/ref/#commands.selectPageDown) with Shift) - - PageUp: [`cursorPageUp`](https://codemirror.net/6/docs/ref/#commands.cursorPageUp) ([`selectPageUp`](https://codemirror.net/6/docs/ref/#commands.selectPageUp) with Shift) - - PageDown: [`cursorPageDown`](https://codemirror.net/6/docs/ref/#commands.cursorPageDown) ([`selectPageDown`](https://codemirror.net/6/docs/ref/#commands.selectPageDown) with Shift) - - Home: [`cursorLineBoundaryBackward`](https://codemirror.net/6/docs/ref/#commands.cursorLineBoundaryBackward) ([`selectLineBoundaryBackward`](https://codemirror.net/6/docs/ref/#commands.selectLineBoundaryBackward) with Shift) - - End: [`cursorLineBoundaryForward`](https://codemirror.net/6/docs/ref/#commands.cursorLineBoundaryForward) ([`selectLineBoundaryForward`](https://codemirror.net/6/docs/ref/#commands.selectLineBoundaryForward) with Shift) - - Ctrl-Home (Cmd-Home on macOS): [`cursorDocStart`](https://codemirror.net/6/docs/ref/#commands.cursorDocStart) ([`selectDocStart`](https://codemirror.net/6/docs/ref/#commands.selectDocStart) with Shift) - - Ctrl-End (Cmd-Home on macOS): [`cursorDocEnd`](https://codemirror.net/6/docs/ref/#commands.cursorDocEnd) ([`selectDocEnd`](https://codemirror.net/6/docs/ref/#commands.selectDocEnd) with Shift) - - Enter: [`insertNewlineAndIndent`](https://codemirror.net/6/docs/ref/#commands.insertNewlineAndIndent) - - Ctrl-a (Cmd-a on macOS): [`selectAll`](https://codemirror.net/6/docs/ref/#commands.selectAll) - - Backspace: [`deleteCharBackward`](https://codemirror.net/6/docs/ref/#commands.deleteCharBackward) - - Delete: [`deleteCharForward`](https://codemirror.net/6/docs/ref/#commands.deleteCharForward) - - Ctrl-Backspace (Alt-Backspace on macOS): [`deleteGroupBackward`](https://codemirror.net/6/docs/ref/#commands.deleteGroupBackward) - - Ctrl-Delete (Alt-Delete on macOS): [`deleteGroupForward`](https://codemirror.net/6/docs/ref/#commands.deleteGroupForward) - - Cmd-Backspace (macOS): [`deleteToLineStart`](https://codemirror.net/6/docs/ref/#commands.deleteToLineStart). - - Cmd-Delete (macOS): [`deleteToLineEnd`](https://codemirror.net/6/docs/ref/#commands.deleteToLineEnd). - */ - const standardKeymap = /*@__PURE__*/[ - { key: "ArrowLeft", run: cursorCharLeft, shift: selectCharLeft, preventDefault: true }, - { key: "Mod-ArrowLeft", mac: "Alt-ArrowLeft", run: cursorGroupLeft, shift: selectGroupLeft }, - { mac: "Cmd-ArrowLeft", run: cursorLineBoundaryBackward, shift: selectLineBoundaryBackward }, - { key: "ArrowRight", run: cursorCharRight, shift: selectCharRight, preventDefault: true }, - { key: "Mod-ArrowRight", mac: "Alt-ArrowRight", run: cursorGroupRight, shift: selectGroupRight }, - { mac: "Cmd-ArrowRight", run: cursorLineBoundaryForward, shift: selectLineBoundaryForward }, - { key: "ArrowUp", run: cursorLineUp, shift: selectLineUp, preventDefault: true }, - { mac: "Cmd-ArrowUp", run: cursorDocStart, shift: selectDocStart }, - { mac: "Ctrl-ArrowUp", run: cursorPageUp, shift: selectPageUp }, - { key: "ArrowDown", run: cursorLineDown, shift: selectLineDown, preventDefault: true }, - { mac: "Cmd-ArrowDown", run: cursorDocEnd, shift: selectDocEnd }, - { mac: "Ctrl-ArrowDown", run: cursorPageDown, shift: selectPageDown }, - { key: "PageUp", run: cursorPageUp, shift: selectPageUp }, - { key: "PageDown", run: cursorPageDown, shift: selectPageDown }, - { key: "Home", run: cursorLineBoundaryBackward, shift: selectLineBoundaryBackward }, - { key: "Mod-Home", run: cursorDocStart, shift: selectDocStart }, - { key: "End", run: cursorLineBoundaryForward, shift: selectLineBoundaryForward }, - { key: "Mod-End", run: cursorDocEnd, shift: selectDocEnd }, - { key: "Enter", run: insertNewlineAndIndent }, - { key: "Mod-a", run: selectAll }, - { key: "Backspace", run: deleteCharBackward, shift: deleteCharBackward }, - { key: "Delete", run: deleteCharForward }, - { key: "Mod-Backspace", mac: "Alt-Backspace", run: deleteGroupBackward }, - { key: "Mod-Delete", mac: "Alt-Delete", run: deleteGroupForward }, - { mac: "Mod-Backspace", run: deleteToLineStart }, - { mac: "Mod-Delete", run: deleteToLineEnd } - ].concat(/*@__PURE__*/emacsStyleKeymap.map(b => ({ mac: b.key, run: b.run, shift: b.shift }))); - /** - The default keymap. Includes all bindings from - [`standardKeymap`](https://codemirror.net/6/docs/ref/#commands.standardKeymap) plus the following: - - - Alt-ArrowLeft (Ctrl-ArrowLeft on macOS): [`cursorSyntaxLeft`](https://codemirror.net/6/docs/ref/#commands.cursorSyntaxLeft) ([`selectSyntaxLeft`](https://codemirror.net/6/docs/ref/#commands.selectSyntaxLeft) with Shift) - - Alt-ArrowRight (Ctrl-ArrowRight on macOS): [`cursorSyntaxRight`](https://codemirror.net/6/docs/ref/#commands.cursorSyntaxRight) ([`selectSyntaxRight`](https://codemirror.net/6/docs/ref/#commands.selectSyntaxRight) with Shift) - - Alt-ArrowUp: [`moveLineUp`](https://codemirror.net/6/docs/ref/#commands.moveLineUp) - - Alt-ArrowDown: [`moveLineDown`](https://codemirror.net/6/docs/ref/#commands.moveLineDown) - - Shift-Alt-ArrowUp: [`copyLineUp`](https://codemirror.net/6/docs/ref/#commands.copyLineUp) - - Shift-Alt-ArrowDown: [`copyLineDown`](https://codemirror.net/6/docs/ref/#commands.copyLineDown) - - Escape: [`simplifySelection`](https://codemirror.net/6/docs/ref/#commands.simplifySelection) - - Ctrl-Enter (Comd-Enter on macOS): [`insertBlankLine`](https://codemirror.net/6/docs/ref/#commands.insertBlankLine) - - Alt-l (Ctrl-l on macOS): [`selectLine`](https://codemirror.net/6/docs/ref/#commands.selectLine) - - Ctrl-i (Cmd-i on macOS): [`selectParentSyntax`](https://codemirror.net/6/docs/ref/#commands.selectParentSyntax) - - Ctrl-[ (Cmd-[ on macOS): [`indentLess`](https://codemirror.net/6/docs/ref/#commands.indentLess) - - Ctrl-] (Cmd-] on macOS): [`indentMore`](https://codemirror.net/6/docs/ref/#commands.indentMore) - - Ctrl-Alt-\\ (Cmd-Alt-\\ on macOS): [`indentSelection`](https://codemirror.net/6/docs/ref/#commands.indentSelection) - - Shift-Ctrl-k (Shift-Cmd-k on macOS): [`deleteLine`](https://codemirror.net/6/docs/ref/#commands.deleteLine) - - Shift-Ctrl-\\ (Shift-Cmd-\\ on macOS): [`cursorMatchingBracket`](https://codemirror.net/6/docs/ref/#commands.cursorMatchingBracket) - */ - const defaultKeymap = /*@__PURE__*/[ - { key: "Alt-ArrowLeft", mac: "Ctrl-ArrowLeft", run: cursorSyntaxLeft, shift: selectSyntaxLeft }, - { key: "Alt-ArrowRight", mac: "Ctrl-ArrowRight", run: cursorSyntaxRight, shift: selectSyntaxRight }, - { key: "Alt-ArrowUp", run: moveLineUp }, - { key: "Shift-Alt-ArrowUp", run: copyLineUp }, - { key: "Alt-ArrowDown", run: moveLineDown }, - { key: "Shift-Alt-ArrowDown", run: copyLineDown }, - { key: "Escape", run: simplifySelection }, - { key: "Mod-Enter", run: insertBlankLine }, - { key: "Alt-l", mac: "Ctrl-l", run: selectLine }, - { key: "Mod-i", run: selectParentSyntax, preventDefault: true }, - { key: "Mod-[", run: indentLess }, - { key: "Mod-]", run: indentMore }, - { key: "Mod-Alt-\\", run: indentSelection }, - { key: "Shift-Mod-k", run: deleteLine }, - { key: "Shift-Mod-\\", run: cursorMatchingBracket } - ].concat(standardKeymap); - - const defaults = { - brackets: ["(", "[", "{", "'", '"'], - before: ")]}:;>" - }; - const closeBracketEffect = /*@__PURE__*/StateEffect.define({ - map(value, mapping) { - let mapped = mapping.mapPos(value, -1, MapMode.TrackAfter); - return mapped == null ? undefined : mapped; - } - }); - const skipBracketEffect = /*@__PURE__*/StateEffect.define({ - map(value, mapping) { return mapping.mapPos(value); } - }); - const closedBracket = /*@__PURE__*/new class extends RangeValue { - }; - closedBracket.startSide = 1; - closedBracket.endSide = -1; - const bracketState = /*@__PURE__*/StateField.define({ - create() { return RangeSet.empty; }, - update(value, tr) { - if (tr.selection) { - let lineStart = tr.state.doc.lineAt(tr.selection.main.head).from; - let prevLineStart = tr.startState.doc.lineAt(tr.startState.selection.main.head).from; - if (lineStart != tr.changes.mapPos(prevLineStart, -1)) - value = RangeSet.empty; - } - value = value.map(tr.changes); - for (let effect of tr.effects) { - if (effect.is(closeBracketEffect)) - value = value.update({ add: [closedBracket.range(effect.value, effect.value + 1)] }); - else if (effect.is(skipBracketEffect)) - value = value.update({ filter: from => from != effect.value }); - } - return value; - } - }); - /** - Extension to enable bracket-closing behavior. When a closeable - bracket is typed, its closing bracket is immediately inserted - after the cursor. When closing a bracket directly in front of a - closing bracket inserted by the extension, the cursor moves over - that bracket. - */ - function closeBrackets() { - return [inputHandler, bracketState]; - } - const definedClosing = "()[]{}<>"; - function closing(ch) { - for (let i = 0; i < definedClosing.length; i += 2) - if (definedClosing.charCodeAt(i) == ch) - return definedClosing.charAt(i + 1); - return fromCodePoint(ch < 128 ? ch : ch + 1); - } - function config$1(state, pos) { - return state.languageDataAt("closeBrackets", pos)[0] || defaults; - } - const android = typeof navigator == "object" && /*@__PURE__*//Android\b/.test(navigator.userAgent); - const inputHandler = /*@__PURE__*/EditorView.inputHandler.of((view, from, to, insert) => { - if ((android ? view.composing : view.compositionStarted) || view.state.readOnly) - return false; - let sel = view.state.selection.main; - if (insert.length > 2 || insert.length == 2 && codePointSize(codePointAt(insert, 0)) == 1 || - from != sel.from || to != sel.to) - return false; - let tr = insertBracket(view.state, insert); - if (!tr) - return false; - view.dispatch(tr); - return true; - }); - /** - Command that implements deleting a pair of matching brackets when - the cursor is between them. - */ - const deleteBracketPair = ({ state, dispatch }) => { - if (state.readOnly) - return false; - let conf = config$1(state, state.selection.main.head); - let tokens = conf.brackets || defaults.brackets; - let dont = null, changes = state.changeByRange(range => { - if (range.empty) { - let before = prevChar(state.doc, range.head); - for (let token of tokens) { - if (token == before && nextChar(state.doc, range.head) == closing(codePointAt(token, 0))) - return { changes: { from: range.head - token.length, to: range.head + token.length }, - range: EditorSelection.cursor(range.head - token.length), - userEvent: "delete.backward" }; - } - } - return { range: dont = range }; - }); - if (!dont) - dispatch(state.update(changes, { scrollIntoView: true })); - return !dont; - }; - /** - Close-brackets related key bindings. Binds Backspace to - [`deleteBracketPair`](https://codemirror.net/6/docs/ref/#closebrackets.deleteBracketPair). - */ - const closeBracketsKeymap = [ - { key: "Backspace", run: deleteBracketPair } - ]; - /** - Implements the extension's behavior on text insertion. If the - given string counts as a bracket in the language around the - selection, and replacing the selection with it requires custom - behavior (inserting a closing version or skipping past a - previously-closed bracket), this function returns a transaction - representing that custom behavior. (You only need this if you want - to programmatically insert brackets—the - [`closeBrackets`](https://codemirror.net/6/docs/ref/#closebrackets.closeBrackets) extension will - take care of running this for user input.) - */ - function insertBracket(state, bracket) { - let conf = config$1(state, state.selection.main.head); - let tokens = conf.brackets || defaults.brackets; - for (let tok of tokens) { - let closed = closing(codePointAt(tok, 0)); - if (bracket == tok) - return closed == tok ? handleSame(state, tok, tokens.indexOf(tok + tok + tok) > -1) - : handleOpen(state, tok, closed, conf.before || defaults.before); - if (bracket == closed && closedBracketAt(state, state.selection.main.from)) - return handleClose(state, tok, closed); - } - return null; - } - function closedBracketAt(state, pos) { - let found = false; - state.field(bracketState).between(0, state.doc.length, from => { - if (from == pos) - found = true; - }); - return found; - } - function nextChar(doc, pos) { - let next = doc.sliceString(pos, pos + 2); - return next.slice(0, codePointSize(codePointAt(next, 0))); - } - function prevChar(doc, pos) { - let prev = doc.sliceString(pos - 2, pos); - return codePointSize(codePointAt(prev, 0)) == prev.length ? prev : prev.slice(1); - } - function handleOpen(state, open, close, closeBefore) { - let dont = null, changes = state.changeByRange(range => { - if (!range.empty) - return { changes: [{ insert: open, from: range.from }, { insert: close, from: range.to }], - effects: closeBracketEffect.of(range.to + open.length), - range: EditorSelection.range(range.anchor + open.length, range.head + open.length) }; - let next = nextChar(state.doc, range.head); - if (!next || /\s/.test(next) || closeBefore.indexOf(next) > -1) - return { changes: { insert: open + close, from: range.head }, - effects: closeBracketEffect.of(range.head + open.length), - range: EditorSelection.cursor(range.head + open.length) }; - return { range: dont = range }; - }); - return dont ? null : state.update(changes, { - scrollIntoView: true, - userEvent: "input.type" - }); - } - function handleClose(state, _open, close) { - let dont = null, moved = state.selection.ranges.map(range => { - if (range.empty && nextChar(state.doc, range.head) == close) - return EditorSelection.cursor(range.head + close.length); - return dont = range; - }); - return dont ? null : state.update({ - selection: EditorSelection.create(moved, state.selection.mainIndex), - scrollIntoView: true, - effects: state.selection.ranges.map(({ from }) => skipBracketEffect.of(from)) - }); - } - // Handles cases where the open and close token are the same, and - // possibly triple quotes (as in `"""abc"""`-style quoting). - function handleSame(state, token, allowTriple) { - let dont = null, changes = state.changeByRange(range => { - if (!range.empty) - return { changes: [{ insert: token, from: range.from }, { insert: token, from: range.to }], - effects: closeBracketEffect.of(range.to + token.length), - range: EditorSelection.range(range.anchor + token.length, range.head + token.length) }; - let pos = range.head, next = nextChar(state.doc, pos); - if (next == token) { - if (nodeStart(state, pos)) { - return { changes: { insert: token + token, from: pos }, - effects: closeBracketEffect.of(pos + token.length), - range: EditorSelection.cursor(pos + token.length) }; - } - else if (closedBracketAt(state, pos)) { - let isTriple = allowTriple && state.sliceDoc(pos, pos + token.length * 3) == token + token + token; - return { range: EditorSelection.cursor(pos + token.length * (isTriple ? 3 : 1)), - effects: skipBracketEffect.of(pos) }; - } - } - else if (allowTriple && state.sliceDoc(pos - 2 * token.length, pos) == token + token && - nodeStart(state, pos - 2 * token.length)) { - return { changes: { insert: token + token + token + token, from: pos }, - effects: closeBracketEffect.of(pos + token.length), - range: EditorSelection.cursor(pos + token.length) }; - } - else if (state.charCategorizer(pos)(next) != CharCategory.Word) { - let prev = state.sliceDoc(pos - 1, pos); - if (prev != token && state.charCategorizer(pos)(prev) != CharCategory.Word && !probablyInString(state, pos, token)) - return { changes: { insert: token + token, from: pos }, - effects: closeBracketEffect.of(pos + token.length), - range: EditorSelection.cursor(pos + token.length) }; - } - return { range: dont = range }; - }); - return dont ? null : state.update(changes, { - scrollIntoView: true, - userEvent: "input.type" - }); - } - function nodeStart(state, pos) { - let tree = syntaxTree(state).resolveInner(pos + 1); - return tree.parent && tree.from == pos; - } - function probablyInString(state, pos, quoteToken) { - let node = syntaxTree(state).resolveInner(pos, -1); - for (let i = 0; i < 5; i++) { - if (state.sliceDoc(node.from, node.from + quoteToken.length) == quoteToken) - return true; - let parent = node.to == pos && node.parent; - if (!parent) - break; - node = parent; - } - return false; - } - - const panelConfig = /*@__PURE__*/Facet.define({ - combine(configs) { - let topContainer, bottomContainer; - for (let c of configs) { - topContainer = topContainer || c.topContainer; - bottomContainer = bottomContainer || c.bottomContainer; - } - return { topContainer, bottomContainer }; - } - }); - /** - Get the active panel created by the given constructor, if any. - This can be useful when you need access to your panels' DOM - structure. - */ - function getPanel(view, panel) { - let plugin = view.plugin(panelPlugin); - let index = plugin ? plugin.specs.indexOf(panel) : -1; - return index > -1 ? plugin.panels[index] : null; - } - const panelPlugin = /*@__PURE__*/ViewPlugin.fromClass(class { - constructor(view) { - this.input = view.state.facet(showPanel); - this.specs = this.input.filter(s => s); - this.panels = this.specs.map(spec => spec(view)); - let conf = view.state.facet(panelConfig); - this.top = new PanelGroup(view, true, conf.topContainer); - this.bottom = new PanelGroup(view, false, conf.bottomContainer); - this.top.sync(this.panels.filter(p => p.top)); - this.bottom.sync(this.panels.filter(p => !p.top)); - for (let p of this.panels) { - p.dom.classList.add("cm-panel"); - if (p.mount) - p.mount(); - } - } - update(update) { - let conf = update.state.facet(panelConfig); - if (this.top.container != conf.topContainer) { - this.top.sync([]); - this.top = new PanelGroup(update.view, true, conf.topContainer); - } - if (this.bottom.container != conf.bottomContainer) { - this.bottom.sync([]); - this.bottom = new PanelGroup(update.view, false, conf.bottomContainer); - } - this.top.syncClasses(); - this.bottom.syncClasses(); - let input = update.state.facet(showPanel); - if (input != this.input) { - let specs = input.filter(x => x); - let panels = [], top = [], bottom = [], mount = []; - for (let spec of specs) { - let known = this.specs.indexOf(spec), panel; - if (known < 0) { - panel = spec(update.view); - mount.push(panel); - } - else { - panel = this.panels[known]; - if (panel.update) - panel.update(update); - } - panels.push(panel); - (panel.top ? top : bottom).push(panel); - } - this.specs = specs; - this.panels = panels; - this.top.sync(top); - this.bottom.sync(bottom); - for (let p of mount) { - p.dom.classList.add("cm-panel"); - if (p.mount) - p.mount(); - } - } - else { - for (let p of this.panels) - if (p.update) - p.update(update); - } - } - destroy() { - this.top.sync([]); - this.bottom.sync([]); - } - }, { - provide: /*@__PURE__*/PluginField.scrollMargins.from(value => ({ top: value.top.scrollMargin(), bottom: value.bottom.scrollMargin() })) - }); - class PanelGroup { - constructor(view, top, container) { - this.view = view; - this.top = top; - this.container = container; - this.dom = undefined; - this.classes = ""; - this.panels = []; - this.syncClasses(); - } - sync(panels) { - for (let p of this.panels) - if (p.destroy && panels.indexOf(p) < 0) - p.destroy(); - this.panels = panels; - this.syncDOM(); - } - syncDOM() { - if (this.panels.length == 0) { - if (this.dom) { - this.dom.remove(); - this.dom = undefined; - } - return; - } - 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 parent = this.container || this.view.dom; - parent.insertBefore(this.dom, this.top ? parent.firstChild : null); - } - let curDOM = this.dom.firstChild; - for (let panel of this.panels) { - if (panel.dom.parentNode == this.dom) { - while (curDOM != panel.dom) - curDOM = rm(curDOM); - curDOM = curDOM.nextSibling; - } - else { - this.dom.insertBefore(panel.dom, curDOM); - } - } - while (curDOM) - curDOM = rm(curDOM); - } - 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) - return; - for (let cls of this.classes.split(" ")) - if (cls) - this.container.classList.remove(cls); - for (let cls of (this.classes = this.view.themeClasses).split(" ")) - if (cls) - this.container.classList.add(cls); - } - } - function rm(node) { - let next = node.nextSibling; - node.remove(); - return next; - } - const baseTheme$4 = /*@__PURE__*/EditorView.baseTheme({ - ".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" - } - }); - /** - Opening a panel is done by providing a constructor function for - the panel through this facet. (The panel is closed again when its - constructor is no longer provided.) Values of `null` are ignored. - */ - const showPanel = /*@__PURE__*/Facet.define({ - enables: [panelPlugin, baseTheme$4] - }); - - function crelt() { - var elt = arguments[0]; - if (typeof elt == "string") elt = document.createElement(elt); - var i = 1, next = arguments[1]; - if (next && typeof next == "object" && next.nodeType == null && !Array.isArray(next)) { - for (var name in next) if (Object.prototype.hasOwnProperty.call(next, name)) { - var value = next[name]; - if (typeof value == "string") elt.setAttribute(name, value); - else if (value != null) elt[name] = value; - } - i++; + /** + * Fetch python plugins from a filePath, saves it on the FS and import + * it as a module, executing any plugin define the module scope. + * + * @param interpreter - the interpreter that will execute the plugins + * @param filePath - path to the python file to fetch + */ + async fetchPythonPlugin(interpreter, filePath) { + const pathArr = filePath.split('/'); + const filename = pathArr.pop(); + // TODO: Would be probably be better to store plugins somewhere like /plugins/python/ or similar + await interpreter._remote.loadFromFile(filename, filePath); + //refresh module cache before trying to import module files into interpreter + interpreter._remote.invalidate_module_path_cache(); + const modulename = filePath.replace(/^.*[\\/]/, '').replace('.py', ''); + console.log(`importing ${modulename}`); + // TODO: This is very specific to Pyodide API and will not work for other interpreters, + // when we add support for other interpreters we will need to move this to the + // interpreter API level and allow each one to implement it in its own way + const module = interpreter._remote.interface.pyimport(modulename); + if (typeof module.plugin !== 'undefined') { + const py_plugin = module.plugin; + py_plugin.init(this); + this.plugins.addPythonPlugin(py_plugin); + } + else { + logger.error(`Cannot find plugin on Python module ${modulename}! Python plugins \ +modules must contain a "plugin" attribute. For more information check the plugins documentation.`); + } } - for (; i < arguments.length; i++) add(elt, arguments[i]); - return elt - } - - function add(elt, child) { - if (typeof child == "string") { - elt.appendChild(document.createTextNode(child)); - } else if (child == null) ; else if (child.nodeType != null) { - elt.appendChild(child); - } else if (Array.isArray(child)) { - for (var i = 0; i < child.length; i++) add(elt, child[i]); - } else { - throw new RangeError("Unsupported child node: " + child) + // lifecycle (7) + executeScripts(interpreter) { + // make_PyScript takes an interpreter and a PyScriptApp as arguments + this.PyScript = make_PyScript(interpreter, this); + customElements.define('py-script', this.PyScript); } - } - - const basicNormalize = typeof String.prototype.normalize == "function" - ? x => x.normalize("NFKD") : x => x; - /** - A search cursor provides an iterator over text matches in a - document. - */ - class SearchCursor { - /** - Create a text cursor. The query is the search string, `from` to - `to` provides the region to search. - - When `normalize` is given, it will be called, on both the query - string and the content it is matched against, before comparing. - You can, for example, create a case-insensitive search by - passing `s => s.toLowerCase()`. - - Text is always normalized with - [`.normalize("NFKD")`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/normalize) - (when supported). - */ - constructor(text, query, from = 0, to = text.length, normalize) { - /** - The current match (only holds a meaningful value after - [`next`](https://codemirror.net/6/docs/ref/#search.SearchCursor.next) has been called and when - `done` is false). - */ - this.value = { from: 0, to: 0 }; - /** - Whether the end of the iterated region has been reached. - */ - this.done = false; - this.matches = []; - this.buffer = ""; - this.bufferPos = 0; - this.iter = text.iterRange(from, to); - this.bufferStart = from; - this.normalize = normalize ? x => normalize(basicNormalize(x)) : basicNormalize; - this.query = this.normalize(query); - } - peek() { - if (this.bufferPos == this.buffer.length) { - this.bufferStart += this.buffer.length; - this.iter.next(); - if (this.iter.done) - return -1; - this.bufferPos = 0; - this.buffer = this.iter.value; - } - return codePointAt(this.buffer, this.bufferPos); - } - /** - Look for the next match. Updates the iterator's - [`value`](https://codemirror.net/6/docs/ref/#search.SearchCursor.value) and - [`done`](https://codemirror.net/6/docs/ref/#search.SearchCursor.done) properties. Should be called - at least once before using the cursor. - */ - next() { - while (this.matches.length) - this.matches.pop(); - return this.nextOverlapping(); - } - /** - The `next` method will ignore matches that partially overlap a - previous match. This method behaves like `next`, but includes - such matches. - */ - nextOverlapping() { - for (;;) { - let next = this.peek(); - if (next < 0) { - this.done = true; - return this; - } - let str = fromCodePoint(next), start = this.bufferStart + this.bufferPos; - this.bufferPos += codePointSize(next); - let norm = this.normalize(str); - for (let i = 0, pos = start;; i++) { - let code = norm.charCodeAt(i); - let match = this.match(code, pos); - if (match) { - this.value = match; - return this; - } - if (i == norm.length - 1) - break; - if (pos == start && i < str.length && str.charCodeAt(i) == code) - pos++; - } - } - } - match(code, pos) { - let match = null; - for (let i = 0; i < this.matches.length; i += 2) { - let index = this.matches[i], keep = false; - if (this.query.charCodeAt(index) == code) { - if (index == this.query.length - 1) { - match = { from: this.matches[i + 1], to: pos + 1 }; - } - else { - this.matches[i]++; - keep = true; - } - } - if (!keep) { - this.matches.splice(i, 2); - i -= 2; - } - } - if (this.query.charCodeAt(0) == code) { - if (this.query.length == 1) - match = { from: pos, to: pos + 1 }; - else - this.matches.push(1, pos); - } - return match; - } - } - if (typeof Symbol != "undefined") - SearchCursor.prototype[Symbol.iterator] = function () { return this; }; - - const empty = { from: -1, to: -1, match: /*@__PURE__*//.*/.exec("") }; - const baseFlags = "gm" + (/x/.unicode == null ? "" : "u"); - /** - This class is similar to [`SearchCursor`](https://codemirror.net/6/docs/ref/#search.SearchCursor) - but searches for a regular expression pattern instead of a plain - string. - */ - class RegExpCursor { - /** - Create a cursor that will search the given range in the given - document. `query` should be the raw pattern (as you'd pass it to - `new RegExp`). - */ - constructor(text, query, options, from = 0, to = text.length) { - this.to = to; - this.curLine = ""; - /** - Set to `true` when the cursor has reached the end of the search - range. - */ - this.done = false; - /** - Will contain an object with the extent of the match and the - match object when [`next`](https://codemirror.net/6/docs/ref/#search.RegExpCursor.next) - sucessfully finds a match. - */ - this.value = empty; - if (/\\[sWDnr]|\n|\r|\[\^/.test(query)) - return new MultilineRegExpCursor(text, query, options, from, to); - this.re = new RegExp(query, baseFlags + ((options === null || options === void 0 ? void 0 : options.ignoreCase) ? "i" : "")); - this.iter = text.iter(); - let startLine = text.lineAt(from); - this.curLineStart = startLine.from; - this.matchPos = from; - this.getLine(this.curLineStart); - } - getLine(skip) { - this.iter.next(skip); - if (this.iter.lineBreak) { - this.curLine = ""; - } - else { - this.curLine = this.iter.value; - if (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; - if (this.curLineStart > this.to) - this.curLine = ""; - else - this.getLine(0); - } - /** - Move to the next match, if there is one. - */ - next() { - for (let off = this.matchPos - this.curLineStart;;) { - this.re.lastIndex = off; - let match = this.matchPos <= this.to && this.re.exec(this.curLine); - if (match) { - let from = this.curLineStart + match.index, to = from + match[0].length; - this.matchPos = to + (from == to ? 1 : 0); - if (from == this.curLine.length) - this.nextLine(); - if (from < to || from > this.value.to) { - this.value = { from, to, match }; - return this; - } - off = this.matchPos - this.curLineStart; - } - else if (this.curLineStart + this.curLine.length < this.to) { - this.nextLine(); - off = 0; - } - else { - this.done = true; - return this; - } - } - } - } - const flattened = /*@__PURE__*/new WeakMap(); - // Reusable (partially) flattened document strings - class FlattenedDoc { - constructor(from, text) { - this.from = from; - this.text = text; - } - get to() { return this.from + this.text.length; } - static get(doc, from, to) { - let cached = flattened.get(doc); - if (!cached || cached.from >= to || cached.to <= from) { - let flat = new FlattenedDoc(from, doc.sliceString(from, to)); - flattened.set(doc, flat); - return flat; - } - if (cached.from == from && cached.to == to) - return cached; - let { text, from: cachedFrom } = cached; - if (cachedFrom > from) { - text = doc.sliceString(from, cachedFrom) + text; - cachedFrom = from; - } - if (cached.to < to) - text += doc.sliceString(cached.to, to); - flattened.set(doc, new FlattenedDoc(cachedFrom, text)); - return new FlattenedDoc(from, text.slice(from - cachedFrom, to - cachedFrom)); - } - } - class MultilineRegExpCursor { - constructor(text, query, options, from, to) { - this.text = text; - this.to = to; - this.done = false; - this.value = empty; - this.matchPos = from; - this.re = new RegExp(query, baseFlags + ((options === null || options === void 0 ? void 0 : options.ignoreCase) ? "i" : "")); - this.flat = FlattenedDoc.get(text, from, this.chunkEnd(from + 5000 /* Base */)); - } - chunkEnd(pos) { - return pos >= this.to ? this.to : this.text.lineAt(pos).to; - } - next() { - for (;;) { - let off = this.re.lastIndex = this.matchPos - this.flat.from; - let match = this.re.exec(this.flat.text); - // Skip empty matches directly after the last match - if (match && !match[0] && match.index == off) { - this.re.lastIndex = off + 1; - match = this.re.exec(this.flat.text); - } - // If a match goes almost to the end of a noncomplete chunk, try - // again, since it'll likely be able to match more - if (match && this.flat.to < this.to && match.index + match[0].length > this.flat.text.length - 10) - match = null; - if (match) { - let from = this.flat.from + match.index, to = from + match[0].length; - this.value = { from, to, match }; - this.matchPos = to + (from == to ? 1 : 0); - return this; - } - else { - if (this.flat.to == this.to) { - this.done = true; - return this; - } - // Grow the flattened doc - this.flat = FlattenedDoc.get(this.text, this.flat.from, this.chunkEnd(this.flat.from + this.flat.text.length * 2)); - } - } - } - } - if (typeof Symbol != "undefined") { - RegExpCursor.prototype[Symbol.iterator] = MultilineRegExpCursor.prototype[Symbol.iterator] = - function () { return this; }; - } - function validRegExp(source) { - try { - new RegExp(source, baseFlags); - return true; - } - catch (_a) { - return false; - } - } - - function createLineDialog(view) { - let input = crelt("input", { class: "cm-textfield", name: "line" }); - let dom = crelt("form", { - class: "cm-gotoLine", - onkeydown: (event) => { - if (event.keyCode == 27) { // Escape - event.preventDefault(); - view.dispatch({ effects: dialogEffect.of(false) }); - view.focus(); - } - else if (event.keyCode == 13) { // Enter - event.preventDefault(); - go(); - } - }, - onsubmit: (event) => { - event.preventDefault(); - go(); - } - }, crelt("label", view.state.phrase("Go to line"), ": ", input), " ", crelt("button", { class: "cm-button", type: "submit" }, view.state.phrase("go"))); - function go() { - let match = /^([+-])?(\d+)?(:\d+)?(%)?$/.exec(input.value); - if (!match) - return; - let { state } = view, startLine = state.doc.lineAt(state.selection.main.head); - let [, sign, ln, cl, percent] = match; - let col = cl ? +cl.slice(1) : 0; - let line = ln ? +ln : startLine.number; - if (ln && percent) { - let pc = line / 100; - if (sign) - pc = pc * (sign == "-" ? -1 : 1) + (startLine.number / state.doc.lines); - line = Math.round(state.doc.lines * pc); - } - else if (ln && sign) { - line = line * (sign == "-" ? -1 : 1) + startLine.number; - } - let docLine = state.doc.line(Math.max(1, Math.min(state.doc.lines, line))); - view.dispatch({ - effects: dialogEffect.of(false), - selection: EditorSelection.cursor(docLine.from + Math.max(0, Math.min(col, docLine.length))), - scrollIntoView: true - }); - view.focus(); - } - return { dom, pos: -10 }; - } - const dialogEffect = /*@__PURE__*/StateEffect.define(); - const dialogField = /*@__PURE__*/StateField.define({ - create() { return true; }, - update(value, tr) { - for (let e of tr.effects) - if (e.is(dialogEffect)) - value = e.value; - return value; - }, - provide: f => showPanel.from(f, val => val ? createLineDialog : null) - }); - /** - Command that shows a dialog asking the user for a line number, and - when a valid position is provided, moves the cursor to that line. - - Supports line numbers, relative line offsets prefixed with `+` or - `-`, document percentages suffixed with `%`, and an optional - column position by adding `:` and a second number after the line - number. - - The dialog can be styled with the `panel.gotoLine` theme - selector. - */ - const gotoLine = view => { - let panel = getPanel(view, createLineDialog); - if (!panel) { - let effects = [dialogEffect.of(true)]; - if (view.state.field(dialogField, false) == null) - effects.push(StateEffect.appendConfig.of([dialogField, baseTheme$1$1])); - view.dispatch({ effects }); - panel = getPanel(view, createLineDialog); - } - if (panel) - panel.dom.querySelector("input").focus(); - return true; - }; - const baseTheme$1$1 = /*@__PURE__*/EditorView.baseTheme({ - ".cm-panel.cm-gotoLine": { - padding: "2px 6px 4px", - "& label": { fontSize: "80%" } - } - }); - - const defaultHighlightOptions = { - highlightWordAroundCursor: false, - minSelectionLength: 1, - maxMatches: 100, - wholeWords: true - }; - const highlightConfig = /*@__PURE__*/Facet.define({ - combine(options) { - return combineConfig(options, defaultHighlightOptions, { - highlightWordAroundCursor: (a, b) => a || b, - minSelectionLength: Math.min, - maxMatches: Math.min - }); - } - }); - /** - This extension highlights text that matches the selection. It uses - the `"cm-selectionMatch"` class for the highlighting. When - `highlightWordAroundCursor` is enabled, the word at the cursor - itself will be highlighted with `"cm-selectionMatch-main"`. - */ - function highlightSelectionMatches(options) { - let ext = [defaultTheme, matchHighlighter]; - if (options) - ext.push(highlightConfig.of(options)); - return ext; - } - const matchDeco = /*@__PURE__*/Decoration.mark({ class: "cm-selectionMatch" }); - const mainMatchDeco = /*@__PURE__*/Decoration.mark({ class: "cm-selectionMatch cm-selectionMatch-main" }); - // Whether the characters directly outside the given positions are non-word characters - function insideWordBoundaries(check, state, from, to) { - return (from == 0 || check(state.sliceDoc(from - 1, from)) != CharCategory.Word) && - (to == state.doc.length || check(state.sliceDoc(to, to + 1)) != CharCategory.Word); - } - // Whether the characters directly at the given positions are word characters - function insideWord(check, state, from, to) { - return check(state.sliceDoc(from, from + 1)) == CharCategory.Word - && check(state.sliceDoc(to - 1, to)) == CharCategory.Word; - } - const matchHighlighter = /*@__PURE__*/ViewPlugin.fromClass(class { - constructor(view) { - this.decorations = this.getDeco(view); - } - update(update) { - if (update.selectionSet || update.docChanged || update.viewportChanged) - this.decorations = this.getDeco(update.view); - } - getDeco(view) { - let conf = view.state.facet(highlightConfig); - let { state } = view, sel = state.selection; - if (sel.ranges.length > 1) - return Decoration.none; - let range = sel.main, query, check = null; - if (range.empty) { - if (!conf.highlightWordAroundCursor) - return Decoration.none; - let word = state.wordAt(range.head); - if (!word) - return Decoration.none; - check = state.charCategorizer(range.head); - query = state.sliceDoc(word.from, word.to); - } - else { - let len = range.to - range.from; - if (len < conf.minSelectionLength || len > 200) - return Decoration.none; - if (conf.wholeWords) { - query = state.sliceDoc(range.from, range.to); // TODO: allow and include leading/trailing space? - check = state.charCategorizer(range.head); - if (!(insideWordBoundaries(check, state, range.from, range.to) - && insideWord(check, state, range.from, range.to))) - return Decoration.none; - } - else { - query = state.sliceDoc(range.from, range.to).trim(); - if (!query) - return Decoration.none; - } - } - let deco = []; - for (let part of view.visibleRanges) { - let cursor = new SearchCursor(state.doc, query, part.from, part.to); - while (!cursor.next().done) { - let { from, to } = cursor.value; - if (!check || insideWordBoundaries(check, state, from, to)) { - if (range.empty && from <= range.from && to >= range.to) - deco.push(mainMatchDeco.range(from, to)); - else if (from >= range.to || to <= range.from) - deco.push(matchDeco.range(from, to)); - if (deco.length > conf.maxMatches) - return Decoration.none; - } - } - } - return Decoration.set(deco); - } - }, { - decorations: v => v.decorations - }); - const defaultTheme = /*@__PURE__*/EditorView.baseTheme({ - ".cm-selectionMatch": { backgroundColor: "#99ff7780" }, - ".cm-searchMatch .cm-selectionMatch": { backgroundColor: "transparent" } - }); - // Select the words around the cursors. - const selectWord = ({ state, dispatch }) => { - let { selection } = state; - let newSel = EditorSelection.create(selection.ranges.map(range => state.wordAt(range.head) || EditorSelection.cursor(range.head)), selection.mainIndex); - if (newSel.eq(selection)) - return false; - dispatch(state.update({ selection: newSel })); - return true; - }; - // Find next occurrence of query relative to last cursor. Wrap around - // the document if there are no more matches. - function findNextOccurrence(state, query) { - let { main, ranges } = state.selection; - let word = state.wordAt(main.head), fullWord = word && word.from == main.from && word.to == main.to; - for (let cycled = false, cursor = new SearchCursor(state.doc, query, ranges[ranges.length - 1].to);;) { - cursor.next(); - if (cursor.done) { - if (cycled) - return null; - cursor = new SearchCursor(state.doc, query, 0, Math.max(0, ranges[ranges.length - 1].from - 1)); - cycled = true; - } - else { - if (cycled && ranges.some(r => r.from == cursor.value.from)) - continue; - if (fullWord) { - let word = state.wordAt(cursor.value.from); - if (!word || word.from != cursor.value.from || word.to != cursor.value.to) - continue; - } - return cursor.value; - } - } - } - /** - Select next occurrence of the current selection. - Expand selection to the word when selection range is empty. - */ - const selectNextOccurrence = ({ state, dispatch }) => { - let { ranges } = state.selection; - if (ranges.some(sel => sel.from === sel.to)) - return selectWord({ state, dispatch }); - let searchedText = state.sliceDoc(ranges[0].from, ranges[0].to); - if (state.selection.ranges.some(r => state.sliceDoc(r.from, r.to) != searchedText)) - return false; - let range = findNextOccurrence(state, searchedText); - if (!range) - return false; - dispatch(state.update({ - selection: state.selection.addRange(EditorSelection.range(range.from, range.to), false), - effects: EditorView.scrollIntoView(range.to) - })); - return true; - }; - - const searchConfigFacet = /*@__PURE__*/Facet.define({ - combine(configs) { - var _a; - return { - top: configs.reduce((val, conf) => val !== null && val !== void 0 ? val : conf.top, undefined) || false, - caseSensitive: configs.reduce((val, conf) => val !== null && val !== void 0 ? val : (conf.caseSensitive || conf.matchCase), undefined) || false, - createPanel: ((_a = configs.find(c => c.createPanel)) === null || _a === void 0 ? void 0 : _a.createPanel) || (view => new SearchPanel(view)) - }; - } - }); - /** - A search query. Part of the editor's search state. - */ - class SearchQuery { - /** - Create a query object. - */ - constructor(config) { - this.search = config.search; - this.caseSensitive = !!config.caseSensitive; - this.regexp = !!config.regexp; - this.replace = config.replace || ""; - this.valid = !!this.search && (!this.regexp || validRegExp(this.search)); - this.unquoted = this.search.replace(/\\([nrt\\])/g, (_, ch) => ch == "n" ? "\n" : ch == "r" ? "\r" : ch == "t" ? "\t" : "\\"); - } - /** - Compare this query to another query. - */ - eq(other) { - return this.search == other.search && this.replace == other.replace && - this.caseSensitive == other.caseSensitive && this.regexp == other.regexp; - } - /** - @internal - */ - create() { - return this.regexp ? new RegExpQuery(this) : new StringQuery(this); - } - getCursor(doc, from = 0, to = doc.length) { - return this.regexp ? regexpCursor(this, doc, from, to) : stringCursor(this, doc, from, to); - } - } - class QueryType { - constructor(spec) { - this.spec = spec; - } - } - function stringCursor(spec, doc, from, to) { - return new SearchCursor(doc, spec.unquoted, from, to, spec.caseSensitive ? undefined : x => x.toLowerCase()); - } - class StringQuery extends QueryType { - constructor(spec) { - super(spec); - } - nextMatch(doc, curFrom, curTo) { - let cursor = stringCursor(this.spec, doc, curTo, doc.length).nextOverlapping(); - if (cursor.done) - cursor = stringCursor(this.spec, doc, 0, curFrom).nextOverlapping(); - return cursor.done ? null : cursor.value; - } - // Searching in reverse is, rather than implementing inverted search - // cursor, done by scanning chunk after chunk forward. - prevMatchInRange(doc, from, to) { - for (let pos = to;;) { - let start = Math.max(from, pos - 10000 /* ChunkSize */ - this.spec.unquoted.length); - let cursor = stringCursor(this.spec, doc, start, pos), range = null; - while (!cursor.nextOverlapping().done) - range = cursor.value; - if (range) - return range; - if (start == from) - return null; - pos -= 10000 /* ChunkSize */; - } - } - prevMatch(doc, curFrom, curTo) { - return this.prevMatchInRange(doc, 0, curFrom) || - this.prevMatchInRange(doc, curTo, doc.length); - } - getReplacement(_result) { return this.spec.replace; } - matchAll(doc, limit) { - let cursor = stringCursor(this.spec, doc, 0, doc.length), ranges = []; - while (!cursor.next().done) { - if (ranges.length >= limit) - return null; - ranges.push(cursor.value); - } - return ranges; - } - highlight(doc, from, to, add) { - let cursor = stringCursor(this.spec, doc, Math.max(0, from - this.spec.unquoted.length), Math.min(to + this.spec.unquoted.length, doc.length)); - while (!cursor.next().done) - add(cursor.value.from, cursor.value.to); - } - } - function regexpCursor(spec, doc, from, to) { - return new RegExpCursor(doc, spec.search, spec.caseSensitive ? undefined : { ignoreCase: true }, from, to); - } - class RegExpQuery extends QueryType { - nextMatch(doc, curFrom, curTo) { - let cursor = regexpCursor(this.spec, doc, curTo, doc.length).next(); - if (cursor.done) - cursor = regexpCursor(this.spec, doc, 0, curFrom).next(); - return cursor.done ? null : cursor.value; - } - prevMatchInRange(doc, from, to) { - for (let size = 1;; size++) { - let start = Math.max(from, to - size * 10000 /* ChunkSize */); - let cursor = regexpCursor(this.spec, doc, start, to), range = null; - while (!cursor.next().done) - range = cursor.value; - if (range && (start == from || range.from > start + 10)) - return range; - if (start == from) - return null; - } - } - prevMatch(doc, curFrom, curTo) { - return this.prevMatchInRange(doc, 0, curFrom) || - this.prevMatchInRange(doc, curTo, doc.length); - } - getReplacement(result) { - return this.spec.replace.replace(/\$([$&\d+])/g, (m, i) => i == "$" ? "$" - : i == "&" ? result.match[0] - : i != "0" && +i < result.match.length ? result.match[i] - : m); - } - matchAll(doc, limit) { - let cursor = regexpCursor(this.spec, doc, 0, doc.length), ranges = []; - while (!cursor.next().done) { - if (ranges.length >= limit) - return null; - ranges.push(cursor.value); - } - return ranges; - } - highlight(doc, from, to, add) { - let cursor = regexpCursor(this.spec, doc, Math.max(0, from - 250 /* HighlightMargin */), Math.min(to + 250 /* HighlightMargin */, doc.length)); - while (!cursor.next().done) - add(cursor.value.from, cursor.value.to); - } - } - /** - A state effect that updates the current search query. Note that - this only has an effect if the search state has been initialized - (by including [`search`](https://codemirror.net/6/docs/ref/#search.search) in your configuration or - by running [`openSearchPanel`](https://codemirror.net/6/docs/ref/#search.openSearchPanel) at least - once). - */ - const setSearchQuery = /*@__PURE__*/StateEffect.define(); - const togglePanel$1 = /*@__PURE__*/StateEffect.define(); - const searchState = /*@__PURE__*/StateField.define({ - create(state) { - return new SearchState(defaultQuery(state).create(), null); - }, - update(value, tr) { - for (let effect of tr.effects) { - if (effect.is(setSearchQuery)) - value = new SearchState(effect.value.create(), value.panel); - else if (effect.is(togglePanel$1)) - value = new SearchState(value.query, effect.value ? createSearchPanel : null); - } - return value; - }, - provide: f => showPanel.from(f, val => val.panel) - }); - class SearchState { - constructor(query, panel) { - this.query = query; - this.panel = panel; - } - } - const matchMark = /*@__PURE__*/Decoration.mark({ class: "cm-searchMatch" }), selectedMatchMark = /*@__PURE__*/Decoration.mark({ class: "cm-searchMatch cm-searchMatch-selected" }); - const searchHighlighter = /*@__PURE__*/ViewPlugin.fromClass(class { - constructor(view) { - this.view = view; - this.decorations = this.highlight(view.state.field(searchState)); - } - update(update) { - let state = update.state.field(searchState); - if (state != update.startState.field(searchState) || update.docChanged || update.selectionSet || update.viewportChanged) - this.decorations = this.highlight(state); - } - highlight({ query, panel }) { - if (!panel || !query.spec.valid) - return Decoration.none; - let { view } = this; - let builder = new RangeSetBuilder(); - for (let i = 0, ranges = view.visibleRanges, l = ranges.length; i < l; i++) { - let { from, to } = ranges[i]; - while (i < l - 1 && to > ranges[i + 1].from - 2 * 250 /* HighlightMargin */) - to = ranges[++i].to; - query.highlight(view.state.doc, from, to, (from, to) => { - let selected = view.state.selection.ranges.some(r => r.from == from && r.to == to); - builder.add(from, to, selected ? selectedMatchMark : matchMark); - }); - } - return builder.finish(); - } - }, { - decorations: v => v.decorations - }); - function searchCommand(f) { - return view => { - let state = view.state.field(searchState, false); - return state && state.query.spec.valid ? f(view, state) : openSearchPanel(view); - }; - } - /** - Open the search panel if it isn't already open, and move the - selection to the first match after the current main selection. - Will wrap around to the start of the document when it reaches the - end. - */ - const findNext = /*@__PURE__*/searchCommand((view, { query }) => { - let { from, to } = view.state.selection.main; - let next = query.nextMatch(view.state.doc, from, to); - if (!next || next.from == from && next.to == to) - return false; - view.dispatch({ - selection: { anchor: next.from, head: next.to }, - scrollIntoView: true, - effects: announceMatch(view, next), - userEvent: "select.search" - }); - return true; - }); - /** - Move the selection to the previous instance of the search query, - before the current main selection. Will wrap past the start - of the document to start searching at the end again. - */ - const findPrevious = /*@__PURE__*/searchCommand((view, { query }) => { - let { state } = view, { from, to } = state.selection.main; - let range = query.prevMatch(state.doc, from, to); - if (!range) - return false; - view.dispatch({ - selection: { anchor: range.from, head: range.to }, - scrollIntoView: true, - effects: announceMatch(view, range), - userEvent: "select.search" - }); - return true; - }); - /** - Select all instances of the search query. - */ - const selectMatches = /*@__PURE__*/searchCommand((view, { query }) => { - let ranges = query.matchAll(view.state.doc, 1000); - if (!ranges || !ranges.length) - return false; - view.dispatch({ - selection: EditorSelection.create(ranges.map(r => EditorSelection.range(r.from, r.to))), - userEvent: "select.search.matches" - }); - return true; - }); - /** - Select all instances of the currently selected text. - */ - const selectSelectionMatches = ({ state, dispatch }) => { - let sel = state.selection; - if (sel.ranges.length > 1 || sel.main.empty) - return false; - let { from, to } = sel.main; - let ranges = [], main = 0; - for (let cur = new SearchCursor(state.doc, state.sliceDoc(from, to)); !cur.next().done;) { - if (ranges.length > 1000) - return false; - if (cur.value.from == from) - main = ranges.length; - ranges.push(EditorSelection.range(cur.value.from, cur.value.to)); - } - dispatch(state.update({ - selection: EditorSelection.create(ranges, main), - userEvent: "select.search.matches" - })); - return true; - }; - /** - Replace the current match of the search query. - */ - const replaceNext = /*@__PURE__*/searchCommand((view, { query }) => { - let { state } = view, { from, to } = state.selection.main; - if (state.readOnly) - return false; - let next = query.nextMatch(state.doc, from, from); - if (!next) - return false; - let changes = [], selection, replacement; - if (next.from == from && next.to == to) { - replacement = state.toText(query.getReplacement(next)); - changes.push({ from: next.from, to: next.to, insert: replacement }); - next = query.nextMatch(state.doc, next.from, next.to); - } - if (next) { - let off = changes.length == 0 || changes[0].from >= next.to ? 0 : next.to - next.from - replacement.length; - selection = { anchor: next.from - off, head: next.to - off }; - } - view.dispatch({ - changes, selection, - scrollIntoView: !!selection, - effects: next ? announceMatch(view, next) : undefined, - userEvent: "input.replace" - }); - return true; - }); - /** - Replace all instances of the search query with the given - replacement. - */ - const replaceAll = /*@__PURE__*/searchCommand((view, { query }) => { - if (view.state.readOnly) - return false; - let changes = query.matchAll(view.state.doc, 1e9).map(match => { - let { from, to } = match; - return { from, to, insert: query.getReplacement(match) }; - }); - if (!changes.length) - return false; - view.dispatch({ - changes, - userEvent: "input.replace.all" - }); - return true; - }); - function createSearchPanel(view) { - return view.state.facet(searchConfigFacet).createPanel(view); - } - function defaultQuery(state, fallback) { - var _a; - let sel = state.selection.main; - let selText = sel.empty || sel.to > sel.from + 100 ? "" : state.sliceDoc(sel.from, sel.to); - let caseSensitive = (_a = fallback === null || fallback === void 0 ? void 0 : fallback.caseSensitive) !== null && _a !== void 0 ? _a : state.facet(searchConfigFacet).caseSensitive; - return fallback && !selText ? fallback : new SearchQuery({ search: selText.replace(/\n/g, "\\n"), caseSensitive }); - } - /** - Make sure the search panel is open and focused. - */ - const openSearchPanel = view => { - let state = view.state.field(searchState, false); - if (state && state.panel) { - let panel = getPanel(view, createSearchPanel); - if (!panel) - return false; - let searchInput = panel.dom.querySelector("[name=search]"); - if (searchInput != view.root.activeElement) { - let query = defaultQuery(view.state, state.query.spec); - if (query.valid) - view.dispatch({ effects: setSearchQuery.of(query) }); - searchInput.focus(); - searchInput.select(); - } - } - else { - view.dispatch({ effects: [ - togglePanel$1.of(true), - state ? setSearchQuery.of(defaultQuery(view.state, state.query.spec)) : StateEffect.appendConfig.of(searchExtensions) - ] }); - } - return true; - }; - /** - Close the search panel. - */ - const closeSearchPanel = view => { - let state = view.state.field(searchState, false); - if (!state || !state.panel) - return false; - let panel = getPanel(view, createSearchPanel); - if (panel && panel.dom.contains(view.root.activeElement)) - view.focus(); - view.dispatch({ effects: togglePanel$1.of(false) }); - return true; - }; - /** - Default search-related key bindings. - - - Mod-f: [`openSearchPanel`](https://codemirror.net/6/docs/ref/#search.openSearchPanel) - - F3, Mod-g: [`findNext`](https://codemirror.net/6/docs/ref/#search.findNext) - - Shift-F3, Shift-Mod-g: [`findPrevious`](https://codemirror.net/6/docs/ref/#search.findPrevious) - - Alt-g: [`gotoLine`](https://codemirror.net/6/docs/ref/#search.gotoLine) - - Mod-d: [`selectNextOccurrence`](https://codemirror.net/6/docs/ref/#search.selectNextOccurrence) - */ - const searchKeymap = [ - { key: "Mod-f", run: openSearchPanel, scope: "editor search-panel" }, - { key: "F3", run: findNext, shift: findPrevious, scope: "editor search-panel", preventDefault: true }, - { key: "Mod-g", run: findNext, shift: findPrevious, scope: "editor search-panel", preventDefault: true }, - { key: "Escape", run: closeSearchPanel, scope: "editor search-panel" }, - { key: "Mod-Shift-l", run: selectSelectionMatches }, - { key: "Alt-g", run: gotoLine }, - { key: "Mod-d", run: selectNextOccurrence, preventDefault: true }, - ]; - class SearchPanel { - constructor(view) { - this.view = view; - let query = this.query = view.state.field(searchState).query.spec; - this.commit = this.commit.bind(this); - this.searchField = crelt("input", { - value: query.search, - placeholder: phrase(view, "Find"), - "aria-label": phrase(view, "Find"), - class: "cm-textfield", - name: "search", - onchange: this.commit, - onkeyup: this.commit - }); - this.replaceField = crelt("input", { - value: query.replace, - placeholder: phrase(view, "Replace"), - "aria-label": phrase(view, "Replace"), - class: "cm-textfield", - name: "replace", - onchange: this.commit, - onkeyup: this.commit - }); - this.caseField = crelt("input", { - type: "checkbox", - name: "case", - checked: query.caseSensitive, - onchange: this.commit - }); - this.reField = crelt("input", { - type: "checkbox", - name: "re", - checked: query.regexp, - onchange: this.commit - }); - function button(name, onclick, content) { - return crelt("button", { class: "cm-button", name, onclick, type: "button" }, content); - } - this.dom = crelt("div", { onkeydown: (e) => this.keydown(e), class: "cm-search" }, [ - this.searchField, - button("next", () => findNext(view), [phrase(view, "next")]), - button("prev", () => findPrevious(view), [phrase(view, "previous")]), - button("select", () => selectMatches(view), [phrase(view, "all")]), - crelt("label", null, [this.caseField, phrase(view, "match case")]), - crelt("label", null, [this.reField, phrase(view, "regexp")]), - ...view.state.readOnly ? [] : [ - crelt("br"), - this.replaceField, - button("replace", () => replaceNext(view), [phrase(view, "replace")]), - button("replaceAll", () => replaceAll(view), [phrase(view, "replace all")]), - crelt("button", { - name: "close", - onclick: () => closeSearchPanel(view), - "aria-label": phrase(view, "close"), - type: "button" - }, ["×"]) - ] - ]); - } - commit() { - let query = new SearchQuery({ - search: this.searchField.value, - caseSensitive: this.caseField.checked, - regexp: this.reField.checked, - replace: this.replaceField.value - }); - if (!query.eq(this.query)) { - this.query = query; - this.view.dispatch({ effects: setSearchQuery.of(query) }); - } - } - keydown(e) { - if (runScopeHandlers(this.view, e, "search-panel")) { - e.preventDefault(); - } - else if (e.keyCode == 13 && e.target == this.searchField) { - e.preventDefault(); - (e.shiftKey ? findPrevious : findNext)(this.view); - } - else if (e.keyCode == 13 && e.target == this.replaceField) { - e.preventDefault(); - replaceNext(this.view); - } - } - update(update) { - for (let tr of update.transactions) - for (let effect of tr.effects) { - if (effect.is(setSearchQuery) && !effect.value.eq(this.query)) - this.setQuery(effect.value); - } - } - setQuery(query) { - this.query = query; - this.searchField.value = query.search; - this.replaceField.value = query.replace; - this.caseField.checked = query.caseSensitive; - this.reField.checked = query.regexp; - } - mount() { - this.searchField.select(); - } - get pos() { return 80; } - get top() { return this.view.state.facet(searchConfigFacet).top; } - } - function phrase(view, phrase) { return view.state.phrase(phrase); } - const AnnounceMargin = 30; - const Break = /[\s\.,:;?!]/; - function announceMatch(view, { from, to }) { - let lineStart = view.state.doc.lineAt(from).from, lineEnd = view.state.doc.lineAt(to).to; - let start = Math.max(lineStart, from - AnnounceMargin), end = Math.min(lineEnd, to + AnnounceMargin); - let text = view.state.sliceDoc(start, end); - if (start != lineStart) { - for (let i = 0; i < AnnounceMargin; i++) - if (!Break.test(text[i + 1]) && Break.test(text[i])) { - text = text.slice(i); - break; - } - } - if (end != lineEnd) { - for (let i = text.length - 1; i > text.length - AnnounceMargin; i--) - if (!Break.test(text[i - 1]) && Break.test(text[i])) { - text = text.slice(0, i); - break; - } - } - return EditorView.announce.of(`${view.state.phrase("current match")}. ${text} ${view.state.phrase("on line")} ${view.state.doc.lineAt(from).number}`); - } - const baseTheme$3 = /*@__PURE__*/EditorView.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" } - }); - const searchExtensions = [ - searchState, - /*@__PURE__*/Prec.lowest(searchHighlighter), - baseTheme$3 - ]; - - const ios = typeof navigator != "undefined" && - !/*@__PURE__*//Edge\/(\d+)/.exec(navigator.userAgent) && /*@__PURE__*//Apple Computer/.test(navigator.vendor) && - (/*@__PURE__*//Mobile\/\w+/.test(navigator.userAgent) || navigator.maxTouchPoints > 2); - const Outside = "-10000px"; - class TooltipViewManager { - constructor(view, facet, createTooltipView) { - this.facet = facet; - this.createTooltipView = createTooltipView; - this.input = view.state.facet(facet); - this.tooltips = this.input.filter(t => t); - this.tooltipViews = this.tooltips.map(createTooltipView); - } - update(update) { - let input = update.state.facet(this.facet); - let tooltips = input.filter(x => x); - if (input === this.input) { - for (let t of this.tooltipViews) - if (t.update) - t.update(update); - return false; - } - let tooltipViews = []; - for (let i = 0; i < tooltips.length; i++) { - let tip = tooltips[i], known = -1; - if (!tip) - continue; - for (let i = 0; i < this.tooltips.length; i++) { - let other = this.tooltips[i]; - if (other && other.create == tip.create) - known = i; - } - if (known < 0) { - tooltipViews[i] = this.createTooltipView(tip); - } - else { - let tooltipView = tooltipViews[i] = this.tooltipViews[known]; - if (tooltipView.update) - tooltipView.update(update); - } - } - for (let t of this.tooltipViews) - if (tooltipViews.indexOf(t) < 0) - t.dom.remove(); - this.input = input; - this.tooltips = tooltips; - this.tooltipViews = tooltipViews; - return true; - } - } - function windowSpace() { - return { top: 0, left: 0, bottom: innerHeight, right: innerWidth }; - } - const tooltipConfig = /*@__PURE__*/Facet.define({ - combine: values => { - var _a, _b, _c; - return ({ - position: ios ? "absolute" : ((_a = values.find(conf => conf.position)) === null || _a === void 0 ? void 0 : _a.position) || "fixed", - parent: ((_b = values.find(conf => conf.parent)) === null || _b === void 0 ? void 0 : _b.parent) || null, - tooltipSpace: ((_c = values.find(conf => conf.tooltipSpace)) === null || _c === void 0 ? void 0 : _c.tooltipSpace) || windowSpace, - }); - } - }); - const tooltipPlugin = /*@__PURE__*/ViewPlugin.fromClass(class { - constructor(view) { - var _a; - this.view = view; - this.inView = true; - this.lastTransaction = 0; - this.measureTimeout = -1; - let config = view.state.facet(tooltipConfig); - this.position = config.position; - this.parent = config.parent; - this.classes = view.themeClasses; - this.createContainer(); - this.measureReq = { read: this.readMeasure.bind(this), write: this.writeMeasure.bind(this), key: this }; - this.manager = new TooltipViewManager(view, showTooltip, t => this.createTooltip(t)); - this.intersectionObserver = typeof IntersectionObserver == "function" ? new IntersectionObserver(entries => { - if (Date.now() > this.lastTransaction - 50 && - entries.length > 0 && entries[entries.length - 1].intersectionRatio < 1) - this.measureSoon(); - }, { threshold: [1] }) : null; - this.observeIntersection(); - (_a = view.dom.ownerDocument.defaultView) === null || _a === void 0 ? void 0 : _a.addEventListener("resize", this.measureSoon = this.measureSoon.bind(this)); - this.maybeMeasure(); - } - createContainer() { - if (this.parent) { - this.container = document.createElement("div"); - this.container.style.position = "relative"; - this.container.className = this.view.themeClasses; - this.parent.appendChild(this.container); - } - else { - this.container = this.view.dom; - } - } - observeIntersection() { - if (this.intersectionObserver) { - this.intersectionObserver.disconnect(); - for (let tooltip of this.manager.tooltipViews) - this.intersectionObserver.observe(tooltip.dom); - } - } - measureSoon() { - if (this.measureTimeout < 0) - this.measureTimeout = setTimeout(() => { - this.measureTimeout = -1; - this.maybeMeasure(); - }, 50); - } - update(update) { - if (update.transactions.length) - this.lastTransaction = Date.now(); - let updated = this.manager.update(update); - if (updated) - this.observeIntersection(); - let shouldMeasure = updated || update.geometryChanged; - let newConfig = update.state.facet(tooltipConfig); - if (newConfig.position != this.position) { - this.position = newConfig.position; - for (let t of this.manager.tooltipViews) - t.dom.style.position = this.position; - shouldMeasure = true; - } - if (newConfig.parent != this.parent) { - if (this.parent) - this.container.remove(); - this.parent = newConfig.parent; - this.createContainer(); - for (let t of this.manager.tooltipViews) - this.container.appendChild(t.dom); - shouldMeasure = true; - } - else if (this.parent && this.view.themeClasses != this.classes) { - this.classes = this.container.className = this.view.themeClasses; - } - if (shouldMeasure) - this.maybeMeasure(); - } - createTooltip(tooltip) { - let tooltipView = tooltip.create(this.view); - tooltipView.dom.classList.add("cm-tooltip"); - if (tooltip.arrow && !tooltipView.dom.querySelector(".cm-tooltip > .cm-tooltip-arrow")) { - let arrow = document.createElement("div"); - arrow.className = "cm-tooltip-arrow"; - tooltipView.dom.appendChild(arrow); - } - tooltipView.dom.style.position = this.position; - tooltipView.dom.style.top = Outside; - this.container.appendChild(tooltipView.dom); - if (tooltipView.mount) - tooltipView.mount(this.view); - return tooltipView; - } - destroy() { - var _a, _b; - (_a = this.view.dom.ownerDocument.defaultView) === null || _a === void 0 ? void 0 : _a.removeEventListener("resize", this.measureSoon); - for (let { dom } of this.manager.tooltipViews) - dom.remove(); - (_b = this.intersectionObserver) === null || _b === void 0 ? void 0 : _b.disconnect(); - clearTimeout(this.measureTimeout); - } - readMeasure() { - let editor = this.view.dom.getBoundingClientRect(); - return { - editor, - parent: this.parent ? this.container.getBoundingClientRect() : editor, - pos: this.manager.tooltips.map((t, i) => { - let tv = this.manager.tooltipViews[i]; - return tv.getCoords ? tv.getCoords(t.pos) : this.view.coordsAtPos(t.pos); - }), - size: this.manager.tooltipViews.map(({ dom }) => dom.getBoundingClientRect()), - space: this.view.state.facet(tooltipConfig).tooltipSpace(this.view), - }; - } - writeMeasure(measured) { - let { editor, space } = measured; - let others = []; - for (let i = 0; i < this.manager.tooltips.length; i++) { - let tooltip = this.manager.tooltips[i], tView = this.manager.tooltipViews[i], { dom } = tView; - let pos = measured.pos[i], size = measured.size[i]; - // Hide tooltips that are outside of the editor. - if (!pos || pos.bottom <= Math.max(editor.top, space.top) || - pos.top >= Math.min(editor.bottom, space.bottom) || - pos.right < Math.max(editor.left, space.left) - .1 || - pos.left > Math.min(editor.right, space.right) + .1) { - dom.style.top = Outside; - continue; - } - let arrow = tooltip.arrow ? tView.dom.querySelector(".cm-tooltip-arrow") : null; - let arrowHeight = arrow ? 7 /* Size */ : 0; - let width = size.right - size.left, height = size.bottom - size.top; - let offset = tView.offset || noOffset, ltr = this.view.textDirection == Direction.LTR; - let left = size.width > space.right - space.left ? (ltr ? space.left : space.right - size.width) - : ltr ? Math.min(pos.left - (arrow ? 14 /* Offset */ : 0) + offset.x, space.right - width) - : Math.max(space.left, pos.left - width + (arrow ? 14 /* Offset */ : 0) - offset.x); - let above = !!tooltip.above; - if (!tooltip.strictSide && (above - ? pos.top - (size.bottom - size.top) - offset.y < space.top - : pos.bottom + (size.bottom - size.top) + offset.y > space.bottom) && - above == (space.bottom - pos.bottom > pos.top - space.top)) - above = !above; - let top = above ? pos.top - height - arrowHeight - offset.y : pos.bottom + arrowHeight + offset.y; - let right = left + width; - if (tView.overlap !== true) - for (let r of others) - if (r.left < right && r.right > left && r.top < top + height && r.bottom > top) - top = above ? r.top - height - 2 - arrowHeight : r.bottom + arrowHeight + 2; - if (this.position == "absolute") { - dom.style.top = (top - measured.parent.top) + "px"; - dom.style.left = (left - measured.parent.left) + "px"; - } - else { - dom.style.top = top + "px"; - dom.style.left = left + "px"; - } - if (arrow) - arrow.style.left = `${pos.left + (ltr ? offset.x : -offset.x) - (left + 14 /* Offset */ - 7 /* Size */)}px`; - if (tView.overlap !== true) - others.push({ left, top, right, bottom: top + height }); - dom.classList.toggle("cm-tooltip-above", above); - dom.classList.toggle("cm-tooltip-below", !above); - if (tView.positioned) - tView.positioned(); - } - } - maybeMeasure() { - if (this.manager.tooltips.length) { - if (this.view.inView) - this.view.requestMeasure(this.measureReq); - if (this.inView != this.view.inView) { - this.inView = this.view.inView; - if (!this.inView) - for (let tv of this.manager.tooltipViews) - tv.dom.style.top = Outside; - } - } - } - }, { - eventHandlers: { - scroll() { this.maybeMeasure(); } - } - }); - const baseTheme$2 = /*@__PURE__*/EditorView.baseTheme({ - ".cm-tooltip": { - zIndex: 100 - }, - "&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: `${7 /* Size */}px`, - width: `${7 /* Size */ * 2}px`, - position: "absolute", - zIndex: -1, - overflow: "hidden", - "&:before, &:after": { - content: "''", - position: "absolute", - width: 0, - height: 0, - borderLeft: `${7 /* Size */}px solid transparent`, - borderRight: `${7 /* Size */}px solid transparent`, - }, - ".cm-tooltip-above &": { - bottom: `-${7 /* Size */}px`, - "&:before": { - borderTop: `${7 /* Size */}px solid #bbb`, - }, - "&:after": { - borderTop: `${7 /* Size */}px solid #f5f5f5`, - bottom: "1px" - } - }, - ".cm-tooltip-below &": { - top: `-${7 /* Size */}px`, - "&:before": { - borderBottom: `${7 /* Size */}px solid #bbb`, - }, - "&:after": { - borderBottom: `${7 /* Size */}px solid #f5f5f5`, - top: "1px" - } - }, - }, - "&dark .cm-tooltip .cm-tooltip-arrow": { - "&:before": { - borderTopColor: "#333338", - borderBottomColor: "#333338" - }, - "&:after": { - borderTopColor: "transparent", - borderBottomColor: "transparent" - } - } - }); - const noOffset = { x: 0, y: 0 }; - /** - Behavior by which an extension can provide a tooltip to be shown. - */ - const showTooltip = /*@__PURE__*/Facet.define({ - enables: [tooltipPlugin, baseTheme$2] - }); - const showHoverTooltip = /*@__PURE__*/Facet.define(); - class HoverTooltipHost { - constructor(view) { - this.view = view; - this.mounted = false; - this.dom = document.createElement("div"); - this.dom.classList.add("cm-tooltip-hover"); - this.manager = new TooltipViewManager(view, showHoverTooltip, t => this.createHostedView(t)); - } - // Needs to be static so that host tooltip instances always match - static create(view) { - return new HoverTooltipHost(view); - } - createHostedView(tooltip) { - let hostedView = tooltip.create(this.view); - hostedView.dom.classList.add("cm-tooltip-section"); - this.dom.appendChild(hostedView.dom); - if (this.mounted && hostedView.mount) - hostedView.mount(this.view); - return hostedView; - } - mount(view) { - for (let hostedView of this.manager.tooltipViews) { - if (hostedView.mount) - hostedView.mount(view); - } - this.mounted = true; - } - positioned() { - for (let hostedView of this.manager.tooltipViews) { - if (hostedView.positioned) - hostedView.positioned(); - } - } - update(update) { - this.manager.update(update); - } - } - const showHoverTooltipHost = /*@__PURE__*/showTooltip.compute([showHoverTooltip], state => { - let tooltips = state.facet(showHoverTooltip).filter(t => t); - if (tooltips.length === 0) - return null; - return { - pos: Math.min(...tooltips.map(t => t.pos)), - end: Math.max(...tooltips.filter(t => t.end != null).map(t => t.end)), - create: HoverTooltipHost.create, - above: tooltips[0].above, - arrow: tooltips.some(t => t.arrow), - }; - }); - class HoverPlugin { - constructor(view, source, field, setHover, hoverTime) { - this.view = view; - this.source = source; - this.field = field; - this.setHover = setHover; - this.hoverTime = hoverTime; - this.hoverTimeout = -1; - this.restartTimeout = -1; - this.pending = null; - this.lastMove = { x: 0, y: 0, target: view.dom, time: 0 }; - this.checkHover = this.checkHover.bind(this); - view.dom.addEventListener("mouseleave", this.mouseleave = this.mouseleave.bind(this)); - view.dom.addEventListener("mousemove", this.mousemove = this.mousemove.bind(this)); - } - update() { - if (this.pending) { - this.pending = null; - clearTimeout(this.restartTimeout); - this.restartTimeout = setTimeout(() => this.startHover(), 20); - } - } - get active() { - return this.view.state.field(this.field); - } - checkHover() { - this.hoverTimeout = -1; - if (this.active) - return; - let hovered = Date.now() - this.lastMove.time; - if (hovered < this.hoverTime) - this.hoverTimeout = setTimeout(this.checkHover, this.hoverTime - hovered); - else - this.startHover(); - } - startHover() { - var _a; - clearTimeout(this.restartTimeout); - let { lastMove } = this; - let pos = this.view.contentDOM.contains(lastMove.target) ? this.view.posAtCoords(lastMove) : null; - if (pos == null) - return; - let posCoords = this.view.coordsAtPos(pos); - if (posCoords == null || lastMove.y < posCoords.top || lastMove.y > posCoords.bottom || - lastMove.x < posCoords.left - this.view.defaultCharacterWidth || - lastMove.x > posCoords.right + this.view.defaultCharacterWidth) - return; - let bidi = this.view.bidiSpans(this.view.state.doc.lineAt(pos)).find(s => s.from <= pos && s.to >= pos); - let rtl = bidi && bidi.dir == Direction.RTL ? -1 : 1; - let open = this.source(this.view, pos, (lastMove.x < posCoords.left ? -rtl : rtl)); - if ((_a = open) === null || _a === void 0 ? void 0 : _a.then) { - let pending = this.pending = { pos }; - open.then(result => { - if (this.pending == pending) { - this.pending = null; - if (result) - this.view.dispatch({ effects: this.setHover.of(result) }); - } - }, e => logException(this.view.state, e, "hover tooltip")); - } - else if (open) { - this.view.dispatch({ effects: this.setHover.of(open) }); - } - } - mousemove(event) { - var _a; - this.lastMove = { x: event.clientX, y: event.clientY, target: event.target, time: Date.now() }; - if (this.hoverTimeout < 0) - this.hoverTimeout = setTimeout(this.checkHover, this.hoverTime); - let tooltip = this.active; - if (tooltip && !isInTooltip(this.lastMove.target) || this.pending) { - let { pos } = tooltip || this.pending, end = (_a = tooltip === null || tooltip === void 0 ? void 0 : tooltip.end) !== null && _a !== void 0 ? _a : pos; - if ((pos == end ? this.view.posAtCoords(this.lastMove) != pos - : !isOverRange(this.view, pos, end, event.clientX, event.clientY, 6 /* MaxDist */))) { - this.view.dispatch({ effects: this.setHover.of(null) }); - this.pending = null; - } - } - } - mouseleave() { - clearTimeout(this.hoverTimeout); - this.hoverTimeout = -1; - if (this.active) - this.view.dispatch({ effects: this.setHover.of(null) }); - } - destroy() { - clearTimeout(this.hoverTimeout); - this.view.dom.removeEventListener("mouseleave", this.mouseleave); - this.view.dom.removeEventListener("mousemove", this.mousemove); - } - } - function isInTooltip(elt) { - for (let cur = elt; cur; cur = cur.parentNode) - if (cur.nodeType == 1 && cur.classList.contains("cm-tooltip")) - return true; - return false; - } - function isOverRange(view, from, to, x, y, margin) { - let range = document.createRange(); - let fromDOM = view.domAtPos(from), toDOM = view.domAtPos(to); - range.setEnd(toDOM.node, toDOM.offset); - range.setStart(fromDOM.node, fromDOM.offset); - let rects = range.getClientRects(); - range.detach(); - for (let i = 0; i < rects.length; i++) { - let rect = rects[i]; - let dist = Math.max(rect.top - y, y - rect.bottom, rect.left - x, x - rect.right); - if (dist <= margin) - return true; - } - return false; - } - /** - Enable a hover tooltip, which shows up when the pointer hovers - over ranges of text. The callback is called when the mouse hovers - over the document text. It should, if there is a tooltip - associated with position `pos` return the tooltip description - (either directly or in a promise). The `side` argument indicates - on which side of the position the pointer is—it will be -1 if the - pointer is before the position, 1 if after the position. - - Note that all hover tooltips are hosted within a single tooltip - container element. This allows multiple tooltips over the same - range to be "merged" together without overlapping. - */ - function hoverTooltip(source, options = {}) { - let setHover = StateEffect.define(); - let hoverState = StateField.define({ - create() { return null; }, - update(value, tr) { - if (value && (options.hideOnChange && (tr.docChanged || tr.selection))) - return null; - for (let effect of tr.effects) { - if (effect.is(setHover)) - return effect.value; - if (effect.is(closeHoverTooltipEffect)) - return null; - } - if (value && tr.docChanged) { - let newPos = tr.changes.mapPos(value.pos, -1, MapMode.TrackDel); - if (newPos == null) - return null; - let copy = Object.assign(Object.create(null), value); - copy.pos = newPos; - if (value.end != null) - copy.end = tr.changes.mapPos(value.end); - return copy; - } - return value; - }, - provide: f => showHoverTooltip.from(f) - }); - return [ - hoverState, - ViewPlugin.define(view => new HoverPlugin(view, source, hoverState, setHover, options.hoverTime || 300 /* Time */)), - showHoverTooltipHost - ]; - } - /** - Get the active tooltip view for a given tooltip, if available. - */ - function getTooltip(view, tooltip) { - let plugin = view.plugin(tooltipPlugin); - if (!plugin) - return null; - let found = plugin.manager.tooltips.indexOf(tooltip); - return found < 0 ? null : plugin.manager.tooltipViews[found]; - } - const closeHoverTooltipEffect = /*@__PURE__*/StateEffect.define(); - - /** - An instance of this is passed to completion source functions. - */ - class CompletionContext { - /** - Create a new completion context. (Mostly useful for testing - completion sources—in the editor, the extension will create - these for you.) - */ - constructor( - /** - The editor state that the completion happens in. - */ - state, - /** - The position at which the completion is happening. - */ - pos, - /** - Indicates whether completion was activated explicitly, or - implicitly by typing. The usual way to respond to this is to - only return completions when either there is part of a - completable entity before the cursor, or `explicit` is true. - */ - explicit) { - this.state = state; - this.pos = pos; - this.explicit = explicit; - /** - @internal - */ - this.abortListeners = []; - } - /** - Get the extent, content, and (if there is a token) type of the - token before `this.pos`. - */ - tokenBefore(types) { - let token = syntaxTree(this.state).resolveInner(this.pos, -1); - while (token && types.indexOf(token.name) < 0) - token = token.parent; - return token ? { from: token.from, to: this.pos, - text: this.state.sliceDoc(token.from, this.pos), - type: token.type } : null; - } - /** - Get the match of the given expression directly before the - cursor. - */ - matchBefore(expr) { - let line = this.state.doc.lineAt(this.pos); - let start = Math.max(line.from, this.pos - 250); - let str = line.text.slice(start - line.from, this.pos - line.from); - let found = str.search(ensureAnchor(expr, false)); - return found < 0 ? null : { from: start + found, to: this.pos, text: str.slice(found) }; - } - /** - Yields true when the query has been aborted. Can be useful in - asynchronous queries to avoid doing work that will be ignored. - */ - get aborted() { return this.abortListeners == null; } - /** - Allows you to register abort handlers, which will be called when - the query is - [aborted](https://codemirror.net/6/docs/ref/#autocomplete.CompletionContext.aborted). - */ - addEventListener(type, listener) { - if (type == "abort" && this.abortListeners) - this.abortListeners.push(listener); - } - } - function toSet(chars) { - let flat = Object.keys(chars).join(""); - let words = /\w/.test(flat); - if (words) - flat = flat.replace(/\w/g, ""); - return `[${words ? "\\w" : ""}${flat.replace(/[^\w\s]/g, "\\$&")}]`; - } - function prefixMatch(options) { - let first = Object.create(null), rest = Object.create(null); - for (let { label } of options) { - first[label[0]] = true; - for (let i = 1; i < label.length; i++) - rest[label[i]] = true; - } - let source = toSet(first) + toSet(rest) + "*$"; - return [new RegExp("^" + source), new RegExp(source)]; - } - /** - Given a a fixed array of options, return an autocompleter that - completes them. - */ - function completeFromList(list) { - let options = list.map(o => typeof o == "string" ? { label: o } : o); - let [span, match] = options.every(o => /^\w+$/.test(o.label)) ? [/\w*$/, /\w+$/] : prefixMatch(options); - return (context) => { - let token = context.matchBefore(match); - return token || context.explicit ? { from: token ? token.from : context.pos, options, span } : null; - }; - } - class Option { - constructor(completion, source, match) { - this.completion = completion; - this.source = source; - this.match = match; - } - } - function cur(state) { return state.selection.main.head; } - // Make sure the given regexp has a $ at its end and, if `start` is - // true, a ^ at its start. - function ensureAnchor(expr, start) { - var _a; - let { source } = expr; - let addStart = start && source[0] != "^", addEnd = source[source.length - 1] != "$"; - if (!addStart && !addEnd) - return expr; - return new RegExp(`${addStart ? "^" : ""}(?:${source})${addEnd ? "$" : ""}`, (_a = expr.flags) !== null && _a !== void 0 ? _a : (expr.ignoreCase ? "i" : "")); - } - /** - This annotation is added to transactions that are produced by - picking a completion. - */ - const pickedCompletion = /*@__PURE__*/Annotation.define(); - function applyCompletion(view, option) { - let apply = option.completion.apply || option.completion.label; - let result = option.source; - if (typeof apply == "string") { - view.dispatch({ - changes: { from: result.from, to: result.to, insert: apply }, - selection: { anchor: result.from + apply.length }, - userEvent: "input.complete", - annotations: pickedCompletion.of(option.completion) - }); - } - else { - apply(view, option.completion, result.from, result.to); - } - } - const SourceCache = /*@__PURE__*/new WeakMap(); - function asSource(source) { - if (!Array.isArray(source)) - return source; - let known = SourceCache.get(source); - if (!known) - SourceCache.set(source, known = completeFromList(source)); - return known; - } - - // A pattern matcher for fuzzy completion matching. Create an instance - // once for a pattern, and then use that to match any number of - // completions. - class FuzzyMatcher { - constructor(pattern) { - this.pattern = pattern; - this.chars = []; - this.folded = []; - // Buffers reused by calls to `match` to track matched character - // positions. - this.any = []; - this.precise = []; - this.byWord = []; - for (let p = 0; p < pattern.length;) { - let char = codePointAt(pattern, p), size = codePointSize(char); - this.chars.push(char); - let part = pattern.slice(p, p + size), upper = part.toUpperCase(); - this.folded.push(codePointAt(upper == part ? part.toLowerCase() : upper, 0)); - p += size; - } - this.astral = pattern.length != this.chars.length; - } - // Matches a given word (completion) against the pattern (input). - // Will return null for no match, and otherwise an array that starts - // with the match score, followed by any number of `from, to` pairs - // indicating the matched parts of `word`. - // - // The score is a number that is more negative the worse the match - // is. See `Penalty` above. - match(word) { - if (this.pattern.length == 0) - return [0]; - if (word.length < this.pattern.length) - return null; - let { chars, folded, any, precise, byWord } = this; - // For single-character queries, only match when they occur right - // at the start - if (chars.length == 1) { - let first = codePointAt(word, 0); - return first == chars[0] ? [0, 0, codePointSize(first)] - : first == folded[0] ? [-200 /* CaseFold */, 0, codePointSize(first)] : null; - } - let direct = word.indexOf(this.pattern); - if (direct == 0) - return [0, 0, this.pattern.length]; - let len = chars.length, anyTo = 0; - if (direct < 0) { - for (let i = 0, e = Math.min(word.length, 200); i < e && anyTo < len;) { - let next = codePointAt(word, i); - if (next == chars[anyTo] || next == folded[anyTo]) - any[anyTo++] = i; - i += codePointSize(next); - } - // No match, exit immediately - if (anyTo < len) - return null; - } - // This tracks the extent of the precise (non-folded, not - // necessarily adjacent) match - let preciseTo = 0; - // Tracks whether there is a match that hits only characters that - // appear to be starting words. `byWordFolded` is set to true when - // a case folded character is encountered in such a match - let byWordTo = 0, byWordFolded = false; - // If we've found a partial adjacent match, these track its state - let adjacentTo = 0, adjacentStart = -1, adjacentEnd = -1; - let hasLower = /[a-z]/.test(word), wordAdjacent = true; - // Go over the option's text, scanning for the various kinds of matches - for (let i = 0, e = Math.min(word.length, 200), prevType = 0 /* NonWord */; i < e && byWordTo < len;) { - let next = codePointAt(word, i); - if (direct < 0) { - if (preciseTo < len && next == chars[preciseTo]) - precise[preciseTo++] = i; - if (adjacentTo < len) { - if (next == chars[adjacentTo] || next == folded[adjacentTo]) { - if (adjacentTo == 0) - adjacentStart = i; - adjacentEnd = i + 1; - adjacentTo++; - } - else { - adjacentTo = 0; - } - } - } - let ch, type = next < 0xff - ? (next >= 48 && next <= 57 || next >= 97 && next <= 122 ? 2 /* Lower */ : next >= 65 && next <= 90 ? 1 /* Upper */ : 0 /* NonWord */) - : ((ch = fromCodePoint(next)) != ch.toLowerCase() ? 1 /* Upper */ : ch != ch.toUpperCase() ? 2 /* Lower */ : 0 /* NonWord */); - if (!i || type == 1 /* Upper */ && hasLower || prevType == 0 /* NonWord */ && type != 0 /* NonWord */) { - if (chars[byWordTo] == next || (folded[byWordTo] == next && (byWordFolded = true))) - byWord[byWordTo++] = i; - else if (byWord.length) - wordAdjacent = false; - } - prevType = type; - i += codePointSize(next); - } - if (byWordTo == len && byWord[0] == 0 && wordAdjacent) - return this.result(-100 /* ByWord */ + (byWordFolded ? -200 /* CaseFold */ : 0), byWord, word); - if (adjacentTo == len && adjacentStart == 0) - return [-200 /* CaseFold */ - word.length, 0, adjacentEnd]; - if (direct > -1) - return [-700 /* NotStart */ - word.length, direct, direct + this.pattern.length]; - if (adjacentTo == len) - return [-200 /* CaseFold */ + -700 /* NotStart */ - word.length, adjacentStart, adjacentEnd]; - if (byWordTo == len) - return this.result(-100 /* ByWord */ + (byWordFolded ? -200 /* CaseFold */ : 0) + -700 /* NotStart */ + - (wordAdjacent ? 0 : -1100 /* Gap */), byWord, word); - return chars.length == 2 ? null : this.result((any[0] ? -700 /* NotStart */ : 0) + -200 /* CaseFold */ + -1100 /* Gap */, any, word); - } - result(score, positions, word) { - let result = [score - word.length], i = 1; - for (let pos of positions) { - let to = pos + (this.astral ? codePointSize(codePointAt(word, pos)) : 1); - if (i > 1 && result[i - 1] == pos) - result[i - 1] = to; - else { - result[i++] = pos; - result[i++] = to; - } - } - return result; - } - } - - const completionConfig = /*@__PURE__*/Facet.define({ - combine(configs) { - return combineConfig(configs, { - activateOnTyping: true, - override: null, - maxRenderedOptions: 100, - defaultKeymap: true, - optionClass: () => "", - aboveCursor: false, - icons: true, - addToOptions: [] - }, { - defaultKeymap: (a, b) => a && b, - icons: (a, b) => a && b, - optionClass: (a, b) => c => joinClass(a(c), b(c)), - addToOptions: (a, b) => a.concat(b) - }); - } - }); - function joinClass(a, b) { - return a ? b ? a + " " + b : a : b; - } - - function optionContent(config) { - let content = config.addToOptions.slice(); - if (config.icons) - content.push({ - render(completion) { - let icon = document.createElement("div"); - icon.classList.add("cm-completionIcon"); - if (completion.type) - icon.classList.add(...completion.type.split(/\s+/g).map(cls => "cm-completionIcon-" + cls)); - icon.setAttribute("aria-hidden", "true"); - return icon; - }, - position: 20 - }); - content.push({ - render(completion, _s, match) { - let labelElt = document.createElement("span"); - labelElt.className = "cm-completionLabel"; - let { label } = completion, off = 0; - for (let j = 1; j < match.length;) { - let from = match[j++], to = match[j++]; - if (from > off) - labelElt.appendChild(document.createTextNode(label.slice(off, from))); - let span = labelElt.appendChild(document.createElement("span")); - span.appendChild(document.createTextNode(label.slice(from, to))); - span.className = "cm-completionMatchedText"; - off = to; - } - if (off < label.length) - labelElt.appendChild(document.createTextNode(label.slice(off))); - return labelElt; - }, - position: 50 - }, { - render(completion) { - if (!completion.detail) - return null; - let detailElt = document.createElement("span"); - detailElt.className = "cm-completionDetail"; - detailElt.textContent = completion.detail; - return detailElt; - }, - position: 80 - }); - return content.sort((a, b) => a.position - b.position).map(a => a.render); - } - function rangeAroundSelected(total, selected, max) { - if (total <= max) - return { from: 0, to: total }; - if (selected <= (total >> 1)) { - let off = Math.floor(selected / max); - return { from: off * max, to: (off + 1) * max }; - } - let off = Math.floor((total - selected) / max); - return { from: total - (off + 1) * max, to: total - off * max }; - } - class CompletionTooltip { - constructor(view, stateField) { - this.view = view; - this.stateField = stateField; - this.info = null; - this.placeInfo = { - read: () => this.measureInfo(), - write: (pos) => this.positionInfo(pos), - key: this - }; - let cState = view.state.field(stateField); - let { options, selected } = cState.open; - let config = view.state.facet(completionConfig); - this.optionContent = optionContent(config); - this.optionClass = config.optionClass; - this.range = rangeAroundSelected(options.length, selected, config.maxRenderedOptions); - this.dom = document.createElement("div"); - this.dom.className = "cm-tooltip-autocomplete"; - this.dom.addEventListener("mousedown", (e) => { - for (let dom = e.target, match; dom && dom != this.dom; dom = dom.parentNode) { - if (dom.nodeName == "LI" && (match = /-(\d+)$/.exec(dom.id)) && +match[1] < options.length) { - applyCompletion(view, options[+match[1]]); - e.preventDefault(); - return; - } - } - }); - this.list = this.dom.appendChild(this.createListBox(options, cState.id, this.range)); - this.list.addEventListener("scroll", () => { - if (this.info) - this.view.requestMeasure(this.placeInfo); - }); - } - mount() { this.updateSel(); } - update(update) { - if (update.state.field(this.stateField) != update.startState.field(this.stateField)) - this.updateSel(); - } - positioned() { - if (this.info) - this.view.requestMeasure(this.placeInfo); - } - updateSel() { - let cState = this.view.state.field(this.stateField), open = cState.open; - if (open.selected < this.range.from || open.selected >= this.range.to) { - this.range = rangeAroundSelected(open.options.length, open.selected, this.view.state.facet(completionConfig).maxRenderedOptions); - this.list.remove(); - this.list = this.dom.appendChild(this.createListBox(open.options, cState.id, this.range)); - this.list.addEventListener("scroll", () => { - if (this.info) - this.view.requestMeasure(this.placeInfo); - }); - } - if (this.updateSelectedOption(open.selected)) { - if (this.info) { - this.info.remove(); - this.info = null; - } - let { completion } = open.options[open.selected]; - let { info } = completion; - if (!info) - return; - let infoResult = typeof info === 'string' ? document.createTextNode(info) : info(completion); - if (!infoResult) - return; - if ('then' in infoResult) { - infoResult.then(node => { - if (node && this.view.state.field(this.stateField, false) == cState) - this.addInfoPane(node); - }).catch(e => logException(this.view.state, e, "completion info")); - } - else { - this.addInfoPane(infoResult); - } - } - } - addInfoPane(content) { - let dom = this.info = document.createElement("div"); - dom.className = "cm-tooltip cm-completionInfo"; - dom.appendChild(content); - this.dom.appendChild(dom); - this.view.requestMeasure(this.placeInfo); - } - updateSelectedOption(selected) { - let set = null; - for (let opt = this.list.firstChild, i = this.range.from; opt; opt = opt.nextSibling, i++) { - if (i == selected) { - if (!opt.hasAttribute("aria-selected")) { - opt.setAttribute("aria-selected", "true"); - set = opt; - } - } - else { - if (opt.hasAttribute("aria-selected")) - opt.removeAttribute("aria-selected"); - } - } - if (set) - scrollIntoView(this.list, set); - return set; - } - measureInfo() { - let sel = this.dom.querySelector("[aria-selected]"); - if (!sel || !this.info) - return null; - let listRect = this.dom.getBoundingClientRect(); - let infoRect = this.info.getBoundingClientRect(); - let selRect = sel.getBoundingClientRect(); - if (selRect.top > Math.min(innerHeight, listRect.bottom) - 10 || selRect.bottom < Math.max(0, listRect.top) + 10) - return null; - let top = Math.max(0, Math.min(selRect.top, innerHeight - infoRect.height)) - listRect.top; - let left = this.view.textDirection == Direction.RTL; - let spaceLeft = listRect.left, spaceRight = innerWidth - listRect.right; - if (left && spaceLeft < Math.min(infoRect.width, spaceRight)) - left = false; - else if (!left && spaceRight < Math.min(infoRect.width, spaceLeft)) - left = true; - return { top, left }; - } - positionInfo(pos) { - if (this.info) { - this.info.style.top = (pos ? pos.top : -1e6) + "px"; - if (pos) { - this.info.classList.toggle("cm-completionInfo-left", pos.left); - this.info.classList.toggle("cm-completionInfo-right", !pos.left); - } - } - } - createListBox(options, id, range) { - const ul = document.createElement("ul"); - ul.id = id; - ul.setAttribute("role", "listbox"); - ul.setAttribute("aria-expanded", "true"); - for (let i = range.from; i < range.to; i++) { - let { completion, match } = options[i]; - const li = ul.appendChild(document.createElement("li")); - li.id = id + "-" + i; - li.setAttribute("role", "option"); - let cls = this.optionClass(completion); - if (cls) - li.className = cls; - for (let source of this.optionContent) { - let node = source(completion, this.view.state, match); - if (node) - li.appendChild(node); - } - } - if (range.from) - ul.classList.add("cm-completionListIncompleteTop"); - if (range.to < options.length) - ul.classList.add("cm-completionListIncompleteBottom"); - return ul; - } - } - // We allocate a new function instance every time the completion - // changes to force redrawing/repositioning of the tooltip - function completionTooltip(stateField) { - return (view) => new CompletionTooltip(view, stateField); - } - function scrollIntoView(container, element) { - let parent = container.getBoundingClientRect(); - let self = element.getBoundingClientRect(); - if (self.top < parent.top) - container.scrollTop -= parent.top - self.top; - else if (self.bottom > parent.bottom) - container.scrollTop += self.bottom - parent.bottom; - } - - const MaxOptions = 300; - // Used to pick a preferred option when two options with the same - // label occur in the result. - function score(option) { - return (option.boost || 0) * 100 + (option.apply ? 10 : 0) + (option.info ? 5 : 0) + - (option.type ? 1 : 0); - } - function sortOptions(active, state) { - let options = [], i = 0; - for (let a of active) - if (a.hasResult()) { - if (a.result.filter === false) { - for (let option of a.result.options) - options.push(new Option(option, a, [1e9 - i++])); - } - else { - let matcher = new FuzzyMatcher(state.sliceDoc(a.from, a.to)), match; - for (let option of a.result.options) - if (match = matcher.match(option.label)) { - if (option.boost != null) - match[0] += option.boost; - options.push(new Option(option, a, match)); - } - } - } - let result = [], prev = null; - for (let opt of options.sort(cmpOption)) { - if (result.length == MaxOptions) - break; - if (!prev || prev.label != opt.completion.label || prev.detail != opt.completion.detail || - prev.type != opt.completion.type || prev.apply != opt.completion.apply) - result.push(opt); - else if (score(opt.completion) > score(prev)) - result[result.length - 1] = opt; - prev = opt.completion; - } - return result; - } - class CompletionDialog { - constructor(options, attrs, tooltip, timestamp, selected) { - this.options = options; - this.attrs = attrs; - this.tooltip = tooltip; - this.timestamp = timestamp; - this.selected = selected; - } - setSelected(selected, id) { - return selected == this.selected || selected >= this.options.length ? this - : new CompletionDialog(this.options, makeAttrs(id, selected), this.tooltip, this.timestamp, selected); - } - static build(active, state, id, prev, conf) { - let options = sortOptions(active, state); - if (!options.length) - return null; - let selected = 0; - if (prev && prev.selected) { - let selectedValue = prev.options[prev.selected].completion; - for (let i = 0; i < options.length; i++) - if (options[i].completion == selectedValue) { - selected = i; - break; - } - } - return new CompletionDialog(options, makeAttrs(id, selected), { - pos: active.reduce((a, b) => b.hasResult() ? Math.min(a, b.from) : a, 1e8), - create: completionTooltip(completionState), - above: conf.aboveCursor, - }, prev ? prev.timestamp : Date.now(), selected); - } - map(changes) { - return new CompletionDialog(this.options, this.attrs, Object.assign(Object.assign({}, this.tooltip), { pos: changes.mapPos(this.tooltip.pos) }), this.timestamp, this.selected); - } - } - class CompletionState { - constructor(active, id, open) { - this.active = active; - this.id = id; - this.open = open; - } - static start() { - return new CompletionState(none, "cm-ac-" + Math.floor(Math.random() * 2e6).toString(36), null); - } - update(tr) { - let { state } = tr, conf = state.facet(completionConfig); - let sources = conf.override || - state.languageDataAt("autocomplete", cur(state)).map(asSource); - let active = sources.map(source => { - let value = this.active.find(s => s.source == source) || - new ActiveSource(source, this.active.some(a => a.state != 0 /* Inactive */) ? 1 /* Pending */ : 0 /* Inactive */); - return value.update(tr, conf); - }); - if (active.length == this.active.length && active.every((a, i) => a == this.active[i])) - active = this.active; - let open = tr.selection || active.some(a => a.hasResult() && tr.changes.touchesRange(a.from, a.to)) || - !sameResults(active, this.active) ? CompletionDialog.build(active, state, this.id, this.open, conf) - : this.open && tr.docChanged ? this.open.map(tr.changes) : this.open; - if (!open && active.every(a => a.state != 1 /* Pending */) && active.some(a => a.hasResult())) - active = active.map(a => a.hasResult() ? new ActiveSource(a.source, 0 /* Inactive */) : a); - for (let effect of tr.effects) - if (effect.is(setSelectedEffect)) - open = open && open.setSelected(effect.value, this.id); - return active == this.active && open == this.open ? this : new CompletionState(active, this.id, open); - } - get tooltip() { return this.open ? this.open.tooltip : null; } - get attrs() { return this.open ? this.open.attrs : baseAttrs; } - } - function sameResults(a, b) { - if (a == b) - return true; - for (let iA = 0, iB = 0;;) { - while (iA < a.length && !a[iA].hasResult) - iA++; - while (iB < b.length && !b[iB].hasResult) - iB++; - let endA = iA == a.length, endB = iB == b.length; - if (endA || endB) - return endA == endB; - if (a[iA++].result != b[iB++].result) - return false; - } - } - const baseAttrs = { - "aria-autocomplete": "list" - }; - function makeAttrs(id, selected) { - return { - "aria-autocomplete": "list", - "aria-haspopup": "listbox", - "aria-activedescendant": id + "-" + selected, - "aria-controls": id - }; - } - const none = []; - function cmpOption(a, b) { - let dScore = b.match[0] - a.match[0]; - if (dScore) - return dScore; - return a.completion.label.localeCompare(b.completion.label); - } - function getUserEvent(tr) { - return tr.isUserEvent("input.type") ? "input" : tr.isUserEvent("delete.backward") ? "delete" : null; - } - class ActiveSource { - constructor(source, state, explicitPos = -1) { - this.source = source; - this.state = state; - this.explicitPos = explicitPos; - } - hasResult() { return false; } - update(tr, conf) { - let event = getUserEvent(tr), value = this; - if (event) - value = value.handleUserEvent(tr, event, conf); - else if (tr.docChanged) - value = value.handleChange(tr); - else if (tr.selection && value.state != 0 /* Inactive */) - value = new ActiveSource(value.source, 0 /* Inactive */); - for (let effect of tr.effects) { - if (effect.is(startCompletionEffect)) - value = new ActiveSource(value.source, 1 /* Pending */, effect.value ? cur(tr.state) : -1); - else if (effect.is(closeCompletionEffect)) - value = new ActiveSource(value.source, 0 /* Inactive */); - else if (effect.is(setActiveEffect)) - for (let active of effect.value) - if (active.source == value.source) - value = active; - } - return value; - } - handleUserEvent(tr, type, conf) { - return type == "delete" || !conf.activateOnTyping ? this.map(tr.changes) : new ActiveSource(this.source, 1 /* Pending */); - } - handleChange(tr) { - return tr.changes.touchesRange(cur(tr.startState)) ? new ActiveSource(this.source, 0 /* Inactive */) : this.map(tr.changes); - } - map(changes) { - return changes.empty || this.explicitPos < 0 ? this : new ActiveSource(this.source, this.state, changes.mapPos(this.explicitPos)); - } - } - class ActiveResult extends ActiveSource { - constructor(source, explicitPos, result, from, to, span) { - super(source, 2 /* Result */, explicitPos); - this.result = result; - this.from = from; - this.to = to; - this.span = span; - } - hasResult() { return true; } - handleUserEvent(tr, type, conf) { - let from = tr.changes.mapPos(this.from), to = tr.changes.mapPos(this.to, 1); - let pos = cur(tr.state); - if ((this.explicitPos < 0 ? pos <= from : pos < this.from) || - pos > to || - type == "delete" && cur(tr.startState) == this.from) - return new ActiveSource(this.source, type == "input" && conf.activateOnTyping ? 1 /* Pending */ : 0 /* Inactive */); - let explicitPos = this.explicitPos < 0 ? -1 : tr.changes.mapPos(this.explicitPos); - if (this.span && (from == to || this.span.test(tr.state.sliceDoc(from, to)))) - return new ActiveResult(this.source, explicitPos, this.result, from, to, this.span); - return new ActiveSource(this.source, 1 /* Pending */, explicitPos); - } - handleChange(tr) { - return tr.changes.touchesRange(this.from, this.to) ? new ActiveSource(this.source, 0 /* Inactive */) : this.map(tr.changes); - } - map(mapping) { - return mapping.empty ? this : - new ActiveResult(this.source, this.explicitPos < 0 ? -1 : mapping.mapPos(this.explicitPos), this.result, mapping.mapPos(this.from), mapping.mapPos(this.to, 1), this.span); - } - } - const startCompletionEffect = /*@__PURE__*/StateEffect.define(); - const closeCompletionEffect = /*@__PURE__*/StateEffect.define(); - const setActiveEffect = /*@__PURE__*/StateEffect.define({ - map(sources, mapping) { return sources.map(s => s.map(mapping)); } - }); - const setSelectedEffect = /*@__PURE__*/StateEffect.define(); - const completionState = /*@__PURE__*/StateField.define({ - create() { return CompletionState.start(); }, - update(value, tr) { return value.update(tr); }, - provide: f => [ - showTooltip.from(f, val => val.tooltip), - EditorView.contentAttributes.from(f, state => state.attrs) - ] - }); - - const CompletionInteractMargin = 75; - /** - Returns a command that moves the completion selection forward or - backward by the given amount. - */ - function moveCompletionSelection(forward, by = "option") { - return (view) => { - let cState = view.state.field(completionState, false); - if (!cState || !cState.open || Date.now() - cState.open.timestamp < CompletionInteractMargin) - return false; - let step = 1, tooltip; - if (by == "page" && (tooltip = getTooltip(view, cState.open.tooltip))) - step = Math.max(2, Math.floor(tooltip.dom.offsetHeight / - tooltip.dom.querySelector("li").offsetHeight) - 1); - let selected = cState.open.selected + step * (forward ? 1 : -1), { length } = cState.open.options; - if (selected < 0) - selected = by == "page" ? 0 : length - 1; - else if (selected >= length) - selected = by == "page" ? length - 1 : 0; - view.dispatch({ effects: setSelectedEffect.of(selected) }); - return true; - }; - } - /** - Accept the current completion. - */ - const acceptCompletion = (view) => { - let cState = view.state.field(completionState, false); - if (view.state.readOnly || !cState || !cState.open || Date.now() - cState.open.timestamp < CompletionInteractMargin) - return false; - applyCompletion(view, cState.open.options[cState.open.selected]); - return true; - }; - /** - Explicitly start autocompletion. - */ - const startCompletion = (view) => { - let cState = view.state.field(completionState, false); - if (!cState) - return false; - view.dispatch({ effects: startCompletionEffect.of(true) }); - return true; - }; - /** - Close the currently active completion. - */ - const closeCompletion = (view) => { - let cState = view.state.field(completionState, false); - if (!cState || !cState.active.some(a => a.state != 0 /* Inactive */)) - return false; - view.dispatch({ effects: closeCompletionEffect.of(null) }); - return true; - }; - class RunningQuery { - constructor(active, context) { - this.active = active; - this.context = context; - this.time = Date.now(); - this.updates = []; - // Note that 'undefined' means 'not done yet', whereas 'null' means - // 'query returned null'. - this.done = undefined; - } - } - const DebounceTime = 50, MaxUpdateCount = 50, MinAbortTime = 1000; - const completionPlugin = /*@__PURE__*/ViewPlugin.fromClass(class { - constructor(view) { - this.view = view; - this.debounceUpdate = -1; - this.running = []; - this.debounceAccept = -1; - this.composing = 0 /* None */; - for (let active of view.state.field(completionState).active) - if (active.state == 1 /* Pending */) - this.startQuery(active); - } - update(update) { - let cState = update.state.field(completionState); - if (!update.selectionSet && !update.docChanged && update.startState.field(completionState) == cState) - return; - let doesReset = update.transactions.some(tr => { - return (tr.selection || tr.docChanged) && !getUserEvent(tr); - }); - for (let i = 0; i < this.running.length; i++) { - let query = this.running[i]; - if (doesReset || - query.updates.length + update.transactions.length > MaxUpdateCount && Date.now() - query.time > MinAbortTime) { - for (let handler of query.context.abortListeners) { - try { - handler(); - } - catch (e) { - logException(this.view.state, e); - } - } - query.context.abortListeners = null; - this.running.splice(i--, 1); - } - else { - query.updates.push(...update.transactions); - } - } - if (this.debounceUpdate > -1) - clearTimeout(this.debounceUpdate); - this.debounceUpdate = cState.active.some(a => a.state == 1 /* Pending */ && !this.running.some(q => q.active.source == a.source)) - ? setTimeout(() => this.startUpdate(), DebounceTime) : -1; - if (this.composing != 0 /* None */) - for (let tr of update.transactions) { - if (getUserEvent(tr) == "input") - this.composing = 2 /* Changed */; - else if (this.composing == 2 /* Changed */ && tr.selection) - this.composing = 3 /* ChangedAndMoved */; - } - } - startUpdate() { - this.debounceUpdate = -1; - let { state } = this.view, cState = state.field(completionState); - for (let active of cState.active) { - if (active.state == 1 /* Pending */ && !this.running.some(r => r.active.source == active.source)) - this.startQuery(active); - } - } - startQuery(active) { - let { state } = this.view, pos = cur(state); - let context = new CompletionContext(state, pos, active.explicitPos == pos); - let pending = new RunningQuery(active, context); - this.running.push(pending); - Promise.resolve(active.source(context)).then(result => { - if (!pending.context.aborted) { - pending.done = result || null; - this.scheduleAccept(); - } - }, err => { - this.view.dispatch({ effects: closeCompletionEffect.of(null) }); - logException(this.view.state, err); - }); - } - scheduleAccept() { - if (this.running.every(q => q.done !== undefined)) - this.accept(); - else if (this.debounceAccept < 0) - this.debounceAccept = setTimeout(() => this.accept(), DebounceTime); - } - // For each finished query in this.running, try to create a result - // or, if appropriate, restart the query. - accept() { - var _a; - if (this.debounceAccept > -1) - clearTimeout(this.debounceAccept); - this.debounceAccept = -1; - let updated = []; - let conf = this.view.state.facet(completionConfig); - for (let i = 0; i < this.running.length; i++) { - let query = this.running[i]; - if (query.done === undefined) - continue; - this.running.splice(i--, 1); - if (query.done) { - let active = new ActiveResult(query.active.source, query.active.explicitPos, query.done, query.done.from, (_a = query.done.to) !== null && _a !== void 0 ? _a : cur(query.updates.length ? query.updates[0].startState : this.view.state), query.done.span && query.done.filter !== false ? ensureAnchor(query.done.span, true) : null); - // Replay the transactions that happened since the start of - // the request and see if that preserves the result - for (let tr of query.updates) - active = active.update(tr, conf); - if (active.hasResult()) { - updated.push(active); - continue; - } - } - let current = this.view.state.field(completionState).active.find(a => a.source == query.active.source); - if (current && current.state == 1 /* Pending */) { - if (query.done == null) { - // Explicitly failed. Should clear the pending status if it - // hasn't been re-set in the meantime. - let active = new ActiveSource(query.active.source, 0 /* Inactive */); - for (let tr of query.updates) - active = active.update(tr, conf); - if (active.state != 1 /* Pending */) - updated.push(active); - } - else { - // Cleared by subsequent transactions. Restart. - this.startQuery(current); - } - } - } - if (updated.length) - this.view.dispatch({ effects: setActiveEffect.of(updated) }); - } - }, { - eventHandlers: { - compositionstart() { - this.composing = 1 /* Started */; - }, - compositionend() { - if (this.composing == 3 /* ChangedAndMoved */) { - // Safari fires compositionend events synchronously, possibly - // from inside an update, so dispatch asynchronously to avoid reentrancy - setTimeout(() => this.view.dispatch({ effects: startCompletionEffect.of(false) }), 20); - } - this.composing = 0 /* None */; - } - } - }); - - const baseTheme$1 = /*@__PURE__*/EditorView.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", - listStyle: "none", - margin: 0, - padding: 0, - "& > li": { - overflowX: "hidden", - textOverflow: "ellipsis", - cursor: "pointer", - padding: "1px 3px", - lineHeight: 1.2 - }, - } - }, - "&light .cm-tooltip-autocomplete ul li[aria-selected]": { - background: "#17c", - color: "white", - }, - "&dark .cm-tooltip-autocomplete ul li[aria-selected]": { - background: "#347", - color: "white", - }, - ".cm-completionListIncompleteTop:before, .cm-completionListIncompleteBottom:after": { - content: '"···"', - opacity: 0.5, - display: "block", - textAlign: "center" - }, - ".cm-tooltip.cm-completionInfo": { - position: "absolute", - padding: "3px 9px", - width: "max-content", - maxWidth: "300px", - }, - ".cm-completionInfo.cm-completionInfo-left": { right: "100%" }, - ".cm-completionInfo.cm-completionInfo-right": { left: "100%" }, - "&light .cm-snippetField": { backgroundColor: "#00000022" }, - "&dark .cm-snippetField": { backgroundColor: "#ffffff22" }, - ".cm-snippetFieldPosition": { - verticalAlign: "text-top", - width: 0, - height: "1.15em", - 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" - }, - ".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: "'🔑\uFE0E'" } // Disable emoji rendering - }, - ".cm-completionIcon-namespace": { - "&:after": { content: "'▢'" } - }, - ".cm-completionIcon-text": { - "&:after": { content: "'abc'", fontSize: "50%", verticalAlign: "middle" } - } - }); - - /** - Returns an extension that enables autocompletion. - */ - function autocompletion(config = {}) { - return [ - completionState, - completionConfig.of(config), - completionPlugin, - completionKeymapExt, - baseTheme$1 - ]; - } - /** - Basic keybindings for autocompletion. - - - Ctrl-Space: [`startCompletion`](https://codemirror.net/6/docs/ref/#autocomplete.startCompletion) - - Escape: [`closeCompletion`](https://codemirror.net/6/docs/ref/#autocomplete.closeCompletion) - - ArrowDown: [`moveCompletionSelection`](https://codemirror.net/6/docs/ref/#autocomplete.moveCompletionSelection)`(true)` - - ArrowUp: [`moveCompletionSelection`](https://codemirror.net/6/docs/ref/#autocomplete.moveCompletionSelection)`(false)` - - PageDown: [`moveCompletionSelection`](https://codemirror.net/6/docs/ref/#autocomplete.moveCompletionSelection)`(true, "page")` - - PageDown: [`moveCompletionSelection`](https://codemirror.net/6/docs/ref/#autocomplete.moveCompletionSelection)`(true, "page")` - - Enter: [`acceptCompletion`](https://codemirror.net/6/docs/ref/#autocomplete.acceptCompletion) - */ - const completionKeymap = [ - { key: "Ctrl-Space", run: startCompletion }, - { key: "Escape", run: closeCompletion }, - { key: "ArrowDown", run: /*@__PURE__*/moveCompletionSelection(true) }, - { key: "ArrowUp", run: /*@__PURE__*/moveCompletionSelection(false) }, - { key: "PageDown", run: /*@__PURE__*/moveCompletionSelection(true, "page") }, - { key: "PageUp", run: /*@__PURE__*/moveCompletionSelection(false, "page") }, - { key: "Enter", run: acceptCompletion } - ]; - const completionKeymapExt = /*@__PURE__*/Prec.highest(/*@__PURE__*/keymap.computeN([completionConfig], state => state.facet(completionConfig).defaultKeymap ? [completionKeymap] : [])); - - /** - Comment or uncomment the current selection. Will use line comments - if available, otherwise falling back to block comments. - */ - const toggleComment = target => { - let config = getConfig(target.state); - return config.line ? toggleLineComment(target) : config.block ? toggleBlockCommentByLine(target) : false; - }; - function command(f, option) { - return ({ state, dispatch }) => { - if (state.readOnly) - return false; - let tr = f(option, state); - if (!tr) - return false; - dispatch(state.update(tr)); - return true; - }; - } - /** - Comment or uncomment the current selection using line comments. - The line comment syntax is taken from the - [`commentTokens`](https://codemirror.net/6/docs/ref/#comment.CommentTokens) [language - data](https://codemirror.net/6/docs/ref/#state.EditorState.languageDataAt). - */ - const toggleLineComment = /*@__PURE__*/command(changeLineComment, 0 /* Toggle */); - /** - Comment or uncomment the current selection using block comments. - The block comment syntax is taken from the - [`commentTokens`](https://codemirror.net/6/docs/ref/#comment.CommentTokens) [language - data](https://codemirror.net/6/docs/ref/#state.EditorState.languageDataAt). - */ - const toggleBlockComment = /*@__PURE__*/command(changeBlockComment, 0 /* Toggle */); - /** - Comment or uncomment the lines around the current selection using - block comments. - */ - const toggleBlockCommentByLine = /*@__PURE__*/command((o, s) => changeBlockComment(o, s, selectedLineRanges(s)), 0 /* Toggle */); - /** - Default key bindings for this package. - - - Ctrl-/ (Cmd-/ on macOS): [`toggleComment`](https://codemirror.net/6/docs/ref/#comment.toggleComment). - - Shift-Alt-a: [`toggleBlockComment`](https://codemirror.net/6/docs/ref/#comment.toggleBlockComment). - */ - const commentKeymap = [ - { key: "Mod-/", run: toggleComment }, - { key: "Alt-A", run: toggleBlockComment } - ]; - function getConfig(state, pos = state.selection.main.head) { - let data = state.languageDataAt("commentTokens", pos); - return data.length ? data[0] : {}; - } - const SearchMargin = 50; - /** - Determines if the given range is block-commented in the given - state. - */ - function findBlockComment(state, { open, close }, from, to) { - let textBefore = state.sliceDoc(from - SearchMargin, from); - let textAfter = state.sliceDoc(to, to + SearchMargin); - let spaceBefore = /\s*$/.exec(textBefore)[0].length, spaceAfter = /^\s*/.exec(textAfter)[0].length; - let beforeOff = textBefore.length - spaceBefore; - if (textBefore.slice(beforeOff - open.length, beforeOff) == open && - textAfter.slice(spaceAfter, spaceAfter + close.length) == close) { - return { open: { pos: from - spaceBefore, margin: spaceBefore && 1 }, - close: { pos: to + spaceAfter, margin: spaceAfter && 1 } }; - } - let startText, endText; - if (to - from <= 2 * SearchMargin) { - startText = endText = state.sliceDoc(from, to); - } - else { - startText = state.sliceDoc(from, from + SearchMargin); - endText = state.sliceDoc(to - SearchMargin, to); - } - let startSpace = /^\s*/.exec(startText)[0].length, endSpace = /\s*$/.exec(endText)[0].length; - let endOff = endText.length - endSpace - close.length; - if (startText.slice(startSpace, startSpace + open.length) == open && - endText.slice(endOff, endOff + close.length) == close) { - return { open: { pos: from + startSpace + open.length, - margin: /\s/.test(startText.charAt(startSpace + open.length)) ? 1 : 0 }, - close: { pos: to - endSpace - close.length, - margin: /\s/.test(endText.charAt(endOff - 1)) ? 1 : 0 } }; - } - return null; - } - function selectedLineRanges(state) { - let ranges = []; - for (let r of state.selection.ranges) { - let fromLine = state.doc.lineAt(r.from); - let toLine = r.to <= fromLine.to ? fromLine : state.doc.lineAt(r.to); - let last = ranges.length - 1; - if (last >= 0 && ranges[last].to > fromLine.from) - ranges[last].to = toLine.to; - else - ranges.push({ from: fromLine.from, to: toLine.to }); - } - return ranges; - } - // Performs toggle, comment and uncomment of block comments in - // languages that support them. - function changeBlockComment(option, state, ranges = state.selection.ranges) { - let tokens = ranges.map(r => getConfig(state, r.from).block); - if (!tokens.every(c => c)) - return null; - let comments = ranges.map((r, i) => findBlockComment(state, tokens[i], r.from, r.to)); - if (option != 2 /* Uncomment */ && !comments.every(c => c)) { - return { changes: state.changes(ranges.map((range, i) => { - if (comments[i]) - return []; - return [{ from: range.from, insert: tokens[i].open + " " }, { from: range.to, insert: " " + tokens[i].close }]; - })) }; - } - else if (option != 1 /* Comment */ && comments.some(c => c)) { - let changes = []; - for (let i = 0, comment; i < comments.length; i++) - if (comment = comments[i]) { - let token = tokens[i], { open, close } = comment; - changes.push({ from: open.pos - token.open.length, to: open.pos + open.margin }, { from: close.pos - close.margin, to: close.pos + token.close.length }); - } - return { changes }; - } - return null; - } - // Performs toggle, comment and uncomment of line comments. - function changeLineComment(option, state, ranges = state.selection.ranges) { - let lines = []; - let prevLine = -1; - for (let { from, to } of ranges) { - let startI = lines.length, minIndent = 1e9; - for (let pos = from; pos <= to;) { - let line = state.doc.lineAt(pos); - if (line.from > prevLine && (from == to || to > line.from)) { - prevLine = line.from; - let token = getConfig(state, pos).line; - if (!token) - continue; - let indent = /^\s*/.exec(line.text)[0].length; - let empty = indent == line.length; - let comment = line.text.slice(indent, indent + token.length) == token ? indent : -1; - if (indent < line.text.length && indent < minIndent) - minIndent = indent; - lines.push({ line, comment, token, indent, empty, single: false }); - } - pos = line.to + 1; - } - if (minIndent < 1e9) - for (let i = startI; i < lines.length; i++) - if (lines[i].indent < lines[i].line.text.length) - lines[i].indent = minIndent; - if (lines.length == startI + 1) - lines[startI].single = true; - } - if (option != 2 /* Uncomment */ && lines.some(l => l.comment < 0 && (!l.empty || l.single))) { - let changes = []; - for (let { line, token, indent, empty, single } of lines) - if (single || !empty) - changes.push({ from: line.from + indent, insert: token + " " }); - let changeSet = state.changes(changes); - return { changes: changeSet, selection: state.selection.map(changeSet, 1) }; - } - else if (option != 1 /* Comment */ && lines.some(l => l.comment >= 0)) { - let changes = []; - for (let { line, comment, token } of lines) - if (comment >= 0) { - let from = line.from + comment, to = from + token.length; - if (line.text[to - line.from] == " ") - to++; - changes.push({ from, to }); - } - return { changes }; - } - return null; - } - - // Don't compute precise column positions for line offsets above this - // (since it could get expensive). Assume offset==column for them. - const MaxOff = 2000; - function rectangleFor(state, a, b) { - let startLine = Math.min(a.line, b.line), endLine = Math.max(a.line, b.line); - let ranges = []; - if (a.off > MaxOff || b.off > MaxOff || a.col < 0 || b.col < 0) { - let startOff = Math.min(a.off, b.off), endOff = Math.max(a.off, b.off); - for (let i = startLine; i <= endLine; i++) { - let line = state.doc.line(i); - if (line.length <= endOff) - ranges.push(EditorSelection.range(line.from + startOff, line.to + endOff)); - } - } - else { - let startCol = Math.min(a.col, b.col), endCol = Math.max(a.col, b.col); - for (let i = startLine; i <= endLine; i++) { - let line = state.doc.line(i); - let start = findColumn(line.text, startCol, state.tabSize, true); - if (start > -1) { - let end = findColumn(line.text, endCol, state.tabSize); - ranges.push(EditorSelection.range(line.from + start, line.from + end)); - } - } - } - return ranges; - } - function absoluteColumn(view, x) { - let ref = view.coordsAtPos(view.viewport.from); - return ref ? Math.round(Math.abs((ref.left - x) / view.defaultCharacterWidth)) : -1; - } - function getPos(view, event) { - let offset = view.posAtCoords({ x: event.clientX, y: event.clientY }, false); - let line = view.state.doc.lineAt(offset), off = offset - line.from; - let col = off > MaxOff ? -1 - : off == line.length ? absoluteColumn(view, event.clientX) - : countColumn(line.text, view.state.tabSize, offset - line.from); - return { line: line.number, col, off }; - } - function rectangleSelectionStyle(view, event) { - let start = getPos(view, event), startSel = view.state.selection; - if (!start) - return null; - return { - update(update) { - if (update.docChanged) { - let newStart = update.changes.mapPos(update.startState.doc.line(start.line).from); - let newLine = update.state.doc.lineAt(newStart); - start = { line: newLine.number, col: start.col, off: Math.min(start.off, newLine.length) }; - startSel = startSel.map(update.changes); - } - }, - get(event, _extend, multiple) { - let cur = getPos(view, event); - if (!cur) - return startSel; - let ranges = rectangleFor(view.state, start, cur); - if (!ranges.length) - return startSel; - if (multiple) - return EditorSelection.create(ranges.concat(startSel.ranges)); - else - return EditorSelection.create(ranges); - } - }; - } - /** - Create an extension that enables rectangular selections. By - default, it will react to left mouse drag with the Alt key held - down. When such a selection occurs, the text within the rectangle - that was dragged over will be selected, as one selection - [range](https://codemirror.net/6/docs/ref/#state.SelectionRange) per line. - */ - function rectangularSelection(options) { - let filter = (options === null || options === void 0 ? void 0 : options.eventFilter) || (e => e.altKey && e.button == 0); - return EditorView.mouseSelectionStyle.of((view, event) => filter(event) ? rectangleSelectionStyle(view, event) : null); - } - const keys = { - Alt: [18, e => e.altKey], - Control: [17, e => e.ctrlKey], - Shift: [16, e => e.shiftKey], - Meta: [91, e => e.metaKey] - }; - const showCrosshair = { style: "cursor: crosshair" }; - /** - Returns an extension that turns the pointer cursor into a - crosshair when a given modifier key, defaulting to Alt, is held - down. Can serve as a visual hint that rectangular selection is - going to happen when paired with - [`rectangularSelection`](https://codemirror.net/6/docs/ref/#rectangular-selection.rectangularSelection). - */ - function crosshairCursor(options = {}) { - let [code, getter] = keys[options.key || "Alt"]; - let plugin = ViewPlugin.fromClass(class { - constructor(view) { - this.view = view; - this.isDown = false; - } - set(isDown) { - if (this.isDown != isDown) { - this.isDown = isDown; - this.view.update([]); - } - } - }, { - eventHandlers: { - keydown(e) { - this.set(e.keyCode == code || getter(e)); - }, - keyup(e) { - if (e.keyCode == code || !getter(e)) - this.set(false); - } - } - }); - return [ - plugin, - EditorView.contentAttributes.of(view => { var _a; return ((_a = view.plugin(plugin)) === null || _a === void 0 ? void 0 : _a.isDown) ? showCrosshair : null; }) - ]; - } - - let nextTagID = 0; - /** - Highlighting tags are markers that denote a highlighting category. - They are [associated](https://codemirror.net/6/docs/ref/#highlight.styleTags) with parts of a syntax - tree by a language mode, and then mapped to an actual CSS style by - a [highlight style](https://codemirror.net/6/docs/ref/#highlight.HighlightStyle). - - Because syntax tree node types and highlight styles have to be - able to talk the same language, CodeMirror uses a mostly _closed_ - [vocabulary](https://codemirror.net/6/docs/ref/#highlight.tags) of syntax tags (as opposed to - traditional open string-based systems, which make it hard for - highlighting themes to cover all the tokens produced by the - various languages). - - It _is_ possible to [define](https://codemirror.net/6/docs/ref/#highlight.Tag^define) your own - highlighting tags for system-internal use (where you control both - the language package and the highlighter), but such tags will not - be picked up by regular highlighters (though you can derive them - from standard tags to allow highlighters to fall back to those). - */ - class Tag { - /** - @internal - */ - constructor( - /** - The set of tags that match this tag, starting with this one - itself, sorted in order of decreasing specificity. @internal - */ - set, - /** - The base unmodified tag that this one is based on, if it's - modified @internal - */ - base, - /** - The modifiers applied to this.base @internal - */ - modified) { - this.set = set; - this.base = base; - this.modified = modified; - /** - @internal - */ - this.id = nextTagID++; - } - /** - Define a new tag. If `parent` is given, the tag is treated as a - sub-tag of that parent, and [highlight - styles](https://codemirror.net/6/docs/ref/#highlight.HighlightStyle) that don't mention this tag - will try to fall back to the parent tag (or grandparent tag, - etc). - */ - static define(parent) { - if (parent === null || parent === void 0 ? void 0 : parent.base) - throw new Error("Can not derive from a modified tag"); - let tag = new Tag([], null, []); - tag.set.push(tag); - if (parent) - for (let t of parent.set) - tag.set.push(t); - return tag; - } - /** - Define a tag _modifier_, which is a function that, given a tag, - will return a tag that is a subtag of the original. Applying the - same modifier to a twice tag will return the same value (`m1(t1) - == m1(t1)`) and applying multiple modifiers will, regardless or - order, produce the same tag (`m1(m2(t1)) == m2(m1(t1))`). - - When multiple modifiers are applied to a given base tag, each - smaller set of modifiers is registered as a parent, so that for - example `m1(m2(m3(t1)))` is a subtype of `m1(m2(t1))`, - `m1(m3(t1)`, and so on. - */ - static defineModifier() { - let mod = new Modifier; - return (tag) => { - if (tag.modified.indexOf(mod) > -1) - return tag; - return Modifier.get(tag.base || tag, tag.modified.concat(mod).sort((a, b) => a.id - b.id)); - }; - } - } - let nextModifierID = 0; - class Modifier { - constructor() { - this.instances = []; - this.id = nextModifierID++; - } - static get(base, mods) { - if (!mods.length) - return base; - let exists = mods[0].instances.find(t => t.base == base && sameArray(mods, t.modified)); - if (exists) - return exists; - let set = [], tag = new Tag(set, base, mods); - for (let m of mods) - m.instances.push(tag); - let configs = permute(mods); - for (let parent of base.set) - for (let config of configs) - set.push(Modifier.get(parent, config)); - return tag; - } - } - function sameArray(a, b) { - return a.length == b.length && a.every((x, i) => x == b[i]); - } - function permute(array) { - let result = [array]; - for (let i = 0; i < array.length; i++) { - for (let a of permute(array.slice(0, i).concat(array.slice(i + 1)))) - result.push(a); - } - return result; - } - /** - This function is used to add a set of tags to a language syntax - via - [`LRParser.configure`](https://lezer.codemirror.net/docs/ref#lr.LRParser.configure). - - The argument object maps node selectors to [highlighting - tags](https://codemirror.net/6/docs/ref/#highlight.Tag) or arrays of tags. - - Node selectors may hold one or more (space-separated) node paths. - Such a path can be a [node - name](https://lezer.codemirror.net/docs/ref#common.NodeType.name), - or multiple node names (or `*` wildcards) separated by slash - characters, as in `"Block/Declaration/VariableName"`. Such a path - matches the final node but only if its direct parent nodes are the - other nodes mentioned. A `*` in such a path matches any parent, - but only a single level—wildcards that match multiple parents - aren't supported, both for efficiency reasons and because Lezer - trees make it rather hard to reason about what they would match.) - - A path can be ended with `/...` to indicate that the tag assigned - to the node should also apply to all child nodes, even if they - match their own style (by default, only the innermost style is - used). - - When a path ends in `!`, as in `Attribute!`, no further matching - happens for the node's child nodes, and the entire node gets the - given style. - - In this notation, node names that contain `/`, `!`, `*`, or `...` - must be quoted as JSON strings. - - For example: - - ```javascript - parser.withProps( - styleTags({ - // Style Number and BigNumber nodes - "Number BigNumber": tags.number, - // Style Escape nodes whose parent is String - "String/Escape": tags.escape, - // Style anything inside Attributes nodes - "Attributes!": tags.meta, - // Add a style to all content inside Italic nodes - "Italic/...": tags.emphasis, - // Style InvalidString nodes as both `string` and `invalid` - "InvalidString": [tags.string, tags.invalid], - // Style the node named "/" as punctuation - '"/"': tags.punctuation - }) - ) - ``` - */ - function styleTags(spec) { - let byName = Object.create(null); - for (let prop in spec) { - let tags = spec[prop]; - if (!Array.isArray(tags)) - tags = [tags]; - for (let part of prop.split(" ")) - if (part) { - let pieces = [], mode = 2 /* Normal */, rest = part; - for (let pos = 0;;) { - if (rest == "..." && pos > 0 && pos + 3 == part.length) { - mode = 1 /* Inherit */; - break; - } - let m = /^"(?:[^"\\]|\\.)*?"|[^\/!]+/.exec(rest); - if (!m) - throw new RangeError("Invalid path: " + part); - pieces.push(m[0] == "*" ? null : m[0][0] == '"' ? JSON.parse(m[0]) : m[0]); - pos += m[0].length; - if (pos == part.length) - break; - let next = part[pos++]; - if (pos == part.length && next == "!") { - mode = 0 /* Opaque */; - break; - } - if (next != "/") - throw new RangeError("Invalid path: " + part); - rest = part.slice(pos); - } - let last = pieces.length - 1, inner = pieces[last]; - if (!inner) - throw new RangeError("Invalid path: " + part); - let rule = new Rule(tags, mode, last > 0 ? pieces.slice(0, last) : null); - byName[inner] = rule.sort(byName[inner]); - } - } - return ruleNodeProp.add(byName); - } - const ruleNodeProp = /*@__PURE__*/new NodeProp(); - const highlightStyle = /*@__PURE__*/Facet.define({ - combine(stylings) { return stylings.length ? HighlightStyle.combinedMatch(stylings) : null; } - }); - const fallbackHighlightStyle = /*@__PURE__*/Facet.define({ - combine(values) { return values.length ? values[0].match : null; } - }); - function getHighlightStyle(state) { - return state.facet(highlightStyle) || state.facet(fallbackHighlightStyle); - } - class Rule { - constructor(tags, mode, context, next) { - this.tags = tags; - this.mode = mode; - this.context = context; - this.next = next; - } - sort(other) { - if (!other || other.depth < this.depth) { - this.next = other; - return this; - } - other.next = this.sort(other.next); - return other; - } - get depth() { return this.context ? this.context.length : 0; } - } - /** - A highlight style associates CSS styles with higlighting - [tags](https://codemirror.net/6/docs/ref/#highlight.Tag). - */ - class HighlightStyle { - constructor(spec, options) { - this.map = Object.create(null); - let modSpec; - function def(spec) { - let cls = StyleModule.newName(); - (modSpec || (modSpec = Object.create(null)))["." + cls] = spec; - return cls; - } - this.all = typeof options.all == "string" ? options.all : options.all ? def(options.all) : null; - for (let style of spec) { - let cls = (style.class || def(Object.assign({}, style, { tag: null }))) + - (this.all ? " " + this.all : ""); - let tags = style.tag; - if (!Array.isArray(tags)) - this.map[tags.id] = cls; - else - for (let tag of tags) - this.map[tag.id] = cls; - } - this.module = modSpec ? new StyleModule(modSpec) : null; - this.scope = options.scope || null; - this.match = this.match.bind(this); - let ext = [treeHighlighter]; - if (this.module) - ext.push(EditorView.styleModule.of(this.module)); - this.extension = ext.concat(options.themeType == null ? highlightStyle.of(this) : - highlightStyle.computeN([EditorView.darkTheme], state => { - return state.facet(EditorView.darkTheme) == (options.themeType == "dark") ? [this] : []; - })); - this.fallback = ext.concat(fallbackHighlightStyle.of(this)); - } - /** - Returns the CSS class associated with the given tag, if any. - This method is bound to the instance by the constructor. - */ - match(tag, scope) { - if (this.scope && scope != this.scope) - return null; - for (let t of tag.set) { - let match = this.map[t.id]; - if (match !== undefined) { - if (t != tag) - this.map[tag.id] = match; - return match; - } - } - return this.map[tag.id] = this.all; - } - /** - Combines an array of highlight styles into a single match - function that returns all of the classes assigned by the styles - for a given tag. - */ - static combinedMatch(styles) { - if (styles.length == 1) - return styles[0].match; - let cache = styles.some(s => s.scope) ? undefined : Object.create(null); - return (tag, scope) => { - let cached = cache && cache[tag.id]; - if (cached !== undefined) - return cached; - let result = null; - for (let style of styles) { - let value = style.match(tag, scope); - if (value) - result = result ? result + " " + value : value; - } - if (cache) - cache[tag.id] = result; - return result; - }; - } - /** - Create a highlighter style that associates the given styles to - the given tags. The spec must be objects that hold a style tag - or array of tags in their `tag` property, and either a single - `class` property providing a static CSS class (for highlighters - like [`classHighlightStyle`](https://codemirror.net/6/docs/ref/#highlight.classHighlightStyle) - that rely on external styling), or a - [`style-mod`](https://github.com/marijnh/style-mod#documentation)-style - set of CSS properties (which define the styling for those tags). - - The CSS rules created for a highlighter will be emitted in the - order of the spec's properties. That means that for elements that - have multiple tags associated with them, styles defined further - down in the list will have a higher CSS precedence than styles - defined earlier. - */ - static define(specs, options) { - return new HighlightStyle(specs, options || {}); - } - /** - Returns the CSS classes (if any) that the highlight styles - active in the given state would assign to the given a style - [tag](https://codemirror.net/6/docs/ref/#highlight.Tag) and (optional) language - [scope](https://codemirror.net/6/docs/ref/#highlight.HighlightStyle^define^options.scope). - */ - static get(state, tag, scope) { - let style = getHighlightStyle(state); - return style && style(tag, scope || NodeType.none); - } - } - class TreeHighlighter { - constructor(view) { - this.markCache = Object.create(null); - this.tree = syntaxTree(view.state); - this.decorations = this.buildDeco(view, getHighlightStyle(view.state)); - } - update(update) { - let tree = syntaxTree(update.state), style = getHighlightStyle(update.state); - let styleChange = style != update.startState.facet(highlightStyle); - if (tree.length < update.view.viewport.to && !styleChange && tree.type == this.tree.type) { - this.decorations = this.decorations.map(update.changes); - } - else if (tree != this.tree || update.viewportChanged || styleChange) { - this.tree = tree; - this.decorations = this.buildDeco(update.view, style); - } - } - buildDeco(view, match) { - if (!match || !this.tree.length) - return Decoration.none; - let builder = new RangeSetBuilder(); - for (let { from, to } of view.visibleRanges) { - highlightTreeRange(this.tree, from, to, match, (from, to, style) => { - builder.add(from, to, this.markCache[style] || (this.markCache[style] = Decoration.mark({ class: style }))); - }); - } - return builder.finish(); - } - } - // This extension installs a highlighter that highlights based on the - // syntax tree and highlight style. - const treeHighlighter = /*@__PURE__*/Prec.high(/*@__PURE__*/ViewPlugin.fromClass(TreeHighlighter, { - decorations: v => v.decorations - })); - const nodeStack = [""]; - class HighlightBuilder { - constructor(at, style, span) { - this.at = at; - this.style = style; - this.span = span; - this.class = ""; - } - startSpan(at, cls) { - if (cls != this.class) { - this.flush(at); - if (at > this.at) - this.at = at; - this.class = cls; - } - } - flush(to) { - if (to > this.at && this.class) - this.span(this.at, to, this.class); - } - highlightRange(cursor, from, to, inheritedClass, depth, scope) { - let { type, from: start, to: end } = cursor; - if (start >= to || end <= from) - return; - nodeStack[depth] = type.name; - if (type.isTop) - scope = type; - let cls = inheritedClass; - let rule = type.prop(ruleNodeProp), opaque = false; - while (rule) { - if (!rule.context || matchContext(rule.context, nodeStack, depth)) { - for (let tag of rule.tags) { - let st = this.style(tag, scope); - if (st) { - if (cls) - cls += " "; - cls += st; - if (rule.mode == 1 /* Inherit */) - inheritedClass += (inheritedClass ? " " : "") + st; - else if (rule.mode == 0 /* Opaque */) - opaque = true; - } - } - break; - } - rule = rule.next; - } - this.startSpan(cursor.from, cls); - if (opaque) - return; - let mounted = cursor.tree && cursor.tree.prop(NodeProp.mounted); - if (mounted && mounted.overlay) { - let inner = cursor.node.enter(mounted.overlay[0].from + start, 1); - let hasChild = cursor.firstChild(); - for (let i = 0, pos = start;; i++) { - let next = i < mounted.overlay.length ? mounted.overlay[i] : null; - let nextPos = next ? next.from + start : end; - let rangeFrom = Math.max(from, pos), rangeTo = Math.min(to, nextPos); - if (rangeFrom < rangeTo && hasChild) { - while (cursor.from < rangeTo) { - this.highlightRange(cursor, rangeFrom, rangeTo, inheritedClass, depth + 1, scope); - this.startSpan(Math.min(to, cursor.to), cls); - if (cursor.to >= nextPos || !cursor.nextSibling()) - break; - } - } - if (!next || nextPos > to) - break; - pos = next.to + start; - if (pos > from) { - this.highlightRange(inner.cursor, Math.max(from, next.from + start), Math.min(to, pos), inheritedClass, depth, mounted.tree.type); - this.startSpan(pos, cls); - } - } - if (hasChild) - cursor.parent(); - } - else if (cursor.firstChild()) { - do { - if (cursor.to <= from) - continue; - if (cursor.from >= to) - break; - this.highlightRange(cursor, from, to, inheritedClass, depth + 1, scope); - this.startSpan(Math.min(to, cursor.to), cls); - } while (cursor.nextSibling()); - cursor.parent(); - } - } - } - function highlightTreeRange(tree, from, to, style, span) { - let builder = new HighlightBuilder(from, style, span); - builder.highlightRange(tree.cursor(), from, to, "", 0, tree.type); - builder.flush(to); - } - function matchContext(context, stack, depth) { - if (context.length > depth - 1) - return false; - for (let d = depth - 1, i = context.length - 1; i >= 0; i--, d--) { - let check = context[i]; - if (check && check != stack[d]) - return false; - } - return true; - } - const t = Tag.define; - const comment = /*@__PURE__*/t(), name = /*@__PURE__*/t(), typeName = /*@__PURE__*/t(name), propertyName = /*@__PURE__*/t(name), literal = /*@__PURE__*/t(), string = /*@__PURE__*/t(literal), number = /*@__PURE__*/t(literal), content = /*@__PURE__*/t(), heading = /*@__PURE__*/t(content), keyword = /*@__PURE__*/t(), operator = /*@__PURE__*/t(), punctuation = /*@__PURE__*/t(), bracket = /*@__PURE__*/t(punctuation), meta = /*@__PURE__*/t(); - /** - The default set of highlighting [tags](https://codemirror.net/6/docs/ref/#highlight.Tag^define) used - by regular language packages and themes. - - This collection is heavily biased towards programming languages, - and necessarily incomplete. A full ontology of syntactic - constructs would fill a stack of books, and be impractical to - write themes for. So try to make do with this set. If all else - fails, [open an - issue](https://github.com/codemirror/codemirror.next) to propose a - new tag, or [define](https://codemirror.net/6/docs/ref/#highlight.Tag^define) a local custom tag for - your use case. - - Note that it is not obligatory to always attach the most specific - tag possible to an element—if your grammar can't easily - distinguish a certain type of element (such as a local variable), - it is okay to style it as its more general variant (a variable). - - For tags that extend some parent tag, the documentation links to - the parent. - */ - const tags = { - /** - A comment. - */ - comment, - /** - A line [comment](https://codemirror.net/6/docs/ref/#highlight.tags.comment). - */ - lineComment: /*@__PURE__*/t(comment), - /** - A block [comment](https://codemirror.net/6/docs/ref/#highlight.tags.comment). - */ - blockComment: /*@__PURE__*/t(comment), - /** - A documentation [comment](https://codemirror.net/6/docs/ref/#highlight.tags.comment). - */ - docComment: /*@__PURE__*/t(comment), - /** - Any kind of identifier. - */ - name, - /** - The [name](https://codemirror.net/6/docs/ref/#highlight.tags.name) of a variable. - */ - variableName: /*@__PURE__*/t(name), - /** - A type [name](https://codemirror.net/6/docs/ref/#highlight.tags.name). - */ - typeName: typeName, - /** - A tag name (subtag of [`typeName`](https://codemirror.net/6/docs/ref/#highlight.tags.typeName)). - */ - tagName: /*@__PURE__*/t(typeName), - /** - A property or field [name](https://codemirror.net/6/docs/ref/#highlight.tags.name). - */ - propertyName: propertyName, - /** - An attribute name (subtag of [`propertyName`](https://codemirror.net/6/docs/ref/#highlight.tags.propertyName)). - */ - attributeName: /*@__PURE__*/t(propertyName), - /** - The [name](https://codemirror.net/6/docs/ref/#highlight.tags.name) of a class. - */ - className: /*@__PURE__*/t(name), - /** - A label [name](https://codemirror.net/6/docs/ref/#highlight.tags.name). - */ - labelName: /*@__PURE__*/t(name), - /** - A namespace [name](https://codemirror.net/6/docs/ref/#highlight.tags.name). - */ - namespace: /*@__PURE__*/t(name), - /** - The [name](https://codemirror.net/6/docs/ref/#highlight.tags.name) of a macro. - */ - macroName: /*@__PURE__*/t(name), - /** - A literal value. - */ - literal, - /** - A string [literal](https://codemirror.net/6/docs/ref/#highlight.tags.literal). - */ - string, - /** - A documentation [string](https://codemirror.net/6/docs/ref/#highlight.tags.string). - */ - docString: /*@__PURE__*/t(string), - /** - A character literal (subtag of [string](https://codemirror.net/6/docs/ref/#highlight.tags.string)). - */ - character: /*@__PURE__*/t(string), - /** - An attribute value (subtag of [string](https://codemirror.net/6/docs/ref/#highlight.tags.string)). - */ - attributeValue: /*@__PURE__*/t(string), - /** - A number [literal](https://codemirror.net/6/docs/ref/#highlight.tags.literal). - */ - number, - /** - An integer [number](https://codemirror.net/6/docs/ref/#highlight.tags.number) literal. - */ - integer: /*@__PURE__*/t(number), - /** - A floating-point [number](https://codemirror.net/6/docs/ref/#highlight.tags.number) literal. - */ - float: /*@__PURE__*/t(number), - /** - A boolean [literal](https://codemirror.net/6/docs/ref/#highlight.tags.literal). - */ - bool: /*@__PURE__*/t(literal), - /** - Regular expression [literal](https://codemirror.net/6/docs/ref/#highlight.tags.literal). - */ - regexp: /*@__PURE__*/t(literal), - /** - An escape [literal](https://codemirror.net/6/docs/ref/#highlight.tags.literal), for example a - backslash escape in a string. - */ - escape: /*@__PURE__*/t(literal), - /** - A color [literal](https://codemirror.net/6/docs/ref/#highlight.tags.literal). - */ - color: /*@__PURE__*/t(literal), - /** - A URL [literal](https://codemirror.net/6/docs/ref/#highlight.tags.literal). - */ - url: /*@__PURE__*/t(literal), - /** - A language keyword. - */ - keyword, - /** - The [keyword](https://codemirror.net/6/docs/ref/#highlight.tags.keyword) for the self or this - object. - */ - self: /*@__PURE__*/t(keyword), - /** - The [keyword](https://codemirror.net/6/docs/ref/#highlight.tags.keyword) for null. - */ - null: /*@__PURE__*/t(keyword), - /** - A [keyword](https://codemirror.net/6/docs/ref/#highlight.tags.keyword) denoting some atomic value. - */ - atom: /*@__PURE__*/t(keyword), - /** - A [keyword](https://codemirror.net/6/docs/ref/#highlight.tags.keyword) that represents a unit. - */ - unit: /*@__PURE__*/t(keyword), - /** - A modifier [keyword](https://codemirror.net/6/docs/ref/#highlight.tags.keyword). - */ - modifier: /*@__PURE__*/t(keyword), - /** - A [keyword](https://codemirror.net/6/docs/ref/#highlight.tags.keyword) that acts as an operator. - */ - operatorKeyword: /*@__PURE__*/t(keyword), - /** - A control-flow related [keyword](https://codemirror.net/6/docs/ref/#highlight.tags.keyword). - */ - controlKeyword: /*@__PURE__*/t(keyword), - /** - A [keyword](https://codemirror.net/6/docs/ref/#highlight.tags.keyword) that defines something. - */ - definitionKeyword: /*@__PURE__*/t(keyword), - /** - A [keyword](https://codemirror.net/6/docs/ref/#highlight.tags.keyword) related to defining or - interfacing with modules. - */ - moduleKeyword: /*@__PURE__*/t(keyword), - /** - An operator. - */ - operator, - /** - An [operator](https://codemirror.net/6/docs/ref/#highlight.tags.operator) that defines something. - */ - derefOperator: /*@__PURE__*/t(operator), - /** - Arithmetic-related [operator](https://codemirror.net/6/docs/ref/#highlight.tags.operator). - */ - arithmeticOperator: /*@__PURE__*/t(operator), - /** - Logical [operator](https://codemirror.net/6/docs/ref/#highlight.tags.operator). - */ - logicOperator: /*@__PURE__*/t(operator), - /** - Bit [operator](https://codemirror.net/6/docs/ref/#highlight.tags.operator). - */ - bitwiseOperator: /*@__PURE__*/t(operator), - /** - Comparison [operator](https://codemirror.net/6/docs/ref/#highlight.tags.operator). - */ - compareOperator: /*@__PURE__*/t(operator), - /** - [Operator](https://codemirror.net/6/docs/ref/#highlight.tags.operator) that updates its operand. - */ - updateOperator: /*@__PURE__*/t(operator), - /** - [Operator](https://codemirror.net/6/docs/ref/#highlight.tags.operator) that defines something. - */ - definitionOperator: /*@__PURE__*/t(operator), - /** - Type-related [operator](https://codemirror.net/6/docs/ref/#highlight.tags.operator). - */ - typeOperator: /*@__PURE__*/t(operator), - /** - Control-flow [operator](https://codemirror.net/6/docs/ref/#highlight.tags.operator). - */ - controlOperator: /*@__PURE__*/t(operator), - /** - Program or markup punctuation. - */ - punctuation, - /** - [Punctuation](https://codemirror.net/6/docs/ref/#highlight.tags.punctuation) that separates - things. - */ - separator: /*@__PURE__*/t(punctuation), - /** - Bracket-style [punctuation](https://codemirror.net/6/docs/ref/#highlight.tags.punctuation). - */ - bracket, - /** - Angle [brackets](https://codemirror.net/6/docs/ref/#highlight.tags.bracket) (usually `<` and `>` - tokens). - */ - angleBracket: /*@__PURE__*/t(bracket), - /** - Square [brackets](https://codemirror.net/6/docs/ref/#highlight.tags.bracket) (usually `[` and `]` - tokens). - */ - squareBracket: /*@__PURE__*/t(bracket), - /** - Parentheses (usually `(` and `)` tokens). Subtag of - [bracket](https://codemirror.net/6/docs/ref/#highlight.tags.bracket). - */ - paren: /*@__PURE__*/t(bracket), - /** - Braces (usually `{` and `}` tokens). Subtag of - [bracket](https://codemirror.net/6/docs/ref/#highlight.tags.bracket). - */ - brace: /*@__PURE__*/t(bracket), - /** - Content, for example plain text in XML or markup documents. - */ - content, - /** - [Content](https://codemirror.net/6/docs/ref/#highlight.tags.content) that represents a heading. - */ - heading, - /** - A level 1 [heading](https://codemirror.net/6/docs/ref/#highlight.tags.heading). - */ - heading1: /*@__PURE__*/t(heading), - /** - A level 2 [heading](https://codemirror.net/6/docs/ref/#highlight.tags.heading). - */ - heading2: /*@__PURE__*/t(heading), - /** - A level 3 [heading](https://codemirror.net/6/docs/ref/#highlight.tags.heading). - */ - heading3: /*@__PURE__*/t(heading), - /** - A level 4 [heading](https://codemirror.net/6/docs/ref/#highlight.tags.heading). - */ - heading4: /*@__PURE__*/t(heading), - /** - A level 5 [heading](https://codemirror.net/6/docs/ref/#highlight.tags.heading). - */ - heading5: /*@__PURE__*/t(heading), - /** - A level 6 [heading](https://codemirror.net/6/docs/ref/#highlight.tags.heading). - */ - heading6: /*@__PURE__*/t(heading), - /** - A prose separator (such as a horizontal rule). - */ - contentSeparator: /*@__PURE__*/t(content), - /** - [Content](https://codemirror.net/6/docs/ref/#highlight.tags.content) that represents a list. - */ - list: /*@__PURE__*/t(content), - /** - [Content](https://codemirror.net/6/docs/ref/#highlight.tags.content) that represents a quote. - */ - quote: /*@__PURE__*/t(content), - /** - [Content](https://codemirror.net/6/docs/ref/#highlight.tags.content) that is emphasized. - */ - emphasis: /*@__PURE__*/t(content), - /** - [Content](https://codemirror.net/6/docs/ref/#highlight.tags.content) that is styled strong. - */ - strong: /*@__PURE__*/t(content), - /** - [Content](https://codemirror.net/6/docs/ref/#highlight.tags.content) that is part of a link. - */ - link: /*@__PURE__*/t(content), - /** - [Content](https://codemirror.net/6/docs/ref/#highlight.tags.content) that is styled as code or - monospace. - */ - monospace: /*@__PURE__*/t(content), - /** - [Content](https://codemirror.net/6/docs/ref/#highlight.tags.content) that has a strike-through - style. - */ - strikethrough: /*@__PURE__*/t(content), - /** - Inserted text in a change-tracking format. - */ - inserted: /*@__PURE__*/t(), - /** - Deleted text. - */ - deleted: /*@__PURE__*/t(), - /** - Changed text. - */ - changed: /*@__PURE__*/t(), - /** - An invalid or unsyntactic element. - */ - invalid: /*@__PURE__*/t(), - /** - Metadata or meta-instruction. - */ - meta, - /** - [Metadata](https://codemirror.net/6/docs/ref/#highlight.tags.meta) that applies to the entire - document. - */ - documentMeta: /*@__PURE__*/t(meta), - /** - [Metadata](https://codemirror.net/6/docs/ref/#highlight.tags.meta) that annotates or adds - attributes to a given syntactic element. - */ - annotation: /*@__PURE__*/t(meta), - /** - Processing instruction or preprocessor directive. Subtag of - [meta](https://codemirror.net/6/docs/ref/#highlight.tags.meta). - */ - processingInstruction: /*@__PURE__*/t(meta), - /** - [Modifier](https://codemirror.net/6/docs/ref/#highlight.Tag^defineModifier) that indicates that a - given element is being defined. Expected to be used with the - various [name](https://codemirror.net/6/docs/ref/#highlight.tags.name) tags. - */ - definition: /*@__PURE__*/Tag.defineModifier(), - /** - [Modifier](https://codemirror.net/6/docs/ref/#highlight.Tag^defineModifier) that indicates that - something is constant. Mostly expected to be used with - [variable names](https://codemirror.net/6/docs/ref/#highlight.tags.variableName). - */ - constant: /*@__PURE__*/Tag.defineModifier(), - /** - [Modifier](https://codemirror.net/6/docs/ref/#highlight.Tag^defineModifier) used to indicate that - a [variable](https://codemirror.net/6/docs/ref/#highlight.tags.variableName) or [property - name](https://codemirror.net/6/docs/ref/#highlight.tags.propertyName) is being called or defined - as a function. - */ - function: /*@__PURE__*/Tag.defineModifier(), - /** - [Modifier](https://codemirror.net/6/docs/ref/#highlight.Tag^defineModifier) that can be applied to - [names](https://codemirror.net/6/docs/ref/#highlight.tags.name) to indicate that they belong to - the language's standard environment. - */ - standard: /*@__PURE__*/Tag.defineModifier(), - /** - [Modifier](https://codemirror.net/6/docs/ref/#highlight.Tag^defineModifier) that indicates a given - [names](https://codemirror.net/6/docs/ref/#highlight.tags.name) is local to some scope. - */ - local: /*@__PURE__*/Tag.defineModifier(), - /** - A generic variant [modifier](https://codemirror.net/6/docs/ref/#highlight.Tag^defineModifier) that - can be used to tag language-specific alternative variants of - some common tag. It is recommended for themes to define special - forms of at least the [string](https://codemirror.net/6/docs/ref/#highlight.tags.string) and - [variable name](https://codemirror.net/6/docs/ref/#highlight.tags.variableName) tags, since those - come up a lot. - */ - special: /*@__PURE__*/Tag.defineModifier() - }; - /** - A default highlight style (works well with light themes). - */ - const defaultHighlightStyle = /*@__PURE__*/HighlightStyle.define([ - { tag: tags.link, - textDecoration: "underline" }, - { tag: tags.heading, - textDecoration: "underline", - fontWeight: "bold" }, - { tag: tags.emphasis, - fontStyle: "italic" }, - { tag: tags.strong, - fontWeight: "bold" }, - { tag: tags.strikethrough, - textDecoration: "line-through" }, - { tag: tags.keyword, - color: "#708" }, - { tag: [tags.atom, tags.bool, tags.url, tags.contentSeparator, tags.labelName], - color: "#219" }, - { tag: [tags.literal, tags.inserted], - color: "#164" }, - { tag: [tags.string, tags.deleted], - color: "#a11" }, - { tag: [tags.regexp, tags.escape, /*@__PURE__*/tags.special(tags.string)], - color: "#e40" }, - { tag: /*@__PURE__*/tags.definition(tags.variableName), - color: "#00f" }, - { tag: /*@__PURE__*/tags.local(tags.variableName), - color: "#30a" }, - { tag: [tags.typeName, tags.namespace], - color: "#085" }, - { tag: tags.className, - color: "#167" }, - { tag: [/*@__PURE__*/tags.special(tags.variableName), tags.macroName], - color: "#256" }, - { tag: /*@__PURE__*/tags.definition(tags.propertyName), - color: "#00c" }, - { tag: tags.comment, - color: "#940" }, - { tag: tags.meta, - color: "#7a757a" }, - { tag: tags.invalid, - color: "#f00" } - ]); - /** - This is a highlight style that adds stable, predictable classes to - tokens, for styling with external CSS. - - These tags are mapped to their name prefixed with `"cmt-"` (for - example `"cmt-comment"`): - - * [`link`](https://codemirror.net/6/docs/ref/#highlight.tags.link) - * [`heading`](https://codemirror.net/6/docs/ref/#highlight.tags.heading) - * [`emphasis`](https://codemirror.net/6/docs/ref/#highlight.tags.emphasis) - * [`strong`](https://codemirror.net/6/docs/ref/#highlight.tags.strong) - * [`keyword`](https://codemirror.net/6/docs/ref/#highlight.tags.keyword) - * [`atom`](https://codemirror.net/6/docs/ref/#highlight.tags.atom) - * [`bool`](https://codemirror.net/6/docs/ref/#highlight.tags.bool) - * [`url`](https://codemirror.net/6/docs/ref/#highlight.tags.url) - * [`labelName`](https://codemirror.net/6/docs/ref/#highlight.tags.labelName) - * [`inserted`](https://codemirror.net/6/docs/ref/#highlight.tags.inserted) - * [`deleted`](https://codemirror.net/6/docs/ref/#highlight.tags.deleted) - * [`literal`](https://codemirror.net/6/docs/ref/#highlight.tags.literal) - * [`string`](https://codemirror.net/6/docs/ref/#highlight.tags.string) - * [`number`](https://codemirror.net/6/docs/ref/#highlight.tags.number) - * [`variableName`](https://codemirror.net/6/docs/ref/#highlight.tags.variableName) - * [`typeName`](https://codemirror.net/6/docs/ref/#highlight.tags.typeName) - * [`namespace`](https://codemirror.net/6/docs/ref/#highlight.tags.namespace) - * [`className`](https://codemirror.net/6/docs/ref/#highlight.tags.className) - * [`macroName`](https://codemirror.net/6/docs/ref/#highlight.tags.macroName) - * [`propertyName`](https://codemirror.net/6/docs/ref/#highlight.tags.propertyName) - * [`operator`](https://codemirror.net/6/docs/ref/#highlight.tags.operator) - * [`comment`](https://codemirror.net/6/docs/ref/#highlight.tags.comment) - * [`meta`](https://codemirror.net/6/docs/ref/#highlight.tags.meta) - * [`punctuation`](https://codemirror.net/6/docs/ref/#highlight.tags.puncutation) - * [`invalid`](https://codemirror.net/6/docs/ref/#highlight.tags.invalid) - - In addition, these mappings are provided: - - * [`regexp`](https://codemirror.net/6/docs/ref/#highlight.tags.regexp), - [`escape`](https://codemirror.net/6/docs/ref/#highlight.tags.escape), and - [`special`](https://codemirror.net/6/docs/ref/#highlight.tags.special)[`(string)`](https://codemirror.net/6/docs/ref/#highlight.tags.string) - are mapped to `"cmt-string2"` - * [`special`](https://codemirror.net/6/docs/ref/#highlight.tags.special)[`(variableName)`](https://codemirror.net/6/docs/ref/#highlight.tags.variableName) - to `"cmt-variableName2"` - * [`local`](https://codemirror.net/6/docs/ref/#highlight.tags.local)[`(variableName)`](https://codemirror.net/6/docs/ref/#highlight.tags.variableName) - to `"cmt-variableName cmt-local"` - * [`definition`](https://codemirror.net/6/docs/ref/#highlight.tags.definition)[`(variableName)`](https://codemirror.net/6/docs/ref/#highlight.tags.variableName) - to `"cmt-variableName cmt-definition"` - * [`definition`](https://codemirror.net/6/docs/ref/#highlight.tags.definition)[`(propertyName)`](https://codemirror.net/6/docs/ref/#highlight.tags.propertyName) - to `"cmt-propertyName cmt-definition"` - */ - /*@__PURE__*/HighlightStyle.define([ - { tag: tags.link, class: "cmt-link" }, - { tag: tags.heading, class: "cmt-heading" }, - { tag: tags.emphasis, class: "cmt-emphasis" }, - { tag: tags.strong, class: "cmt-strong" }, - { tag: tags.keyword, class: "cmt-keyword" }, - { tag: tags.atom, class: "cmt-atom" }, - { tag: tags.bool, class: "cmt-bool" }, - { tag: tags.url, class: "cmt-url" }, - { tag: tags.labelName, class: "cmt-labelName" }, - { tag: tags.inserted, class: "cmt-inserted" }, - { tag: tags.deleted, class: "cmt-deleted" }, - { tag: tags.literal, class: "cmt-literal" }, - { tag: tags.string, class: "cmt-string" }, - { tag: tags.number, class: "cmt-number" }, - { tag: [tags.regexp, tags.escape, /*@__PURE__*/tags.special(tags.string)], class: "cmt-string2" }, - { tag: tags.variableName, class: "cmt-variableName" }, - { tag: /*@__PURE__*/tags.local(tags.variableName), class: "cmt-variableName cmt-local" }, - { tag: /*@__PURE__*/tags.definition(tags.variableName), class: "cmt-variableName cmt-definition" }, - { tag: /*@__PURE__*/tags.special(tags.variableName), class: "cmt-variableName2" }, - { tag: /*@__PURE__*/tags.definition(tags.propertyName), class: "cmt-propertyName cmt-definition" }, - { tag: tags.typeName, class: "cmt-typeName" }, - { tag: tags.namespace, class: "cmt-namespace" }, - { tag: tags.className, class: "cmt-className" }, - { tag: tags.macroName, class: "cmt-macroName" }, - { tag: tags.propertyName, class: "cmt-propertyName" }, - { tag: tags.operator, class: "cmt-operator" }, - { tag: tags.comment, class: "cmt-comment" }, - { tag: tags.meta, class: "cmt-meta" }, - { tag: tags.invalid, class: "cmt-invalid" }, - { tag: tags.punctuation, class: "cmt-punctuation" } - ]); - - class SelectedDiagnostic { - constructor(from, to, diagnostic) { - this.from = from; - this.to = to; - this.diagnostic = diagnostic; - } - } - class LintState { - constructor(diagnostics, panel, selected) { - this.diagnostics = diagnostics; - this.panel = panel; - this.selected = selected; - } - static init(diagnostics, panel, state) { - let ranges = Decoration.set(diagnostics.map((d) => { - // For zero-length ranges or ranges covering only a line break, create a widget - return d.from == d.to || (d.from == d.to - 1 && state.doc.lineAt(d.from).to == d.from) - ? Decoration.widget({ - widget: new DiagnosticWidget(d), - diagnostic: d - }).range(d.from) - : Decoration.mark({ - attributes: { class: "cm-lintRange cm-lintRange-" + d.severity }, - diagnostic: d - }).range(d.from, d.to); - }), true); - return new LintState(ranges, panel, findDiagnostic(ranges)); - } - } - function findDiagnostic(diagnostics, diagnostic = null, after = 0) { - let found = null; - diagnostics.between(after, 1e9, (from, to, { spec }) => { - if (diagnostic && spec.diagnostic != diagnostic) - return; - found = new SelectedDiagnostic(from, to, spec.diagnostic); - return false; - }); - return found; - } - function maybeEnableLint(state, effects) { - return state.field(lintState, false) ? effects : effects.concat(StateEffect.appendConfig.of([ - lintState, - EditorView.decorations.compute([lintState], state => { - let { selected, panel } = state.field(lintState); - return !selected || !panel || selected.from == selected.to ? Decoration.none : Decoration.set([ - activeMark.range(selected.from, selected.to) - ]); - }), - hoverTooltip(lintTooltip), - baseTheme - ])); - } - /** - The state effect that updates the set of active diagnostics. Can - be useful when writing an extension that needs to track these. - */ - const setDiagnosticsEffect = /*@__PURE__*/StateEffect.define(); - const togglePanel = /*@__PURE__*/StateEffect.define(); - const movePanelSelection = /*@__PURE__*/StateEffect.define(); - const lintState = /*@__PURE__*/StateField.define({ - create() { - return new LintState(Decoration.none, null, null); - }, - update(value, tr) { - if (tr.docChanged) { - let mapped = value.diagnostics.map(tr.changes), selected = null; - if (value.selected) { - let selPos = tr.changes.mapPos(value.selected.from, 1); - selected = findDiagnostic(mapped, value.selected.diagnostic, selPos) || findDiagnostic(mapped, null, selPos); - } - value = new LintState(mapped, value.panel, selected); - } - for (let effect of tr.effects) { - if (effect.is(setDiagnosticsEffect)) { - value = LintState.init(effect.value, value.panel, tr.state); - } - else if (effect.is(togglePanel)) { - value = new LintState(value.diagnostics, effect.value ? LintPanel.open : null, value.selected); - } - else if (effect.is(movePanelSelection)) { - value = new LintState(value.diagnostics, value.panel, effect.value); - } - } - return value; - }, - provide: f => [showPanel.from(f, val => val.panel), - EditorView.decorations.from(f, s => s.diagnostics)] - }); - const activeMark = /*@__PURE__*/Decoration.mark({ class: "cm-lintRange cm-lintRange-active" }); - function lintTooltip(view, pos, side) { - let { diagnostics } = view.state.field(lintState); - let found = [], stackStart = 2e8, stackEnd = 0; - diagnostics.between(pos - (side < 0 ? 1 : 0), pos + (side > 0 ? 1 : 0), (from, to, { spec }) => { - if (pos >= from && pos <= to && - (from == to || ((pos > from || side > 0) && (pos < to || side < 0)))) { - found.push(spec.diagnostic); - stackStart = Math.min(from, stackStart); - stackEnd = Math.max(to, stackEnd); - } - }); - if (!found.length) - return null; - return { - pos: stackStart, - end: stackEnd, - above: view.state.doc.lineAt(stackStart).to < stackEnd, - create() { - return { dom: diagnosticsTooltip(view, found) }; - } - }; - } - function diagnosticsTooltip(view, diagnostics) { - return crelt("ul", { class: "cm-tooltip-lint" }, diagnostics.map(d => renderDiagnostic(view, d, false))); - } - /** - Command to open and focus the lint panel. - */ - const openLintPanel = (view) => { - let field = view.state.field(lintState, false); - if (!field || !field.panel) - view.dispatch({ effects: maybeEnableLint(view.state, [togglePanel.of(true)]) }); - let panel = getPanel(view, LintPanel.open); - if (panel) - panel.dom.querySelector(".cm-panel-lint ul").focus(); - return true; - }; - /** - Command to close the lint panel, when open. - */ - const closeLintPanel = (view) => { - let field = view.state.field(lintState, false); - if (!field || !field.panel) - return false; - view.dispatch({ effects: togglePanel.of(false) }); - return true; - }; - /** - Move the selection to the next diagnostic. - */ - const nextDiagnostic = (view) => { - let field = view.state.field(lintState, false); - if (!field) - return false; - let sel = view.state.selection.main, next = field.diagnostics.iter(sel.to + 1); - if (!next.value) { - next = field.diagnostics.iter(0); - if (!next.value || next.from == sel.from && next.to == sel.to) - return false; - } - view.dispatch({ selection: { anchor: next.from, head: next.to }, scrollIntoView: true }); - return true; - }; - /** - A set of default key bindings for the lint functionality. - - - Ctrl-Shift-m (Cmd-Shift-m on macOS): [`openLintPanel`](https://codemirror.net/6/docs/ref/#lint.openLintPanel) - - F8: [`nextDiagnostic`](https://codemirror.net/6/docs/ref/#lint.nextDiagnostic) - */ - const lintKeymap = [ - { key: "Mod-Shift-m", run: openLintPanel }, - { key: "F8", run: nextDiagnostic } - ]; - function assignKeys(actions) { - let assigned = []; - if (actions) - actions: for (let { name } of actions) { - for (let i = 0; i < name.length; i++) { - let ch = name[i]; - if (/[a-zA-Z]/.test(ch) && !assigned.some(c => c.toLowerCase() == ch.toLowerCase())) { - assigned.push(ch); - continue actions; - } - } - assigned.push(""); - } - return assigned; - } - function renderDiagnostic(view, diagnostic, inPanel) { - var _a; - let keys = inPanel ? assignKeys(diagnostic.actions) : []; - return crelt("li", { class: "cm-diagnostic cm-diagnostic-" + diagnostic.severity }, crelt("span", { class: "cm-diagnosticText" }, diagnostic.message), (_a = diagnostic.actions) === null || _a === void 0 ? void 0 : _a.map((action, i) => { - let click = (e) => { - e.preventDefault(); - let found = findDiagnostic(view.state.field(lintState).diagnostics, diagnostic); - if (found) - action.apply(view, found.from, found.to); - }; - let { name } = action, keyIndex = keys[i] ? name.indexOf(keys[i]) : -1; - let nameElt = keyIndex < 0 ? name : [name.slice(0, keyIndex), - crelt("u", name.slice(keyIndex, keyIndex + 1)), - name.slice(keyIndex + 1)]; - return crelt("button", { - type: "button", - class: "cm-diagnosticAction", - onclick: click, - onmousedown: click, - "aria-label": ` Action: ${name}${keyIndex < 0 ? "" : ` (access key "${keys[i]})"`}.` - }, nameElt); - }), diagnostic.source && crelt("div", { class: "cm-diagnosticSource" }, diagnostic.source)); - } - class DiagnosticWidget extends WidgetType { - constructor(diagnostic) { - super(); - this.diagnostic = diagnostic; - } - eq(other) { return other.diagnostic == this.diagnostic; } - toDOM() { - return crelt("span", { class: "cm-lintPoint cm-lintPoint-" + this.diagnostic.severity }); - } - } - class PanelItem { - constructor(view, diagnostic) { - this.diagnostic = diagnostic; - this.id = "item_" + Math.floor(Math.random() * 0xffffffff).toString(16); - this.dom = renderDiagnostic(view, diagnostic, true); - this.dom.id = this.id; - this.dom.setAttribute("role", "option"); - } - } - class LintPanel { - constructor(view) { - this.view = view; - this.items = []; - let onkeydown = (event) => { - if (event.keyCode == 27) { // Escape - closeLintPanel(this.view); - this.view.focus(); - } - else if (event.keyCode == 38 || event.keyCode == 33) { // ArrowUp, PageUp - this.moveSelection((this.selectedIndex - 1 + this.items.length) % this.items.length); - } - else if (event.keyCode == 40 || event.keyCode == 34) { // ArrowDown, PageDown - this.moveSelection((this.selectedIndex + 1) % this.items.length); - } - else if (event.keyCode == 36) { // Home - this.moveSelection(0); - } - else if (event.keyCode == 35) { // End - this.moveSelection(this.items.length - 1); - } - else if (event.keyCode == 13) { // Enter - this.view.focus(); - } - else if (event.keyCode >= 65 && event.keyCode <= 90 && this.selectedIndex >= 0) { // A-Z - let { diagnostic } = this.items[this.selectedIndex], keys = assignKeys(diagnostic.actions); - for (let i = 0; i < keys.length; i++) - if (keys[i].toUpperCase().charCodeAt(0) == event.keyCode) { - let found = findDiagnostic(this.view.state.field(lintState).diagnostics, diagnostic); - if (found) - diagnostic.actions[i].apply(view, found.from, found.to); - } - } - else { - return; - } - event.preventDefault(); - }; - let onclick = (event) => { - for (let i = 0; i < this.items.length; i++) { - if (this.items[i].dom.contains(event.target)) - this.moveSelection(i); - } - }; - this.list = crelt("ul", { - tabIndex: 0, - role: "listbox", - "aria-label": this.view.state.phrase("Diagnostics"), - onkeydown, - onclick - }); - this.dom = crelt("div", { class: "cm-panel-lint" }, this.list, crelt("button", { - type: "button", - name: "close", - "aria-label": this.view.state.phrase("close"), - onclick: () => closeLintPanel(this.view) - }, "×")); - this.update(); - } - get selectedIndex() { - let selected = this.view.state.field(lintState).selected; - if (!selected) - return -1; - for (let i = 0; i < this.items.length; i++) - if (this.items[i].diagnostic == selected.diagnostic) - return i; - return -1; - } - update() { - let { diagnostics, selected } = this.view.state.field(lintState); - let i = 0, needsSync = false, newSelectedItem = null; - diagnostics.between(0, this.view.state.doc.length, (_start, _end, { spec }) => { - let found = -1, item; - for (let j = i; j < this.items.length; j++) - if (this.items[j].diagnostic == spec.diagnostic) { - found = j; - break; - } - if (found < 0) { - item = new PanelItem(this.view, spec.diagnostic); - this.items.splice(i, 0, item); - needsSync = true; - } - else { - item = this.items[found]; - if (found > i) { - this.items.splice(i, found - i); - needsSync = true; - } - } - if (selected && item.diagnostic == selected.diagnostic) { - if (!item.dom.hasAttribute("aria-selected")) { - item.dom.setAttribute("aria-selected", "true"); - newSelectedItem = item; - } - } - else if (item.dom.hasAttribute("aria-selected")) { - item.dom.removeAttribute("aria-selected"); - } - i++; - }); - while (i < this.items.length && !(this.items.length == 1 && this.items[0].diagnostic.from < 0)) { - needsSync = true; - this.items.pop(); - } - if (this.items.length == 0) { - this.items.push(new PanelItem(this.view, { - from: -1, to: -1, - severity: "info", - message: this.view.state.phrase("No diagnostics") - })); - needsSync = true; - } - if (newSelectedItem) { - this.list.setAttribute("aria-activedescendant", newSelectedItem.id); - this.view.requestMeasure({ - key: this, - read: () => ({ sel: newSelectedItem.dom.getBoundingClientRect(), panel: this.list.getBoundingClientRect() }), - write: ({ sel, panel }) => { - if (sel.top < panel.top) - this.list.scrollTop -= panel.top - sel.top; - else if (sel.bottom > panel.bottom) - this.list.scrollTop += sel.bottom - panel.bottom; - } - }); - } - else if (this.selectedIndex < 0) { - this.list.removeAttribute("aria-activedescendant"); - } - if (needsSync) - this.sync(); - } - sync() { - let domPos = this.list.firstChild; - function rm() { - let prev = domPos; - domPos = prev.nextSibling; - prev.remove(); - } - for (let item of this.items) { - if (item.dom.parentNode == this.list) { - while (domPos != item.dom) - rm(); - domPos = item.dom.nextSibling; - } - else { - this.list.insertBefore(item.dom, domPos); - } - } - while (domPos) - rm(); - } - moveSelection(selectedIndex) { - if (this.selectedIndex < 0) - return; - let field = this.view.state.field(lintState); - let selection = findDiagnostic(field.diagnostics, this.items[selectedIndex].diagnostic); - if (!selection) - return; - this.view.dispatch({ - selection: { anchor: selection.from, head: selection.to }, - scrollIntoView: true, - effects: movePanelSelection.of(selection) - }); - } - static open(view) { return new LintPanel(view); } - } - function svg(content, attrs = `viewBox="0 0 40 40"`) { - return `url('data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" ${attrs}>${encodeURIComponent(content)}</svg>')`; - } - function underline(color) { - return svg(`<path d="m0 2.5 l2 -1.5 l1 0 l2 1.5 l1 0" stroke="${color}" fill="none" stroke-width=".7"/>`, `width="6" height="3"`); - } - const baseTheme = /*@__PURE__*/EditorView.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-diagnosticAction": { - font: "inherit", - border: "none", - padding: "2px 4px", - backgroundColor: "#444", - color: "white", - borderRadius: "3px", - marginLeft: "8px" - }, - ".cm-diagnosticSource": { - fontSize: "70%", - opacity: .7 - }, - ".cm-lintRange": { - backgroundPosition: "left bottom", - backgroundRepeat: "repeat-x", - paddingBottom: "0.7px", - }, - ".cm-lintRange-error": { backgroundImage: /*@__PURE__*/underline("#d11") }, - ".cm-lintRange-warning": { backgroundImage: /*@__PURE__*/underline("orange") }, - ".cm-lintRange-info": { backgroundImage: /*@__PURE__*/underline("#999") }, - ".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-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 - } - } - }); - - /** - This is an extension value that just pulls together a whole lot of - extensions that you might want in a basic editor. It is meant as a - convenient helper to quickly set up CodeMirror without installing - and importing a lot of packages. - - Specifically, it includes... - - - [the default command bindings](https://codemirror.net/6/docs/ref/#commands.defaultKeymap) - - [line numbers](https://codemirror.net/6/docs/ref/#gutter.lineNumbers) - - [special character highlighting](https://codemirror.net/6/docs/ref/#view.highlightSpecialChars) - - [the undo history](https://codemirror.net/6/docs/ref/#history.history) - - [a fold gutter](https://codemirror.net/6/docs/ref/#fold.foldGutter) - - [custom selection drawing](https://codemirror.net/6/docs/ref/#view.drawSelection) - - [drop cursor](https://codemirror.net/6/docs/ref/#view.dropCursor) - - [multiple selections](https://codemirror.net/6/docs/ref/#state.EditorState^allowMultipleSelections) - - [reindentation on input](https://codemirror.net/6/docs/ref/#language.indentOnInput) - - [the default highlight style](https://codemirror.net/6/docs/ref/#highlight.defaultHighlightStyle) (as fallback) - - [bracket matching](https://codemirror.net/6/docs/ref/#matchbrackets.bracketMatching) - - [bracket closing](https://codemirror.net/6/docs/ref/#closebrackets.closeBrackets) - - [autocompletion](https://codemirror.net/6/docs/ref/#autocomplete.autocompletion) - - [rectangular selection](https://codemirror.net/6/docs/ref/#rectangular-selection.rectangularSelection) and [crosshair cursor](https://codemirror.net/6/docs/ref/#rectangular-selection.crosshairCursor) - - [active line highlighting](https://codemirror.net/6/docs/ref/#view.highlightActiveLine) - - [active line gutter highlighting](https://codemirror.net/6/docs/ref/#gutter.highlightActiveLineGutter) - - [selection match highlighting](https://codemirror.net/6/docs/ref/#search.highlightSelectionMatches) - - [search](https://codemirror.net/6/docs/ref/#search.searchKeymap) - - [commenting](https://codemirror.net/6/docs/ref/#comment.commentKeymap) - - [linting](https://codemirror.net/6/docs/ref/#lint.lintKeymap) - - (You'll probably want to add some language package to your setup - too.) - - This package does not allow customization. The idea is that, once - you decide you want to configure your editor more precisely, you - take this package's source (which is just a bunch of imports and - an array literal), copy it into your own code, and adjust it as - desired. - */ - const basicSetup = [ - /*@__PURE__*/lineNumbers(), - /*@__PURE__*/highlightActiveLineGutter(), - /*@__PURE__*/highlightSpecialChars(), - /*@__PURE__*/history(), - /*@__PURE__*/foldGutter(), - /*@__PURE__*/drawSelection(), - /*@__PURE__*/dropCursor(), - /*@__PURE__*/EditorState.allowMultipleSelections.of(true), - /*@__PURE__*/indentOnInput(), - defaultHighlightStyle.fallback, - /*@__PURE__*/bracketMatching(), - /*@__PURE__*/closeBrackets(), - /*@__PURE__*/autocompletion(), - /*@__PURE__*/rectangularSelection(), - /*@__PURE__*/crosshairCursor(), - /*@__PURE__*/highlightActiveLine(), - /*@__PURE__*/highlightSelectionMatches(), - /*@__PURE__*/keymap.of([ - ...closeBracketsKeymap, - ...defaultKeymap, - ...searchKeymap, - ...historyKeymap, - ...foldKeymap, - ...commentKeymap, - ...completionKeymap, - ...lintKeymap - ]) - ]; - - /// A parse stack. These are used internally by the parser to track - /// parsing progress. They also provide some properties and methods - /// that external code such as a tokenizer can use to get information - /// about the parse state. - class Stack { - /// @internal - constructor( - /// The parse that this stack is part of @internal - p, - /// Holds state, input pos, buffer index triplets for all but the - /// top state @internal - stack, - /// The current parse state @internal - state, - // The position at which the next reduce should take place. This - // can be less than `this.pos` when skipped expressions have been - // added to the stack (which should be moved outside of the next - // reduction) - /// @internal - reducePos, - /// The input position up to which this stack has parsed. - pos, - /// The dynamic score of the stack, including dynamic precedence - /// and error-recovery penalties - /// @internal - score, - // The output buffer. Holds (type, start, end, size) quads - // representing nodes created by the parser, where `size` is - // amount of buffer array entries covered by this node. - /// @internal - buffer, - // The base offset of the buffer. When stacks are split, the split - // instance shared the buffer history with its parent up to - // `bufferBase`, which is the absolute offset (including the - // offset of previous splits) into the buffer at which this stack - // starts writing. - /// @internal - bufferBase, - /// @internal - curContext, - /// @internal - lookAhead = 0, - // A parent stack from which this was split off, if any. This is - // set up so that it always points to a stack that has some - // additional buffer content, never to a stack with an equal - // `bufferBase`. - /// @internal - parent) { - this.p = p; - this.stack = stack; - this.state = state; - this.reducePos = reducePos; - this.pos = pos; - this.score = score; - this.buffer = buffer; - this.bufferBase = bufferBase; - this.curContext = curContext; - this.lookAhead = lookAhead; - this.parent = parent; - } - /// @internal - toString() { - return `[${this.stack.filter((_, i) => i % 3 == 0).concat(this.state)}]@${this.pos}${this.score ? "!" + this.score : ""}`; - } - // Start an empty stack - /// @internal - static start(p, state, pos = 0) { - let cx = p.parser.context; - return new Stack(p, [], state, pos, pos, 0, [], 0, cx ? new StackContext(cx, cx.start) : null, 0, null); - } - /// The stack's current [context](#lr.ContextTracker) value, if - /// any. Its type will depend on the context tracker's type - /// parameter, or it will be `null` if there is no context - /// tracker. - get context() { return this.curContext ? this.curContext.context : null; } - // Push a state onto the stack, tracking its start position as well - // as the buffer base at that point. - /// @internal - pushState(state, start) { - this.stack.push(this.state, start, this.bufferBase + this.buffer.length); - this.state = state; - } - // Apply a reduce action - /// @internal - reduce(action) { - let depth = action >> 19 /* ReduceDepthShift */, type = action & 65535 /* ValueMask */; - let { parser } = this.p; - let dPrec = parser.dynamicPrecedence(type); - if (dPrec) - this.score += dPrec; - if (depth == 0) { - this.pushState(parser.getGoto(this.state, type, true), this.reducePos); - // Zero-depth reductions are a special case—they add stuff to - // the stack without popping anything off. - if (type < parser.minRepeatTerm) - this.storeNode(type, this.reducePos, this.reducePos, 4, true); - this.reduceContext(type, this.reducePos); - return; - } - // Find the base index into `this.stack`, content after which will - // be dropped. Note that with `StayFlag` reductions we need to - // consume two extra frames (the dummy parent node for the skipped - // expression and the state that we'll be staying in, which should - // be moved to `this.state`). - let base = this.stack.length - ((depth - 1) * 3) - (action & 262144 /* StayFlag */ ? 6 : 0); - let start = this.stack[base - 2]; - let bufferBase = this.stack[base - 1], count = this.bufferBase + this.buffer.length - bufferBase; - // Store normal terms or `R -> R R` repeat reductions - if (type < parser.minRepeatTerm || (action & 131072 /* RepeatFlag */)) { - let pos = parser.stateFlag(this.state, 1 /* Skipped */) ? this.pos : this.reducePos; - this.storeNode(type, start, pos, count + 4, true); - } - if (action & 262144 /* StayFlag */) { - this.state = this.stack[base]; - } - else { - let baseStateID = this.stack[base - 3]; - this.state = parser.getGoto(baseStateID, type, true); - } - while (this.stack.length > base) - this.stack.pop(); - this.reduceContext(type, start); - } - // Shift a value into the buffer - /// @internal - storeNode(term, start, end, size = 4, isReduce = false) { - if (term == 0 /* Err */) { // Try to omit/merge adjacent error nodes - let cur = this, top = this.buffer.length; - if (top == 0 && cur.parent) { - top = cur.bufferBase - cur.parent.bufferBase; - cur = cur.parent; - } - if (top > 0 && cur.buffer[top - 4] == 0 /* Err */ && cur.buffer[top - 1] > -1) { - if (start == end) - return; - if (cur.buffer[top - 2] >= start) { - cur.buffer[top - 2] = end; - return; - } - } - } - if (!isReduce || this.pos == end) { // Simple case, just append - this.buffer.push(term, start, end, size); - } - else { // There may be skipped nodes that have to be moved forward - let index = this.buffer.length; - if (index > 0 && this.buffer[index - 4] != 0 /* Err */) - while (index > 0 && this.buffer[index - 2] > end) { - // Move this record forward - this.buffer[index] = this.buffer[index - 4]; - this.buffer[index + 1] = this.buffer[index - 3]; - this.buffer[index + 2] = this.buffer[index - 2]; - this.buffer[index + 3] = this.buffer[index - 1]; - index -= 4; - if (size > 4) - size -= 4; - } - this.buffer[index] = term; - this.buffer[index + 1] = start; - this.buffer[index + 2] = end; - this.buffer[index + 3] = size; - } - } - // Apply a shift action - /// @internal - shift(action, next, nextEnd) { - let start = this.pos; - if (action & 131072 /* GotoFlag */) { - this.pushState(action & 65535 /* ValueMask */, this.pos); - } - else if ((action & 262144 /* StayFlag */) == 0) { // Regular shift - let nextState = action, { parser } = this.p; - if (nextEnd > this.pos || next <= parser.maxNode) { - this.pos = nextEnd; - if (!parser.stateFlag(nextState, 1 /* Skipped */)) - this.reducePos = nextEnd; - } - this.pushState(nextState, start); - this.shiftContext(next, start); - if (next <= parser.maxNode) - this.buffer.push(next, start, nextEnd, 4); - } - else { // Shift-and-stay, which means this is a skipped token - this.pos = nextEnd; - this.shiftContext(next, start); - if (next <= this.p.parser.maxNode) - this.buffer.push(next, start, nextEnd, 4); - } - } - // Apply an action - /// @internal - apply(action, next, nextEnd) { - if (action & 65536 /* ReduceFlag */) - this.reduce(action); - else - this.shift(action, next, nextEnd); - } - // Add a prebuilt (reused) node into the buffer. - /// @internal - useNode(value, next) { - let index = this.p.reused.length - 1; - if (index < 0 || this.p.reused[index] != value) { - this.p.reused.push(value); - index++; - } - let start = this.pos; - this.reducePos = this.pos = start + value.length; - this.pushState(next, start); - this.buffer.push(index, start, this.reducePos, -1 /* size == -1 means this is a reused value */); - if (this.curContext) - this.updateContext(this.curContext.tracker.reuse(this.curContext.context, value, this, this.p.stream.reset(this.pos - value.length))); - } - // Split the stack. Due to the buffer sharing and the fact - // that `this.stack` tends to stay quite shallow, this isn't very - // expensive. - /// @internal - split() { - let parent = this; - let off = parent.buffer.length; - // Because the top of the buffer (after this.pos) may be mutated - // to reorder reductions and skipped tokens, and shared buffers - // should be immutable, this copies any outstanding skipped tokens - // to the new buffer, and puts the base pointer before them. - while (off > 0 && parent.buffer[off - 2] > parent.reducePos) - off -= 4; - let buffer = parent.buffer.slice(off), base = parent.bufferBase + off; - // Make sure parent points to an actual parent with content, if there is such a parent. - while (parent && base == parent.bufferBase) - parent = parent.parent; - return new Stack(this.p, this.stack.slice(), this.state, this.reducePos, this.pos, this.score, buffer, base, this.curContext, this.lookAhead, parent); - } - // Try to recover from an error by 'deleting' (ignoring) one token. - /// @internal - recoverByDelete(next, nextEnd) { - let isNode = next <= this.p.parser.maxNode; - if (isNode) - this.storeNode(next, this.pos, nextEnd, 4); - this.storeNode(0 /* Err */, this.pos, nextEnd, isNode ? 8 : 4); - this.pos = this.reducePos = nextEnd; - this.score -= 190 /* Delete */; - } - /// Check if the given term would be able to be shifted (optionally - /// after some reductions) on this stack. This can be useful for - /// external tokenizers that want to make sure they only provide a - /// given token when it applies. - canShift(term) { - for (let sim = new SimulatedStack(this);;) { - let action = this.p.parser.stateSlot(sim.state, 4 /* DefaultReduce */) || this.p.parser.hasAction(sim.state, term); - if ((action & 65536 /* ReduceFlag */) == 0) - return true; - if (action == 0) - return false; - sim.reduce(action); - } - } - // Apply up to Recover.MaxNext recovery actions that conceptually - // inserts some missing token or rule. - /// @internal - recoverByInsert(next) { - if (this.stack.length >= 300 /* MaxInsertStackDepth */) - return []; - let nextStates = this.p.parser.nextStates(this.state); - if (nextStates.length > 4 /* MaxNext */ << 1 || this.stack.length >= 120 /* DampenInsertStackDepth */) { - let best = []; - for (let i = 0, s; i < nextStates.length; i += 2) { - if ((s = nextStates[i + 1]) != this.state && this.p.parser.hasAction(s, next)) - best.push(nextStates[i], s); - } - if (this.stack.length < 120 /* DampenInsertStackDepth */) - for (let i = 0; best.length < 4 /* MaxNext */ << 1 && i < nextStates.length; i += 2) { - let s = nextStates[i + 1]; - if (!best.some((v, i) => (i & 1) && v == s)) - best.push(nextStates[i], s); - } - nextStates = best; - } - let result = []; - for (let i = 0; i < nextStates.length && result.length < 4 /* MaxNext */; i += 2) { - let s = nextStates[i + 1]; - if (s == this.state) - continue; - let stack = this.split(); - stack.storeNode(0 /* Err */, stack.pos, stack.pos, 4, true); - stack.pushState(s, this.pos); - stack.shiftContext(nextStates[i], this.pos); - stack.score -= 200 /* Insert */; - result.push(stack); - } - return result; - } - // Force a reduce, if possible. Return false if that can't - // be done. - /// @internal - forceReduce() { - let reduce = this.p.parser.stateSlot(this.state, 5 /* ForcedReduce */); - if ((reduce & 65536 /* ReduceFlag */) == 0) - return false; - let { parser } = this.p; - if (!parser.validAction(this.state, reduce)) { - let depth = reduce >> 19 /* ReduceDepthShift */, term = reduce & 65535 /* ValueMask */; - let target = this.stack.length - depth * 3; - if (target < 0 || parser.getGoto(this.stack[target], term, false) < 0) - return false; - this.storeNode(0 /* Err */, this.reducePos, this.reducePos, 4, true); - this.score -= 100 /* Reduce */; - } - this.reduce(reduce); - return true; - } - /// @internal - forceAll() { - while (!this.p.parser.stateFlag(this.state, 2 /* Accepting */)) { - if (!this.forceReduce()) { - this.storeNode(0 /* Err */, this.pos, this.pos, 4, true); - break; - } - } - return this; - } - /// Check whether this state has no further actions (assumed to be a direct descendant of the - /// top state, since any other states must be able to continue - /// somehow). @internal - get deadEnd() { - if (this.stack.length != 3) - return false; - let { parser } = this.p; - return parser.data[parser.stateSlot(this.state, 1 /* Actions */)] == 65535 /* End */ && - !parser.stateSlot(this.state, 4 /* DefaultReduce */); - } - /// Restart the stack (put it back in its start state). Only safe - /// when this.stack.length == 3 (state is directly below the top - /// state). @internal - restart() { - this.state = this.stack[0]; - this.stack.length = 0; - } - /// @internal - sameState(other) { - if (this.state != other.state || this.stack.length != other.stack.length) - return false; - for (let i = 0; i < this.stack.length; i += 3) - if (this.stack[i] != other.stack[i]) - return false; - return true; - } - /// Get the parser used by this stack. - get parser() { return this.p.parser; } - /// Test whether a given dialect (by numeric ID, as exported from - /// the terms file) is enabled. - dialectEnabled(dialectID) { return this.p.parser.dialect.flags[dialectID]; } - shiftContext(term, start) { - if (this.curContext) - this.updateContext(this.curContext.tracker.shift(this.curContext.context, term, this, this.p.stream.reset(start))); - } - reduceContext(term, start) { - if (this.curContext) - this.updateContext(this.curContext.tracker.reduce(this.curContext.context, term, this, this.p.stream.reset(start))); - } - /// @internal - emitContext() { - let last = this.buffer.length - 1; - if (last < 0 || this.buffer[last] != -3) - this.buffer.push(this.curContext.hash, this.reducePos, this.reducePos, -3); - } - /// @internal - emitLookAhead() { - let last = this.buffer.length - 1; - if (last < 0 || this.buffer[last] != -4) - this.buffer.push(this.lookAhead, this.reducePos, this.reducePos, -4); - } - updateContext(context) { - if (context != this.curContext.context) { - let newCx = new StackContext(this.curContext.tracker, context); - if (newCx.hash != this.curContext.hash) - this.emitContext(); - this.curContext = newCx; - } - } - /// @internal - setLookAhead(lookAhead) { - if (lookAhead > this.lookAhead) { - this.emitLookAhead(); - this.lookAhead = lookAhead; - } - } - /// @internal - close() { - if (this.curContext && this.curContext.tracker.strict) - this.emitContext(); - if (this.lookAhead > 0) - this.emitLookAhead(); - } - } - class StackContext { - constructor(tracker, context) { - this.tracker = tracker; - this.context = context; - this.hash = tracker.strict ? tracker.hash(context) : 0; - } - } - var Recover; - (function (Recover) { - Recover[Recover["Insert"] = 200] = "Insert"; - Recover[Recover["Delete"] = 190] = "Delete"; - Recover[Recover["Reduce"] = 100] = "Reduce"; - Recover[Recover["MaxNext"] = 4] = "MaxNext"; - Recover[Recover["MaxInsertStackDepth"] = 300] = "MaxInsertStackDepth"; - Recover[Recover["DampenInsertStackDepth"] = 120] = "DampenInsertStackDepth"; - })(Recover || (Recover = {})); - // Used to cheaply run some reductions to scan ahead without mutating - // an entire stack - class SimulatedStack { - constructor(start) { - this.start = start; - this.state = start.state; - this.stack = start.stack; - this.base = this.stack.length; - } - reduce(action) { - let term = action & 65535 /* ValueMask */, depth = action >> 19 /* ReduceDepthShift */; - if (depth == 0) { - if (this.stack == this.start.stack) - this.stack = this.stack.slice(); - this.stack.push(this.state, 0, 0); - this.base += 3; - } - else { - this.base -= (depth - 1) * 3; - } - let goto = this.start.p.parser.getGoto(this.stack[this.base - 3], term, true); - this.state = goto; - } - } - // This is given to `Tree.build` to build a buffer, and encapsulates - // the parent-stack-walking necessary to read the nodes. - class StackBufferCursor { - constructor(stack, pos, index) { - this.stack = stack; - this.pos = pos; - this.index = index; - this.buffer = stack.buffer; - if (this.index == 0) - this.maybeNext(); - } - static create(stack, pos = stack.bufferBase + stack.buffer.length) { - return new StackBufferCursor(stack, pos, pos - stack.bufferBase); - } - maybeNext() { - let next = this.stack.parent; - if (next != null) { - this.index = this.stack.bufferBase - next.bufferBase; - this.stack = next; - this.buffer = next.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; - if (this.index == 0) - this.maybeNext(); - } - fork() { - return new StackBufferCursor(this.stack, this.pos, this.index); - } - } - - class CachedToken { - constructor() { - this.start = -1; - this.value = -1; - this.end = -1; - this.extended = -1; - this.lookAhead = 0; - this.mask = 0; - this.context = 0; - } - } - const nullToken = new CachedToken; - /// [Tokenizers](#lr.ExternalTokenizer) interact with the input - /// through this interface. It presents the input as a stream of - /// characters, tracking lookahead and hiding the complexity of - /// [ranges](#common.Parser.parse^ranges) from tokenizer code. - class InputStream { - /// @internal - constructor( - /// @internal - input, - /// @internal - ranges) { - this.input = input; - this.ranges = ranges; - /// @internal - this.chunk = ""; - /// @internal - this.chunkOff = 0; - /// Backup chunk - this.chunk2 = ""; - this.chunk2Pos = 0; - /// The character code of the next code unit in the input, or -1 - /// when the stream is at the end of the input. - this.next = -1; - /// @internal - this.token = nullToken; - this.rangeIndex = 0; - this.pos = this.chunkPos = ranges[0].from; - this.range = ranges[0]; - this.end = ranges[ranges.length - 1].to; - this.readNext(); - } - resolveOffset(offset, assoc) { - let range = this.range, index = this.rangeIndex; - let pos = this.pos + offset; - while (pos < range.from) { - if (!index) - return null; - let next = this.ranges[--index]; - pos -= range.from - next.to; - range = next; - } - while (assoc < 0 ? pos > range.to : pos >= range.to) { - if (index == this.ranges.length - 1) - return null; - let next = this.ranges[++index]; - pos += next.from - range.to; - range = next; - } - return pos; - } - /// Look at a code unit near the stream position. `.peek(0)` equals - /// `.next`, `.peek(-1)` gives you the previous character, and so - /// on. - /// - /// Note that looking around during tokenizing creates dependencies - /// on potentially far-away content, which may reduce the - /// effectiveness incremental parsing—when looking forward—or even - /// cause invalid reparses when looking backward more than 25 code - /// units, since the library does not track lookbehind. - peek(offset) { - let idx = this.chunkOff + offset, pos, result; - if (idx >= 0 && idx < this.chunk.length) { - pos = this.pos + offset; - result = this.chunk.charCodeAt(idx); - } - else { - let resolved = this.resolveOffset(offset, 1); - if (resolved == null) - return -1; - pos = resolved; - if (pos >= this.chunk2Pos && pos < this.chunk2Pos + this.chunk2.length) { - result = this.chunk2.charCodeAt(pos - this.chunk2Pos); - } - else { - let i = this.rangeIndex, range = this.range; - while (range.to <= pos) - range = this.ranges[++i]; - this.chunk2 = this.input.chunk(this.chunk2Pos = pos); - if (pos + this.chunk2.length > range.to) - this.chunk2 = this.chunk2.slice(0, range.to - pos); - result = this.chunk2.charCodeAt(0); - } - } - if (pos >= this.token.lookAhead) - this.token.lookAhead = pos + 1; - return result; - } - /// Accept a token. By default, the end of the token is set to the - /// current stream position, but you can pass an offset (relative to - /// the stream position) to change that. - acceptToken(token, endOffset = 0) { - let end = endOffset ? this.resolveOffset(endOffset, -1) : this.pos; - if (end == null || end < this.token.start) - throw new RangeError("Token end out of bounds"); - this.token.value = token; - this.token.end = end; - } - getChunk() { - if (this.pos >= this.chunk2Pos && this.pos < this.chunk2Pos + this.chunk2.length) { - let { chunk, chunkPos } = this; - this.chunk = this.chunk2; - this.chunkPos = this.chunk2Pos; - this.chunk2 = chunk; - this.chunk2Pos = chunkPos; - this.chunkOff = this.pos - this.chunkPos; - } - else { - this.chunk2 = this.chunk; - this.chunk2Pos = this.chunkPos; - let nextChunk = this.input.chunk(this.pos); - let end = this.pos + nextChunk.length; - this.chunk = end > this.range.to ? nextChunk.slice(0, this.range.to - this.pos) : nextChunk; - this.chunkPos = this.pos; - this.chunkOff = 0; - } - } - readNext() { - if (this.chunkOff >= this.chunk.length) { - this.getChunk(); - if (this.chunkOff == this.chunk.length) - return this.next = -1; - } - return this.next = this.chunk.charCodeAt(this.chunkOff); - } - /// Move the stream forward N (defaults to 1) code units. Returns - /// the new value of [`next`](#lr.InputStream.next). - advance(n = 1) { - this.chunkOff += n; - while (this.pos + n >= this.range.to) { - if (this.rangeIndex == this.ranges.length - 1) - return this.setDone(); - n -= this.range.to - this.pos; - this.range = this.ranges[++this.rangeIndex]; - this.pos = this.range.from; - } - this.pos += n; - if (this.pos >= this.token.lookAhead) - this.token.lookAhead = this.pos + 1; - return this.readNext(); - } - setDone() { - this.pos = this.chunkPos = this.end; - this.range = this.ranges[this.rangeIndex = this.ranges.length - 1]; - this.chunk = ""; - return this.next = -1; - } - /// @internal - reset(pos, token) { - if (token) { - this.token = token; - token.start = pos; - token.lookAhead = pos + 1; - token.value = token.extended = -1; - } - else { - this.token = nullToken; - } - if (this.pos != pos) { - this.pos = pos; - if (pos == this.end) { - this.setDone(); - return this; - } - while (pos < this.range.from) - this.range = this.ranges[--this.rangeIndex]; - while (pos >= this.range.to) - this.range = this.ranges[++this.rangeIndex]; - if (pos >= this.chunkPos && pos < this.chunkPos + this.chunk.length) { - this.chunkOff = pos - this.chunkPos; - } - else { - this.chunk = ""; - this.chunkOff = 0; - } - this.readNext(); - } - return this; - } - /// @internal - read(from, to) { - if (from >= this.chunkPos && to <= this.chunkPos + this.chunk.length) - return this.chunk.slice(from - this.chunkPos, to - this.chunkPos); - if (from >= this.chunk2Pos && to <= this.chunk2Pos + this.chunk2.length) - return this.chunk2.slice(from - this.chunk2Pos, to - this.chunk2Pos); - if (from >= this.range.from && to <= this.range.to) - return this.input.read(from, to); - let result = ""; - for (let r of this.ranges) { - if (r.from >= to) - break; - if (r.to > from) - result += this.input.read(Math.max(r.from, from), Math.min(r.to, to)); - } - return result; - } - } - /// @internal - class TokenGroup { - constructor(data, id) { - this.data = data; - this.id = id; - } - token(input, stack) { readToken(this.data, input, stack, this.id); } - } - TokenGroup.prototype.contextual = TokenGroup.prototype.fallback = TokenGroup.prototype.extend = false; - /// `@external tokens` declarations in the grammar should resolve to - /// an instance of this class. - class ExternalTokenizer { - /// Create a tokenizer. The first argument is the function that, - /// given an input stream, scans for the types of tokens it - /// recognizes at the stream's position, and calls - /// [`acceptToken`](#lr.InputStream.acceptToken) when it finds - /// one. - constructor( - /// @internal - token, options = {}) { - this.token = token; - this.contextual = !!options.contextual; - this.fallback = !!options.fallback; - this.extend = !!options.extend; - } - } - // Tokenizer data is stored a big uint16 array containing, for each - // state: - // - // - A group bitmask, indicating what token groups are reachable from - // this state, so that paths that can only lead to tokens not in - // any of the current groups can be cut off early. - // - // - The position of the end of the state's sequence of accepting - // tokens - // - // - The number of outgoing edges for the state - // - // - The accepting tokens, as (token id, group mask) pairs - // - // - The outgoing edges, as (start character, end character, state - // index) triples, with end character being exclusive - // - // This function interprets that data, running through a stream as - // long as new states with the a matching group mask can be reached, - // and updating `token` when it matches a token. - function readToken(data, input, stack, group) { - let state = 0, groupMask = 1 << group, { parser } = stack.p, { dialect } = parser; - scan: for (;;) { - if ((groupMask & data[state]) == 0) - break; - let accEnd = data[state + 1]; - // Check whether this state can lead to a token in the current group - // Accept tokens in this state, possibly overwriting - // lower-precedence / shorter tokens - for (let i = state + 3; i < accEnd; i += 2) - if ((data[i + 1] & groupMask) > 0) { - let term = data[i]; - if (dialect.allows(term) && - (input.token.value == -1 || input.token.value == term || parser.overrides(term, input.token.value))) { - input.acceptToken(term); - break; - } - } - // Do a binary search on the state's edges - for (let next = input.next, low = 0, high = data[state + 2]; low < high;) { - let mid = (low + high) >> 1; - let index = accEnd + mid + (mid << 1); - let from = data[index], to = data[index + 1]; - if (next < from) - high = mid; - else if (next >= to) - low = mid + 1; - else { - state = data[index + 2]; - input.advance(); - continue scan; - } - } - break; - } - } - - // See lezer-generator/src/encode.ts for comments about the encoding - // used here - function decodeArray(input, Type = Uint16Array) { - if (typeof input != "string") - return input; - let array = null; - for (let pos = 0, out = 0; pos < input.length;) { - let value = 0; - for (;;) { - let next = input.charCodeAt(pos++), stop = false; - if (next == 126 /* BigValCode */) { - value = 65535 /* BigVal */; - break; - } - if (next >= 92 /* Gap2 */) - next--; - if (next >= 34 /* Gap1 */) - next--; - let digit = next - 32 /* Start */; - if (digit >= 46 /* Base */) { - digit -= 46 /* Base */; - stop = true; - } - value += digit; - if (stop) - break; - value *= 46 /* Base */; - } - if (array) - array[out++] = value; - else - array = new Type(value); - } - return array; - } - - // FIXME find some way to reduce recovery work done when the input - // doesn't match the grammar at all. - // Environment variable used to control console output - const verbose = typeof process != "undefined" && /\bparse\b/.test(process.env.LOG); - let stackIDs = null; - var Safety; - (function (Safety) { - Safety[Safety["Margin"] = 25] = "Margin"; - })(Safety || (Safety = {})); - function cutAt(tree, pos, side) { - let cursor = tree.fullCursor(); - cursor.moveTo(pos); - for (;;) { - if (!(side < 0 ? cursor.childBefore(pos) : cursor.childAfter(pos))) - for (;;) { - if ((side < 0 ? cursor.to < pos : cursor.from > pos) && !cursor.type.isError) - return side < 0 ? Math.max(0, Math.min(cursor.to - 1, pos - 25 /* Margin */)) - : Math.min(tree.length, Math.max(cursor.from + 1, pos + 25 /* Margin */)); - if (side < 0 ? cursor.prevSibling() : cursor.nextSibling()) - break; - if (!cursor.parent()) - return side < 0 ? 0 : tree.length; - } - } - } - class FragmentCursor { - constructor(fragments, nodeSet) { - this.fragments = fragments; - this.nodeSet = nodeSet; - this.i = 0; - this.fragment = null; - this.safeFrom = -1; - this.safeTo = -1; - this.trees = []; - this.start = []; - this.index = []; - this.nextFragment(); - } - nextFragment() { - let fr = this.fragment = this.i == this.fragments.length ? null : this.fragments[this.i++]; - if (fr) { - this.safeFrom = fr.openStart ? cutAt(fr.tree, fr.from + fr.offset, 1) - fr.offset : fr.from; - this.safeTo = fr.openEnd ? cutAt(fr.tree, fr.to + fr.offset, -1) - fr.offset : fr.to; - while (this.trees.length) { - this.trees.pop(); - this.start.pop(); - this.index.pop(); - } - this.trees.push(fr.tree); - this.start.push(-fr.offset); - this.index.push(0); - this.nextStart = this.safeFrom; - } - else { - this.nextStart = 1e9; - } - } - // `pos` must be >= any previously given `pos` for this cursor - nodeAt(pos) { - if (pos < this.nextStart) - return null; - while (this.fragment && this.safeTo <= pos) - this.nextFragment(); - if (!this.fragment) - return null; - for (;;) { - let last = this.trees.length - 1; - if (last < 0) { // End of tree - this.nextFragment(); - return null; - } - let top = this.trees[last], index = this.index[last]; - if (index == top.children.length) { - this.trees.pop(); - this.start.pop(); - this.index.pop(); - continue; - } - let next = top.children[index]; - let start = this.start[last] + top.positions[index]; - if (start > pos) { - this.nextStart = start; - return null; - } - if (next instanceof Tree) { - if (start == pos) { - if (start < this.safeFrom) - return null; - let end = start + next.length; - if (end <= this.safeTo) { - let lookAhead = next.prop(NodeProp.lookAhead); - if (!lookAhead || end + lookAhead < this.fragment.to) - return next; - } - } - this.index[last]++; - if (start + next.length >= Math.max(this.safeFrom, pos)) { // Enter this node - this.trees.push(next); - this.start.push(start); - this.index.push(0); - } - } - else { - this.index[last]++; - this.nextStart = start + next.length; - } - } - } - } - class TokenCache { - constructor(parser, stream) { - this.stream = stream; - this.tokens = []; - this.mainToken = null; - this.actions = []; - this.tokens = parser.tokenizers.map(_ => new CachedToken); - } - getActions(stack) { - let actionIndex = 0; - let main = null; - let { parser } = stack.p, { tokenizers } = parser; - let mask = parser.stateSlot(stack.state, 3 /* TokenizerMask */); - let context = stack.curContext ? stack.curContext.hash : 0; - let lookAhead = 0; - for (let i = 0; i < tokenizers.length; i++) { - if (((1 << i) & mask) == 0) - continue; - let tokenizer = tokenizers[i], token = this.tokens[i]; - if (main && !tokenizer.fallback) - continue; - if (tokenizer.contextual || token.start != stack.pos || token.mask != mask || token.context != context) { - this.updateCachedToken(token, tokenizer, stack); - token.mask = mask; - token.context = context; - } - if (token.lookAhead > token.end + 25 /* Margin */) - lookAhead = Math.max(token.lookAhead, lookAhead); - if (token.value != 0 /* Err */) { - let startIndex = actionIndex; - if (token.extended > -1) - actionIndex = this.addActions(stack, token.extended, token.end, actionIndex); - actionIndex = this.addActions(stack, token.value, token.end, actionIndex); - if (!tokenizer.extend) { - main = token; - if (actionIndex > startIndex) - break; - } - } - } - while (this.actions.length > actionIndex) - this.actions.pop(); - if (lookAhead) - stack.setLookAhead(lookAhead); - if (!main && stack.pos == this.stream.end) { - main = new CachedToken; - main.value = stack.p.parser.eofTerm; - main.start = main.end = stack.pos; - actionIndex = this.addActions(stack, main.value, main.end, actionIndex); - } - this.mainToken = main; - return this.actions; - } - getMainToken(stack) { - if (this.mainToken) - return this.mainToken; - let main = new CachedToken, { pos, p } = stack; - main.start = pos; - main.end = Math.min(pos + 1, p.stream.end); - main.value = pos == p.stream.end ? p.parser.eofTerm : 0 /* Err */; - return main; - } - updateCachedToken(token, tokenizer, stack) { - tokenizer.token(this.stream.reset(stack.pos, token), stack); - if (token.value > -1) { - let { parser } = stack.p; - for (let i = 0; i < parser.specialized.length; i++) - if (parser.specialized[i] == token.value) { - let result = parser.specializers[i](this.stream.read(token.start, token.end), stack); - if (result >= 0 && stack.p.parser.dialect.allows(result >> 1)) { - if ((result & 1) == 0 /* Specialize */) - token.value = result >> 1; - else - token.extended = result >> 1; - break; - } - } - } - else { - token.value = 0 /* Err */; - token.end = Math.min(stack.p.stream.end, stack.pos + 1); - } - } - putAction(action, token, end, index) { - // Don't add duplicate actions - for (let i = 0; i < index; i += 3) - if (this.actions[i] == action) - return index; - this.actions[index++] = action; - this.actions[index++] = token; - this.actions[index++] = end; - return index; - } - addActions(stack, token, end, index) { - let { state } = stack, { parser } = stack.p, { data } = parser; - for (let set = 0; set < 2; set++) { - for (let i = parser.stateSlot(state, set ? 2 /* Skip */ : 1 /* Actions */);; i += 3) { - if (data[i] == 65535 /* End */) { - if (data[i + 1] == 1 /* Next */) { - i = pair(data, i + 2); - } - else { - if (index == 0 && data[i + 1] == 2 /* Other */) - index = this.putAction(pair(data, i + 2), token, end, index); - break; - } - } - if (data[i] == token) - index = this.putAction(pair(data, i + 1), token, end, index); - } - } - return index; - } - } - var Rec; - (function (Rec) { - Rec[Rec["Distance"] = 5] = "Distance"; - Rec[Rec["MaxRemainingPerStep"] = 3] = "MaxRemainingPerStep"; - // When two stacks have been running independently long enough to - // add this many elements to their buffers, prune one. - Rec[Rec["MinBufferLengthPrune"] = 500] = "MinBufferLengthPrune"; - Rec[Rec["ForceReduceLimit"] = 10] = "ForceReduceLimit"; - // Once a stack reaches this depth (in .stack.length) force-reduce - // it back to CutTo to avoid creating trees that overflow the stack - // on recursive traversal. - Rec[Rec["CutDepth"] = 15000] = "CutDepth"; - Rec[Rec["CutTo"] = 9000] = "CutTo"; - })(Rec || (Rec = {})); - class Parse { - constructor(parser, input, fragments, ranges) { - this.parser = parser; - this.input = input; - this.ranges = ranges; - this.recovering = 0; - this.nextStackID = 0x2654; // ♔, ♕, ♖, ♗, ♘, ♙, ♠, ♡, ♢, ♣, ♤, ♥, ♦, ♧ - this.minStackPos = 0; - this.reused = []; - this.stoppedAt = null; - this.stream = new InputStream(input, ranges); - this.tokens = new TokenCache(parser, this.stream); - this.topTerm = parser.top[1]; - let { from } = ranges[0]; - this.stacks = [Stack.start(this, parser.top[0], from)]; - this.fragments = fragments.length && this.stream.end - from > parser.bufferLength * 4 - ? new FragmentCursor(fragments, parser.nodeSet) : null; - } - get parsedPos() { - return this.minStackPos; - } - // Move the parser forward. This will process all parse stacks at - // `this.pos` and try to advance them to a further position. If no - // stack for such a position is found, it'll start error-recovery. - // - // When the parse is finished, this will return a syntax tree. When - // not, it returns `null`. - advance() { - let stacks = this.stacks, pos = this.minStackPos; - // This will hold stacks beyond `pos`. - let newStacks = this.stacks = []; - let stopped, stoppedTokens; - // Keep advancing any stacks at `pos` until they either move - // forward or can't be advanced. Gather stacks that can't be - // advanced further in `stopped`. - for (let i = 0; i < stacks.length; i++) { - let stack = stacks[i]; - for (;;) { - this.tokens.mainToken = null; - if (stack.pos > pos) { - newStacks.push(stack); - } - else if (this.advanceStack(stack, newStacks, stacks)) { - continue; - } - else { - if (!stopped) { - stopped = []; - stoppedTokens = []; - } - stopped.push(stack); - let tok = this.tokens.getMainToken(stack); - stoppedTokens.push(tok.value, tok.end); - } - break; - } - } - if (!newStacks.length) { - let finished = stopped && findFinished(stopped); - if (finished) - return this.stackToTree(finished); - if (this.parser.strict) { - if (verbose && stopped) - console.log("Stuck with token " + (this.tokens.mainToken ? this.parser.getName(this.tokens.mainToken.value) : "none")); - throw new SyntaxError("No parse at " + pos); - } - if (!this.recovering) - this.recovering = 5 /* Distance */; - } - if (this.recovering && stopped) { - let finished = this.stoppedAt != null && stopped[0].pos > this.stoppedAt ? stopped[0] - : this.runRecovery(stopped, stoppedTokens, newStacks); - if (finished) - return this.stackToTree(finished.forceAll()); - } - if (this.recovering) { - let maxRemaining = this.recovering == 1 ? 1 : this.recovering * 3 /* MaxRemainingPerStep */; - if (newStacks.length > maxRemaining) { - newStacks.sort((a, b) => b.score - a.score); - while (newStacks.length > maxRemaining) - newStacks.pop(); - } - if (newStacks.some(s => s.reducePos > pos)) - this.recovering--; - } - else if (newStacks.length > 1) { - // Prune stacks that are in the same state, or that have been - // running without splitting for a while, to avoid getting stuck - // with multiple successful stacks running endlessly on. - outer: for (let i = 0; i < newStacks.length - 1; i++) { - let stack = newStacks[i]; - for (let j = i + 1; j < newStacks.length; j++) { - let other = newStacks[j]; - if (stack.sameState(other) || - stack.buffer.length > 500 /* MinBufferLengthPrune */ && other.buffer.length > 500 /* MinBufferLengthPrune */) { - if (((stack.score - other.score) || (stack.buffer.length - other.buffer.length)) > 0) { - newStacks.splice(j--, 1); - } - else { - newStacks.splice(i--, 1); - continue outer; - } - } - } - } - } - this.minStackPos = newStacks[0].pos; - for (let i = 1; i < newStacks.length; i++) - if (newStacks[i].pos < this.minStackPos) - this.minStackPos = newStacks[i].pos; - return null; - } - stopAt(pos) { - if (this.stoppedAt != null && this.stoppedAt < pos) - throw new RangeError("Can't move stoppedAt forward"); - this.stoppedAt = pos; - } - // Returns an updated version of the given stack, or null if the - // stack can't advance normally. When `split` and `stacks` are - // given, stacks split off by ambiguous operations will be pushed to - // `split`, or added to `stacks` if they move `pos` forward. - advanceStack(stack, stacks, split) { - let start = stack.pos, { parser } = this; - let base = verbose ? this.stackID(stack) + " -> " : ""; - if (this.stoppedAt != null && start > this.stoppedAt) - return stack.forceReduce() ? stack : null; - if (this.fragments) { - let strictCx = stack.curContext && stack.curContext.tracker.strict, cxHash = strictCx ? stack.curContext.hash : 0; - for (let cached = this.fragments.nodeAt(start); cached;) { - let match = this.parser.nodeSet.types[cached.type.id] == cached.type ? parser.getGoto(stack.state, cached.type.id) : -1; - if (match > -1 && cached.length && (!strictCx || (cached.prop(NodeProp.contextHash) || 0) == cxHash)) { - stack.useNode(cached, match); - if (verbose) - console.log(base + this.stackID(stack) + ` (via reuse of ${parser.getName(cached.type.id)})`); - return true; - } - if (!(cached instanceof Tree) || cached.children.length == 0 || cached.positions[0] > 0) - break; - let inner = cached.children[0]; - if (inner instanceof Tree && cached.positions[0] == 0) - cached = inner; - else - break; - } - } - let defaultReduce = parser.stateSlot(stack.state, 4 /* DefaultReduce */); - if (defaultReduce > 0) { - stack.reduce(defaultReduce); - if (verbose) - console.log(base + this.stackID(stack) + ` (via always-reduce ${parser.getName(defaultReduce & 65535 /* ValueMask */)})`); - return true; - } - if (stack.stack.length >= 15000 /* CutDepth */) { - while (stack.stack.length > 9000 /* CutTo */ && stack.forceReduce()) { } - } - let actions = this.tokens.getActions(stack); - for (let i = 0; i < actions.length;) { - let action = actions[i++], term = actions[i++], end = actions[i++]; - let last = i == actions.length || !split; - let localStack = last ? stack : stack.split(); - localStack.apply(action, term, end); - if (verbose) - console.log(base + this.stackID(localStack) + ` (via ${(action & 65536 /* ReduceFlag */) == 0 ? "shift" - : `reduce of ${parser.getName(action & 65535 /* ValueMask */)}`} for ${parser.getName(term)} @ ${start}${localStack == stack ? "" : ", split"})`); - if (last) - return true; - else if (localStack.pos > start) - stacks.push(localStack); - else - split.push(localStack); - } - return false; - } - // Advance a given stack forward as far as it will go. Returns the - // (possibly updated) stack if it got stuck, or null if it moved - // forward and was given to `pushStackDedup`. - advanceFully(stack, newStacks) { - let pos = stack.pos; - for (;;) { - if (!this.advanceStack(stack, null, null)) - return false; - if (stack.pos > pos) { - pushStackDedup(stack, newStacks); - return true; - } - } - } - runRecovery(stacks, tokens, newStacks) { - let finished = null, restarted = false; - for (let i = 0; i < stacks.length; i++) { - let stack = stacks[i], token = tokens[i << 1], tokenEnd = tokens[(i << 1) + 1]; - let base = verbose ? this.stackID(stack) + " -> " : ""; - if (stack.deadEnd) { - if (restarted) - continue; - restarted = true; - stack.restart(); - if (verbose) - console.log(base + this.stackID(stack) + " (restarted)"); - let done = this.advanceFully(stack, newStacks); - if (done) - continue; - } - let force = stack.split(), forceBase = base; - for (let j = 0; force.forceReduce() && j < 10 /* ForceReduceLimit */; j++) { - if (verbose) - console.log(forceBase + this.stackID(force) + " (via force-reduce)"); - let done = this.advanceFully(force, newStacks); - if (done) - break; - if (verbose) - forceBase = this.stackID(force) + " -> "; - } - for (let insert of stack.recoverByInsert(token)) { - if (verbose) - console.log(base + this.stackID(insert) + " (via recover-insert)"); - this.advanceFully(insert, newStacks); - } - if (this.stream.end > stack.pos) { - if (tokenEnd == stack.pos) { - tokenEnd++; - token = 0 /* Err */; - } - stack.recoverByDelete(token, tokenEnd); - if (verbose) - console.log(base + this.stackID(stack) + ` (via recover-delete ${this.parser.getName(token)})`); - pushStackDedup(stack, newStacks); - } - else if (!finished || finished.score < stack.score) { - finished = stack; - } - } - return finished; - } - // Convert the stack's buffer to a syntax tree. - stackToTree(stack) { - stack.close(); - return Tree.build({ buffer: StackBufferCursor.create(stack), - nodeSet: this.parser.nodeSet, - topID: this.topTerm, - maxBufferLength: this.parser.bufferLength, - reused: this.reused, - start: this.ranges[0].from, - length: stack.pos - this.ranges[0].from, - minRepeatType: this.parser.minRepeatTerm }); - } - stackID(stack) { - let id = (stackIDs || (stackIDs = new WeakMap)).get(stack); - if (!id) - stackIDs.set(stack, id = String.fromCodePoint(this.nextStackID++)); - return id + stack; - } - } - function pushStackDedup(stack, newStacks) { - for (let i = 0; i < newStacks.length; i++) { - let other = newStacks[i]; - if (other.pos == stack.pos && other.sameState(stack)) { - if (newStacks[i].score < stack.score) - newStacks[i] = stack; - return; - } - } - newStacks.push(stack); - } - class Dialect { - constructor(source, flags, disabled) { - this.source = source; - this.flags = flags; - this.disabled = disabled; - } - allows(term) { return !this.disabled || this.disabled[term] == 0; } - } - const id = x => x; - /// Context trackers are used to track stateful context (such as - /// indentation in the Python grammar, or parent elements in the XML - /// grammar) needed by external tokenizers. You declare them in a - /// grammar file as `@context exportName from "module"`. - /// - /// Context values should be immutable, and can be updated (replaced) - /// on shift or reduce actions. - /// - /// The export used in a `@context` declaration should be of this - /// type. - class ContextTracker { - /// Define a context tracker. - constructor(spec) { - this.start = spec.start; - this.shift = spec.shift || id; - this.reduce = spec.reduce || id; - this.reuse = spec.reuse || id; - this.hash = spec.hash || (() => 0); - this.strict = spec.strict !== false; - } - } - /// A parser holds the parse tables for a given grammar, as generated - /// by `lezer-generator`. - class LRParser extends Parser { - /// @internal - constructor(spec) { - super(); - /// @internal - this.wrappers = []; - if (spec.version != 13 /* Version */) - throw new RangeError(`Parser version (${spec.version}) doesn't match runtime version (${13 /* Version */})`); - let nodeNames = spec.nodeNames.split(" "); - this.minRepeatTerm = nodeNames.length; - for (let i = 0; i < spec.repeatNodeCount; i++) - nodeNames.push(""); - let topTerms = Object.keys(spec.topRules).map(r => spec.topRules[r][1]); - let nodeProps = []; - for (let i = 0; i < nodeNames.length; i++) - nodeProps.push([]); - function setProp(nodeID, prop, value) { - nodeProps[nodeID].push([prop, prop.deserialize(String(value))]); - } - if (spec.nodeProps) - for (let propSpec of spec.nodeProps) { - let prop = propSpec[0]; - for (let i = 1; i < propSpec.length;) { - let next = propSpec[i++]; - if (next >= 0) { - setProp(next, prop, propSpec[i++]); - } - else { - let value = propSpec[i + -next]; - for (let j = -next; j > 0; j--) - setProp(propSpec[i++], prop, value); - i++; - } - } - } - this.nodeSet = new NodeSet(nodeNames.map((name, i) => NodeType.define({ - name: i >= this.minRepeatTerm ? undefined : name, - id: i, - props: nodeProps[i], - top: topTerms.indexOf(i) > -1, - error: i == 0, - skipped: spec.skippedNodes && spec.skippedNodes.indexOf(i) > -1 - }))); - this.strict = false; - this.bufferLength = DefaultBufferLength; - let tokenArray = decodeArray(spec.tokenData); - this.context = spec.context; - this.specialized = new Uint16Array(spec.specialized ? spec.specialized.length : 0); - this.specializers = []; - if (spec.specialized) - for (let i = 0; i < spec.specialized.length; i++) { - this.specialized[i] = spec.specialized[i].term; - this.specializers[i] = spec.specialized[i].get; - } - this.states = decodeArray(spec.states, Uint32Array); - this.data = decodeArray(spec.stateData); - this.goto = decodeArray(spec.goto); - this.maxTerm = spec.maxTerm; - this.tokenizers = spec.tokenizers.map(value => typeof value == "number" ? new TokenGroup(tokenArray, value) : value); - this.topRules = spec.topRules; - this.dialects = spec.dialects || {}; - this.dynamicPrecedences = spec.dynamicPrecedences || null; - this.tokenPrecTable = spec.tokenPrec; - this.termNames = spec.termNames || null; - this.maxNode = this.nodeSet.types.length - 1; - this.dialect = this.parseDialect(); - this.top = this.topRules[Object.keys(this.topRules)[0]]; - } - createParse(input, fragments, ranges) { - let parse = new Parse(this, input, fragments, ranges); - for (let w of this.wrappers) - parse = w(parse, input, fragments, ranges); - return parse; - } - /// Get a goto table entry @internal - getGoto(state, term, loose = false) { - let table = this.goto; - if (term >= table[0]) - return -1; - for (let pos = table[term + 1];;) { - let groupTag = table[pos++], last = groupTag & 1; - let target = table[pos++]; - if (last && loose) - return target; - for (let end = pos + (groupTag >> 1); pos < end; pos++) - if (table[pos] == state) - return target; - if (last) - return -1; - } - } - /// Check if this state has an action for a given terminal @internal - hasAction(state, terminal) { - let data = this.data; - for (let set = 0; set < 2; set++) { - for (let i = this.stateSlot(state, set ? 2 /* Skip */ : 1 /* Actions */), next;; i += 3) { - if ((next = data[i]) == 65535 /* End */) { - if (data[i + 1] == 1 /* Next */) - next = data[i = pair(data, i + 2)]; - else if (data[i + 1] == 2 /* Other */) - return pair(data, i + 2); - else - break; - } - if (next == terminal || next == 0 /* Err */) - return pair(data, i + 1); - } - } - return 0; - } - /// @internal - stateSlot(state, slot) { - return this.states[(state * 6 /* Size */) + slot]; - } - /// @internal - stateFlag(state, flag) { - return (this.stateSlot(state, 0 /* Flags */) & flag) > 0; - } - /// @internal - validAction(state, action) { - if (action == this.stateSlot(state, 4 /* DefaultReduce */)) - return true; - for (let i = this.stateSlot(state, 1 /* Actions */);; i += 3) { - if (this.data[i] == 65535 /* End */) { - if (this.data[i + 1] == 1 /* Next */) - i = pair(this.data, i + 2); - else - return false; - } - if (action == pair(this.data, i + 1)) - return true; - } - } - /// Get the states that can follow this one through shift actions or - /// goto jumps. @internal - nextStates(state) { - let result = []; - for (let i = this.stateSlot(state, 1 /* Actions */);; i += 3) { - if (this.data[i] == 65535 /* End */) { - if (this.data[i + 1] == 1 /* Next */) - i = pair(this.data, i + 2); - else - break; - } - if ((this.data[i + 2] & (65536 /* ReduceFlag */ >> 16)) == 0) { - let value = this.data[i + 1]; - if (!result.some((v, i) => (i & 1) && v == value)) - result.push(this.data[i], value); - } - } - return result; - } - /// @internal - overrides(token, prev) { - let iPrev = findOffset(this.data, this.tokenPrecTable, prev); - return iPrev < 0 || findOffset(this.data, this.tokenPrecTable, token) < iPrev; - } - /// Configure the parser. Returns a new parser instance that has the - /// given settings modified. Settings not provided in `config` are - /// kept from the original parser. - configure(config) { - // Hideous reflection-based kludge to make it easy to create a - // slightly modified copy of a parser. - let copy = Object.assign(Object.create(LRParser.prototype), this); - if (config.props) - copy.nodeSet = this.nodeSet.extend(...config.props); - if (config.top) { - let info = this.topRules[config.top]; - if (!info) - throw new RangeError(`Invalid top rule name ${config.top}`); - copy.top = info; - } - if (config.tokenizers) - copy.tokenizers = this.tokenizers.map(t => { - let found = config.tokenizers.find(r => r.from == t); - return found ? found.to : t; - }); - if (config.contextTracker) - copy.context = config.contextTracker; - if (config.dialect) - copy.dialect = this.parseDialect(config.dialect); - if (config.strict != null) - copy.strict = config.strict; - if (config.wrap) - copy.wrappers = copy.wrappers.concat(config.wrap); - if (config.bufferLength != null) - copy.bufferLength = config.bufferLength; - return copy; - } - /// Returns the name associated with a given term. This will only - /// work for all terms when the parser was generated with the - /// `--names` option. By default, only the names of tagged terms are - /// stored. - getName(term) { - return this.termNames ? this.termNames[term] : String(term <= this.maxNode && this.nodeSet.types[term].name || term); - } - /// The eof term id is always allocated directly after the node - /// types. @internal - get eofTerm() { return this.maxNode + 1; } - /// The type of top node produced by the parser. - get topNode() { return this.nodeSet.types[this.top[1]]; } - /// @internal - dynamicPrecedence(term) { - let prec = this.dynamicPrecedences; - return prec == null ? 0 : prec[term] || 0; - } - /// @internal - parseDialect(dialect) { - let values = Object.keys(this.dialects), flags = values.map(() => false); - if (dialect) - for (let part of dialect.split(" ")) { - let id = values.indexOf(part); - if (id >= 0) - flags[id] = true; - } - let disabled = null; - for (let i = 0; i < values.length; i++) - if (!flags[i]) { - for (let j = this.dialects[values[i]], id; (id = this.data[j++]) != 65535 /* End */;) - (disabled || (disabled = new Uint8Array(this.maxTerm + 1)))[id] = 1; - } - return new Dialect(dialect, flags, disabled); - } - /// (used by the output of the parser generator) @internal - static deserialize(spec) { - return new LRParser(spec); - } - } - function pair(data, off) { return data[off] | (data[off + 1] << 16); } - function findOffset(data, start, term) { - for (let i = start, next; (next = data[i]) != 65535 /* End */; i++) - if (next == term) - return i - start; - return -1; - } - function findFinished(stacks) { - let best = null; - for (let stack of stacks) { - let stopped = stack.p.stoppedAt; - if ((stack.pos == stack.p.stream.end || stopped != null && stack.pos > stopped) && - stack.p.parser.stateFlag(stack.state, 2 /* Accepting */) && - (!best || best.score < stack.score)) - best = stack; - } - return best; - } - - // This file was generated by lezer-generator. You probably shouldn't edit it. - const printKeyword = 1, - indent = 162, - dedent = 163, - newline$1 = 164, - newlineBracketed = 165, - newlineEmpty = 166, - eof = 167, - ParenthesizedExpression = 21, - ParenL = 22, - TupleExpression = 47, - ComprehensionExpression = 48, - ArrayExpression = 52, - BracketL = 53, - ArrayComprehensionExpression = 55, - DictionaryExpression = 56, - BraceL = 57, - DictionaryComprehensionExpression = 59, - SetExpression = 60, - SetComprehensionExpression = 61, - ArgList = 63, - subscript = 203, - FormatReplacement = 71, - importList = 228, - ParamList = 121; - - const newline = 10, carriageReturn = 13, space = 32, tab = 9, hash = 35, parenOpen = 40, dot = 46; - - const bracketed = [ - ParenthesizedExpression, TupleExpression, ComprehensionExpression, importList, ArgList, ParamList, - ArrayExpression, ArrayComprehensionExpression, subscript, - SetExpression, SetComprehensionExpression, - DictionaryExpression, DictionaryComprehensionExpression, FormatReplacement - ]; - - const newlines = new ExternalTokenizer((input, stack) => { - if (input.next < 0) { - input.acceptToken(eof); - } else if (input.next != newline && input.next != carriageReturn) ; else if (stack.context.depth < 0) { - input.acceptToken(newlineBracketed, 1); - } else { - input.advance(); - let spaces = 0; - while (input.next == space || input.next == tab) { input.advance(); spaces++; } - let empty = input.next == newline || input.next == carriageReturn || input.next == hash; - input.acceptToken(empty ? newlineEmpty : newline$1, -spaces); + // ================= registraton API ==================== + logStatus(msg) { + logger.info(msg); + const ev = new CustomEvent('py-status-message', { detail: msg }); + document.dispatchEvent(ev); } - }, {contextual: true, fallback: true}); - - const indentation = new ExternalTokenizer((input, stack) => { - let cDepth = stack.context.depth; - if (cDepth < 0) return - let prev = input.peek(-1); - if ((prev == newline || prev == carriageReturn) && stack.context.depth >= 0) { - let depth = 0, chars = 0; - for (;;) { - if (input.next == space) depth++; - else if (input.next == tab) depth += 8 - (depth % 8); - else break - input.advance(); - chars++; - } - if (depth != cDepth && - input.next != newline && input.next != carriageReturn && input.next != hash) { - if (depth < cDepth) input.acceptToken(dedent, -chars); - else input.acceptToken(indent); - } + registerStdioListener(stdio) { + this._stdioMultiplexer.addListener(stdio); } - }); + } + function pyscript_get_config() { + return globalApp.config; + } + globalExport('pyscript_get_config', pyscript_get_config); + // main entry point of execution + const globalApp = new PyScriptApp(); + globalApp.main(); + const interpreter = globalApp.interpreter; + // TODO: This is for backwards compatibility, it should be removed + // when we finish the deprecation cycle of `runtime` + const runtime = globalApp.interpreter; - function IndentLevel(parent, depth) { - this.parent = parent; - // -1 means this is not an actual indent level but a set of brackets - this.depth = depth; - this.hash = (parent ? parent.hash + parent.hash << 8 : 0) + depth + (depth << 4); - } + exports.PyScriptApp = PyScriptApp; + exports.interpreter = interpreter; + exports.runtime = runtime; + exports.version = version; - const topIndent = new IndentLevel(null, 0); + Object.defineProperty(exports, '__esModule', { value: true }); - function countIndent(space) { - let depth = 0; - for (let i = 0; i < space.length; i++) - depth += space.charCodeAt(i) == tab ? 8 - (depth % 8) : 1; - return depth - } + return exports; - const trackIndent = new ContextTracker({ - start: topIndent, - reduce(context, term) { - return context.depth < 0 && bracketed.indexOf(term) > -1 ? context.parent : context - }, - shift(context, term, stack, input) { - if (term == indent) return new IndentLevel(context, countIndent(input.read(input.pos, stack.pos))) - if (term == dedent) return context.parent - if (term == ParenL || term == BracketL || term == BraceL) return new IndentLevel(context, -1) - return context - }, - hash(context) { return context.hash } - }); - - const legacyPrint = new ExternalTokenizer(input => { - for (let i = 0; i < 5; i++) { - if (input.next != "print".charCodeAt(i)) return - input.advance(); - } - if (/\w/.test(String.fromCharCode(input.next))) return - for (let off = 0;; off++) { - let next = input.peek(off); - if (next == space || next == tab) continue - if (next != parenOpen && next != dot && next != newline && next != carriageReturn && next != hash) - input.acceptToken(printKeyword); - return - } - }); - - // This file was generated by lezer-generator. You probably shouldn't edit it. - const spec_identifier = {__proto__:null,await:40, or:48, and:50, in:54, not:56, is:58, if:64, else:66, lambda:70, yield:88, from:90, async:98, for:100, None:152, True:154, False:154, del:168, pass:172, break:176, continue:180, return:184, raise:192, import:196, as:198, global:202, nonlocal:204, assert:208, elif:218, while:222, try:228, except:230, finally:232, with:236, def:240, class:250}; - const parser = LRParser.deserialize({ - version: 13, - states: "!?pO`Q$IXOOO%cQ$I[O'#GaOOQ$IS'#Cm'#CmOOQ$IS'#Cn'#CnO'RQ$IWO'#ClO(tQ$I[O'#G`OOQ$IS'#Ga'#GaOOQ$IS'#DR'#DROOQ$IS'#G`'#G`O)bQ$IWO'#CqO)rQ$IWO'#DbO*SQ$IWO'#DfOOQ$IS'#Ds'#DsO*gO`O'#DsO*oOpO'#DsO*wO!bO'#DtO+SO#tO'#DtO+_O&jO'#DtO+jO,UO'#DtO-lQ$I[O'#GQOOQ$IS'#GQ'#GQO'RQ$IWO'#GPO/OQ$I[O'#GPOOQ$IS'#E]'#E]O/gQ$IWO'#E^OOQ$IS'#GO'#GOO/qQ$IWO'#F}OOQ$IV'#F}'#F}O/|Q$IWO'#FPOOQ$IS'#Fr'#FrO0RQ$IWO'#FOOOQ$IV'#H]'#H]OOQ$IV'#F|'#F|OOQ$IT'#FR'#FRQ`Q$IXOOO'RQ$IWO'#CoO0aQ$IWO'#CzO0hQ$IWO'#DOO0vQ$IWO'#GeO1WQ$I[O'#EQO'RQ$IWO'#EROOQ$IS'#ET'#ETOOQ$IS'#EV'#EVOOQ$IS'#EX'#EXO1lQ$IWO'#EZO2SQ$IWO'#E_O/|Q$IWO'#EaO2gQ$I[O'#EaO/|Q$IWO'#EdO/gQ$IWO'#EgO/gQ$IWO'#EkO/gQ$IWO'#EnO2rQ$IWO'#EpO2yQ$IWO'#EuO3UQ$IWO'#EqO/gQ$IWO'#EuO/|Q$IWO'#EwO/|Q$IWO'#E|OOQ$IS'#Cc'#CcOOQ$IS'#Cd'#CdOOQ$IS'#Ce'#CeOOQ$IS'#Cf'#CfOOQ$IS'#Cg'#CgOOQ$IS'#Ch'#ChOOQ$IS'#Cj'#CjO'RQ$IWO,58|O'RQ$IWO,58|O'RQ$IWO,58|O'RQ$IWO,58|O'RQ$IWO,58|O'RQ$IWO,58|O3ZQ$IWO'#DmOOQ$IS,5:W,5:WO3nQ$IWO'#GoOOQ$IS,5:Z,5:ZO3{Q%1`O,5:ZO4QQ$I[O,59WO0aQ$IWO,59_O0aQ$IWO,59_O0aQ$IWO,59_O6pQ$IWO,59_O6uQ$IWO,59_O6|Q$IWO,59gO7TQ$IWO'#G`O8ZQ$IWO'#G_OOQ$IS'#G_'#G_OOQ$IS'#DX'#DXO8rQ$IWO,59]O'RQ$IWO,59]O9QQ$IWO,59]O9VQ$IWO,5:PO'RQ$IWO,5:POOQ$IS,59|,59|O9eQ$IWO,59|O9jQ$IWO,5:VO'RQ$IWO,5:VO'RQ$IWO,5:TOOQ$IS,5:Q,5:QO9{Q$IWO,5:QO:QQ$IWO,5:UOOOO'#FZ'#FZO:VO`O,5:_OOQ$IS,5:_,5:_OOOO'#F['#F[O:_OpO,5:_O:gQ$IWO'#DuOOOO'#F]'#F]O:wO!bO,5:`OOQ$IS,5:`,5:`OOOO'#F`'#F`O;SO#tO,5:`OOOO'#Fa'#FaO;_O&jO,5:`OOOO'#Fb'#FbO;jO,UO,5:`OOQ$IS'#Fc'#FcO;uQ$I[O,5:dO>gQ$I[O,5<kO?QQ%GlO,5<kO?qQ$I[O,5<kOOQ$IS,5:x,5:xO@YQ$IXO'#FkOAiQ$IWO,5;TOOQ$IV,5<i,5<iOAtQ$I[O'#HXOB]Q$IWO,5;kOOQ$IS-E9p-E9pOOQ$IV,5;j,5;jO3PQ$IWO'#EwOOQ$IT-E9P-E9POBeQ$I[O,59ZODlQ$I[O,59fOEVQ$IWO'#GbOEbQ$IWO'#GbO/|Q$IWO'#GbOEmQ$IWO'#DQOEuQ$IWO,59jOEzQ$IWO'#GfO'RQ$IWO'#GfO/gQ$IWO,5=POOQ$IS,5=P,5=PO/gQ$IWO'#D|OOQ$IS'#D}'#D}OFiQ$IWO'#FeOFyQ$IWO,58zOFyQ$IWO,58zO)eQ$IWO,5:jOGXQ$I[O'#GhOOQ$IS,5:m,5:mOOQ$IS,5:u,5:uOGlQ$IWO,5:yOG}Q$IWO,5:{OOQ$IS'#Fh'#FhOH]Q$I[O,5:{OHkQ$IWO,5:{OHpQ$IWO'#H[OOQ$IS,5;O,5;OOIOQ$IWO'#HWOOQ$IS,5;R,5;RO3UQ$IWO,5;VO3UQ$IWO,5;YOIaQ$I[O'#H^O'RQ$IWO'#H^OIkQ$IWO,5;[O2rQ$IWO,5;[O/gQ$IWO,5;aO/|Q$IWO,5;cOIpQ$IXO'#ElOJyQ$IZO,5;]ON[Q$IWO'#H_O3UQ$IWO,5;aONgQ$IWO,5;cONlQ$IWO,5;hO!#aQ$I[O1G.hO!#hQ$I[O1G.hO!&XQ$I[O1G.hO!&cQ$I[O1G.hO!(|Q$I[O1G.hO!)aQ$I[O1G.hO!)tQ$IWO'#GnO!*SQ$I[O'#GQO/gQ$IWO'#GnO!*^Q$IWO'#GmOOQ$IS,5:X,5:XO!*fQ$IWO,5:XO!*kQ$IWO'#GpO!*vQ$IWO'#GpO!+ZQ$IWO,5=ZOOQ$IS'#Dq'#DqOOQ$IS1G/u1G/uOOQ$IS1G.y1G.yO!,ZQ$I[O1G.yO!,bQ$I[O1G.yO0aQ$IWO1G.yO!,}Q$IWO1G/ROOQ$IS'#DW'#DWO/gQ$IWO,59qOOQ$IS1G.w1G.wO!-UQ$IWO1G/cO!-fQ$IWO1G/cO!-nQ$IWO1G/dO'RQ$IWO'#GgO!-sQ$IWO'#GgO!-xQ$I[O1G.wO!.YQ$IWO,59fO!/`Q$IWO,5=VO!/pQ$IWO,5=VO!/xQ$IWO1G/kO!/}Q$I[O1G/kOOQ$IS1G/h1G/hO!0_Q$IWO,5=QO!1UQ$IWO,5=QO/gQ$IWO1G/oO!1sQ$IWO1G/qO!1xQ$I[O1G/qO!2YQ$I[O1G/oOOQ$IS1G/l1G/lOOQ$IS1G/p1G/pOOOO-E9X-E9XOOQ$IS1G/y1G/yOOOO-E9Y-E9YO!2jQ$IWO'#G{O/gQ$IWO'#G{O!2xQ$IWO,5:aOOOO-E9Z-E9ZOOQ$IS1G/z1G/zOOOO-E9^-E9^OOOO-E9_-E9_OOOO-E9`-E9`OOQ$IS-E9a-E9aO!3TQ%GlO1G2VO!3tQ$I[O1G2VO'RQ$IWO,5<OOOQ$IS,5<O,5<OOOQ$IS-E9b-E9bOOQ$IS,5<V,5<VOOQ$IS-E9i-E9iOOQ$IV1G0o1G0oO/|Q$IWO'#FgO!4]Q$I[O,5=sOOQ$IS1G1V1G1VO!4tQ$IWO1G1VOOQ$IS'#DS'#DSO/gQ$IWO,5<|OOQ$IS,5<|,5<|O!4yQ$IWO'#FSO!5UQ$IWO,59lO!5^Q$IWO1G/UO!5hQ$I[O,5=QOOQ$IS1G2k1G2kOOQ$IS,5:h,5:hO!6XQ$IWO'#GPOOQ$IS,5<P,5<POOQ$IS-E9c-E9cO!6jQ$IWO1G.fOOQ$IS1G0U1G0UO!6xQ$IWO,5=SO!7YQ$IWO,5=SO/gQ$IWO1G0eO/gQ$IWO1G0eO/|Q$IWO1G0gOOQ$IS-E9f-E9fO!7kQ$IWO1G0gO!7vQ$IWO1G0gO!7{Q$IWO,5=vO!8ZQ$IWO,5=vO!8iQ$IWO,5=rO!9PQ$IWO,5=rO!9bQ$IZO1G0qO!<pQ$IZO1G0tO!?{Q$IWO,5=xO!@VQ$IWO,5=xO!@_Q$I[O,5=xO/gQ$IWO1G0vO!@iQ$IWO1G0vO3UQ$IWO1G0{ONgQ$IWO1G0}OOQ$IV,5;W,5;WO!@nQ$IYO,5;WO!@sQ$IZO1G0wO!DUQ$IWO'#FoO3UQ$IWO1G0wO3UQ$IWO1G0wO!DcQ$IWO,5=yO!DpQ$IWO,5=yO/|Q$IWO,5=yOOQ$IV1G0{1G0{O!DxQ$IWO'#EyO!EZQ%1`O1G0}OOQ$IV1G1S1G1SO3UQ$IWO1G1SOOQ$IS,5=Y,5=YOOQ$IS'#Dn'#DnO/gQ$IWO,5=YO!EcQ$IWO,5=XO!EvQ$IWO,5=XOOQ$IS1G/s1G/sO!FOQ$IWO,5=[O!F`Q$IWO,5=[O!FhQ$IWO,5=[O!F{Q$IWO,5=[O!G]Q$IWO,5=[OOQ$IS1G2u1G2uOOQ$IS7+$e7+$eO!5^Q$IWO7+$mO!IOQ$IWO1G.yO!IVQ$IWO1G.yOOQ$IS1G/]1G/]OOQ$IS,5;p,5;pO'RQ$IWO,5;pOOQ$IS7+$}7+$}O!I^Q$IWO7+$}OOQ$IS-E9S-E9SOOQ$IS7+%O7+%OO!InQ$IWO,5=RO'RQ$IWO,5=ROOQ$IS7+$c7+$cO!IsQ$IWO7+$}O!I{Q$IWO7+%OO!JQQ$IWO1G2qOOQ$IS7+%V7+%VO!JbQ$IWO1G2qO!JjQ$IWO7+%VOOQ$IS,5;o,5;oO'RQ$IWO,5;oO!JoQ$IWO1G2lOOQ$IS-E9R-E9RO!KfQ$IWO7+%ZOOQ$IS7+%]7+%]O!KtQ$IWO1G2lO!LcQ$IWO7+%]O!LhQ$IWO1G2rO!LxQ$IWO1G2rO!MQQ$IWO7+%ZO!MVQ$IWO,5=gO!MmQ$IWO,5=gO!MmQ$IWO,5=gO!M{O!LQO'#DwO!NWOSO'#G|OOOO1G/{1G/{O!N]Q$IWO1G/{O!NeQ%GlO7+'qO# UQ$I[O1G1jP# oQ$IWO'#FdOOQ$IS,5<R,5<ROOQ$IS-E9e-E9eOOQ$IS7+&q7+&qOOQ$IS1G2h1G2hOOQ$IS,5;n,5;nOOQ$IS-E9Q-E9QOOQ$IS7+$p7+$pO# |Q$IWO,5<kO#!gQ$IWO,5<kO#!xQ$I[O,5;qO##]Q$IWO1G2nOOQ$IS-E9T-E9TOOQ$IS7+&P7+&PO##mQ$IWO7+&POOQ$IS7+&R7+&RO##{Q$IWO'#HZO/|Q$IWO'#HYO#$aQ$IWO7+&ROOQ$IS,5<U,5<UO#$lQ$IWO1G3bOOQ$IS-E9h-E9hOOQ$IS,5<Q,5<QO#$zQ$IWO1G3^OOQ$IS-E9d-E9dO#%bQ$IZO7+&]O!DUQ$IWO'#FmO3UQ$IWO7+&]O3UQ$IWO7+&`O#(pQ$I[O,5<YO'RQ$IWO,5<YO#(zQ$IWO1G3dOOQ$IS-E9l-E9lO#)UQ$IWO1G3dO3UQ$IWO7+&bO/gQ$IWO7+&bOOQ$IV7+&g7+&gO!EZQ%1`O7+&iO#)^Q$IXO1G0rOOQ$IV-E9m-E9mO3UQ$IWO7+&cO3UQ$IWO7+&cOOQ$IV,5<Z,5<ZO#+PQ$IWO,5<ZOOQ$IV7+&c7+&cO#+[Q$IZO7+&cO#.gQ$IWO,5<[O#.rQ$IWO1G3eOOQ$IS-E9n-E9nO#/PQ$IWO1G3eO#/XQ$IWO'#HaO#/gQ$IWO'#HaO/|Q$IWO'#HaOOQ$IS'#Ha'#HaO#/rQ$IWO'#H`OOQ$IS,5;e,5;eO#/zQ$IWO,5;eO/gQ$IWO'#E{OOQ$IV7+&i7+&iO3UQ$IWO7+&iOOQ$IV7+&n7+&nOOQ$IS1G2t1G2tOOQ$IS,5;s,5;sO#0PQ$IWO1G2sOOQ$IS-E9V-E9VO#0dQ$IWO,5;tO#0oQ$IWO,5;tO#1SQ$IWO1G2vOOQ$IS-E9W-E9WO#1dQ$IWO1G2vO#1lQ$IWO1G2vO#1|Q$IWO1G2vO#1dQ$IWO1G2vOOQ$IS<<HX<<HXO#2XQ$I[O1G1[OOQ$IS<<Hi<<HiP#2fQ$IWO'#FUO6|Q$IWO1G2mO#2sQ$IWO1G2mO#2xQ$IWO<<HiOOQ$IS<<Hj<<HjO#3YQ$IWO7+(]OOQ$IS<<Hq<<HqO#3jQ$I[O1G1ZP#4ZQ$IWO'#FTO#4hQ$IWO7+(^O#4xQ$IWO7+(^O#5QQ$IWO<<HuO#5VQ$IWO7+(WOOQ$IS<<Hw<<HwO#5|Q$IWO,5;rO'RQ$IWO,5;rOOQ$IS-E9U-E9UOOQ$IS<<Hu<<HuOOQ$IS,5;x,5;xO/gQ$IWO,5;xO#6RQ$IWO1G3ROOQ$IS-E9[-E9[O#6iQ$IWO1G3ROOOO'#F_'#F_O#6wO!LQO,5:cOOOO,5=h,5=hOOOO7+%g7+%gO#7SQ$IWO1G2VO#7mQ$IWO1G2VP'RQ$IWO'#FVO/gQ$IWO<<IkO#8OQ$IWO,5=uO#8aQ$IWO,5=uO/|Q$IWO,5=uO#8rQ$IWO,5=tOOQ$IS<<Im<<ImP/|Q$IWO'#FjP/gQ$IWO'#FfOOQ$IV-E9k-E9kO3UQ$IWO<<IwOOQ$IV,5<X,5<XO3UQ$IWO,5<XOOQ$IV<<Iw<<IwOOQ$IV<<Iz<<IzO#8wQ$I[O1G1tP#9RQ$IWO'#FnO#9YQ$IWO7+)OO#9dQ$IZO<<I|O3UQ$IWO<<I|OOQ$IV<<JT<<JTO3UQ$IWO<<JTOOQ$IV'#Fl'#FlO#<oQ$IZO7+&^OOQ$IV<<I}<<I}O#>hQ$IZO<<I}OOQ$IV1G1u1G1uO/|Q$IWO1G1uO3UQ$IWO<<I}O/|Q$IWO1G1vP/gQ$IWO'#FpO#AsQ$IWO7+)PO#BQQ$IWO7+)POOQ$IS'#Ez'#EzO/gQ$IWO,5={O#BYQ$IWO,5={OOQ$IS,5={,5={O#BeQ$IWO,5=zO#BvQ$IWO,5=zOOQ$IS1G1P1G1POOQ$IS,5;g,5;gP#COQ$IWO'#FXO#C`Q$IWO1G1`O#CsQ$IWO1G1`O#DTQ$IWO1G1`P#D`Q$IWO'#FYO#DmQ$IWO7+(bO#D}Q$IWO7+(bO#D}Q$IWO7+(bO#EVQ$IWO7+(bO#EgQ$IWO7+(XO6|Q$IWO7+(XOOQ$ISAN>TAN>TO#FQQ$IWO<<KxOOQ$ISAN>aAN>aO/gQ$IWO1G1^O#FbQ$I[O1G1^P#FlQ$IWO'#FWOOQ$IS1G1d1G1dP#FyQ$IWO'#F^O#GWQ$IWO7+(mOOOO-E9]-E9]O#GnQ$IWO7+'qOOQ$ISAN?VAN?VO#HXQ$IWO,5<TO#HmQ$IWO1G3aOOQ$IS-E9g-E9gO#IOQ$IWO1G3aOOQ$IS1G3`1G3`OOQ$IVAN?cAN?cOOQ$IV1G1s1G1sO3UQ$IWOAN?hO#IaQ$IZOAN?hOOQ$IVAN?oAN?oOOQ$IV-E9j-E9jOOQ$IV<<Ix<<IxO3UQ$IWOAN?iO3UQ$IWO7+'aOOQ$IVAN?iAN?iOOQ$IS7+'b7+'bO#LlQ$IWO<<LkOOQ$IS1G3g1G3gO/gQ$IWO1G3gOOQ$IS,5<],5<]O#LyQ$IWO1G3fOOQ$IS-E9o-E9oO#M[Q$IWO7+&zO#MlQ$IWO7+&zOOQ$IS7+&z7+&zO#MwQ$IWO<<K|O#NXQ$IWO<<K|O#NXQ$IWO<<K|O#NaQ$IWO'#GiOOQ$IS<<Ks<<KsO#NkQ$IWO<<KsOOQ$IS7+&x7+&xO/|Q$IWO1G1oP/|Q$IWO'#FiO$ UQ$IWO7+({O$ gQ$IWO7+({OOQ$IVG25SG25SO3UQ$IWOG25SOOQ$IVG25TG25TOOQ$IV<<J{<<J{OOQ$IS7+)R7+)RP$ xQ$IWO'#FqOOQ$IS<<Jf<<JfO$!WQ$IWO<<JfO$!hQ$IWOANAhO$!xQ$IWOANAhO$#QQ$IWO'#GjOOQ$IS'#Gj'#GjO0hQ$IWO'#DaO$#kQ$IWO,5=TOOQ$ISANA_ANA_OOQ$IS7+'Z7+'ZO$$SQ$IWO<<LgOOQ$IVLD*nLD*nOOQ$ISAN@QAN@QO$$eQ$IWOG27SO$$uQ$IWO,59{OOQ$IS1G2o1G2oO#NaQ$IWO1G/gOOQ$IS7+%R7+%RO6|Q$IWO'#CzO6|Q$IWO,59_O6|Q$IWO,59_O6|Q$IWO,59_O$$zQ$I[O,5<kO6|Q$IWO1G.yO/gQ$IWO1G/UO/gQ$IWO7+$mP$%_Q$IWO'#FdO'RQ$IWO'#GPO$%lQ$IWO,59_O$%qQ$IWO,59_O$%xQ$IWO,59jO$%}Q$IWO1G/RO0hQ$IWO'#DOO6|Q$IWO,59g", - stateData: "$&e~O$oOS$lOS$kOSQOS~OPhOTeOdsOfXOltOp!SOsuO|vO}!PO!R!VO!S!UO!VYO!ZZO!fdO!mdO!ndO!odO!vxO!xyO!zzO!|{O#O|O#S}O#U!OO#X!QO#Y!QO#[!RO#c!TO#f!WO#j!XO#l!YO#q!ZO#tlO$jqO$zQO${QO%PRO%QVO%f[O%g]O%j^O%m_O%s`O%vaO%xbO~OT!aO]!aO_!bOf!iO!V!kO!d!mO$u![O$v!]O$w!^O$x!_O$y!_O$z!`O${!`O$|!aO$}!aO%O!aO~Oh%TXi%TXj%TXk%TXl%TXm%TXp%TXw%TXx%TX!s%TX#^%TX$j%TX$m%TX%V%TX!O%TX!R%TX!S%TX%W%TX!W%TX![%TX}%TX#V%TXq%TX!j%TX~P$_OdsOfXO!VYO!ZZO!fdO!mdO!ndO!odO$zQO${QO%PRO%QVO%f[O%g]O%j^O%m_O%s`O%vaO%xbO~Ow%SXx%SX#^%SX$j%SX$m%SX%V%SX~Oh!pOi!qOj!oOk!oOl!rOm!sOp!tO!s%SX~P(`OT!zOl-dOs-rO|vO~P'ROT!}Ol-dOs-rO!W#OO~P'ROT#RO_#SOl-dOs-rO![#TO~P'RO%h#WO%i#YO~O%k#ZO%l#YO~O!Z#]O%n#^O%r#`O~O!Z#]O%t#aO%u#`O~O!Z#]O%i#`O%w#cO~O!Z#]O%l#`O%y#eO~OT$tX]$tX_$tXf$tXh$tXi$tXj$tXk$tXl$tXm$tXp$tXw$tX!V$tX!d$tX$u$tX$v$tX$w$tX$x$tX$y$tX$z$tX${$tX$|$tX$}$tX%O$tX!O$tX!R$tX!S$tX~O%f[O%g]O%j^O%m_O%s`O%vaO%xbOx$tX!s$tX#^$tX$j$tX$m$tX%V$tX%W$tX!W$tX![$tX}$tX#V$tXq$tX!j$tX~P+uOw#jOx$sX!s$sX#^$sX$j$sX$m$sX%V$sX~Ol-dOs-rO~P'RO#^#mO$j#oO$m#oO~O%QVO~O!R#tO#l!YO#q!ZO#tlO~OltO~P'ROT#yO_#zO%QVOxtP~OT$OOl-dOs-rO}$PO~P'ROx$RO!s$WO%V$SO#^!tX$j!tX$m!tX~OT$OOl-dOs-rO#^!}X$j!}X$m!}X~P'ROl-dOs-rO#^#RX$j#RX$m#RX~P'RO!d$^O!m$^O%QVO~OT$hO~P'RO!S$jO#j$kO#l$lO~Ox$mO~OT${O_${Ol-dOs-rO!O$}O~P'ROl-dOs-rOx%QO~P'RO%e%SO~O_!bOf!iO!V!kO!d!mOT`a]`ah`ai`aj`ak`al`am`ap`aw`ax`a!s`a#^`a$j`a$m`a$u`a$v`a$w`a$x`a$y`a$z`a${`a$|`a$}`a%O`a%V`a!O`a!R`a!S`a%W`a!W`a![`a}`a#V`aq`a!j`a~Ok%XO~Ol%XO~P'ROl-dO~P'ROh-fOi-gOj-eOk-eOl-nOm-oOp-sO!O%SX!R%SX!S%SX%W%SX!W%SX![%SX}%SX#V%SX!j%SX~P(`O%W%ZOw%RX!O%RX!R%RX!S%RX!W%RXx%RX~Ow%^O!O%]O!R%bO!S%aO~O!O%]O~Ow%eO!R%bO!S%aO!W%_X~O!W%iO~Ow%jOx%lO!R%bO!S%aO![%YX~O![%pO~O![%qO~O%h#WO%i%sO~O%k#ZO%l%sO~OT%vOl-dOs-rO|vO~P'RO!Z#]O%n#^O%r%yO~O!Z#]O%t#aO%u%yO~O!Z#]O%i%yO%w#cO~O!Z#]O%l%yO%y#eO~OT!la]!la_!laf!lah!lai!laj!lak!lal!lam!lap!law!lax!la!V!la!d!la!s!la#^!la$j!la$m!la$u!la$v!la$w!la$x!la$y!la$z!la${!la$|!la$}!la%O!la%V!la!O!la!R!la!S!la%W!la!W!la![!la}!la#V!laq!la!j!la~P#vOw&OOx$sa!s$sa#^$sa$j$sa$m$sa%V$sa~P$_OT&QOltOsuOx$sa!s$sa#^$sa$j$sa$m$sa%V$sa~P'ROw&OOx$sa!s$sa#^$sa$j$sa$m$sa%V$sa~OPhOTeOltOsuO|vO}!PO!vxO!xyO!zzO!|{O#O|O#S}O#U!OO#X!QO#Y!QO#[!RO#^$_X$j$_X$m$_X~P'RO#^#mO$j&VO$m&VO~O!d&WOf%{X$j%{X#V%{X#^%{X$m%{X#U%{X~Of!iO$j&YO~Ohcaicajcakcalcamcapcawcaxca!sca#^ca$jca$mca%Vca!Oca!Rca!Sca%Wca!Wca![ca}ca#Vcaqca!jca~P$_Opnawnaxna#^na$jna$mna%Vna~Oh!pOi!qOj!oOk!oOl!rOm!sO!sna~PDTO%V&[Ow%UXx%UX~O%QVOw%UXx%UX~Ow&_OxtX~Ox&aO~Ow%jO#^%YX$j%YX$m%YX!O%YXx%YX![%YX!j%YX%V%YX~OT-mOl-dOs-rO|vO~P'RO%V$SO#^Sa$jSa$mSa~Ow&jO#^%[X$j%[X$m%[Xk%[X~P$_Ow&mO}&lO#^#Ra$j#Ra$m#Ra~O#V&nO#^#Ta$j#Ta$m#Ta~O!d$^O!m$^O#U&pO%QVO~O#U&pO~Ow&rO#^&OX$j&OX$m&OX~Ow&tO#^%zX$j%zX$m%zXx%zX~Ow&xOk&QX~P$_Ok&{O~OPhOTeOltOsuO|vO}!PO!vxO!xyO!zzO!|{O#O|O#S}O#U!OO#X!QO#Y!QO#[!RO$j'QO~P'ROq'UO#g'SO#h'TOP#eaT#ead#eaf#eal#eap#eas#ea|#ea}#ea!R#ea!S#ea!V#ea!Z#ea!f#ea!m#ea!n#ea!o#ea!v#ea!x#ea!z#ea!|#ea#O#ea#S#ea#U#ea#X#ea#Y#ea#[#ea#c#ea#f#ea#j#ea#l#ea#q#ea#t#ea$g#ea$j#ea$z#ea${#ea%P#ea%Q#ea%f#ea%g#ea%j#ea%m#ea%s#ea%v#ea%x#ea$i#ea$m#ea~Ow'VO#V'XOx&RX~Of'ZO~Of!iOx$mO~OT!aO]!aO_!bOf!iO!V!kO!d!mO$w!^O$x!_O$y!_O$z!`O${!`O$|!aO$}!aO%O!aOhUiiUijUikUilUimUipUiwUixUi!sUi#^Ui$jUi$mUi$uUi%VUi!OUi!RUi!SUi%WUi!WUi![Ui}Ui#VUiqUi!jUi~O$v!]O~PNtO$vUi~PNtOT!aO]!aO_!bOf!iO!V!kO!d!mO$z!`O${!`O$|!aO$}!aO%O!aOhUiiUijUikUilUimUipUiwUixUi!sUi#^Ui$jUi$mUi$uUi$vUi$wUi%VUi!OUi!RUi!SUi%WUi!WUi![Ui}Ui#VUiqUi!jUi~O$x!_O$y!_O~P!#oO$xUi$yUi~P!#oO_!bOf!iO!V!kO!d!mOhUiiUijUikUilUimUipUiwUixUi!sUi#^Ui$jUi$mUi$uUi$vUi$wUi$xUi$yUi$zUi${Ui%VUi!OUi!RUi!SUi%WUi!WUi![Ui}Ui#VUiqUi!jUi~OT!aO]!aO$|!aO$}!aO%O!aO~P!&mOTUi]Ui$|Ui$}Ui%OUi~P!&mO!R%bO!S%aOw%bX!O%bX~O%V'`O%W'`O~P+uOw'bO!O%aX~O!O'dO~Ow'eOx'gO!W%dX~Ol-dOs-rOw'eOx'hO!W%dX~P'RO!W'jO~Oj!oOk!oOl!rOm!sOhgipgiwgixgi!sgi#^gi$jgi$mgi%Vgi~Oi!qO~P!+`Oigi~P!+`Oh-fOi-gOj-eOk-eOl-nOm-oO~Oq'lO~P!,iOT'qOl-dOs-rO!O'rO~P'ROw'sO!O'rO~O!O'uO~O!S'wO~Ow'sO!O'xO!R%bO!S%aO~P$_Oh-fOi-gOj-eOk-eOl-nOm-oO!Ona!Rna!Sna%Wna!Wna![na}na#Vnaqna!jna~PDTOT'qOl-dOs-rO!W%_a~P'ROw'{O!W%_a~O!W'|O~Ow'{O!R%bO!S%aO!W%_a~P$_OT(QOl-dOs-rO![%Ya#^%Ya$j%Ya$m%Ya!O%Yax%Ya!j%Ya%V%Ya~P'ROw(RO![%Ya#^%Ya$j%Ya$m%Ya!O%Yax%Ya!j%Ya%V%Ya~O![(UO~Ow(RO!R%bO!S%aO![%Ya~P$_Ow(XO!R%bO!S%aO![%`a~P$_Ow([Ox%oX![%oX!j%oX~Ox(_O![(aO!j(bO~OT&QOltOsuOx$si!s$si#^$si$j$si$m$si%V$si~P'ROw(cOx$si!s$si#^$si$j$si$m$si%V$si~O!d&WOf%{a$j%{a#V%{a#^%{a$m%{a#U%{a~O$j(hO~OT#yO_#zO%QVO~Ow&_Oxta~OltOsuO~P'ROw(RO#^%Ya$j%Ya$m%Ya!O%Yax%Ya![%Ya!j%Ya%V%Ya~P$_Ow(mO#^$sX$j$sX$m$sX%V$sX~O%V$SO#^Si$jSi$mSi~O#^%[a$j%[a$m%[ak%[a~P'ROw(pO#^%[a$j%[a$m%[ak%[a~OT(tOf(vO%QVO~O#U(wO~O%QVO#^&Oa$j&Oa$m&Oa~Ow(yO#^&Oa$j&Oa$m&Oa~Ol-dOs-rO#^%za$j%za$m%zax%za~P'ROw(|O#^%za$j%za$m%zax%za~Oq)QO#a)POP#_iT#_id#_if#_il#_ip#_is#_i|#_i}#_i!R#_i!S#_i!V#_i!Z#_i!f#_i!m#_i!n#_i!o#_i!v#_i!x#_i!z#_i!|#_i#O#_i#S#_i#U#_i#X#_i#Y#_i#[#_i#c#_i#f#_i#j#_i#l#_i#q#_i#t#_i$g#_i$j#_i$z#_i${#_i%P#_i%Q#_i%f#_i%g#_i%j#_i%m#_i%s#_i%v#_i%x#_i$i#_i$m#_i~Oq)ROP#biT#bid#bif#bil#bip#bis#bi|#bi}#bi!R#bi!S#bi!V#bi!Z#bi!f#bi!m#bi!n#bi!o#bi!v#bi!x#bi!z#bi!|#bi#O#bi#S#bi#U#bi#X#bi#Y#bi#[#bi#c#bi#f#bi#j#bi#l#bi#q#bi#t#bi$g#bi$j#bi$z#bi${#bi%P#bi%Q#bi%f#bi%g#bi%j#bi%m#bi%s#bi%v#bi%x#bi$i#bi$m#bi~OT)TOk&Qa~P'ROw)UOk&Qa~Ow)UOk&Qa~P$_Ok)YO~O$h)]O~Oq)`O#g'SO#h)_OP#eiT#eid#eif#eil#eip#eis#ei|#ei}#ei!R#ei!S#ei!V#ei!Z#ei!f#ei!m#ei!n#ei!o#ei!v#ei!x#ei!z#ei!|#ei#O#ei#S#ei#U#ei#X#ei#Y#ei#[#ei#c#ei#f#ei#j#ei#l#ei#q#ei#t#ei$g#ei$j#ei$z#ei${#ei%P#ei%Q#ei%f#ei%g#ei%j#ei%m#ei%s#ei%v#ei%x#ei$i#ei$m#ei~Ol-dOs-rOx$mO~P'ROl-dOs-rOx&Ra~P'ROw)fOx&Ra~OT)jO_)kO!O)nO$|)lO%QVO~Ox$mO&U)pO~OT${O_${Ol-dOs-rO!O%aa~P'ROw)vO!O%aa~Ol-dOs-rOx)yO!W%da~P'ROw)zO!W%da~Ol-dOs-rOw)zOx)}O!W%da~P'ROl-dOs-rOw)zO!W%da~P'ROw)zOx)}O!W%da~Oj-eOk-eOl-nOm-oOhgipgiwgi!Ogi!Rgi!Sgi%Wgi!Wgixgi![gi#^gi$jgi$mgi}gi#Vgiqgi!jgi%Vgi~Oi-gO~P!GhOigi~P!GhOT'qOl-dOs-rO!O*SO~P'ROk*UO~Ow*WO!O*SO~O!O*XO~OT'qOl-dOs-rO!W%_i~P'ROw*YO!W%_i~O!W*ZO~OT(QOl-dOs-rO![%Yi#^%Yi$j%Yi$m%Yi!O%Yix%Yi!j%Yi%V%Yi~P'ROw*^O!R%bO!S%aO![%`i~Ow*aO![%Yi#^%Yi$j%Yi$m%Yi!O%Yix%Yi!j%Yi%V%Yi~O![*bO~O_*dOl-dOs-rO![%`i~P'ROw*^O![%`i~O![*fO~OT*hOl-dOs-rOx%oa![%oa!j%oa~P'ROw*iOx%oa![%oa!j%oa~O!Z#]O%q*lO![!kX~O![*nO~Ox(_O![*oO~OT&QOltOsuOx$sq!s$sq#^$sq$j$sq$m$sq%V$sq~P'ROw$Wix$Wi!s$Wi#^$Wi$j$Wi$m$Wi%V$Wi~P$_OT&QOltOsuO~P'ROT&QOl-dOs-rO#^$sa$j$sa$m$sa%V$sa~P'ROw*pO#^$sa$j$sa$m$sa%V$sa~Ow#ya#^#ya$j#ya$m#yak#ya~P$_O#^%[i$j%[i$m%[ik%[i~P'ROw*sO#^#Rq$j#Rq$m#Rq~Ow*tO#V*vO#^%}X$j%}X$m%}X!O%}X~OT*xOf(vO%QVO~O%QVO#^&Oi$j&Oi$m&Oi~Ol-dOs-rO#^%zi$j%zi$m%zix%zi~P'ROq*|O#a)POP#_qT#_qd#_qf#_ql#_qp#_qs#_q|#_q}#_q!R#_q!S#_q!V#_q!Z#_q!f#_q!m#_q!n#_q!o#_q!v#_q!x#_q!z#_q!|#_q#O#_q#S#_q#U#_q#X#_q#Y#_q#[#_q#c#_q#f#_q#j#_q#l#_q#q#_q#t#_q$g#_q$j#_q$z#_q${#_q%P#_q%Q#_q%f#_q%g#_q%j#_q%m#_q%s#_q%v#_q%x#_q$i#_q$m#_q~Ok$baw$ba~P$_OT)TOk&Qi~P'ROw+TOk&Qi~OPhOTeOltOp!SOsuO|vO}!PO!R!VO!S!UO!vxO!xyO!zzO!|{O#O|O#S}O#U!OO#X!QO#Y!QO#[!RO#c!TO#f!WO#j!XO#l!YO#q!ZO#tlO~P'ROw+_Ox$mO#V+_O~O#h+`OP#eqT#eqd#eqf#eql#eqp#eqs#eq|#eq}#eq!R#eq!S#eq!V#eq!Z#eq!f#eq!m#eq!n#eq!o#eq!v#eq!x#eq!z#eq!|#eq#O#eq#S#eq#U#eq#X#eq#Y#eq#[#eq#c#eq#f#eq#j#eq#l#eq#q#eq#t#eq$g#eq$j#eq$z#eq${#eq%P#eq%Q#eq%f#eq%g#eq%j#eq%m#eq%s#eq%v#eq%x#eq$i#eq$m#eq~O#V+aOw$dax$da~Ol-dOs-rOx&Ri~P'ROw+cOx&Ri~Ox$RO%V+eOw&TX!O&TX~O%QVOw&TX!O&TX~Ow+iO!O&SX~O!O+kO~OT${O_${Ol-dOs-rO!O%ai~P'ROx+nOw#|a!W#|a~Ol-dOs-rOx+oOw#|a!W#|a~P'ROl-dOs-rOx)yO!W%di~P'ROw+rO!W%di~Ol-dOs-rOw+rO!W%di~P'ROw+rOx+uO!W%di~Ow#xi!O#xi!W#xi~P$_OT'qOl-dOs-rO~P'ROk+wO~OT'qOl-dOs-rO!O+xO~P'ROT'qOl-dOs-rO!W%_q~P'ROw#wi![#wi#^#wi$j#wi$m#wi!O#wix#wi!j#wi%V#wi~P$_OT(QOl-dOs-rO~P'RO_*dOl-dOs-rO![%`q~P'ROw+yO![%`q~O![+zO~OT(QOl-dOs-rO![%Yq#^%Yq$j%Yq$m%Yq!O%Yqx%Yq!j%Yq%V%Yq~P'ROx+{O~OT*hOl-dOs-rOx%oi![%oi!j%oi~P'ROw,QOx%oi![%oi!j%oi~O!Z#]O%q*lO![!ka~OT&QOl-dOs-rO#^$si$j$si$m$si%V$si~P'ROw,SO#^$si$j$si$m$si%V$si~O%QVO#^%}a$j%}a$m%}a!O%}a~Ow,VO#^%}a$j%}a$m%}a!O%}a~O!O,YO~Ok$biw$bi~P$_OT)TO~P'ROT)TOk&Qq~P'ROq,]OP#dyT#dyd#dyf#dyl#dyp#dys#dy|#dy}#dy!R#dy!S#dy!V#dy!Z#dy!f#dy!m#dy!n#dy!o#dy!v#dy!x#dy!z#dy!|#dy#O#dy#S#dy#U#dy#X#dy#Y#dy#[#dy#c#dy#f#dy#j#dy#l#dy#q#dy#t#dy$g#dy$j#dy$z#dy${#dy%P#dy%Q#dy%f#dy%g#dy%j#dy%m#dy%s#dy%v#dy%x#dy$i#dy$m#dy~OPhOTeOltOp!SOsuO|vO}!PO!R!VO!S!UO!vxO!xyO!zzO!|{O#O|O#S}O#U!OO#X!QO#Y!QO#[!RO#c!TO#f!WO#j!XO#l!YO#q!ZO#tlO$i,aO$m,aO~P'RO#h,bOP#eyT#eyd#eyf#eyl#eyp#eys#ey|#ey}#ey!R#ey!S#ey!V#ey!Z#ey!f#ey!m#ey!n#ey!o#ey!v#ey!x#ey!z#ey!|#ey#O#ey#S#ey#U#ey#X#ey#Y#ey#[#ey#c#ey#f#ey#j#ey#l#ey#q#ey#t#ey$g#ey$j#ey$z#ey${#ey%P#ey%Q#ey%f#ey%g#ey%j#ey%m#ey%s#ey%v#ey%x#ey$i#ey$m#ey~Ol-dOs-rOx&Rq~P'ROw,fOx&Rq~O%V+eOw&Ta!O&Ta~OT)jO_)kO$|)lO%QVO!O&Sa~Ow,jO!O&Sa~OT${O_${Ol-dOs-rO~P'ROl-dOs-rOx,lOw#|i!W#|i~P'ROl-dOs-rOw#|i!W#|i~P'ROx,lOw#|i!W#|i~Ol-dOs-rOx)yO~P'ROl-dOs-rOx)yO!W%dq~P'ROw,oO!W%dq~Ol-dOs-rOw,oO!W%dq~P'ROp,rO!R%bO!S%aO!O%Zq!W%Zq![%Zqw%Zq~P!,iO_*dOl-dOs-rO![%`y~P'ROw#zi![#zi~P$_O_*dOl-dOs-rO~P'ROT*hOl-dOs-rO~P'ROT*hOl-dOs-rOx%oq![%oq!j%oq~P'ROT&QOl-dOs-rO#^$sq$j$sq$m$sq%V$sq~P'RO#V,vOw$]a#^$]a$j$]a$m$]a!O$]a~O%QVO#^%}i$j%}i$m%}i!O%}i~Ow,xO#^%}i$j%}i$m%}i!O%}i~Oq,{OP#d!RT#d!Rd#d!Rf#d!Rl#d!Rp#d!Rs#d!R|#d!R}#d!R!R#d!R!S#d!R!V#d!R!Z#d!R!f#d!R!m#d!R!n#d!R!o#d!R!v#d!R!x#d!R!z#d!R!|#d!R#O#d!R#S#d!R#U#d!R#X#d!R#Y#d!R#[#d!R#c#d!R#f#d!R#j#d!R#l#d!R#q#d!R#t#d!R$g#d!R$j#d!R$z#d!R${#d!R%P#d!R%Q#d!R%f#d!R%g#d!R%j#d!R%m#d!R%s#d!R%v#d!R%x#d!R$i#d!R$m#d!R~Ol-dOs-rOx&Ry~P'ROT)jO_)kO$|)lO%QVO!O&Si~Ol-dOs-rOw#|q!W#|q~P'ROx-ROw#|q!W#|q~Ol-dOs-rOx)yO!W%dy~P'ROw-SO!W%dy~Ol-dOs-WO~P'ROp,rO!R%bO!S%aO!O%Zy!W%Zy![%Zyw%Zy~P!,iO%QVO#^%}q$j%}q$m%}q!O%}q~Ow-[O#^%}q$j%}q$m%}q!O%}q~OT)jO_)kO$|)lO%QVO~Ol-dOs-rOw#|y!W#|y~P'ROl-dOs-rOx)yO!W%d!R~P'ROw-_O!W%d!R~Op%^X!O%^X!R%^X!S%^X!W%^X![%^Xw%^X~P!,iOp,rO!R%bO!S%aO!O%]a!W%]a![%]aw%]a~O%QVO#^%}y$j%}y$m%}y!O%}y~Ol-dOs-rOx)yO!W%d!Z~P'ROx-bO~Ow*pO#^$sa$j$sa$m$sa%V$sa~P$_OT&QOl-dOs-rO~P'ROk-iO~Ol-iO~P'ROx-jO~Oq-kO~P!,iO%g%j%v%x%f!Z%n%t%w%y%m%s%m%Q~", - goto: "!-g&UPPPP&VP&_)p*V*m+U+n,XP,sP&_-a-a&_P&_P0rPPPPPP0r3bPP3bP5n5w:zPP:};];`PPP&_&_PP;l&_PP&_&_PP&_&_&_&_;p<d&_P<gP<j<j@PP@e&_PPP@i@o&VP&V&VP&VP&VP&VP&VP&V&V&VP&VPP&VPP&VP@uP@|ASP@|P@|@|PPP@|PB{PCUC[CbB{P@|ChPCoCuC{DXDkDqD{EREoEuE{FRF]FcFiFoFuF{G_GiGoGuG{HVH]HcHiHoHyIPIZIaPPPPPPPPPIjIrI{JVJbPPPPPPPPPPPPNw! a!%o!({PP!)T!)c!)l!*b!*X!*k!*q!*t!*w!*z!+S!+pPPPPPPPPPP!+s!+vPPPPPPPPP!+|!,Y!,f!,l!,u!,x!-O!-U!-[!-_]iOr#m$m)]+Z'odOSXYZehrstvx|}!R!S!T!U!X!c!d!e!f!g!h!i!k!o!p!q!s!t!z!}#R#S#]#j#m$O$P$R$T$W$h$j$k$m${%Q%X%[%^%a%e%j%l%v&O&Q&]&a&j&l&m&t&x&{'S'V'a'b'e'g'h'l'q's'w'{(Q(R(X([(c(e(m(p(|)P)T)U)Y)])f)p)v)y)z)}*T*U*W*Y*]*^*a*d*h*i*p*r*s*z+S+T+Z+b+c+f+m+n+o+q+r+u+w+y+{+},P,Q,S,f,h,l,o,r-R-S-_-b-d-e-f-g-i-j-k-l-m-o-sw!cP#i#v$X$g%c%h%n%o&b&z(d(o)S*R*[+R+|-hy!dP#i#v$X$g$s%c%h%n%o&b&z(d(o)S*R*[+R+|-h{!eP#i#v$X$g$s$t%c%h%n%o&b&z(d(o)S*R*[+R+|-h}!fP#i#v$X$g$s$t$u%c%h%n%o&b&z(d(o)S*R*[+R+|-h!P!gP#i#v$X$g$s$t$u$v%c%h%n%o&b&z(d(o)S*R*[+R+|-h!R!hP#i#v$X$g$s$t$u$v$w%c%h%n%o&b&z(d(o)S*R*[+R+|-h!V!hP!n#i#v$X$g$s$t$u$v$w$x%c%h%n%o&b&z(d(o)S*R*[+R+|-h'oSOSXYZehrstvx|}!R!S!T!U!X!c!d!e!f!g!h!i!k!o!p!q!s!t!z!}#R#S#]#j#m$O$P$R$T$W$h$j$k$m${%Q%X%[%^%a%e%j%l%v&O&Q&]&a&j&l&m&t&x&{'S'V'a'b'e'g'h'l'q's'w'{(Q(R(X([(c(e(m(p(|)P)T)U)Y)])f)p)v)y)z)}*T*U*W*Y*]*^*a*d*h*i*p*r*s*z+S+T+Z+b+c+f+m+n+o+q+r+u+w+y+{+},P,Q,S,f,h,l,o,r-R-S-_-b-d-e-f-g-i-j-k-l-m-o-s&ZUOXYZhrtv|}!R!S!T!X!i!k!o!p!q!s!t#]#j#m$P$R$T$W$k$m${%Q%X%[%^%e%j%l%v&O&]&a&l&m&t&{'S'V'a'b'e'g'h'l's'{(R(X([(c(e(m(|)P)Y)])f)p)v)y)z)}*T*U*W*Y*]*^*a*h*i*p*s*z+Z+b+c+f+m+n+o+q+r+u+w+y+{+},P,Q,S,f,h,l,o,r-R-S-_-b-d-e-f-g-i-j-k-l-o-s%eWOXYZhrv|}!R!S!T!X!i!k#]#j#m$P$R$T$W$k$m${%Q%[%^%e%j%l%v&O&]&a&l&m&t&{'S'V'a'b'e'g'h'l's'{(R(X([(c(e(m(|)P)Y)])f)p)v)y)z)}*T*W*Y*]*^*a*h*i*p*s*z+Z+b+c+f+m+n+o+q+r+u+y+{+},P,Q,S,f,h,l,o-R-S-_-j-k-lQ#|uQ-`-WR-p-r'fdOSXYZehrstvx|}!R!S!T!U!X!c!d!e!f!g!h!k!o!p!q!s!t!z!}#R#S#]#j#m$O$P$R$T$W$h$j$k$m${%Q%X%[%^%a%e%j%l%v&O&Q&]&a&j&l&m&t&x&{'S'V'a'e'g'h'l'q's'w'{(Q(R(X([(c(e(m(p(|)P)T)U)Y)])f)p)y)z)}*T*U*W*Y*]*^*a*d*h*i*p*r*s*z+S+T+Z+b+c+f+n+o+q+r+u+w+y+{+},P,Q,S,f,h,l,o,r-R-S-_-b-d-e-f-g-i-j-k-l-m-o-sW#pl!O!P$_W#xu&_-W-rQ$a!QQ$q!YQ$r!ZW$z!i'b)v+mS&^#y#zQ'O$lQ(f&WQ(t&nU(u&p(v(wU(x&r(y*yQ)h'XW)i'Z+i,j-PS+h)j)kY,U*t,V,w,x-[Q,X*vQ,c+_Q,e+aR-Z,vR&]#xi!wXY!S!T%^%e's'{)P*T*W*YR%[!vQ!{XQ%w#]Q&f$TR&i$WT-V,r-b!U!jP!n#i#v$X$g$s$t$u$v$w$x%c%h%n%o&b&z(d(o)S*R*[+R+|-hQ&Z#qR'^$rR'a$zR%T!m'ncOSXYZehrstvx|}!R!S!T!U!X!c!d!e!f!g!h!i!k!o!p!q!s!t!z!}#R#S#]#j#m$O$P$R$T$W$h$j$k$m${%Q%X%[%^%a%e%j%l%v&O&Q&]&a&j&l&m&t&x&{'S'V'a'b'e'g'h'l'q's'w'{(Q(R(X([(c(e(m(p(|)P)T)U)Y)])f)p)v)y)z)}*T*U*W*Y*]*^*a*d*h*i*p*r*s*z+S+T+Z+b+c+f+m+n+o+q+r+u+w+y+{+},P,Q,S,f,h,l,o,r-R-S-_-b-d-e-f-g-i-j-k-l-m-o-sT#gc#hS#^_#_S#a`#bS#ca#dS#eb#fT*l(_*mT(`%w(bQ$VwR+g)iX$Tw$U$V&hZkOr$m)]+ZXoOr)]+ZQ$n!WQ&v$eQ&w$fQ'Y$pQ']$rQ)Z&}Q)a'SQ)c'TQ)d'UQ)q'[Q)s'^Q*})PQ+P)QQ+Q)RQ+U)XS+W)[)rQ+[)_Q+])`Q+^)bQ,Z*|Q,[+OQ,^+VQ,_+XQ,d+`Q,z,]Q,|,bQ,},cR-],{WoOr)]+ZR#snQ'[$qR)['OQ+f)iR,h+gQ)r'[R+X)[ZmOnr)]+ZQrOR#urQ&`#{R(k&`S%k#Q#}S(S%k(VT(V%n&bQ%_!yQ%f!|W't%_%f'y'}Q'y%cR'}%hQ&k$XR(q&kQ(Y%oQ*_(TT*e(Y*_Q'c$|R)w'cS'f%P%QY){'f)|+s,p-TU)|'g'h'iU+s)}*O*PS,p+t+uR-T,qQ#X]R%r#XQ#[^R%t#[Q#__R%x#_Q(]%uS*j(]*kR*k(^Q*m(_R,R*mQ#b`R%z#bQ#daR%{#dQ#fbR%|#fQ#hcR%}#hQ#kfQ&P#iW&S#k&P(n*qQ(n&eR*q-hQ$UwS&g$U&hR&h$VQ&u$cR(}&uQ&X#pR(g&XQ$_!PR&o$_Q*u(uS,W*u,yR,y,XQ&s$aR(z&sQ#njR&U#nQ+Z)]R,`+ZQ)O&vR*{)OQ&y$gS)V&y)WR)W&zQ'R$nR)^'RQ'W$oS)g'W+dR+d)hQ+j)mR,k+jWnOr)]+ZR#rnSqOrT+Y)]+ZWpOr)]+ZR'P$mYjOr$m)]+ZR&T#m[wOr#m$m)]+ZR&f$T&YPOXYZhrtv|}!R!S!T!X!i!k!o!p!q!s!t#]#j#m$P$R$T$W$k$m${%Q%X%[%^%e%j%l%v&O&]&a&l&m&t&{'S'V'a'b'e'g'h'l's'{(R(X([(c(e(m(|)P)Y)])f)p)v)y)z)}*T*U*W*Y*]*^*a*h*i*p*s*z+Z+b+c+f+m+n+o+q+r+u+w+y+{+},P,Q,S,f,h,l,o,r-R-S-_-b-d-e-f-g-i-j-k-l-o-sQ!nSQ#ieQ#vsU$Xx%a'wS$g!U$jQ$s!cQ$t!dQ$u!eQ$v!fQ$w!gQ$x!hQ%c!zQ%h!}Q%n#RQ%o#SQ&b$OQ&z$hQ(d&QU(o&j(p*rW)S&x)U+S+TQ*R'qQ*[(QQ+R)TQ+|*dR-h-mQ!yXQ!|YQ$e!SQ$f!T^'p%^%e's'{*T*W*YR+O)P[fOr#m$m)]+Zh!vXY!S!T%^%e's'{)P*T*W*YQ#QZQ#lhS#}v|Q$[}W$c!R$W&{)YS$o!X$kW$y!i'b)v+mQ%P!kQ%u#]`&R#j&O(c(e(m*p,S-lQ&c$PQ&d$RQ&e$TQ'_${Q'i%QQ'o%[W(P%j(R*]*aQ(T%lQ(^%vQ(i&]S(l&a-jQ(r&lQ(s&mU({&t(|*zQ)b'SY)e'V)f+b+c,fQ)t'a^)x'e)z+q+r,o-S-_Q*O'gQ*P'hS*Q'l-kW*c(X*^+y+}W*g([*i,P,QQ+l)pQ+p)yQ+t)}Q,O*hQ,T*sQ,g+fQ,m+nQ,n+oQ,q+uQ,u+{Q-O,hQ-Q,lR-^-RhTOr#j#m$m&O&a'l(c(e)]+Z$z!uXYZhv|}!R!S!T!X!i!k#]$P$R$T$W$k${%Q%[%^%e%j%l%v&]&l&m&t&{'S'V'a'b'e'g'h's'{(R(X([(m(|)P)Y)f)p)v)y)z)}*T*W*Y*]*^*a*h*i*p*s*z+b+c+f+m+n+o+q+r+u+y+{+},P,Q,S,f,h,l,o-R-S-_-j-k-lQ#wtW%U!o!s-e-oQ%V!pQ%W!qQ%Y!tQ%d-dS'k%X-iQ'm-fQ'n-gQ+v*UQ,t+wS-U,r-bR-q-sU#{u-W-rR(j&_[gOr#m$m)]+ZX!xX#]$T$WQ#VZQ$QvR$Z|Q%`!yQ%g!|Q%m#QQ'_$yQ'z%cQ(O%hQ(W%nQ(Z%oQ*`(TQ,s+vQ-Y,tR-a-XQ$YxQ'v%aR*V'wQ-X,rR-c-bR#PYR#UZR%O!iQ$|!iV)u'b)v+m!V!lP!n#i#v$X$g$s$t$u$v$w$x%c%h%n%o&b&z(d(o)S*R*[+R+|-hR%R!kR%w#]Q(a%wR*o(bQ$d!RQ&i$WQ)X&{R+V)YQ#qlQ$]!OQ$`!PR&q$_Q(t&pR*x(wQ(t&pQ*w(vR*x(wR$b!QXpOr)]+ZQ$i!UR&|$jQ$p!XR&}$kR)o'ZQ)m'ZV,i+i,j-P", - nodeNames: "⚠ print Comment Script AssignStatement * BinaryExpression BitOp BitOp BitOp BitOp ArithOp ArithOp @ ArithOp ** UnaryExpression ArithOp BitOp AwaitExpression await ParenthesizedExpression ( BinaryExpression or and CompareOp in not is UnaryExpression ConditionalExpression if else LambdaExpression lambda ParamList VariableName AssignOp , : NamedExpression AssignOp YieldExpression yield from ) TupleExpression ComprehensionExpression async for LambdaExpression ArrayExpression [ ] ArrayComprehensionExpression DictionaryExpression { } DictionaryComprehensionExpression SetExpression SetComprehensionExpression CallExpression ArgList AssignOp MemberExpression . PropertyName Number String FormatString FormatReplacement FormatConversion FormatSpec ContinuedString Ellipsis None Boolean TypeDef AssignOp UpdateStatement UpdateOp ExpressionStatement DeleteStatement del PassStatement pass BreakStatement break ContinueStatement continue ReturnStatement return YieldStatement PrintStatement RaiseStatement raise ImportStatement import as ScopeStatement global nonlocal AssertStatement assert StatementGroup ; IfStatement Body elif WhileStatement while ForStatement TryStatement try except finally WithStatement with FunctionDefinition def ParamList AssignOp TypeDef ClassDefinition class DecoratedStatement Decorator At", - maxTerm: 236, - context: trackIndent, - nodeProps: [ - [NodeProp.group, -14,4,80,82,83,85,87,89,91,93,94,95,97,100,103,"Statement Statement",-22,6,16,19,21,37,47,48,52,55,56,59,60,61,62,65,68,69,70,74,75,76,77,"Expression",-9,105,107,110,112,113,117,119,124,126,"Statement"] - ], - skippedNodes: [0,2], - repeatNodeCount: 32, - tokenData: "&AaMgR!^OX$}XY!#xY[$}[]!#x]p$}pq!#xqr!&Srs!)yst!C{tu$}uv$+}vw$.awx$/mxy$Lgyz$Mmz{$Ns{|%#c|}%$o}!O%%u!O!P%([!P!Q%3b!Q!R%6Q!R![%:S![!]%EO!]!^%Gb!^!_%Hh!_!`%KW!`!a%Ld!a!b$}!b!c& P!c!d&!_!d!e&$P!e!h&!_!h!i&.R!i!t&!_!t!u&7g!u!w&!_!w!x&,a!x!}&!_!}#O&9q#O#P!%b#P#Q&:w#Q#R&;}#R#S&!_#S#T$}#T#U&!_#U#V&$P#V#Y&!_#Y#Z&.R#Z#f&!_#f#g&7g#g#i&!_#i#j&,a#j#o&!_#o#p&=Z#p#q&>P#q#r&?]#r#s&@Z#s$g$}$g~&!_<r%`Z%q7[%hS%kW%n`%tp%w!b%y#tOr$}rs&Rsw$}wxFSx#O$}#O#P! n#P#o$}#o#p!#U#p#q$}#q#r!!S#r~$}9[&^Z%q7[%hS%n`%w!bOr'PrsCxsw'Pwx(Px#O'P#O#P>v#P#o'P#o#pCU#p#q'P#q#r?[#r~'P9['^Z%q7[%hS%kW%n`%w!bOr'Prs&Rsw'Pwx(Px#O'P#O#P>v#P#o'P#o#pCU#p#q'P#q#r?[#r~'P8z(WZ%q7[%kWOr(yrs)wsw(ywx;bx#O(y#O#P2V#P#o(y#o#p7n#p#q(y#q#r2k#r~(y8z)UZ%q7[%hS%kW%w!bOr(yrs)wsw(ywx(Px#O(y#O#P2V#P#o(y#o#p7n#p#q(y#q#r2k#r~(y8z*QZ%q7[%hS%w!bOr(yrs*ssw(ywx(Px#O(y#O#P2V#P#o(y#o#p7n#p#q(y#q#r2k#r~(y8z*|Z%q7[%hS%w!bOr(yrs+osw(ywx(Px#O(y#O#P2V#P#o(y#o#p7n#p#q(y#q#r2k#r~(y8r+xX%q7[%hS%w!bOw+owx,ex#O+o#O#P.V#P#o+o#o#p0^#p#q+o#q#r.k#r~+o8r,jX%q7[Ow+owx-Vx#O+o#O#P.V#P#o+o#o#p0^#p#q+o#q#r.k#r~+o8r-[X%q7[Ow+owx-wx#O+o#O#P.V#P#o+o#o#p0^#p#q+o#q#r.k#r~+o7[-|R%q7[O#o-w#p#q-w#r~-w8r.[T%q7[O#o+o#o#p.k#p#q+o#q#r.k#r~+o!f.rV%hS%w!bOw.kwx/Xx#O.k#O#P0W#P#o.k#o#p0^#p~.k!f/[VOw.kwx/qx#O.k#O#P0W#P#o.k#o#p0^#p~.k!f/tUOw.kx#O.k#O#P0W#P#o.k#o#p0^#p~.k!f0ZPO~.k!f0cV%hSOw0xwx1^x#O0x#O#P2P#P#o0x#o#p.k#p~0xS0}T%hSOw0xwx1^x#O0x#O#P2P#P~0xS1aTOw0xwx1px#O0x#O#P2P#P~0xS1sSOw0xx#O0x#O#P2P#P~0xS2SPO~0x8z2[T%q7[O#o(y#o#p2k#p#q(y#q#r2k#r~(y!n2tX%hS%kW%w!bOr2krs3asw2kwx4wx#O2k#O#P7h#P#o2k#o#p7n#p~2k!n3hX%hS%w!bOr2krs4Tsw2kwx4wx#O2k#O#P7h#P#o2k#o#p7n#p~2k!n4[X%hS%w!bOr2krs.ksw2kwx4wx#O2k#O#P7h#P#o2k#o#p7n#p~2k!n4|X%kWOr2krs3asw2kwx5ix#O2k#O#P7h#P#o2k#o#p7n#p~2k!n5nX%kWOr2krs3asw2kwx6Zx#O2k#O#P7h#P#o2k#o#p7n#p~2kW6`T%kWOr6Zrs6os#O6Z#O#P7b#P~6ZW6rTOr6Zrs7Rs#O6Z#O#P7b#P~6ZW7USOr6Zs#O6Z#O#P7b#P~6ZW7ePO~6Z!n7kPO~2k!n7uX%hS%kWOr8brs9Osw8bwx:Ux#O8b#O#P;[#P#o8b#o#p2k#p~8b[8iV%hS%kWOr8brs9Osw8bwx:Ux#O8b#O#P;[#P~8b[9TV%hSOr8brs9jsw8bwx:Ux#O8b#O#P;[#P~8b[9oV%hSOr8brs0xsw8bwx:Ux#O8b#O#P;[#P~8b[:ZV%kWOr8brs9Osw8bwx:px#O8b#O#P;[#P~8b[:uV%kWOr8brs9Osw8bwx6Zx#O8b#O#P;[#P~8b[;_PO~8b8z;iZ%q7[%kWOr(yrs)wsw(ywx<[x#O(y#O#P2V#P#o(y#o#p7n#p#q(y#q#r2k#r~(y7d<cX%q7[%kWOr<[rs=Os#O<[#O#P>b#P#o<[#o#p6Z#p#q<[#q#r6Z#r~<[7d=TX%q7[Or<[rs=ps#O<[#O#P>b#P#o<[#o#p6Z#p#q<[#q#r6Z#r~<[7d=uX%q7[Or<[rs-ws#O<[#O#P>b#P#o<[#o#p6Z#p#q<[#q#r6Z#r~<[7d>gT%q7[O#o<[#o#p6Z#p#q<[#q#r6Z#r~<[9[>{T%q7[O#o'P#o#p?[#p#q'P#q#r?[#r~'P#O?gX%hS%kW%n`%w!bOr?[rs@Ssw?[wx4wx#O?[#O#PCO#P#o?[#o#pCU#p~?[#O@]X%hS%n`%w!bOr?[rs@xsw?[wx4wx#O?[#O#PCO#P#o?[#o#pCU#p~?[#OARX%hS%n`%w!bOr?[rsAnsw?[wx4wx#O?[#O#PCO#P#o?[#o#pCU#p~?[!vAwV%hS%n`%w!bOwAnwx/Xx#OAn#O#PB^#P#oAn#o#pBd#p~An!vBaPO~An!vBiV%hSOw0xwx1^x#O0x#O#P2P#P#o0x#o#pAn#p~0x#OCRPO~?[#OC]X%hS%kWOr8brs9Osw8bwx:Ux#O8b#O#P;[#P#o8b#o#p?[#p~8b9[DTZ%q7[%hS%n`%w!bOr'PrsDvsw'Pwx(Px#O'P#O#P>v#P#o'P#o#pCU#p#q'P#q#r?[#r~'P9SERX%q7[%hS%n`%w!bOwDvwx,ex#ODv#O#PEn#P#oDv#o#pBd#p#qDv#q#rAn#r~Dv9SEsT%q7[O#oDv#o#pAn#p#qDv#q#rAn#r~Dv<bF_Z%q7[%kW%tp%y#tOrGQrs)wswGQwxM^x#OGQ#O#PHS#P#oGQ#o#pLj#p#qGQ#q#rHh#r~GQ<bGaZ%q7[%hS%kW%tp%w!b%y#tOrGQrs)wswGQwxFSx#OGQ#O#PHS#P#oGQ#o#pLj#p#qGQ#q#rHh#r~GQ<bHXT%q7[O#oGQ#o#pHh#p#qGQ#q#rHh#r~GQ&UHuX%hS%kW%tp%w!b%y#tOrHhrs3aswHhwxIbx#OHh#O#PLd#P#oHh#o#pLj#p~Hh&UIkX%kW%tp%y#tOrHhrs3aswHhwxJWx#OHh#O#PLd#P#oHh#o#pLj#p~Hh&UJaX%kW%tp%y#tOrHhrs3aswHhwxJ|x#OHh#O#PLd#P#oHh#o#pLj#p~Hh$nKVX%kW%tp%y#tOrJ|rs6oswJ|wxJ|x#OJ|#O#PKr#P#oJ|#o#pKx#p~J|$nKuPO~J|$nK}V%kWOr6Zrs6os#O6Z#O#P7b#P#o6Z#o#pJ|#p~6Z&ULgPO~Hh&ULqX%hS%kWOr8brs9Osw8bwx:Ux#O8b#O#P;[#P#o8b#o#pHh#p~8b<bMiZ%q7[%kW%tp%y#tOrGQrs)wswGQwxN[x#OGQ#O#PHS#P#oGQ#o#pLj#p#qGQ#q#rHh#r~GQ:zNgZ%q7[%kW%tp%y#tOrN[rs=OswN[wxN[x#ON[#O#P! Y#P#oN[#o#pKx#p#qN[#q#rJ|#r~N[:z! _T%q7[O#oN[#o#pJ|#p#qN[#q#rJ|#r~N[<r! sT%q7[O#o$}#o#p!!S#p#q$}#q#r!!S#r~$}&f!!cX%hS%kW%n`%tp%w!b%y#tOr!!Srs@Ssw!!SwxIbx#O!!S#O#P!#O#P#o!!S#o#p!#U#p~!!S&f!#RPO~!!S&f!#]X%hS%kWOr8brs9Osw8bwx:Ux#O8b#O#P;[#P#o8b#o#p!!S#p~8bMg!$]a%q7[%hS%kW$o1s%n`%tp%w!b%y#tOX$}XY!#xY[$}[]!#x]p$}pq!#xqr$}rs&Rsw$}wxFSx#O$}#O#P!%b#P#o$}#o#p!#U#p#q$}#q#r!!S#r~$}Mg!%gX%q7[OY$}YZ!#xZ]$}]^!#x^#o$}#o#p!!S#p#q$}#q#r!!S#r~$}<u!&eb%q7[%hS%kW%n`%tp%w!b%y#tOr$}rs&Rsw$}wxFSx!_$}!_!`!'m!`#O$}#O#P! n#P#T$}#T#U!(s#U#f$}#f#g!(s#g#h!(s#h#o$}#o#p!#U#p#q$}#q#r!!S#r~$}<u!(QZjR%q7[%hS%kW%n`%tp%w!b%y#tOr$}rs&Rsw$}wxFSx#O$}#O#P! n#P#o$}#o#p!#U#p#q$}#q#r!!S#r~$}<u!)WZ!jR%q7[%hS%kW%n`%tp%w!b%y#tOr$}rs&Rsw$}wxFSx#O$}#O#P! n#P#o$}#o#p!#U#p#q$}#q#r!!S#r~$}G{!*Y_%up%q7[%hS%f,X%n`%w!bOY!+XYZ'PZ]!+X]^'P^r!+Xrs!BPsw!+Xwx!-gx#O!+X#O#P!>e#P#o!+X#o#p!@}#p#q!+X#q#r!>y#r~!+XDe!+h_%q7[%hS%kW%f,X%n`%w!bOY!+XYZ'PZ]!+X]^'P^r!+Xrs!,gsw!+Xwx!-gx#O!+X#O#P!>e#P#o!+X#o#p!@}#p#q!+X#q#r!>y#r~!+XDe!,tZ%q7[%hS%f,X%n`%w!bOr'PrsCxsw'Pwx(Px#O'P#O#P>v#P#o'P#o#pCU#p#q'P#q#r?[#r~'PDT!-p_%q7[%kW%f,XOY!.oYZ(yZ]!.o]^(y^r!.ors!/{sw!.owx!;Rx#O!.o#O#P!0y#P#o!.o#o#p!6m#p#q!.o#q#r!1_#r~!.oDT!.|_%q7[%hS%kW%f,X%w!bOY!.oYZ(yZ]!.o]^(y^r!.ors!/{sw!.owx!-gx#O!.o#O#P!0y#P#o!.o#o#p!6m#p#q!.o#q#r!1_#r~!.oDT!0WZ%q7[%hS%f,X%w!bOr(yrs*ssw(ywx(Px#O(y#O#P2V#P#o(y#o#p7n#p#q(y#q#r2k#r~(yDT!1OT%q7[O#o!.o#o#p!1_#p#q!.o#q#r!1_#r~!.o-w!1j]%hS%kW%f,X%w!bOY!1_YZ2kZ]!1_]^2k^r!1_rs!2csw!1_wx!3Xx#O!1_#O#P!6g#P#o!1_#o#p!6m#p~!1_-w!2lX%hS%f,X%w!bOr2krs4Tsw2kwx4wx#O2k#O#P7h#P#o2k#o#p7n#p~2k-w!3`]%kW%f,XOY!1_YZ2kZ]!1_]^2k^r!1_rs!2csw!1_wx!4Xx#O!1_#O#P!6g#P#o!1_#o#p!6m#p~!1_-w!4`]%kW%f,XOY!1_YZ2kZ]!1_]^2k^r!1_rs!2csw!1_wx!5Xx#O!1_#O#P!6g#P#o!1_#o#p!6m#p~!1_,a!5`X%kW%f,XOY!5XYZ6ZZ]!5X]^6Z^r!5Xrs!5{s#O!5X#O#P!6a#P~!5X,a!6QT%f,XOr6Zrs7Rs#O6Z#O#P7b#P~6Z,a!6dPO~!5X-w!6jPO~!1_-w!6v]%hS%kW%f,XOY!7oYZ8bZ]!7o]^8b^r!7ors!8ksw!7owx!9Xx#O!7o#O#P!:{#P#o!7o#o#p!1_#p~!7o,e!7xZ%hS%kW%f,XOY!7oYZ8bZ]!7o]^8b^r!7ors!8ksw!7owx!9Xx#O!7o#O#P!:{#P~!7o,e!8rV%hS%f,XOr8brs9jsw8bwx:Ux#O8b#O#P;[#P~8b,e!9`Z%kW%f,XOY!7oYZ8bZ]!7o]^8b^r!7ors!8ksw!7owx!:Rx#O!7o#O#P!:{#P~!7o,e!:YZ%kW%f,XOY!7oYZ8bZ]!7o]^8b^r!7ors!8ksw!7owx!5Xx#O!7o#O#P!:{#P~!7o,e!;OPO~!7oDT!;[_%q7[%kW%f,XOY!.oYZ(yZ]!.o]^(y^r!.ors!/{sw!.owx!<Zx#O!.o#O#P!0y#P#o!.o#o#p!6m#p#q!.o#q#r!1_#r~!.oBm!<d]%q7[%kW%f,XOY!<ZYZ<[Z]!<Z]^<[^r!<Zrs!=]s#O!<Z#O#P!>P#P#o!<Z#o#p!5X#p#q!<Z#q#r!5X#r~!<ZBm!=dX%q7[%f,XOr<[rs=ps#O<[#O#P>b#P#o<[#o#p6Z#p#q<[#q#r6Z#r~<[Bm!>UT%q7[O#o!<Z#o#p!5X#p#q!<Z#q#r!5X#r~!<ZDe!>jT%q7[O#o!+X#o#p!>y#p#q!+X#q#r!>y#r~!+X.X!?W]%hS%kW%f,X%n`%w!bOY!>yYZ?[Z]!>y]^?[^r!>yrs!@Psw!>ywx!3Xx#O!>y#O#P!@w#P#o!>y#o#p!@}#p~!>y.X!@[X%hS%f,X%n`%w!bOr?[rs@xsw?[wx4wx#O?[#O#PCO#P#o?[#o#pCU#p~?[.X!@zPO~!>y.X!AW]%hS%kW%f,XOY!7oYZ8bZ]!7o]^8b^r!7ors!8ksw!7owx!9Xx#O!7o#O#P!:{#P#o!7o#o#p!>y#p~!7oGZ!B^Z%q7[%hS%f,X%n`%w!bOr'Prs!CPsw'Pwx(Px#O'P#O#P>v#P#o'P#o#pCU#p#q'P#q#r?[#r~'PGZ!C`X%l#|%q7[%hS%j,X%n`%w!bOwDvwx,ex#ODv#O#PEn#P#oDv#o#pBd#p#qDv#q#rAn#r~DvMg!D`_Q1s%q7[%hS%kW%n`%tp%w!b%y#tOY!C{YZ$}Z]!C{]^$}^r!C{rs!E_sw!C{wx#Hqx#O!C{#O#P$(i#P#o!C{#o#p$*{#p#q!C{#q#r$)]#r~!C{JP!El_Q1s%q7[%hS%n`%w!bOY!FkYZ'PZ]!Fk]^'P^r!Fkrs#Eksw!Fkwx!Gyx#O!Fk#O#P#=u#P#o!Fk#o#p#Di#p#q!Fk#q#r#>i#r~!FkJP!Fz_Q1s%q7[%hS%kW%n`%w!bOY!FkYZ'PZ]!Fk]^'P^r!Fkrs!E_sw!Fkwx!Gyx#O!Fk#O#P#=u#P#o!Fk#o#p#Di#p#q!Fk#q#r#>i#r~!FkIo!HS_Q1s%q7[%kWOY!IRYZ(yZ]!IR]^(y^r!IRrs!J_sw!IRwx#8wx#O!IR#O#P#*R#P#o!IR#o#p#2}#p#q!IR#q#r#*u#r~!IRIo!I`_Q1s%q7[%hS%kW%w!bOY!IRYZ(yZ]!IR]^(y^r!IRrs!J_sw!IRwx!Gyx#O!IR#O#P#*R#P#o!IR#o#p#2}#p#q!IR#q#r#*u#r~!IRIo!Jj_Q1s%q7[%hS%w!bOY!IRYZ(yZ]!IR]^(y^r!IRrs!Kisw!IRwx!Gyx#O!IR#O#P#*R#P#o!IR#o#p#2}#p#q!IR#q#r#*u#r~!IRIo!Kt_Q1s%q7[%hS%w!bOY!IRYZ(yZ]!IR]^(y^r!IRrs!Lssw!IRwx!Gyx#O!IR#O#P#*R#P#o!IR#o#p#2}#p#q!IR#q#r#*u#r~!IRIg!MO]Q1s%q7[%hS%w!bOY!LsYZ+oZ]!Ls]^+o^w!Lswx!Mwx#O!Ls#O#P#!y#P#o!Ls#o#p#&m#p#q!Ls#q#r##m#r~!LsIg!NO]Q1s%q7[OY!LsYZ+oZ]!Ls]^+o^w!Lswx!Nwx#O!Ls#O#P#!y#P#o!Ls#o#p#&m#p#q!Ls#q#r##m#r~!LsIg# O]Q1s%q7[OY!LsYZ+oZ]!Ls]^+o^w!Lswx# wx#O!Ls#O#P#!y#P#o!Ls#o#p#&m#p#q!Ls#q#r##m#r~!LsHP#!OXQ1s%q7[OY# wYZ-wZ]# w]^-w^#o# w#o#p#!k#p#q# w#q#r#!k#r~# w1s#!pRQ1sOY#!kZ]#!k^~#!kIg##QXQ1s%q7[OY!LsYZ+oZ]!Ls]^+o^#o!Ls#o#p##m#p#q!Ls#q#r##m#r~!Ls3Z##vZQ1s%hS%w!bOY##mYZ.kZ]##m]^.k^w##mwx#$ix#O##m#O#P#&X#P#o##m#o#p#&m#p~##m3Z#$nZQ1sOY##mYZ.kZ]##m]^.k^w##mwx#%ax#O##m#O#P#&X#P#o##m#o#p#&m#p~##m3Z#%fZQ1sOY##mYZ.kZ]##m]^.k^w##mwx#!kx#O##m#O#P#&X#P#o##m#o#p#&m#p~##m3Z#&^TQ1sOY##mYZ.kZ]##m]^.k^~##m3Z#&tZQ1s%hSOY#'gYZ0xZ]#'g]^0x^w#'gwx#(Zx#O#'g#O#P#)m#P#o#'g#o#p##m#p~#'g1w#'nXQ1s%hSOY#'gYZ0xZ]#'g]^0x^w#'gwx#(Zx#O#'g#O#P#)m#P~#'g1w#(`XQ1sOY#'gYZ0xZ]#'g]^0x^w#'gwx#({x#O#'g#O#P#)m#P~#'g1w#)QXQ1sOY#'gYZ0xZ]#'g]^0x^w#'gwx#!kx#O#'g#O#P#)m#P~#'g1w#)rTQ1sOY#'gYZ0xZ]#'g]^0x^~#'gIo#*YXQ1s%q7[OY!IRYZ(yZ]!IR]^(y^#o!IR#o#p#*u#p#q!IR#q#r#*u#r~!IR3c#+Q]Q1s%hS%kW%w!bOY#*uYZ2kZ]#*u]^2k^r#*urs#+ysw#*uwx#-}x#O#*u#O#P#2i#P#o#*u#o#p#2}#p~#*u3c#,S]Q1s%hS%w!bOY#*uYZ2kZ]#*u]^2k^r#*urs#,{sw#*uwx#-}x#O#*u#O#P#2i#P#o#*u#o#p#2}#p~#*u3c#-U]Q1s%hS%w!bOY#*uYZ2kZ]#*u]^2k^r#*urs##msw#*uwx#-}x#O#*u#O#P#2i#P#o#*u#o#p#2}#p~#*u3c#.U]Q1s%kWOY#*uYZ2kZ]#*u]^2k^r#*urs#+ysw#*uwx#.}x#O#*u#O#P#2i#P#o#*u#o#p#2}#p~#*u3c#/U]Q1s%kWOY#*uYZ2kZ]#*u]^2k^r#*urs#+ysw#*uwx#/}x#O#*u#O#P#2i#P#o#*u#o#p#2}#p~#*u1{#0UXQ1s%kWOY#/}YZ6ZZ]#/}]^6Z^r#/}rs#0qs#O#/}#O#P#2T#P~#/}1{#0vXQ1sOY#/}YZ6ZZ]#/}]^6Z^r#/}rs#1cs#O#/}#O#P#2T#P~#/}1{#1hXQ1sOY#/}YZ6ZZ]#/}]^6Z^r#/}rs#!ks#O#/}#O#P#2T#P~#/}1{#2YTQ1sOY#/}YZ6ZZ]#/}]^6Z^~#/}3c#2nTQ1sOY#*uYZ2kZ]#*u]^2k^~#*u3c#3W]Q1s%hS%kWOY#4PYZ8bZ]#4P]^8b^r#4Prs#4{sw#4Pwx#6ox#O#4P#O#P#8c#P#o#4P#o#p#*u#p~#4P2P#4YZQ1s%hS%kWOY#4PYZ8bZ]#4P]^8b^r#4Prs#4{sw#4Pwx#6ox#O#4P#O#P#8c#P~#4P2P#5SZQ1s%hSOY#4PYZ8bZ]#4P]^8b^r#4Prs#5usw#4Pwx#6ox#O#4P#O#P#8c#P~#4P2P#5|ZQ1s%hSOY#4PYZ8bZ]#4P]^8b^r#4Prs#'gsw#4Pwx#6ox#O#4P#O#P#8c#P~#4P2P#6vZQ1s%kWOY#4PYZ8bZ]#4P]^8b^r#4Prs#4{sw#4Pwx#7ix#O#4P#O#P#8c#P~#4P2P#7pZQ1s%kWOY#4PYZ8bZ]#4P]^8b^r#4Prs#4{sw#4Pwx#/}x#O#4P#O#P#8c#P~#4P2P#8hTQ1sOY#4PYZ8bZ]#4P]^8b^~#4PIo#9Q_Q1s%q7[%kWOY!IRYZ(yZ]!IR]^(y^r!IRrs!J_sw!IRwx#:Px#O!IR#O#P#*R#P#o!IR#o#p#2}#p#q!IR#q#r#*u#r~!IRHX#:Y]Q1s%q7[%kWOY#:PYZ<[Z]#:P]^<[^r#:Prs#;Rs#O#:P#O#P#=R#P#o#:P#o#p#/}#p#q#:P#q#r#/}#r~#:PHX#;Y]Q1s%q7[OY#:PYZ<[Z]#:P]^<[^r#:Prs#<Rs#O#:P#O#P#=R#P#o#:P#o#p#/}#p#q#:P#q#r#/}#r~#:PHX#<Y]Q1s%q7[OY#:PYZ<[Z]#:P]^<[^r#:Prs# ws#O#:P#O#P#=R#P#o#:P#o#p#/}#p#q#:P#q#r#/}#r~#:PHX#=YXQ1s%q7[OY#:PYZ<[Z]#:P]^<[^#o#:P#o#p#/}#p#q#:P#q#r#/}#r~#:PJP#=|XQ1s%q7[OY!FkYZ'PZ]!Fk]^'P^#o!Fk#o#p#>i#p#q!Fk#q#r#>i#r~!Fk3s#>v]Q1s%hS%kW%n`%w!bOY#>iYZ?[Z]#>i]^?[^r#>irs#?osw#>iwx#-}x#O#>i#O#P#DT#P#o#>i#o#p#Di#p~#>i3s#?z]Q1s%hS%n`%w!bOY#>iYZ?[Z]#>i]^?[^r#>irs#@ssw#>iwx#-}x#O#>i#O#P#DT#P#o#>i#o#p#Di#p~#>i3s#AO]Q1s%hS%n`%w!bOY#>iYZ?[Z]#>i]^?[^r#>irs#Awsw#>iwx#-}x#O#>i#O#P#DT#P#o#>i#o#p#Di#p~#>i3k#BSZQ1s%hS%n`%w!bOY#AwYZAnZ]#Aw]^An^w#Awwx#$ix#O#Aw#O#P#Bu#P#o#Aw#o#p#CZ#p~#Aw3k#BzTQ1sOY#AwYZAnZ]#Aw]^An^~#Aw3k#CbZQ1s%hSOY#'gYZ0xZ]#'g]^0x^w#'gwx#(Zx#O#'g#O#P#)m#P#o#'g#o#p#Aw#p~#'g3s#DYTQ1sOY#>iYZ?[Z]#>i]^?[^~#>i3s#Dr]Q1s%hS%kWOY#4PYZ8bZ]#4P]^8b^r#4Prs#4{sw#4Pwx#6ox#O#4P#O#P#8c#P#o#4P#o#p#>i#p~#4PJP#Ex_Q1s%q7[%hS%n`%w!bOY!FkYZ'PZ]!Fk]^'P^r!Fkrs#Fwsw!Fkwx!Gyx#O!Fk#O#P#=u#P#o!Fk#o#p#Di#p#q!Fk#q#r#>i#r~!FkIw#GU]Q1s%q7[%hS%n`%w!bOY#FwYZDvZ]#Fw]^Dv^w#Fwwx!Mwx#O#Fw#O#P#G}#P#o#Fw#o#p#CZ#p#q#Fw#q#r#Aw#r~#FwIw#HUXQ1s%q7[OY#FwYZDvZ]#Fw]^Dv^#o#Fw#o#p#Aw#p#q#Fw#q#r#Aw#r~#FwMV#IO_Q1s%q7[%kW%tp%y#tOY#I}YZGQZ]#I}]^GQ^r#I}rs!J_sw#I}wx$%]x#O#I}#O#P#K_#P#o#I}#o#p$$Z#p#q#I}#q#r#LR#r~#I}MV#J`_Q1s%q7[%hS%kW%tp%w!b%y#tOY#I}YZGQZ]#I}]^GQ^r#I}rs!J_sw#I}wx#Hqx#O#I}#O#P#K_#P#o#I}#o#p$$Z#p#q#I}#q#r#LR#r~#I}MV#KfXQ1s%q7[OY#I}YZGQZ]#I}]^GQ^#o#I}#o#p#LR#p#q#I}#q#r#LR#r~#I}6y#Lb]Q1s%hS%kW%tp%w!b%y#tOY#LRYZHhZ]#LR]^Hh^r#LRrs#+ysw#LRwx#MZx#O#LR#O#P$#u#P#o#LR#o#p$$Z#p~#LR6y#Mf]Q1s%kW%tp%y#tOY#LRYZHhZ]#LR]^Hh^r#LRrs#+ysw#LRwx#N_x#O#LR#O#P$#u#P#o#LR#o#p$$Z#p~#LR6y#Nj]Q1s%kW%tp%y#tOY#LRYZHhZ]#LR]^Hh^r#LRrs#+ysw#LRwx$ cx#O#LR#O#P$#u#P#o#LR#o#p$$Z#p~#LR5c$ n]Q1s%kW%tp%y#tOY$ cYZJ|Z]$ c]^J|^r$ crs#0qsw$ cwx$ cx#O$ c#O#P$!g#P#o$ c#o#p$!{#p~$ c5c$!lTQ1sOY$ cYZJ|Z]$ c]^J|^~$ c5c$#SZQ1s%kWOY#/}YZ6ZZ]#/}]^6Z^r#/}rs#0qs#O#/}#O#P#2T#P#o#/}#o#p$ c#p~#/}6y$#zTQ1sOY#LRYZHhZ]#LR]^Hh^~#LR6y$$d]Q1s%hS%kWOY#4PYZ8bZ]#4P]^8b^r#4Prs#4{sw#4Pwx#6ox#O#4P#O#P#8c#P#o#4P#o#p#LR#p~#4PMV$%j_Q1s%q7[%kW%tp%y#tOY#I}YZGQZ]#I}]^GQ^r#I}rs!J_sw#I}wx$&ix#O#I}#O#P#K_#P#o#I}#o#p$$Z#p#q#I}#q#r#LR#r~#I}Ko$&v_Q1s%q7[%kW%tp%y#tOY$&iYZN[Z]$&i]^N[^r$&irs#;Rsw$&iwx$&ix#O$&i#O#P$'u#P#o$&i#o#p$!{#p#q$&i#q#r$ c#r~$&iKo$'|XQ1s%q7[OY$&iYZN[Z]$&i]^N[^#o$&i#o#p$ c#p#q$&i#q#r$ c#r~$&iMg$(pXQ1s%q7[OY!C{YZ$}Z]!C{]^$}^#o!C{#o#p$)]#p#q!C{#q#r$)]#r~!C{7Z$)n]Q1s%hS%kW%n`%tp%w!b%y#tOY$)]YZ!!SZ]$)]]^!!S^r$)]rs#?osw$)]wx#MZx#O$)]#O#P$*g#P#o$)]#o#p$*{#p~$)]7Z$*lTQ1sOY$)]YZ!!SZ]$)]]^!!S^~$)]7Z$+U]Q1s%hS%kWOY#4PYZ8bZ]#4P]^8b^r#4Prs#4{sw#4Pwx#6ox#O#4P#O#P#8c#P#o#4P#o#p$)]#p~#4PGz$,b]$}Q%q7[%hS%kW%n`%tp%w!b%y#tOr$}rs&Rsw$}wxFSx!_$}!_!`$-Z!`#O$}#O#P! n#P#o$}#o#p!#U#p#q$}#q#r!!S#r~$}Gz$-nZ!s,W%q7[%hS%kW%n`%tp%w!b%y#tOr$}rs&Rsw$}wxFSx#O$}#O#P! n#P#o$}#o#p!#U#p#q$}#q#r!!S#r~$}Gz$.t]$wQ%q7[%hS%kW%n`%tp%w!b%y#tOr$}rs&Rsw$}wxFSx!_$}!_!`$-Z!`#O$}#O#P! n#P#o$}#o#p!#U#p#q$}#q#r!!S#r~$}G{$/|_%r`%q7[%kW%f,X%tp%y#tOY$0{YZGQZ]$0{]^GQ^r$0{rs$2]sw$0{wx$Jex#O$0{#O#P$Fw#P#o$0{#o#p$Ic#p#q$0{#q#r$G]#r~$0{Gk$1^_%q7[%hS%kW%f,X%tp%w!b%y#tOY$0{YZGQZ]$0{]^GQ^r$0{rs$2]sw$0{wx$Ewx#O$0{#O#P$Fw#P#o$0{#o#p$Ic#p#q$0{#q#r$G]#r~$0{DT$2h_%q7[%hS%f,X%w!bOY$3gYZ(yZ]$3g]^(y^r$3grs$Basw$3gwx$4sx#O$3g#O#P$5o#P#o$3g#o#p$={#p#q$3g#q#r$6T#r~$3gDT$3t_%q7[%hS%kW%f,X%w!bOY$3gYZ(yZ]$3g]^(y^r$3grs$2]sw$3gwx$4sx#O$3g#O#P$5o#P#o$3g#o#p$={#p#q$3g#q#r$6T#r~$3gDT$4|Z%q7[%kW%f,XOr(yrs)wsw(ywx;bx#O(y#O#P2V#P#o(y#o#p7n#p#q(y#q#r2k#r~(yDT$5tT%q7[O#o$3g#o#p$6T#p#q$3g#q#r$6T#r~$3g-w$6`]%hS%kW%f,X%w!bOY$6TYZ2kZ]$6T]^2k^r$6Trs$7Xsw$6Twx$=Rx#O$6T#O#P$=u#P#o$6T#o#p$={#p~$6T-w$7b]%hS%f,X%w!bOY$6TYZ2kZ]$6T]^2k^r$6Trs$8Zsw$6Twx$=Rx#O$6T#O#P$=u#P#o$6T#o#p$={#p~$6T-w$8d]%hS%f,X%w!bOY$6TYZ2kZ]$6T]^2k^r$6Trs$9]sw$6Twx$=Rx#O$6T#O#P$=u#P#o$6T#o#p$={#p~$6T-o$9fZ%hS%f,X%w!bOY$9]YZ.kZ]$9]]^.k^w$9]wx$:Xx#O$9]#O#P$:s#P#o$9]#o#p$:y#p~$9]-o$:^V%f,XOw.kwx/qx#O.k#O#P0W#P#o.k#o#p0^#p~.k-o$:vPO~$9]-o$;QZ%hS%f,XOY$;sYZ0xZ]$;s]^0x^w$;swx$<gx#O$;s#O#P$<{#P#o$;s#o#p$9]#p~$;s,]$;zX%hS%f,XOY$;sYZ0xZ]$;s]^0x^w$;swx$<gx#O$;s#O#P$<{#P~$;s,]$<lT%f,XOw0xwx1px#O0x#O#P2P#P~0x,]$=OPO~$;s-w$=YX%kW%f,XOr2krs3asw2kwx5ix#O2k#O#P7h#P#o2k#o#p7n#p~2k-w$=xPO~$6T-w$>U]%hS%kW%f,XOY$>}YZ8bZ]$>}]^8b^r$>}rs$?ysw$>}wx$Amx#O$>}#O#P$BZ#P#o$>}#o#p$6T#p~$>},e$?WZ%hS%kW%f,XOY$>}YZ8bZ]$>}]^8b^r$>}rs$?ysw$>}wx$Amx#O$>}#O#P$BZ#P~$>},e$@QZ%hS%f,XOY$>}YZ8bZ]$>}]^8b^r$>}rs$@ssw$>}wx$Amx#O$>}#O#P$BZ#P~$>},e$@zZ%hS%f,XOY$>}YZ8bZ]$>}]^8b^r$>}rs$;ssw$>}wx$Amx#O$>}#O#P$BZ#P~$>},e$AtV%kW%f,XOr8brs9Osw8bwx:px#O8b#O#P;[#P~8b,e$B^PO~$>}DT$Bl_%q7[%hS%f,X%w!bOY$3gYZ(yZ]$3g]^(y^r$3grs$Cksw$3gwx$4sx#O$3g#O#P$5o#P#o$3g#o#p$={#p#q$3g#q#r$6T#r~$3gC{$Cv]%q7[%hS%f,X%w!bOY$CkYZ+oZ]$Ck]^+o^w$Ckwx$Dox#O$Ck#O#P$Ec#P#o$Ck#o#p$:y#p#q$Ck#q#r$9]#r~$CkC{$DvX%q7[%f,XOw+owx-Vx#O+o#O#P.V#P#o+o#o#p0^#p#q+o#q#r.k#r~+oC{$EhT%q7[O#o$Ck#o#p$9]#p#q$Ck#q#r$9]#r~$CkGk$FUZ%q7[%kW%f,X%tp%y#tOrGQrs)wswGQwxM^x#OGQ#O#PHS#P#oGQ#o#pLj#p#qGQ#q#rHh#r~GQGk$F|T%q7[O#o$0{#o#p$G]#p#q$0{#q#r$G]#r~$0{1_$Gl]%hS%kW%f,X%tp%w!b%y#tOY$G]YZHhZ]$G]]^Hh^r$G]rs$7Xsw$G]wx$Hex#O$G]#O#P$I]#P#o$G]#o#p$Ic#p~$G]1_$HpX%kW%f,X%tp%y#tOrHhrs3aswHhwxJWx#OHh#O#PLd#P#oHh#o#pLj#p~Hh1_$I`PO~$G]1_$Il]%hS%kW%f,XOY$>}YZ8bZ]$>}]^8b^r$>}rs$?ysw$>}wx$Amx#O$>}#O#P$BZ#P#o$>}#o#p$G]#p~$>}Gk$JrZ%q7[%kW%f,X%tp%y#tOrGQrs)wswGQwx$Kex#OGQ#O#PHS#P#oGQ#o#pLj#p#qGQ#q#rHh#r~GQGk$KtZ%i!f%q7[%kW%g,X%tp%y#tOrN[rs=OswN[wxN[x#ON[#O#P! Y#P#oN[#o#pKx#p#qN[#q#rJ|#r~N[G{$LzZf,X%q7[%hS%kW%n`%tp%w!b%y#tOr$}rs&Rsw$}wxFSx#O$}#O#P! n#P#o$}#o#p!#U#p#q$}#q#r!!S#r~$}<u$NQZ!OR%q7[%hS%kW%n`%tp%w!b%y#tOr$}rs&Rsw$}wxFSx#O$}#O#P! n#P#o$}#o#p!#U#p#q$}#q#r!!S#r~$}G{% W_T,X%q7[%hS%kW%n`%tp%w!b%y#tOr$}rs&Rsw$}wxFSxz$}z{%!V{!_$}!_!`$-Z!`#O$}#O#P! n#P#o$}#o#p!#U#p#q$}#q#r!!S#r~$}G{%!j]_R%q7[%hS%kW%n`%tp%w!b%y#tOr$}rs&Rsw$}wxFSx!_$}!_!`$-Z!`#O$}#O#P! n#P#o$}#o#p!#U#p#q$}#q#r!!S#r~$}G{%#v]$z,X%q7[%hS%kW%n`%tp%w!b%y#tOr$}rs&Rsw$}wxFSx!_$}!_!`$-Z!`#O$}#O#P! n#P#o$}#o#p!#U#p#q$}#q#r!!S#r~$}<u%%SZwR%q7[%hS%kW%n`%tp%w!b%y#tOr$}rs&Rsw$}wxFSx#O$}#O#P! n#P#o$}#o#p!#U#p#q$}#q#r!!S#r~$}Mg%&Y^${,X%q7[%hS%kW%n`%tp%w!b%y#tOr$}rs&Rsw$}wxFSx!_$}!_!`$-Z!`!a%'U!a#O$}#O#P! n#P#o$}#o#p!#U#p#q$}#q#r!!S#r~$}B^%'iZ&U&j%q7[%hS%kW%n`%tp%w!b%y#tOr$}rs&Rsw$}wxFSx#O$}#O#P! n#P#o$}#o#p!#U#p#q$}#q#r!!S#r~$}G{%(o_!dQ%q7[%hS%kW%n`%tp%w!b%y#tOr$}rs&Rsw$}wxFSx!O$}!O!P%)n!P!Q$}!Q![%,O![#O$}#O#P! n#P#o$}#o#p!#U#p#q$}#q#r!!S#r~$}G{%*P]%q7[%hS%kW%n`%tp%w!b%y#tOr$}rs&Rsw$}wxFSx!O$}!O!P%*x!P#O$}#O#P! n#P#o$}#o#p!#U#p#q$}#q#r!!S#r~$}G{%+]Z!m,X%q7[%hS%kW%n`%tp%w!b%y#tOr$}rs&Rsw$}wxFSx#O$}#O#P! n#P#o$}#o#p!#U#p#q$}#q#r!!S#r~$}Gy%,cg!f,V%q7[%hS%kW%n`%tp%w!b%y#tOr$}rs&Rsw$}wxFSx!Q$}!Q![%,O![!g$}!g!h%-z!h!l$}!l!m%2[!m#O$}#O#P! n#P#R$}#R#S%,O#S#X$}#X#Y%-z#Y#^$}#^#_%2[#_#o$}#o#p!#U#p#q$}#q#r!!S#r~$}Gy%.]a%q7[%hS%kW%n`%tp%w!b%y#tOr$}rs&Rsw$}wxFSx{$}{|%/b|}$}}!O%/b!O!Q$}!Q![%0l![#O$}#O#P! n#P#o$}#o#p!#U#p#q$}#q#r!!S#r~$}Gy%/s]%q7[%hS%kW%n`%tp%w!b%y#tOr$}rs&Rsw$}wxFSx!Q$}!Q![%0l![#O$}#O#P! n#P#o$}#o#p!#U#p#q$}#q#r!!S#r~$}Gy%1Pc!f,V%q7[%hS%kW%n`%tp%w!b%y#tOr$}rs&Rsw$}wxFSx!Q$}!Q![%0l![!l$}!l!m%2[!m#O$}#O#P! n#P#R$}#R#S%0l#S#^$}#^#_%2[#_#o$}#o#p!#U#p#q$}#q#r!!S#r~$}Gy%2oZ!f,V%q7[%hS%kW%n`%tp%w!b%y#tOr$}rs&Rsw$}wxFSx#O$}#O#P! n#P#o$}#o#p!#U#p#q$}#q#r!!S#r~$}G{%3u_$|R%q7[%hS%kW%n`%tp%w!b%y#tOr$}rs&Rsw$}wxFSx!P$}!P!Q%4t!Q!_$}!_!`$-Z!`#O$}#O#P! n#P#o$}#o#p!#U#p#q$}#q#r!!S#r~$}Gz%5X]%OQ%q7[%hS%kW%n`%tp%w!b%y#tOr$}rs&Rsw$}wxFSx!_$}!_!`$-Z!`#O$}#O#P! n#P#o$}#o#p!#U#p#q$}#q#r!!S#r~$}Gy%6eu!f,V%q7[%hS%kW%n`%tp%w!b%y#tOr$}rs&Rsw$}wxFSx!O$}!O!P%8x!P!Q$}!Q![%:S![!d$}!d!e%<U!e!g$}!g!h%-z!h!l$}!l!m%2[!m!q$}!q!r%?O!r!z$}!z!{%Ar!{#O$}#O#P! n#P#R$}#R#S%:S#S#U$}#U#V%<U#V#X$}#X#Y%-z#Y#^$}#^#_%2[#_#c$}#c#d%?O#d#l$}#l#m%Ar#m#o$}#o#p!#U#p#q$}#q#r!!S#r~$}Gy%9Z]%q7[%hS%kW%n`%tp%w!b%y#tOr$}rs&Rsw$}wxFSx!Q$}!Q![%,O![#O$}#O#P! n#P#o$}#o#p!#U#p#q$}#q#r!!S#r~$}Gy%:gi!f,V%q7[%hS%kW%n`%tp%w!b%y#tOr$}rs&Rsw$}wxFSx!O$}!O!P%8x!P!Q$}!Q![%:S![!g$}!g!h%-z!h!l$}!l!m%2[!m#O$}#O#P! n#P#R$}#R#S%:S#S#X$}#X#Y%-z#Y#^$}#^#_%2[#_#o$}#o#p!#U#p#q$}#q#r!!S#r~$}Gy%<g`%q7[%hS%kW%n`%tp%w!b%y#tOr$}rs&Rsw$}wxFSx!Q$}!Q!R%=i!R!S%=i!S#O$}#O#P! n#P#R$}#R#S%=i#S#o$}#o#p!#U#p#q$}#q#r!!S#r~$}Gy%=|`!f,V%q7[%hS%kW%n`%tp%w!b%y#tOr$}rs&Rsw$}wxFSx!Q$}!Q!R%=i!R!S%=i!S#O$}#O#P! n#P#R$}#R#S%=i#S#o$}#o#p!#U#p#q$}#q#r!!S#r~$}Gy%?a_%q7[%hS%kW%n`%tp%w!b%y#tOr$}rs&Rsw$}wxFSx!Q$}!Q!Y%@`!Y#O$}#O#P! n#P#R$}#R#S%@`#S#o$}#o#p!#U#p#q$}#q#r!!S#r~$}Gy%@s_!f,V%q7[%hS%kW%n`%tp%w!b%y#tOr$}rs&Rsw$}wxFSx!Q$}!Q!Y%@`!Y#O$}#O#P! n#P#R$}#R#S%@`#S#o$}#o#p!#U#p#q$}#q#r!!S#r~$}Gy%BTc%q7[%hS%kW%n`%tp%w!b%y#tOr$}rs&Rsw$}wxFSx!Q$}!Q![%C`![!c$}!c!i%C`!i#O$}#O#P! n#P#R$}#R#S%C`#S#T$}#T#Z%C`#Z#o$}#o#p!#U#p#q$}#q#r!!S#r~$}Gy%Csc!f,V%q7[%hS%kW%n`%tp%w!b%y#tOr$}rs&Rsw$}wxFSx!Q$}!Q![%C`![!c$}!c!i%C`!i#O$}#O#P! n#P#R$}#R#S%C`#S#T$}#T#Z%C`#Z#o$}#o#p!#U#p#q$}#q#r!!S#r~$}Mg%Ec]x1s%q7[%hS%kW%n`%tp%w!b%y#tOr$}rs&Rsw$}wxFSx!_$}!_!`%F[!`#O$}#O#P! n#P#o$}#o#p!#U#p#q$}#q#r!!S#r~$}<u%FoZ%WR%q7[%hS%kW%n`%tp%w!b%y#tOr$}rs&Rsw$}wxFSx#O$}#O#P! n#P#o$}#o#p!#U#p#q$}#q#r!!S#r~$}G{%GuZ#^,X%q7[%hS%kW%n`%tp%w!b%y#tOr$}rs&Rsw$}wxFSx#O$}#O#P! n#P#o$}#o#p!#U#p#q$}#q#r!!S#r~$}G{%H{_jR%q7[%hS%kW%n`%tp%w!b%y#tOr$}rs&Rsw$}wxFSx!^$}!^!_%Iz!_!`!'m!`!a!'m!a#O$}#O#P! n#P#o$}#o#p!#U#p#q$}#q#r!!S#r~$}Gz%J_]$xQ%q7[%hS%kW%n`%tp%w!b%y#tOr$}rs&Rsw$}wxFSx!_$}!_!`$-Z!`#O$}#O#P! n#P#o$}#o#p!#U#p#q$}#q#r!!S#r~$}G{%Kk]%V,X%q7[%hS%kW%n`%tp%w!b%y#tOr$}rs&Rsw$}wxFSx!_$}!_!`!'m!`#O$}#O#P! n#P#o$}#o#p!#U#p#q$}#q#r!!S#r~$}G{%Lw^jR%q7[%hS%kW%n`%tp%w!b%y#tOr$}rs&Rsw$}wxFSx!_$}!_!`!'m!`!a%Ms!a#O$}#O#P! n#P#o$}#o#p!#U#p#q$}#q#r!!S#r~$}Gz%NW]$yQ%q7[%hS%kW%n`%tp%w!b%y#tOr$}rs&Rsw$}wxFSx!_$}!_!`$-Z!`#O$}#O#P! n#P#o$}#o#p!#U#p#q$}#q#r!!S#r~$}G{& f]]Q#tP%q7[%hS%kW%n`%tp%w!b%y#tOr$}rs&Rsw$}wxFSx!_$}!_!`$-Z!`#O$}#O#P! n#P#o$}#o#p!#U#p#q$}#q#r!!S#r~$}Mg&!tc%q7[%hS%kW%e&j%n`%tp%w!b%y#t%Q,XOr$}rs&Rsw$}wxFSx!Q$}!Q![&!_![!c$}!c!}&!_!}#O$}#O#P! n#P#R$}#R#S&!_#S#T$}#T#o&!_#o#p!#U#p#q$}#q#r!!S#r$g$}$g~&!_Mg&$fg%q7[%hS%kW%e&j%n`%tp%w!b%y#t%Q,XOr$}rs&%}sw$}wx&)Tx!Q$}!Q![&!_![!c$}!c!t&!_!t!u&,a!u!}&!_!}#O$}#O#P! n#P#R$}#R#S&!_#S#T$}#T#f&!_#f#g&,a#g#o&!_#o#p!#U#p#q$}#q#r!!S#r$g$}$g~&!_De&&[_%q7[%hS%f,X%n`%w!bOY!+XYZ'PZ]!+X]^'P^r!+Xrs&'Zsw!+Xwx!-gx#O!+X#O#P!>e#P#o!+X#o#p!@}#p#q!+X#q#r!>y#r~!+XDe&'hZ%q7[%hS%f,X%n`%w!bOr'Prs&(Zsw'Pwx(Px#O'P#O#P>v#P#o'P#o#pCU#p#q'P#q#r?[#r~'PD]&(hX%q7[%hS%j,X%n`%w!bOwDvwx,ex#ODv#O#PEn#P#oDv#o#pBd#p#qDv#q#rAn#r~DvGk&)b_%q7[%kW%f,X%tp%y#tOY$0{YZGQZ]$0{]^GQ^r$0{rs$2]sw$0{wx&*ax#O$0{#O#P$Fw#P#o$0{#o#p$Ic#p#q$0{#q#r$G]#r~$0{Gk&*nZ%q7[%kW%f,X%tp%y#tOrGQrs)wswGQwx&+ax#OGQ#O#PHS#P#oGQ#o#pLj#p#qGQ#q#rHh#r~GQFT&+nZ%q7[%kW%g,X%tp%y#tOrN[rs=OswN[wxN[x#ON[#O#P! Y#P#oN[#o#pKx#p#qN[#q#rJ|#r~N[Mg&,vc%q7[%hS%kW%e&j%n`%tp%w!b%y#t%Q,XOr$}rs&%}sw$}wx&)Tx!Q$}!Q![&!_![!c$}!c!}&!_!}#O$}#O#P! n#P#R$}#R#S&!_#S#T$}#T#o&!_#o#p!#U#p#q$}#q#r!!S#r$g$}$g~&!_Mg&.hg%q7[%hS%kW%e&j%n`%tp%w!b%y#t%Q,XOr$}rs&0Psw$}wx&2wx!Q$}!Q![&!_![!c$}!c!t&!_!t!u&5u!u!}&!_!}#O$}#O#P! n#P#R$}#R#S&!_#S#T$}#T#f&!_#f#g&5u#g#o&!_#o#p!#U#p#q$}#q#r!!S#r$g$}$g~&!_De&0^Z%q7[%hS%n`%w!b%s,XOr'Prs&1Psw'Pwx(Px#O'P#O#P>v#P#o'P#o#pCU#p#q'P#q#r?[#r~'PDe&1[Z%q7[%hS%n`%w!bOr'Prs&1}sw'Pwx(Px#O'P#O#P>v#P#o'P#o#pCU#p#q'P#q#r?[#r~'PD]&2[X%q7[%hS%x,X%n`%w!bOwDvwx,ex#ODv#O#PEn#P#oDv#o#pBd#p#qDv#q#rAn#r~DvGk&3UZ%q7[%kW%tp%y#t%m,XOrGQrs)wswGQwx&3wx#OGQ#O#PHS#P#oGQ#o#pLj#p#qGQ#q#rHh#r~GQGk&4SZ%q7[%kW%tp%y#tOrGQrs)wswGQwx&4ux#OGQ#O#PHS#P#oGQ#o#pLj#p#qGQ#q#rHh#r~GQFT&5SZ%q7[%kW%v,X%tp%y#tOrN[rs=OswN[wxN[x#ON[#O#P! Y#P#oN[#o#pKx#p#qN[#q#rJ|#r~N[Mg&6[c%q7[%hS%kW%e&j%n`%tp%w!b%y#t%Q,XOr$}rs&0Psw$}wx&2wx!Q$}!Q![&!_![!c$}!c!}&!_!}#O$}#O#P! n#P#R$}#R#S&!_#S#T$}#T#o&!_#o#p!#U#p#q$}#q#r!!S#r$g$}$g~&!_Mg&7|k%q7[%hS%kW%e&j%n`%tp%w!b%y#t%Q,XOr$}rs&%}sw$}wx&)Tx!Q$}!Q![&!_![!c$}!c!h&!_!h!i&5u!i!t&!_!t!u&,a!u!}&!_!}#O$}#O#P! n#P#R$}#R#S&!_#S#T$}#T#U&!_#U#V&,a#V#Y&!_#Y#Z&5u#Z#o&!_#o#p!#U#p#q$}#q#r!!S#r$g$}$g~&!_G{&:UZ!V,X%q7[%hS%kW%n`%tp%w!b%y#tOr$}rs&Rsw$}wxFSx#O$}#O#P! n#P#o$}#o#p!#U#p#q$}#q#r!!S#r~$}<u&;[Z!WR%q7[%hS%kW%n`%tp%w!b%y#tOr$}rs&Rsw$}wxFSx#O$}#O#P! n#P#o$}#o#p!#U#p#q$}#q#r!!S#r~$}Gz&<b]$vQ%q7[%hS%kW%n`%tp%w!b%y#tOr$}rs&Rsw$}wxFSx!_$}!_!`$-Z!`#O$}#O#P! n#P#o$}#o#p!#U#p#q$}#q#r!!S#r~$}Gy&=dX%hS%kW!ZGmOr8brs9Osw8bwx:Ux#O8b#O#P;[#P#o8b#o#p!!S#p~8bGz&>d]$uQ%q7[%hS%kW%n`%tp%w!b%y#tOr$}rs&Rsw$}wxFSx!_$}!_!`$-Z!`#O$}#O#P! n#P#o$}#o#p!#U#p#q$}#q#r!!S#r~$}<u&?nX![7_%hS%kW%n`%tp%w!b%y#tOr!!Srs@Ssw!!SwxIbx#O!!S#O#P!#O#P#o!!S#o#p!#U#p~!!SGy&@nZ%P,V%q7[%hS%kW%n`%tp%w!b%y#tOr$}rs&Rsw$}wxFSx#O$}#O#P! n#P#o$}#o#p!#U#p#q$}#q#r!!S#r~$}", - tokenizers: [legacyPrint, indentation, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, newlines], - topRules: {"Script":[0,3]}, - specialized: [{term: 186, get: value => spec_identifier[value] || -1}], - tokenPrec: 6584 - }); - - function indentBody(context, node) { - let base = context.lineIndent(node.from); - let line = context.lineAt(context.pos, -1), to = line.from + line.text.length; - // Don't consider blank, deindented lines at the end of the - // block part of the block - if (!/\S/.test(line.text) && - context.node.to < to + 100 && - !/\S/.test(context.state.sliceDoc(to, context.node.to)) && - context.lineIndent(context.pos, -1) <= base) - return null; - // A normally deindenting keyword that appears at a higher - // indentation than the block should probably be handled by the next - // level - if (/^\s*(else:|elif |except |finally:)/.test(context.textAfter) && context.lineIndent(context.pos, -1) > base) - return null; - return base + context.unit; - } - /** - A language provider based on the [Lezer Python - parser](https://github.com/lezer-parser/python), extended with - highlighting and indentation information. - */ - const pythonLanguage = /*@__PURE__*/LRLanguage.define({ - parser: /*@__PURE__*/parser.configure({ - props: [ - /*@__PURE__*/indentNodeProp.add({ - Body: context => { var _a; return (_a = indentBody(context, context.node)) !== null && _a !== void 0 ? _a : context.continue(); }, - IfStatement: cx => /^\s*(else:|elif )/.test(cx.textAfter) ? cx.baseIndent : cx.continue(), - TryStatement: cx => /^\s*(except |finally:)/.test(cx.textAfter) ? cx.baseIndent : cx.continue(), - "TupleExpression ComprehensionExpression ParamList ArgList ParenthesizedExpression": /*@__PURE__*/delimitedIndent({ closing: ")" }), - "DictionaryExpression DictionaryComprehensionExpression SetExpression SetComprehensionExpression": /*@__PURE__*/delimitedIndent({ closing: "}" }), - "ArrayExpression ArrayComprehensionExpression": /*@__PURE__*/delimitedIndent({ closing: "]" }), - Script: context => { - if (context.pos + /\s*/.exec(context.textAfter)[0].length >= context.node.to) { - let endBody = null; - for (let cur = context.node, to = cur.to;;) { - cur = cur.lastChild; - if (!cur || cur.to != to) - break; - if (cur.type.name == "Body") - endBody = cur; - } - if (endBody) { - let bodyIndent = indentBody(context, endBody); - if (bodyIndent != null) - return bodyIndent; - } - } - return context.continue(); - } - }), - /*@__PURE__*/foldNodeProp.add({ - "ArrayExpression DictionaryExpression": foldInside$1, - Body: (node, state) => ({ from: node.from + 1, to: node.to - (node.to == state.doc.length ? 0 : 1) }) - }), - /*@__PURE__*/styleTags({ - "async \"*\" \"**\" FormatConversion FormatSpec": tags.modifier, - "for while if elif else try except finally return raise break continue with pass assert await yield": tags.controlKeyword, - "in not and or is del": tags.operatorKeyword, - "from def class global nonlocal lambda": tags.definitionKeyword, - import: tags.moduleKeyword, - "with as print": tags.keyword, - Boolean: tags.bool, - None: tags.null, - VariableName: tags.variableName, - "CallExpression/VariableName": /*@__PURE__*/tags.function(tags.variableName), - "FunctionDefinition/VariableName": /*@__PURE__*/tags.function(/*@__PURE__*/tags.definition(tags.variableName)), - "ClassDefinition/VariableName": /*@__PURE__*/tags.definition(tags.className), - PropertyName: tags.propertyName, - "CallExpression/MemberExpression/PropertyName": /*@__PURE__*/tags.function(tags.propertyName), - Comment: tags.lineComment, - Number: tags.number, - String: tags.string, - FormatString: /*@__PURE__*/tags.special(tags.string), - UpdateOp: tags.updateOperator, - ArithOp: tags.arithmeticOperator, - BitOp: tags.bitwiseOperator, - CompareOp: tags.compareOperator, - AssignOp: tags.definitionOperator, - Ellipsis: tags.punctuation, - At: tags.meta, - "( )": tags.paren, - "[ ]": tags.squareBracket, - "{ }": tags.brace, - ".": tags.derefOperator, - ", ;": tags.separator - }) - ], - }), - languageData: { - closeBrackets: { brackets: ["(", "[", "{", "'", '"', "'''", '"""'] }, - commentTokens: { line: "#" }, - indentOnInput: /^\s*([\}\]\)]|else:|elif |except |finally:)$/ - } - }); - /** - Python language support. - */ - function python() { - return new LanguageSupport(pythonLanguage); - } - - // Using https://github.com/one-dark/vscode-one-dark-theme/ as reference for the colors - const chalky = "#e5c07b", coral = "#e06c75", cyan = "#56b6c2", invalid = "#ffffff", ivory = "#abb2bf", stone = "#7d8799", // Brightened compared to original to increase contrast - malibu = "#61afef", sage = "#98c379", whiskey = "#d19a66", violet = "#c678dd", darkBackground = "#21252b", highlightBackground = "#2c313a", background = "#282c34", tooltipBackground = "#353a42", selection = "#3E4451", cursor = "#528bff"; - /** - The editor theme styles for One Dark. - */ - const oneDarkTheme = /*@__PURE__*/EditorView.theme({ - "&": { - color: ivory, - backgroundColor: background - }, - ".cm-content": { - caretColor: cursor - }, - "&.cm-focused .cm-cursor": { borderLeftColor: cursor }, - "&.cm-focused .cm-selectionBackground, .cm-selectionBackground, .cm-content ::selection": { backgroundColor: selection }, - ".cm-panels": { backgroundColor: darkBackground, color: ivory }, - ".cm-panels.cm-panels-top": { borderBottom: "2px solid black" }, - ".cm-panels.cm-panels-bottom": { borderTop: "2px solid black" }, - ".cm-searchMatch": { - backgroundColor: "#72a1ff59", - outline: "1px solid #457dff" - }, - ".cm-searchMatch.cm-searchMatch-selected": { - backgroundColor: "#6199ff2f" - }, - ".cm-activeLine": { backgroundColor: highlightBackground }, - ".cm-selectionMatch": { backgroundColor: "#aafe661a" }, - "&.cm-focused .cm-matchingBracket, &.cm-focused .cm-nonmatchingBracket": { - backgroundColor: "#bad0f847", - outline: "1px solid #515a6b" - }, - ".cm-gutters": { - backgroundColor: background, - color: stone, - border: "none" - }, - ".cm-activeLineGutter": { - backgroundColor: highlightBackground - }, - ".cm-foldPlaceholder": { - backgroundColor: "transparent", - border: "none", - color: "#ddd" - }, - ".cm-tooltip": { - border: "none", - backgroundColor: tooltipBackground - }, - ".cm-tooltip .cm-tooltip-arrow:before": { - borderTopColor: "transparent", - borderBottomColor: "transparent" - }, - ".cm-tooltip .cm-tooltip-arrow:after": { - borderTopColor: tooltipBackground, - borderBottomColor: tooltipBackground - }, - ".cm-tooltip-autocomplete": { - "& > ul > li[aria-selected]": { - backgroundColor: highlightBackground, - color: ivory - } - } - }, { dark: true }); - /** - The highlighting style for code in the One Dark theme. - */ - /*@__PURE__*/HighlightStyle.define([ - { tag: tags.keyword, - color: violet }, - { tag: [tags.name, tags.deleted, tags.character, tags.propertyName, tags.macroName], - color: coral }, - { tag: [/*@__PURE__*/tags.function(tags.variableName), tags.labelName], - color: malibu }, - { tag: [tags.color, /*@__PURE__*/tags.constant(tags.name), /*@__PURE__*/tags.standard(tags.name)], - color: whiskey }, - { tag: [/*@__PURE__*/tags.definition(tags.name), tags.separator], - color: ivory }, - { tag: [tags.typeName, tags.className, tags.number, tags.changed, tags.annotation, tags.modifier, tags.self, tags.namespace], - color: chalky }, - { tag: [tags.operator, tags.operatorKeyword, tags.url, tags.escape, tags.regexp, tags.link, /*@__PURE__*/tags.special(tags.string)], - color: cyan }, - { tag: [tags.meta, tags.comment], - color: stone }, - { tag: tags.strong, - fontWeight: "bold" }, - { tag: tags.emphasis, - fontStyle: "italic" }, - { tag: tags.strikethrough, - textDecoration: "line-through" }, - { tag: tags.link, - color: stone, - textDecoration: "underline" }, - { tag: tags.heading, - fontWeight: "bold", - color: coral }, - { tag: [tags.atom, tags.bool, /*@__PURE__*/tags.special(tags.variableName)], - color: whiskey }, - { tag: [tags.processingInstruction, tags.string, tags.inserted], - color: sage }, - { tag: tags.invalid, - color: invalid }, - ]); - - const logger$7 = getLogger('py-repl'); - function createCmdHandler(el) { - // Creates a codemirror cmd handler that calls the el.evaluate when an event - // triggers that specific cmd - return () => { - void el.evaluate(); - return true; - }; - } - let initialTheme; - function getEditorTheme(el) { - return initialTheme || (initialTheme = el.getAttribute('theme')); - } - class PyRepl extends BaseEvalElement { - editor; - editorNode; - constructor() { - super(); - // add an extra div where we can attach the codemirror editor - this.editorNode = document.createElement('div'); - addClasses(this.editorNode, ['editor-box']); - this.shadow.appendChild(this.wrapper); - } - connectedCallback() { - this.checkId(); - this.code = htmlDecode(this.innerHTML); - this.innerHTML = ''; - const languageConf = new Compartment(); - const extensions = [ - basicSetup, - languageConf.of(python()), - keymap.of([ - ...defaultKeymap, - { key: 'Ctrl-Enter', run: createCmdHandler(this) }, - { key: 'Shift-Enter', run: createCmdHandler(this) }, - ]), - ]; - if (getEditorTheme(this) === 'dark') { - extensions.push(oneDarkTheme); - } - this.editor = new EditorView({ - state: EditorState.create({ - doc: this.code.trim(), - extensions, - }), - parent: this.editorNode, - }); - const mainDiv = document.createElement('div'); - addClasses(mainDiv, ['py-repl-box']); - // Styles that we use to hide the labels whilst also keeping it accessible for screen readers - const labelStyle = 'overflow:hidden; display:block; width:1px; height:1px'; - // Code editor Label - this.editorNode.id = 'code-editor'; - const editorLabel = document.createElement('label'); - editorLabel.innerHTML = 'Python Script Area'; - editorLabel.setAttribute('style', labelStyle); - editorLabel.htmlFor = 'code-editor'; - mainDiv.append(editorLabel); - // add Editor to main PyScript div - mainDiv.appendChild(this.editorNode); - // Play Button - this.btnRun = document.createElement('button'); - this.btnRun.id = 'btnRun'; - this.btnRun.innerHTML = - '<svg id="" class="svelte-fa svelte-ps5qeg" style="height:20px;width:20px;vertical-align:-.125em;transform-origin:center;overflow:visible;color:green" viewBox="0 0 384 512" aria-hidden="true" role="img" xmlns="http://www.w3.org/2000/svg"><g transform="translate(192 256)" transform-origin="96 0"><g transform="translate(0,0) scale(1,1)"><path d="M361 215C375.3 223.8 384 239.3 384 256C384 272.7 375.3 288.2 361 296.1L73.03 472.1C58.21 482 39.66 482.4 24.52 473.9C9.377 465.4 0 449.4 0 432V80C0 62.64 9.377 46.63 24.52 38.13C39.66 29.64 58.21 29.99 73.03 39.04L361 215z" fill="currentColor" transform="translate(-192 -256)"></path></g></g></svg>'; - addClasses(this.btnRun, ['absolute', 'repl-play-button']); - // Play Button Label - const btnLabel = document.createElement('label'); - btnLabel.innerHTML = 'Python Script Run Button'; - btnLabel.setAttribute('style', labelStyle); - btnLabel.htmlFor = 'btnRun'; - this.editorNode.appendChild(btnLabel); - this.editorNode.appendChild(this.btnRun); - this.btnRun.addEventListener('click', () => { - void this.evaluate(); - }); - if (!this.id) { - logger$7.warn("WARNING: <py-repl> defined without an id. <py-repl> should always have an id, otherwise multiple <py-repl> in the same page will not work!"); - } - if (!this.hasAttribute('exec-id')) { - this.setAttribute('exec-id', '1'); - } - if (!this.hasAttribute('root')) { - this.setAttribute('root', this.id); - } - if (this.hasAttribute('output')) { - this.errorElement = this.outputElement = document.getElementById(this.getAttribute('output')); - } - else { - if (this.hasAttribute('std-out')) { - this.outputElement = document.getElementById(this.getAttribute('std-out')); - } - else { - // In this case neither output or std-out have been provided so we need - // to create a new output div to output to - this.outputElement = document.createElement('div'); - this.outputElement.classList.add('output'); - this.outputElement.hidden = true; - this.outputElement.id = this.id + '-' + this.getAttribute('exec-id'); - // add the output div id if there's not output pre-defined - mainDiv.appendChild(this.outputElement); - } - this.errorElement = this.hasAttribute('std-err') - ? document.getElementById(this.getAttribute('std-err')) - : this.outputElement; - } - this.appendChild(mainDiv); - this.editor.focus(); - logger$7.debug(`element ${this.id} successfully connected`); - } - addToOutput(s) { - this.outputElement.innerHTML += '<div>' + s + '</div>'; - this.outputElement.hidden = false; - } - preEvaluate() { - this.setOutputMode("replace"); - if (!this.appendOutput) { - this.outputElement.innerHTML = ''; - } - } - postEvaluate() { - this.outputElement.hidden = false; - this.outputElement.style.display = 'block'; - if (this.hasAttribute('auto-generate')) { - const allPyRepls = document.querySelectorAll(`py-repl[root='${this.getAttribute('root')}'][exec-id]`); - const lastRepl = allPyRepls[allPyRepls.length - 1]; - const lastExecId = lastRepl.getAttribute('exec-id'); - const nextExecId = parseInt(lastExecId) + 1; - const newPyRepl = document.createElement('py-repl'); - newPyRepl.setAttribute('root', this.getAttribute('root')); - newPyRepl.id = this.getAttribute('root') + '-' + nextExecId.toString(); - if (this.hasAttribute('auto-generate')) { - newPyRepl.setAttribute('auto-generate', ''); - this.removeAttribute('auto-generate'); - } - if (this.hasAttribute('output-mode')) { - newPyRepl.setAttribute('output-mode', this.getAttribute('output-mode')); - } - const addReplAttribute = (attribute) => { - if (this.hasAttribute(attribute)) { - newPyRepl.setAttribute(attribute, this.getAttribute(attribute)); - } - }; - addReplAttribute('output'); - addReplAttribute('std-out'); - addReplAttribute('std-err'); - newPyRepl.setAttribute('exec-id', nextExecId.toString()); - this.parentElement.appendChild(newPyRepl); - } - } - getSourceFromElement() { - return this.editor.state.doc.toString(); - } - } - - const logger$6 = getLogger('py-box'); - class PyBox extends HTMLElement { - shadow; - wrapper; - theme; - widths; - constructor() { - super(); - // attach shadow so we can preserve the element original innerHtml content - this.shadow = this.attachShadow({ mode: 'open' }); - this.wrapper = document.createElement('slot'); - this.shadow.appendChild(this.wrapper); - } - connectedCallback() { - const mainDiv = document.createElement('div'); - addClasses(mainDiv, ['py-box']); - // Hack: for some reason when moving children, the editor box duplicates children - // meaning that we end up with 2 editors, if there's a <py-repl> inside the <py-box> - // so, if we have more than 2 children with the cm-editor class, we remove one of them - while (this.childNodes.length > 0) { - if (this.firstChild.nodeName == 'PY-REPL') { - // in this case we need to remove the child and create a new one from scratch - const replDiv = document.createElement('div'); - // we need to put the new repl inside a div so that if the repl has auto-generate true - // it can replicate itself inside that constrained div - replDiv.appendChild(this.firstChild.cloneNode()); - mainDiv.appendChild(replDiv); - this.firstChild.remove(); - } - else { - if (this.firstChild.nodeName != '#text') { - mainDiv.appendChild(this.firstChild); - } - else { - this.firstChild.remove(); - } - } - } - // now we need to set widths - this.widths = []; - if (this.hasAttribute('widths')) { - for (const w of this.getAttribute('widths').split(';')) { - if (w.includes('/')) - this.widths.push(w.split('/')[0]); - else - this.widths.push(w); - } - } - else { - this.widths = Array(mainDiv.children.length).fill('1 1 0'); - } - this.widths.forEach((width, index) => { - const node = mainDiv.childNodes[index]; - node.style.flex = width; - addClasses(node, ['py-box-child']); - }); - this.appendChild(mainDiv); - logger$6.info('py-box connected'); - } - } - - const logger$5 = getLogger('py-button'); - class PyButton extends BaseEvalElement { - widths; - label; - class; - defaultClass; - mount_name; - constructor() { - super(); - this.defaultClass = ['py-button']; - if (this.hasAttribute('label')) { - this.label = this.getAttribute('label'); - } - // Styling does the same thing as class in normal HTML. Using the name "class" makes the style to malfunction - if (this.hasAttribute('styling')) { - const klass = this.getAttribute('styling').trim(); - if (klass === '') { - this.class = this.defaultClass; - } - else { - // trim each element to remove unnecessary spaces which makes the button style to malfunction - this.class = klass - .split(' ') - .map(x => x.trim()) - .filter(x => x !== ''); - } - } - else { - this.class = this.defaultClass; - } - } - connectedCallback() { - this.checkId(); - this.code = htmlDecode(this.innerHTML); - this.mount_name = this.id.split('-').join('_'); - this.innerHTML = ''; - const mainDiv = document.createElement('button'); - mainDiv.innerHTML = this.label; - addClasses(mainDiv, this.class); - mainDiv.id = this.id; - this.id = `${this.id}-container`; - this.appendChild(mainDiv); - this.code = this.code.split('self').join(this.mount_name); - let registrationCode = `from pyodide.ffi import create_proxy`; - registrationCode += `\n${this.mount_name} = Element("${mainDiv.id}")`; - if (this.code.includes('def on_focus')) { - this.code = this.code.replace('def on_focus', `def on_focus_${this.mount_name}`); - registrationCode += `\n${this.mount_name}.element.addEventListener('focus', create_proxy(on_focus_${this.mount_name}))`; - } - if (this.code.includes('def on_click')) { - this.code = this.code.replace('def on_click', `def on_click_${this.mount_name}`); - registrationCode += `\n${this.mount_name}.element.addEventListener('click', create_proxy(on_click_${this.mount_name}))`; - } - // now that we appended and the element is attached, lets connect with the event handlers - // defined for this widget - this.runAfterRuntimeInitialized(async () => { - await this.eval(this.code); - await this.eval(registrationCode); - logger$5.debug('registered handlers'); - }); - logger$5.debug('py-button connected'); - } - } - - class PyTitle extends BaseEvalElement { - widths; - label; - mount_name; - constructor() { - super(); - } - connectedCallback() { - this.label = htmlDecode(this.innerHTML); - this.mount_name = this.id.split('-').join('_'); - this.innerHTML = ''; - const mainDiv = document.createElement('div'); - const divContent = document.createElement('h1'); - addClasses(mainDiv, ['py-title']); - divContent.innerHTML = this.label; - mainDiv.id = this.id; - this.id = `${this.id}-container`; - mainDiv.appendChild(divContent); - this.appendChild(mainDiv); - } - } - - const logger$4 = getLogger('py-inputbox'); - class PyInputBox extends BaseEvalElement { - widths; - label; - mount_name; - constructor() { - super(); - if (this.hasAttribute('label')) { - this.label = this.getAttribute('label'); - } - } - connectedCallback() { - this.checkId(); - this.code = htmlDecode(this.innerHTML); - this.mount_name = this.id.split('-').join('_'); - this.innerHTML = ''; - const mainDiv = document.createElement('input'); - mainDiv.type = 'text'; - addClasses(mainDiv, ['py-input']); - mainDiv.id = this.id; - this.id = `${this.id}-container`; - this.appendChild(mainDiv); - // now that we appended and the element is attached, lets connect with the event handlers - // defined for this widget - this.appendChild(mainDiv); - this.code = this.code.split('self').join(this.mount_name); - let registrationCode = `from pyodide.ffi import create_proxy`; - registrationCode += `\n${this.mount_name} = Element("${mainDiv.id}")`; - if (this.code.includes('def on_keypress')) { - this.code = this.code.replace('def on_keypress', `def on_keypress_${this.mount_name}`); - registrationCode += `\n${this.mount_name}.element.addEventListener('keypress', create_proxy(on_keypress_${this.mount_name}))`; - } - // TODO: For now we delay execution to allow pyodide to load but in the future this - // should really wait for it to load.. - this.runAfterRuntimeInitialized(async () => { - await this.eval(this.code); - await this.eval(registrationCode); - logger$4.debug('registered handlers'); - }); - } - } - - /* - These were taken from main.js because some of our components call - runAfterRuntimeInitialized immediately when we are creating the custom - element, this was causing tests to fail since runAfterRuntimeInitialized - expects the runtime to have been loaded before being called. - - This function is now called from within the `runtime.initialize`. Once - the runtime finished initializing, then we will create the custom elements - so they are rendered in the page and we will always have a runtime available. - - Ideally, this would live under utils.js, but importing all the components in - the utils.js file was causing jest to fail with weird errors such as: - "ReferenceError: Cannot access 'BaseEvalElement' before initialization" coming - from the PyScript class. - - */ - function createCustomElements() { - /* eslint-disable @typescript-eslint/no-unused-vars */ - customElements.define('py-repl', PyRepl); - customElements.define('py-box', PyBox); - customElements.define('py-title', PyTitle); - customElements.define('py-register-widget', PyWidget); - customElements.define('py-inputbox', PyInputBox); - customElements.define('py-button', PyButton); - /* eslint-enable @typescript-eslint/no-unused-vars */ - } - - const logger$3 = getLogger('pyscript/runtime'); - const version = "<<VERSION>>"; - let loader$1; - globalLoader.subscribe(value => { - loader$1 = value; - }); - let initializers_; - initializers.subscribe((value) => { - initializers_ = value; - }); - let postInitializers_; - postInitializers.subscribe((value) => { - postInitializers_ = value; - }); - let scriptsQueue_; - scriptsQueue.subscribe((value) => { - scriptsQueue_ = value; - }); - let appConfig_$1 = { - autoclose_loader: true - }; - appConfig.subscribe((value) => { - if (value) { - appConfig_$1 = value; - } - }); - /* - Runtime class is a super class that all different runtimes must respect - and adhere to. - - Currently, the only runtime available is Pyodide as indicated by the - `RuntimeInterpreter` type above. This serves as a Union of types of - different runtimes/interpreters which will be added in near future. - - The class has abstract methods available which each runtime is supposed - to implement. - - Methods available handle loading of the interpreter, initialization, - running code, loading and installation of packages, loading from files etc. - - For an example implementation, refer to the `PyodideRuntime` class - in `pyodide.ts` - */ - class Runtime extends Object { - /** - * initializes the page which involves loading of runtime, - * as well as evaluating all the code inside <py-script> tags - * along with initializers and postInitializers - * */ - async initialize() { - loader$1?.log('Loading runtime...'); - await this.loadInterpreter(); - const newEnv = { - id: 'default', - runtime: this, - state: 'loading', - }; - runtimeLoaded.set(this); - // Inject the loader into the runtime namespace - // eslint-disable-next-line - this.globals.set('pyscript_loader', loader$1); - loader$1?.log('Runtime created...'); - loadedEnvironments.update(environments => ({ - ...environments, - [newEnv['id']]: newEnv, - })); - // now we call all initializers before we actually executed all page scripts - loader$1?.log('Initializing components...'); - for (const initializer of initializers_) { - await initializer(); - } - loader$1?.log('Initializing scripts...'); - for (const script of scriptsQueue_) { - void script.evaluate(); - } - scriptsQueue.set([]); - // now we call all post initializers AFTER we actually executed all page scripts - loader$1?.log('Running post initializers...'); - // Finally create the custom elements for pyscript such as pybutton - createCustomElements(); - if (appConfig_$1 && appConfig_$1.autoclose_loader) { - loader$1?.close(); - } - for (const initializer of postInitializers_) { - await initializer(); - } - // NOTE: this message is used by integration tests to know that - // pyscript initialization has complete. If you change it, you need to - // change it also in tests/integration/support.py - logger$3.info('PyScript page fully initialized'); - } - } - - var pyscript = "import asyncio\nimport base64\nimport io\nimport sys\nimport time\nfrom textwrap import dedent\n\nimport micropip # noqa: F401\nfrom js import console, document\n\nloop = asyncio.get_event_loop()\n\nMIME_METHODS = {\n \"__repr__\": \"text/plain\",\n \"_repr_html_\": \"text/html\",\n \"_repr_markdown_\": \"text/markdown\",\n \"_repr_svg_\": \"image/svg+xml\",\n \"_repr_png_\": \"image/png\",\n \"_repr_pdf_\": \"application/pdf\",\n \"_repr_jpeg_\": \"image/jpeg\",\n \"_repr_latex\": \"text/latex\",\n \"_repr_json_\": \"application/json\",\n \"_repr_javascript_\": \"application/javascript\",\n \"savefig\": \"image/png\",\n}\n\n\ndef render_image(mime, value, meta):\n data = f\"data:{mime};charset=utf-8;base64,{value}\"\n attrs = \" \".join(['{k}=\"{v}\"' for k, v in meta.items()])\n return f'<img src=\"{data}\" {attrs}</img>'\n\n\ndef identity(value, meta):\n return value\n\n\nMIME_RENDERERS = {\n \"text/plain\": identity,\n \"text/html\": identity,\n \"image/png\": lambda value, meta: render_image(\"image/png\", value, meta),\n \"image/jpeg\": lambda value, meta: render_image(\"image/jpeg\", value, meta),\n \"image/svg+xml\": identity,\n \"application/json\": identity,\n \"application/javascript\": lambda value, meta: f\"<script>{value}</script>\",\n}\n\n\ndef eval_formatter(obj, print_method):\n \"\"\"\n Evaluates a formatter method.\n \"\"\"\n if print_method == \"__repr__\":\n return repr(obj)\n elif hasattr(obj, print_method):\n if print_method == \"savefig\":\n buf = io.BytesIO()\n obj.savefig(buf, format=\"png\")\n buf.seek(0)\n return base64.b64encode(buf.read()).decode(\"utf-8\")\n return getattr(obj, print_method)()\n elif print_method == \"_repr_mimebundle_\":\n return {}, {}\n return None\n\n\ndef format_mime(obj):\n \"\"\"\n Formats object using _repr_x_ methods.\n \"\"\"\n if isinstance(obj, str):\n return obj, \"text/plain\"\n\n mimebundle = eval_formatter(obj, \"_repr_mimebundle_\")\n if isinstance(mimebundle, tuple):\n format_dict, _ = mimebundle\n else:\n format_dict = mimebundle\n\n output, not_available = None, []\n for method, mime_type in reversed(MIME_METHODS.items()):\n if mime_type in format_dict:\n output = format_dict[mime_type]\n else:\n output = eval_formatter(obj, method)\n\n if output is None:\n continue\n elif mime_type not in MIME_RENDERERS:\n not_available.append(mime_type)\n continue\n break\n if output is None:\n if not_available:\n console.warn(\n f\"Rendered object requested unavailable MIME renderers: {not_available}\"\n )\n output = repr(output)\n mime_type = \"text/plain\"\n elif isinstance(output, tuple):\n output, meta = output\n else:\n meta = {}\n return MIME_RENDERERS[mime_type](output, meta), mime_type\n\n\nclass PyScript:\n loop = loop\n\n @staticmethod\n def run_until_complete(f):\n _ = loop.run_until_complete(f)\n\n @staticmethod\n def write(element_id, value, append=False, exec_id=0):\n \"\"\"Writes value to the element with id \"element_id\"\"\"\n Element(element_id).write(value=value, append=append)\n console.warn(\n dedent(\n \"\"\"PyScript Deprecation Warning: PyScript.write is\n marked as deprecated and will be removed sometime soon. Please, use\n Element(<id>).write instead.\"\"\"\n )\n )\n\n\nclass Element:\n def __init__(self, element_id, element=None):\n self._id = element_id\n self._element = element\n\n @property\n def id(self):\n return self._id\n\n @property\n def element(self):\n \"\"\"Return the dom element\"\"\"\n if not self._element:\n self._element = document.querySelector(f\"#{self._id}\")\n return self._element\n\n @property\n def value(self):\n return self.element.value\n\n @property\n def innerHtml(self):\n return self.element.innerHtml\n\n def write(self, value, append=False):\n out_element_id = self.id\n\n html, mime_type = format_mime(value)\n if html == \"\\n\":\n return\n\n if append:\n child = document.createElement(\"div\")\n exec_id = self.element.childElementCount + 1\n out_element_id = child.id = f\"{self.id}-{exec_id}\"\n self.element.appendChild(child)\n\n out_element = document.querySelector(f\"#{out_element_id}\")\n\n if mime_type in (\"application/javascript\", \"text/html\"):\n script_element = document.createRange().createContextualFragment(html)\n out_element.appendChild(script_element)\n else:\n out_element.innerHTML = html\n\n def clear(self):\n if hasattr(self.element, \"value\"):\n self.element.value = \"\"\n else:\n self.write(\"\", append=False)\n\n def select(self, query, from_content=False):\n el = self.element\n if from_content:\n el = el.content\n\n _el = el.querySelector(query)\n if _el:\n return Element(_el.id, _el)\n else:\n console.warn(f\"WARNING: can't find element matching query {query}\")\n\n def clone(self, new_id=None, to=None):\n if new_id is None:\n new_id = self.element.id\n\n clone = self.element.cloneNode(True)\n clone.id = new_id\n\n if to:\n to.element.appendChild(clone)\n\n # Inject it into the DOM\n self.element.after(clone)\n\n return Element(clone.id, clone)\n\n def remove_class(self, classname):\n if isinstance(classname, list):\n for cl in classname:\n self.remove_class(cl)\n else:\n self.element.classList.remove(classname)\n\n def add_class(self, classname):\n self.element.classList.add(classname)\n\n\ndef add_classes(element, class_list):\n for klass in class_list.split(\" \"):\n element.classList.add(klass)\n\n\ndef create(what, id_=None, classes=\"\"):\n element = document.createElement(what)\n if id_:\n element.id = id_\n add_classes(element, classes)\n return Element(id_, element)\n\n\nclass PyWidgetTheme:\n def __init__(self, main_style_classes):\n self.main_style_classes = main_style_classes\n\n def theme_it(self, widget):\n for klass in self.main_style_classes.split(\" \"):\n widget.classList.add(klass)\n\n\nclass PyItemTemplate(Element):\n label_fields = None\n\n def __init__(self, data, labels=None, state_key=None, parent=None):\n self.data = data\n\n self.register_parent(parent)\n\n if not labels:\n labels = list(self.data.keys())\n self.labels = labels\n\n self.state_key = state_key\n\n super().__init__(self._id)\n\n def register_parent(self, parent):\n self._parent = parent\n if parent:\n self._id = f\"{self._parent._id}-c-{len(self._parent._children)}\"\n self.data[\"id\"] = self._id\n else:\n self._id = None\n\n def create(self):\n new_child = create(\"div\", self._id, \"py-li-element\")\n new_child._element.innerHTML = dedent(\n f\"\"\"\n <label id=\"{self._id}\" for=\"flex items-center p-2 \">\n <input class=\"mr-2\" type=\"checkbox\" class=\"task-check\">\n <p>{self.render_content()}</p>\n </label>\n \"\"\"\n )\n return new_child\n\n def on_click(self, evt):\n pass\n\n def pre_append(self):\n pass\n\n def post_append(self):\n self.element.click = self.on_click\n self.element.onclick = self.on_click\n\n self._post_append()\n\n def _post_append(self):\n pass\n\n def strike(self, value, extra=None):\n if value:\n self.add_class(\"line-through\")\n else:\n self.remove_class(\"line-through\")\n\n def render_content(self):\n return \" - \".join([self.data[f] for f in self.labels])\n\n\nclass PyListTemplate:\n theme = PyWidgetTheme(\"py-li-element\")\n item_class = PyItemTemplate\n\n def __init__(self, parent):\n self.parent = parent\n self._children = []\n self._id = self.parent.id\n\n @property\n def children(self):\n return self._children\n\n @property\n def data(self):\n return [c.data for c in self._children]\n\n def render_children(self):\n binds = {}\n for i, c in enumerate(self._children):\n txt = c.element.innerHTML\n rnd = str(time.time()).replace(\".\", \"\")[-5:]\n new_id = f\"{c.element.id}-{i}-{rnd}\"\n binds[new_id] = c.element.id\n txt = txt.replace(\">\", f\" id='{new_id}'>\")\n print(txt)\n\n def foo(evt):\n evtEl = evt.srcElement\n srcEl = Element(binds[evtEl.id])\n srcEl.element.onclick()\n evtEl.classList = srcEl.element.classList\n\n for new_id in binds:\n Element(new_id).element.onclick = foo\n\n def connect(self):\n self.md = main_div = document.createElement(\"div\")\n main_div.id = self._id + \"-list-tasks-container\"\n\n if self.theme:\n self.theme.theme_it(main_div)\n\n self.parent.appendChild(main_div)\n\n def add(self, *args, **kws):\n if not isinstance(args[0], self.item_class):\n child = self.item_class(*args, **kws)\n else:\n child = args[0]\n child.register_parent(self)\n return self._add(child)\n\n def _add(self, child_elem):\n self.pre_child_append(child_elem)\n child_elem.pre_append()\n self._children.append(child_elem)\n self.md.appendChild(child_elem.create().element)\n child_elem.post_append()\n self.child_appended(child_elem)\n return child_elem\n\n def pre_child_append(self, child):\n pass\n\n def child_appended(self, child):\n \"\"\"Overwrite me to define logic\"\"\"\n pass\n\n\nclass OutputCtxManager:\n def __init__(self, out=None, output_to_console=True, append=True):\n self._out = out\n self._prev = out\n self.output_to_console = output_to_console\n self._append = append\n\n def change(self, out=None, output_to_console=True, append=True):\n self._prev = self._out\n self._out = out\n self.output_to_console = output_to_console\n self._append = append\n\n def revert(self):\n self._out = self._prev\n\n def write(self, value):\n if self._out:\n Element(self._out).write(value, self._append)\n\n if self.output_to_console:\n console.info(value)\n\n\nclass OutputManager:\n def __init__(self, out=None, err=None, output_to_console=True, append=True):\n sys.stdout = self._out_manager = OutputCtxManager(\n out=out, output_to_console=output_to_console, append=append\n )\n sys.stderr = self._err_manager = OutputCtxManager(\n out=err, output_to_console=output_to_console, append=append\n )\n self.output_to_console = output_to_console\n self._append = append\n\n def change(self, out=None, err=None, output_to_console=True, append=True):\n self._out_manager.change(\n out=out, output_to_console=output_to_console, append=append\n )\n sys.stdout = self._out_manager\n self._err_manager.change(\n out=err, output_to_console=output_to_console, append=append\n )\n sys.stderr = self._err_manager\n self.output_to_console = output_to_console\n self._append = append\n\n def revert(self):\n self._out_manager.revert()\n self._err_manager.revert()\n sys.stdout = self._out_manager\n sys.stderr = self._err_manager\n\n\npyscript = PyScript()\noutput_manager = OutputManager()\n"; - - const logger$2 = getLogger('pyscript/pyodide'); - class PyodideRuntime extends Runtime { - src; - name; - lang; - interpreter; - globals; - constructor(src = 'https://cdn.jsdelivr.net/pyodide/v0.21.2/full/pyodide.js', name = 'pyodide-default', lang = 'python') { - logger$2.info('Runtime config:', { name, lang, src }); - super(); - this.src = src; - this.name = name; - this.lang = lang; - } - /** - * Although `loadPyodide` is used below, - * notice that it is not imported i.e. - * import { loadPyodide } from 'pyodide'; - * is not used at the top of this file. - * - * This is because, if it's used, loadPyodide - * behaves mischievously i.e. it tries to load - * `pyodide.asm.js` and `pyodide_py.tar` but - * with paths that are wrong such as: - * - * http://127.0.0.1:8080/build/pyodide_py.tar - * which results in a 404 since `build` doesn't - * contain these files and is clearly the wrong - * path. - */ - async loadInterpreter() { - logger$2.info('Loading pyodide'); - // eslint-disable-next-line - // @ts-ignore - this.interpreter = await loadPyodide({ - stdout: console.log, - stderr: console.log, - fullStdLib: false, - }); - this.globals = this.interpreter.globals; - // XXX: ideally, we should load micropip only if we actually need it - await this.loadPackage('micropip'); - logger$2.info('importing pyscript.py'); - await this.run(pyscript); - logger$2.info('pyodide loaded and initialized'); - } - async run(code) { - return await this.interpreter.runPythonAsync(code); - } - registerJsModule(name, module) { - this.interpreter.registerJsModule(name, module); - } - async loadPackage(names) { - logger$2.info(`pyodide.loadPackage: ${names.toString()}`); - await this.interpreter.loadPackage(names, logger$2.info.bind(logger$2), logger$2.info.bind(logger$2)); - } - async installPackage(package_name) { - if (package_name.length > 0) { - logger$2.info(`micropip install ${package_name.toString()}`); - const micropip = this.globals.get('micropip'); - await micropip.install(package_name); - micropip.destroy(); - } - } - async loadFromFile(path) { - const filename = getLastPath(path); - await this.run(` - from pyodide.http import pyfetch - from js import console - - try: - response = await pyfetch("${path}") - except Exception as err: - console.warn("PyScript: Access to local files (using 'paths:' in py-env) is not available when directly opening a HTML file; you must use a webserver to serve the additional files. See https://github.com/pyscript/pyscript/issues/257#issuecomment-1119595062 on starting a simple webserver with Python.") - raise(err) - content = await response.bytes() - with open("${filename}", "wb") as f: - f.write(content) - `); - } - } - - // Subscriber used to connect to the first available runtime (can be pyodide or others) - let runtimeSpec; - runtimeLoaded.subscribe(value => { - runtimeSpec = value; - }); - let appConfig_; - appConfig.subscribe(value => { - appConfig_ = value; - }); - const logger$1 = getLogger('py-config'); - /** - * Configures general metadata about the PyScript application such - * as a list of runtimes, name, version, closing the loader - * automatically, etc. - * - * Also initializes the different runtimes passed. If no runtime is passed, - * the default runtime based on Pyodide is used. - */ - class PyConfig extends BaseEvalElement { - widths; - label; - mount_name; - details; - operation; - values; - constructor() { - super(); - } - extractFromSrc(configType) { - if (this.hasAttribute('src')) { - logger$1.info('config set from src attribute'); - return validateConfig(readTextFromPath(this.getAttribute('src')), configType); - } - return {}; - } - extractFromInline(configType) { - if (this.innerHTML !== '') { - this.code = this.innerHTML; - this.innerHTML = ''; - logger$1.info('config set from inline'); - return validateConfig(this.code, configType); - } - return {}; - } - injectMetadata() { - this.values.pyscript = { - "version": version, - "time": new Date().toISOString() - }; - } - connectedCallback() { - const configType = this.hasAttribute("type") ? this.getAttribute("type") : "toml"; - let srcConfig = this.extractFromSrc(configType); - const inlineConfig = this.extractFromInline(configType); - // first make config from src whole if it is partial - srcConfig = mergeConfig(srcConfig, defaultConfig$1); - // then merge inline config and config from src - this.values = mergeConfig(inlineConfig, srcConfig); - this.injectMetadata(); - appConfig.set(this.values); - logger$1.info('config set:', this.values); - addInitializer(this.loadPackages); - addInitializer(this.loadPaths); - this.loadRuntimes(); - } - log(msg) { - const newLog = document.createElement('p'); - newLog.innerText = msg; - this.details.appendChild(newLog); - } - close() { - this.remove(); - } - loadPackages = async () => { - const env = appConfig_.packages; - logger$1.info("Loading env: ", env); - await runtimeSpec.installPackage(env); - }; - loadPaths = async () => { - const paths = appConfig_.paths; - logger$1.info("Paths to load: ", paths); - for (const singleFile of paths) { - logger$1.info(` loading path: ${singleFile}`); - try { - await runtimeSpec.loadFromFile(singleFile); - } - catch (e) { - //Should we still export full error contents to console? - handleFetchError(e, singleFile); - } - } - logger$1.info("All paths loaded"); - }; - loadRuntimes() { - logger$1.info('Initializing runtimes'); - for (const runtime of this.values.runtimes) { - const runtimeObj = new PyodideRuntime(runtime.src, runtime.name, runtime.lang); - const script = document.createElement('script'); // create a script DOM node - script.src = runtimeObj.src; // set its src to the provided URL - script.addEventListener('load', () => { - void runtimeObj.initialize(); - }); - document.head.appendChild(script); - } - } - } - - const logger = getLogger('pyscript/main'); - /* eslint-disable @typescript-eslint/no-unused-vars */ - customElements.define('py-script', PyScript); - customElements.define('py-loader', PyLoader); - customElements.define('py-config', PyConfig); - customElements.define('py-env', PyEnv); - /* eslint-disable @typescript-eslint/no-unused-vars */ - // As first thing, loop for application configs - logger.info('checking for py-config'); - const config = document.querySelector('py-config'); - if (!config) { - const loader = document.createElement('py-config'); - document.body.append(loader); - } - // add loader to the page body - logger.info('add py-loader'); - const loader = document.createElement('py-loader'); - document.body.append(loader); - globalLoader.set(loader); - -})(); +})({}); //# sourceMappingURL=pyscript.js.map diff --git a/examples/01_hello_world/resources/pyscript_bootstrap_templates-0.1.0-py3-none-any.whl b/examples/01_hello_world/resources/pyscript_bootstrap_templates-0.1.0-py3-none-any.whl index 7d580e9..19acf2b 100644 Binary files a/examples/01_hello_world/resources/pyscript_bootstrap_templates-0.1.0-py3-none-any.whl and b/examples/01_hello_world/resources/pyscript_bootstrap_templates-0.1.0-py3-none-any.whl differ diff --git a/examples/01_hello_world/resources/pyscript_bootstrap_templates-0.2.0-py3-none-any.whl b/examples/01_hello_world/resources/pyscript_bootstrap_templates-0.2.0-py3-none-any.whl new file mode 100644 index 0000000..e1a2da0 Binary files /dev/null and b/examples/01_hello_world/resources/pyscript_bootstrap_templates-0.2.0-py3-none-any.whl differ diff --git a/examples/01_hello_world/serviceWorker.js b/examples/01_hello_world/serviceWorker.js index 48c1c7d..106a7b1 100644 --- a/examples/01_hello_world/serviceWorker.js +++ b/examples/01_hello_world/serviceWorker.js @@ -1,5 +1,5 @@ -const pwa_version = "01_hello_world_202210161638" +const pwa_version = "01_hello_world_202306031006" const assets = ["./index.html", "./main.py", "./resources/bootstrap.css", @@ -7,7 +7,7 @@ const assets = ["./index.html", "./resources/pyscript.css", "./resources/pyscript.js", "./resources/pyscript.py", - "./resources/pyscript_bootstrap_templates-0.1.0-py3-none-any.whl", + "./resources/pyscript_bootstrap_templates-0.2.0-py3-none-any.whl", "./resources/pwa.js", "./site.js", ] diff --git a/examples/02_image_filter/config.json b/examples/02_image_filter/config.json index bcaef3f..3bf1990 100644 --- a/examples/02_image_filter/config.json +++ b/examples/02_image_filter/config.json @@ -11,7 +11,7 @@ "pyscript_py_url": "https://pyscript.net/latest/pyscript.py", "bootstrap_css_url": "https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css", "bootstrap_js_url": "https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js", - "pyscript_bootstrap_templates_wheel_url": "../dist/pyscript_bootstrap_templates-0.1.0-py3-none-any.whl", + "pyscript_bootstrap_templates_wheel_url": "../dist/pyscript_bootstrap_templates-0.2.0-py3-none-any.whl", "pwa_bg_color": "#000000", "pwa_theme_color": "#ffffff" } \ No newline at end of file diff --git a/examples/02_image_filter/index.html b/examples/02_image_filter/index.html index b2b1e4b..dd0de16 100644 --- a/examples/02_image_filter/index.html +++ b/examples/02_image_filter/index.html @@ -19,9 +19,11 @@ <body style="width: 100%; height: 100%"> <py-config type="json"> { - "autoclose_loader": true, + "splashscreen": { + "autoclose": true + }, "packages": [ - "./resources/pyscript_bootstrap_templates-0.1.0-py3-none-any.whl", + "./resources/pyscript_bootstrap_templates-0.2.0-py3-none-any.whl", "numpy", "scikit-image" ], diff --git a/examples/02_image_filter/resources/pyscript.css b/examples/02_image_filter/resources/pyscript.css index be94299..10a1f1c 100644 --- a/examples/02_image_filter/resources/pyscript.css +++ b/examples/02_image_filter/resources/pyscript.css @@ -1,9 +1,35 @@ -:not(:defined) { - display: none +/* py-config - not a component */ +py-config { + display: none; +} +/* py-{el} - components not defined */ +py-script:not(:defined) { + display: none; } -html{ - font-family: ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, "Noto Sans", sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji"; +py-repl:not(:defined) { + display: none; +} + +py-title:not(:defined) { + display: none; +} + +py-inputbox:not(:defined) { + display: none; +} + +py-button:not(:defined) { + display: none; +} + +py-box:not(:defined) { + display: none; +} + +html { + font-family: ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', + Arial, 'Noto Sans', sans-serif, 'Apple Color Emoji', 'Segoe UI Emoji', 'Segoe UI Symbol', 'Noto Color Emoji'; line-height: 1.5; } @@ -24,6 +50,7 @@ html{ border-right: 4px solid rgba(255, 255, 255, 0); animation: spinner 0.6s linear infinite; } + @keyframes spinner { to { transform: rotate(360deg); @@ -81,27 +108,68 @@ html{ right: 5%; } -.py-box{ +/* Pop-up second layer end */ +.alert-banner { + position: relative; + padding: 0.5rem 1.5rem 0.5rem 0.5rem; + margin: 5px 0; +} + +.alert-banner p { + margin: 0; +} + +.py-error { + background-color: #ffe9e8; + border: solid; + border-color: #f0625f; + color: #9d041c; +} + +.py-warning { + background-color: rgb(255, 244, 229); + border: solid; + border-color: #ffa016; + color: #794700; +} + +.alert-banner.py-error > #alert-close-button { + color: #9d041c; +} + +.alert-banner.py-warning > #alert-close-button { + color: #794700; +} + +#alert-close-button { + position: absolute; + right: 0.5rem; + top: 0.5rem; + cursor: pointer; + background: transparent; + border: none; +} + +.py-box { display: flex; flex-direction: row; justify-content: flex-start; } -.py-box div.py-box-child * -{ +.py-box div.py-box-child * { max-width: 100%; } -.py-repl-box{ +.py-repl-box { flex-direction: column; } -.editor-box{ +.py-repl-editor { --tw-border-opacity: 1; border-color: rgba(209, 213, 219, var(--tw-border-opacity)); border-width: 1px; position: relative; - --tw-ring-inset: var(--tw-empty,/*!*/ /*!*/); + --tw-ring-inset: var(--tw-empty, /*!*/ /*!*/); --tw-ring-offset-width: 0px; --tw-ring-offset-color: #fff; --tw-ring-color: rgba(59, 130, 246, 0.5); @@ -113,14 +181,14 @@ html{ box-sizing: border-box; border-width: 1px; border-style: solid; - border-color: rgb(209, 213, 219) + border-color: rgb(209, 213, 219); } -.editor-box:hover button{ +.editor-box:hover button { opacity: 1; } -.repl-play-button{ +.py-repl-run-button { opacity: 0; bottom: 0.25rem; right: 0.25rem; @@ -154,65 +222,64 @@ html{ border: 0; } -.repl-play-button:hover{ +.py-repl-run-button:hover { opacity: 1; } -.py-title{ +.py-title { text-transform: uppercase; text-align: center; } -.py-title h1{ +.py-title h1 { font-weight: 700; font-size: 1.875rem; } -.py-input{ +.py-input { padding: 0.5rem; --tw-border-opacity: 1; border-color: rgba(209, 213, 219, var(--tw-border-opacity)); border-width: 1px; - border-radius: 0.25rem; + border-radius: 0.25rem; margin-right: 0.75rem; border-style: solid; width: auto; } -.py-box input.py-input{ +.py-box input.py-input { width: -webkit-fill-available; } -.central-content{ +.central-content { max-width: 20rem; margin-left: auto; margin-right: auto; } input { - text-rendering: auto; - color: -internal-light-dark(black, white); - letter-spacing: normal; - word-spacing: normal; - line-height: normal; - text-transform: none; - text-indent: 0px; - text-shadow: none; - display: inline-block; - text-align: start; - appearance: auto; - -webkit-rtl-ordering: logical; - cursor: text; - background-color: -internal-light-dark(rgb(255, 255, 255), rgb(59, 59, 59)); - margin: 0em; - padding: 1px 2px; - border-width: 2px; - border-style: inset; - border-color: -internal-light-dark(rgb(118, 118, 118), rgb(133, 133, 133)); - border-image: initial; + text-rendering: auto; + color: -internal-light-dark(black, white); + letter-spacing: normal; + word-spacing: normal; + line-height: normal; + text-transform: none; + text-indent: 0px; + text-shadow: none; + display: inline-block; + text-align: start; + appearance: auto; + -webkit-rtl-ordering: logical; + background-color: -internal-light-dark(rgb(255, 255, 255), rgb(59, 59, 59)); + margin: 0em; + padding: 1px 2px; + border-width: 2px; + border-style: inset; + border-color: -internal-light-dark(rgb(118, 118, 118), rgb(133, 133, 133)); + border-image: initial; } -.py-button{ +.py-button { --tw-text-opacity: 1; color: rgba(255, 255, 255, var(--tw-text-opacity)); padding: 0.5rem; @@ -222,17 +289,22 @@ input { border-color: rgba(37, 99, 235, var(--tw-border-opacity)); border-width: 1px; border-radius: 0.25rem; + cursor: pointer; } -.py-li-element p{ +.py-li-element p { margin: 5px; } -.py-li-element p{ +.py-li-element p { display: inline; } -button, input, optgroup, select, textarea { +button, +input, +optgroup, +select, +textarea { font-family: inherit; font-size: 100%; line-height: 1.15; @@ -242,3 +314,19 @@ button, input, optgroup, select, textarea { .line-through { text-decoration: line-through; } + +/* ===== py-terminal plugin ===== */ +/* XXX: it would be nice if these rules were stored in e.g. pyterminal.css and + bundled together at build time (by rollup?) */ + +.py-terminal { + min-height: 10em; + background-color: black; + color: white; + padding: 0.5rem; + overflow: auto; +} + +.py-terminal-hidden { + display: none; +} diff --git a/examples/02_image_filter/resources/pyscript.js b/examples/02_image_filter/resources/pyscript.js index e9b92a0..4bc0b89 100644 --- a/examples/02_image_filter/resources/pyscript.js +++ b/examples/02_image_filter/resources/pyscript.js @@ -1,4167 +1,28471 @@ -(function () { - 'use strict'; +var pyscript = (function (exports) { + 'use strict'; - function noop() { } - function safe_not_equal(a, b) { - return a != a ? b == b : a !== b || ((a && typeof a === 'object') || typeof a === 'function'); + var parser$2 = /* + * Generated by PEG.js 0.10.0. + * + * http://pegjs.org/ + */ + (function() { + + function peg$subclass(child, parent) { + function ctor() { this.constructor = child; } + ctor.prototype = parent.prototype; + child.prototype = new ctor(); } - Promise.resolve(); - const subscriber_queue = []; - /** - * Create a `Writable` store that allows both updating and reading by subscription. - * @param {*=}value initial value - * @param {StartStopNotifier=}start start and stop notifications for subscriptions - */ - function writable(value, start = noop) { - let stop; - const subscribers = new Set(); - function set(new_value) { - if (safe_not_equal(value, new_value)) { - value = new_value; - if (stop) { // store is ready - const run_queue = !subscriber_queue.length; - for (const subscriber of subscribers) { - subscriber[1](); - subscriber_queue.push(subscriber, value); - } - if (run_queue) { - for (let i = 0; i < subscriber_queue.length; i += 2) { - subscriber_queue[i][0](subscriber_queue[i + 1]); - } - subscriber_queue.length = 0; - } - } + function peg$SyntaxError(message, expected, found, location) { + this.message = message; + this.expected = expected; + this.found = found; + this.location = location; + this.name = "SyntaxError"; + + if (typeof Error.captureStackTrace === "function") { + Error.captureStackTrace(this, peg$SyntaxError); + } + } + + peg$subclass(peg$SyntaxError, Error); + + peg$SyntaxError.buildMessage = function(expected, found) { + var DESCRIBE_EXPECTATION_FNS = { + literal: function(expectation) { + return "\"" + literalEscape(expectation.text) + "\""; + }, + + "class": function(expectation) { + var escapedParts = "", + i; + + for (i = 0; i < expectation.parts.length; i++) { + escapedParts += expectation.parts[i] instanceof Array + ? classEscape(expectation.parts[i][0]) + "-" + classEscape(expectation.parts[i][1]) + : classEscape(expectation.parts[i]); + } + + return "[" + (expectation.inverted ? "^" : "") + escapedParts + "]"; + }, + + any: function(expectation) { + return "any character"; + }, + + end: function(expectation) { + return "end of input"; + }, + + other: function(expectation) { + return expectation.description; } + }; + + function hex(ch) { + return ch.charCodeAt(0).toString(16).toUpperCase(); + } + + function literalEscape(s) { + return s + .replace(/\\/g, '\\\\') + .replace(/"/g, '\\"') + .replace(/\0/g, '\\0') + .replace(/\t/g, '\\t') + .replace(/\n/g, '\\n') + .replace(/\r/g, '\\r') + .replace(/[\x00-\x0F]/g, function(ch) { return '\\x0' + hex(ch); }) + .replace(/[\x10-\x1F\x7F-\x9F]/g, function(ch) { return '\\x' + hex(ch); }); + } + + function classEscape(s) { + return s + .replace(/\\/g, '\\\\') + .replace(/\]/g, '\\]') + .replace(/\^/g, '\\^') + .replace(/-/g, '\\-') + .replace(/\0/g, '\\0') + .replace(/\t/g, '\\t') + .replace(/\n/g, '\\n') + .replace(/\r/g, '\\r') + .replace(/[\x00-\x0F]/g, function(ch) { return '\\x0' + hex(ch); }) + .replace(/[\x10-\x1F\x7F-\x9F]/g, function(ch) { return '\\x' + hex(ch); }); + } + + function describeExpectation(expectation) { + return DESCRIBE_EXPECTATION_FNS[expectation.type](expectation); + } + + function describeExpected(expected) { + var descriptions = new Array(expected.length), + i, j; + + for (i = 0; i < expected.length; i++) { + descriptions[i] = describeExpectation(expected[i]); } - function update(fn) { - set(fn(value)); - } - function subscribe(run, invalidate = noop) { - const subscriber = [run, invalidate]; - subscribers.add(subscriber); - if (subscribers.size === 1) { - stop = start(set) || noop; + + descriptions.sort(); + + if (descriptions.length > 0) { + for (i = 1, j = 1; i < descriptions.length; i++) { + if (descriptions[i - 1] !== descriptions[i]) { + descriptions[j] = descriptions[i]; + j++; } - run(value); - return () => { - subscribers.delete(subscriber); - if (subscribers.size === 0) { - stop(); - stop = null; - } - }; + } + descriptions.length = j; } - return { set, update, subscribe }; - } - /* Very simple logger interface. + switch (descriptions.length) { + case 1: + return descriptions[0]; - Each module is expected to create its own logger by doing e.g.: + case 2: + return descriptions[0] + " or " + descriptions[1]; - const logger = getLogger('my-prefix'); - - and then use it instead of console: - - logger.info('hello', 'world'); - logger.warn('...'); - logger.error('...'); - - The logger automatically adds the prefix "[my-prefix]" to all logs; so e.g., the - above call would print: - - [my-prefix] hello world - - logger.log is intentionally omitted. The idea is that PyScript should not - write anything to console.log, to leave it free for the user. - - Currently, the logger does not to anything more than that. In the future, - we might want to add additional features such as the ability to - enable/disable logs on a global or per-module basis. - */ - const _cache = new Map(); - function getLogger(prefix) { - let logger = _cache.get(prefix); - if (logger === undefined) { - logger = _makeLogger(prefix); - _cache.set(prefix, logger); + default: + return descriptions.slice(0, -1).join(", ") + + ", or " + + descriptions[descriptions.length - 1]; } - return logger; - } - function _makeLogger(prefix) { - prefix = "[" + prefix + "] "; - function make(level) { - const out_fn = console[level].bind(console); - function fn(fmt, ...args) { - out_fn(prefix + fmt, ...args); - } - return fn; - } - // 'log' is intentionally omitted - const debug = make('debug'); - const info = make('info'); - const warn = make('warn'); - const error = make('error'); - return { debug, info, warn, error }; - } + } - /* - A store for Runtime which can encompass any - runtime, but currently only has Pyodide as its offering. - */ - const runtimeLoaded = writable(); - const loadedEnvironments = writable({}); - const scriptsQueue = writable([]); - const initializers = writable([]); - const postInitializers = writable([]); - const globalLoader = writable(); - const appConfig = writable(); - const addToScriptsQueue = (script) => { - scriptsQueue.update(scriptsQueue => [...scriptsQueue, script]); - }; - const addInitializer = (initializer) => { - initializers.update(initializers => [...initializers, initializer]); - }; - const addPostInitializer = (initializer) => { - postInitializers.update(postInitializers => [...postInitializers, initializer]); + function describeFound(found) { + return found ? "\"" + literalEscape(found) + "\"" : "end of input"; + } + + return "Expected " + describeExpected(expected) + " but " + describeFound(found) + " found."; }; - // taken from https://github.com/Gin-Quin/fast-toml - let e = "", t$1 = 0; - function i$2(e, t = 0) { - let i; - for (; (i = e[t++]) && (" " == i || "\t" == i || "\r" == i);) - ; - return t - 1; - } - function n(e) { - switch (e[0]) { - case void 0: - return ""; - case '"': - return (function (e) { - let t, i = 0, n = ""; - for (; (t = e.indexOf("\\", i) + 1);) { - switch (((n += e.slice(i, t - 1)), e[t])) { - case "\\": - n += "\\"; - break; - case '"': - n += '"'; - break; - case "\r": - "\n" == e[t + 1] && t++; - case "\n": - break; - case "b": - n += "\b"; - break; - case "t": - n += "\t"; - break; - case "n": - n += "\n"; - break; - case "f": - n += "\f"; - break; - case "r": - n += "\r"; - break; - case "u": - (n += String.fromCharCode(parseInt(e.substr(t + 1, 4), 16))), (t += 4); - break; - case "U": - (n += String.fromCharCode(parseInt(e.substr(t + 1, 8), 16))), (t += 8); - break; - default: - throw r(e[t]); - } - i = t + 1; + function peg$parse(input, options) { + options = options !== void 0 ? options : {}; + + var peg$FAILED = {}, + + peg$startRuleFunctions = { Expressions: peg$parseExpressions }, + peg$startRuleFunction = peg$parseExpressions, + + peg$c0 = function() { + return g_root; + }, + peg$c1 = function(path) { + g_context = findContext(g_root, true, path); + }, + peg$c2 = function(path) { + g_context = findContext(g_root, false, path); + }, + peg$c3 = function(keyValue) { + checkTableKey(g_context.table, keyValue[0]); + g_context.table[keyValue[0]] = keyValue[1]; + }, + peg$c4 = peg$otherExpectation("Newline"), + peg$c5 = "\n", + peg$c6 = peg$literalExpectation("\n", false), + peg$c7 = "\r\n", + peg$c8 = peg$literalExpectation("\r\n", false), + peg$c9 = peg$otherExpectation("Whitespace"), + peg$c10 = /^[ \t]/, + peg$c11 = peg$classExpectation([" ", "\t"], false, false), + peg$c12 = peg$otherExpectation("Comment"), + peg$c13 = "#", + peg$c14 = peg$literalExpectation("#", false), + peg$c15 = peg$anyExpectation(), + peg$c16 = "=", + peg$c17 = peg$literalExpectation("=", false), + peg$c18 = function(key, value) { + return [key, value.value]; + }, + peg$c19 = function() { + return text(); + }, + peg$c20 = peg$otherExpectation("[a-z], [A-Z], [0-9], \"-\", \"_\""), + peg$c21 = /^[a-zA-Z0-9\-_]/, + peg$c22 = peg$classExpectation([["a", "z"], ["A", "Z"], ["0", "9"], "-", "_"], false, false), + peg$c23 = function(chars) { + return chars.join(''); + }, + peg$c24 = peg$otherExpectation("DoubleQuote"), + peg$c25 = "\"", + peg$c26 = peg$literalExpectation("\"", false), + peg$c27 = peg$otherExpectation("SingleQuote"), + peg$c28 = "'", + peg$c29 = peg$literalExpectation("'", false), + peg$c30 = peg$otherExpectation("ThreeDoubleQuotes"), + peg$c31 = "\"\"\"", + peg$c32 = peg$literalExpectation("\"\"\"", false), + peg$c33 = peg$otherExpectation("ThreeSingleQuotes"), + peg$c34 = "'''", + peg$c35 = peg$literalExpectation("'''", false), + peg$c36 = function(chars) { + return { + type: 'String', + value: chars.join('') + }; + }, + peg$c37 = peg$otherExpectation("NormalCharacter"), + peg$c38 = /^[^\0-\x1F"\\]/, + peg$c39 = peg$classExpectation([["\0", "\x1F"], "\"", "\\"], true, false), + peg$c40 = "u", + peg$c41 = peg$literalExpectation("u", false), + peg$c42 = "U", + peg$c43 = peg$literalExpectation("U", false), + peg$c44 = function() { + var s = text(); + if (s.length <= 2) { + return unescape(s[1]); + } + return fromCodePoint(parseInt(s.substr(2), 16)); + }, + peg$c45 = peg$otherExpectation("\"b\", \"f\", \"n\", \"r\", \"t\""), + peg$c46 = /^[bfnrt]/, + peg$c47 = peg$classExpectation(["b", "f", "n", "r", "t"], false, false), + peg$c48 = peg$otherExpectation("Backslash"), + peg$c49 = "\\", + peg$c50 = peg$literalExpectation("\\", false), + peg$c51 = peg$otherExpectation("FourHexadecimalDigits"), + peg$c52 = peg$otherExpectation("EightHexadecimalDigits"), + peg$c53 = /^[0-9A-Fa-f]/, + peg$c54 = peg$classExpectation([["0", "9"], ["A", "F"], ["a", "f"]], false, false), + peg$c55 = function() { + var s = text(); + return { + type: 'String', + value: s.substr(1, s.length - 2) + }; + }, + peg$c56 = /^[^\0-\x08\n-\x1F']/, + peg$c57 = peg$classExpectation([["\0", "\b"], ["\n", "\x1F"], "'"], true, false), + peg$c58 = function(chars) { + return { + type: 'String', + value: chars.join('').replace(/\\\r?\n(?:\r?\n|[ \t])*/g, '') + }; + }, + peg$c59 = /^[^\0-\x1F\\]/, + peg$c60 = peg$classExpectation([["\0", "\x1F"], "\\"], true, false), + peg$c61 = peg$otherExpectation("AnyCharacter"), + peg$c62 = /^[^\0-\x08\n-\x1F]/, + peg$c63 = peg$classExpectation([["\0", "\b"], ["\n", "\x1F"]], true, false), + peg$c64 = "true", + peg$c65 = peg$literalExpectation("true", false), + peg$c66 = function() { + return { + type: 'Boolean', + value: true + }; + }, + peg$c67 = "false", + peg$c68 = peg$literalExpectation("false", false), + peg$c69 = function() { + return { + type: 'Boolean', + value: false + }; + }, + peg$c70 = function() { + // A double-precision 64-bit floating-point number in IEEE 754 standard. + var s = text(); + var number = parseFloat(s.replace(/_/g, '')); + if (!isFiniteNumber(number)) { + error(s + 'is not a 64-bit floating-point number.'); + } + return { + type: 'Float', + value: number + }; + }, + peg$c71 = ".", + peg$c72 = peg$literalExpectation(".", false), + peg$c73 = "_", + peg$c74 = peg$literalExpectation("_", false), + peg$c75 = "e", + peg$c76 = peg$literalExpectation("e", false), + peg$c77 = "E", + peg$c78 = peg$literalExpectation("E", false), + peg$c79 = function() { + // Be careful of JavaScript limits: + // 1) Number.MAX_SAFE_INTEGER = 9007199254740991 + // 2) Number.MIN_SAFE_INTEGER = -9007199254740991 + var s = text(); + var number = s.replace(/_/g, ''); + // Check if it is a 64-bit signed integer. + var invalid = false; + if (number[0] === '-') { + var minInt = '-9223372036854775808'; + if (number.length > minInt.length || + (number.length === minInt.length && number > minInt)) { + invalid = true; } - return n + e.slice(i); - })(e.slice(1, -1)); - case "'": - return e.slice(1, -1); - case "0": - case "1": - case "2": - case "3": - case "4": - case "5": - case "6": - case "7": - case "8": - case "9": - case "+": - case "-": - case ".": - let t = e; - if ((-1 != t.indexOf("_") && (t = t.replace(/_/g, "")), !isNaN(t))) - return +t; - if ("-" == e[4] && "-" == e[7]) { - let t = new Date(e); - if ("Invalid Date" != t.toString()) - return t; - } - else if (":" == e[2] && ":" == e[5] && e.length >= 7) { - let t = new Date("0000-01-01T" + e + "Z"); - if ("Invalid Date" != t.toString()) - return t; - } - return e; - } - switch (e) { - case "true": - return !0; - case "false": - return !1; - case "nan": - case "NaN": - return !1; - case "null": - return null; - case "inf": - case "+inf": - case "Infinity": - case "+Infinity": - return 1 / 0; - case "-inf": - case "-Infinity": - return -1 / 0; - } - return e; - } - function r(i) { - let n = (function () { - let i = e[t$1], n = t$1; - "\n" == i && n--; - let r = 1, s = e.lastIndexOf("\n", n), a = e.indexOf("\n", n); - -1 == a && (a = 1 / 0); - ("," != i && "\n" != i) || (n = s + 1); - if (-1 == s) - return { line: r, column: n + 1, position: n, lineContent: e.slice(0, a).trim() }; - const c = n - s + 1, o = e.slice(s + 1, a).trim(); - r++; - for (; -1 != (s = e.lastIndexOf("\n", s - 1));) - r++; - return { line: r, column: c, position: n, lineContent: o }; - })(), r = String(n.line); - return (i += "\n" + r + " | " + n.lineContent + "\n"), (i += " ".repeat(r.length + n.column + 2) + "^"), SyntaxError(i); - } - function s(e, i = 0, n = !1) { - let a, c = e[i], o = c, f = c, l = !0, u = !1; - switch (c) { - case '"': - case "'": - if (((a = i + 1), n && e[i + 1] == c && e[i + 2] == c ? ((f = c + c + c), (a += 2)) : (u = !0), "'" == c)) - a = e.indexOf(f, a) + 1; - else - for (; (a = e.indexOf(f, a) + 1);) { - let t = !0, i = a - 1; - for (; "\\" == e[--i];) - t = !t; - if (t) - break; + } else { + if (number[0] === '+') { + number = number.substr(1); } - if (!a) - throw r("Missing " + f + " closer"); - if (c != f) - a += 2; - else if (u) { - let n = e.indexOf("\n", i + 1) + 1; - if (n && n < a) - throw ((t$1 = n - 2), r("Forbidden end-of-line character in single-line string")); - } - return a; - case "(": - f = ")"; - break; - case "{": - f = "}"; - break; - case "[": - f = "]"; - break; - case "<": - f = ">"; - break; - default: - l = !1; - } - let h = 0; - for (; (c = e[++i]);) - if (c == f) { - if (0 == h) - return i + 1; - h--; - } - else if ('"' == c || "'" == c) { - i = s(e, i, n) - 1; - } - else - l && c == o && h++; - throw r("Missing " + f); - } - function a(e) { - "string" != typeof e && (e = String(e)); - let t, i, n = -1, a = "", c = []; - for (; (i = e[++n]);) - switch (i) { - case ".": - if (!a) - throw r('Unexpected "."'); - c.push(a), (a = ""); - continue; - case '"': - case "'": - if (((t = s(e, n)), t == n + 2)) - throw r("Empty string key"); - (a += e.slice(n + 1, t - 1)), (n = t - 1); - continue; - default: - a += i; - } - return a && c.push(a), c; - } - function c(e, t = []) { - const i = t.pop(); - for (let i of t) { - if ("object" != typeof e) { - throw r('["' + t.slice(0, t.indexOf(i) + 1).join('"].["') + '"]' + " must be an object"); - } - void 0 === e[i] && (e[i] = {}), (e = e[i]) instanceof Array && (e = e[e.length - 1]); - } - return [e, i]; - } - class o { - root; - data; - inlineScopeList; - constructor() { - this.root = {}; - this.data = this.root; - this.inlineScopeList = []; - } - get isRoot() { - return this.data == this.root; - } - set(e, t) { - let [i, n] = c(this.data, a(e)); - if ("string" == typeof i) - throw "Wtf the scope is a string. Please report the bug"; - if (n in i) - throw r(`Re-writing the key '${e}'`); - return (i[n] = t), t; - } - push(e) { - if (!(this.data instanceof Array)) { - if (!this.isRoot) - throw r("Missing key"); - (this.data = Object.assign([], this.data)), (this.root = this.data); - } - return this.data.push(e), this; - } - use(e) { - return ((this.data = (function (e, t = []) { - for (let i of t) { - //if (void 0 === e) e = lastData[lastElt] = {}; - //else - if ("object" != typeof e) { - throw r('["' + t.slice(0, t.indexOf(i) + 1).join('"].["') + '"]' + " must be an object"); + var maxInt = '9223372036854775807'; + if (number.length > maxInt.length || + (number.length === maxInt.length && number > maxInt)) { + invalid = true; } - void 0 === e[i] && (e[i] = {}), (e = e[i]) instanceof Array && (e = e[e.length - 1]); - } - return e; - })(this.root, a(e))), - this); + } + if (invalid) { + error(s + ' is not a 64-bit signed integer.'); + } + number = parseInt(number, 10); + if (!isFiniteNumber(number)) { + error(s + ' is not a 64-bit signed integer.'); + } + return { + type: 'Integer', + value: number + }; + }, + peg$c80 = "+", + peg$c81 = peg$literalExpectation("+", false), + peg$c82 = "-", + peg$c83 = peg$literalExpectation("-", false), + peg$c84 = /^[1-9]/, + peg$c85 = peg$classExpectation([["1", "9"]], false, false), + peg$c86 = /^[0-9]/, + peg$c87 = peg$classExpectation([["0", "9"]], false, false), + peg$c88 = "T", + peg$c89 = peg$literalExpectation("T", false), + peg$c90 = function() { + var s = text(); + var date = new Date(s); + if (!isFiniteNumber(date.getTime())) { + error('Date-time ' + s + ' is invalid. It does not conform to RFC 3339 or this is a browser-specific problem.'); + } + return { + type: 'DateTime', + value: date + }; + }, + peg$c91 = peg$otherExpectation("FullDate (YYYY-mm-dd)"), + peg$c92 = ":", + peg$c93 = peg$literalExpectation(":", false), + peg$c94 = peg$otherExpectation("Hour (HH)"), + peg$c95 = peg$otherExpectation("Minute (MM)"), + peg$c96 = peg$otherExpectation("Second (SS)"), + peg$c97 = peg$otherExpectation("TimeOffset (Z or +/-HH:MM)"), + peg$c98 = "Z", + peg$c99 = peg$literalExpectation("Z", false), + peg$c100 = "[", + peg$c101 = peg$literalExpectation("[", false), + peg$c102 = ",", + peg$c103 = peg$literalExpectation(",", false), + peg$c104 = "]", + peg$c105 = peg$literalExpectation("]", false), + peg$c106 = function(values) { + var o = { + type: 'Array', + value: values ? values[0] : [] + }; + for (var i = 0, arr = o.value, l = arr.length; i < l; i++) { + arr[i] = arr[i].value; + } + return o; + }, + peg$c107 = function(value, opt) { + var array = [value]; + if (opt) { + var type = value.type; + for (var i = 0, arr = opt[3], l = arr.length; i < l; i++) { + if (type !== arr[i].type) { + error(stringify(arr[i].value) + ' should be of type "' + type + + '".'); + } + array.push(arr[i]); + } + } + return array; + }, + peg$c108 = "{", + peg$c109 = peg$literalExpectation("{", false), + peg$c110 = "}", + peg$c111 = peg$literalExpectation("}", false), + peg$c112 = function(opt) { + var table = {}; + if (opt) { + table[opt[0][0]] = opt[0][1]; + for (var i = 0, arr = opt[1], l = arr.length; i < l; i++) { + var kv = arr[i][3]; + checkTableKey(table, kv[0]); + table[kv[0]] = kv[1]; + } + } + return { + type: 'InlineTable', + value: table + }; + }, + peg$c113 = function(path) { + return path; + }, + peg$c114 = function(key, arr) { + var path = [key]; + for (var i = 0, l = arr.length; i < l; i++) { + path.push(arr[i][3]); + } + return path; + }, + + peg$currPos = 0, + peg$savedPos = 0, + peg$posDetailsCache = [{ line: 1, column: 1 }], + peg$maxFailPos = 0, + peg$maxFailExpected = [], + peg$silentFails = 0, + + peg$result; + + if ("startRule" in options) { + if (!(options.startRule in peg$startRuleFunctions)) { + throw new Error("Can't start parsing from rule \"" + options.startRule + "\"."); } - useArray(e) { - let [t, i] = c(this.root, a(e)); - return (this.data = {}), void 0 === t[i] && (t[i] = []), t[i].push(this.data), this; - } - enter(e, t) { - return this.inlineScopeList.push(this.data), this.set(e, t), (this.data = t), this; - } - enterArray(e) { - return this.inlineScopeList.push(this.data), this.push(e), (this.data = e), this; - } - exit() { - return (this.data = this.inlineScopeList.pop()), this; - } - } - function f(a) { - "string" != typeof a && (a = String(a)); - const c = new o(), f = []; - (e = a), (t$1 = 0); - let l, u, h = "", d = "", p = e[0], w = !0; - const g = () => { - if (((h = h.trimEnd()), w)) - h && c.push(n(h)); - else { - if (!h) - throw r("Expected key before ="); - if (!d) - throw r("Expected value after ="); - c.set(h, n(d.trimEnd())); + + peg$startRuleFunction = peg$startRuleFunctions[options.startRule]; + } + + function text() { + return input.substring(peg$savedPos, peg$currPos); + } + + function error(message, location) { + location = location !== void 0 ? location : peg$computeLocation(peg$savedPos, peg$currPos); + + throw peg$buildSimpleError(message, location); + } + + function peg$literalExpectation(text, ignoreCase) { + return { type: "literal", text: text, ignoreCase: ignoreCase }; + } + + function peg$classExpectation(parts, inverted, ignoreCase) { + return { type: "class", parts: parts, inverted: inverted, ignoreCase: ignoreCase }; + } + + function peg$anyExpectation() { + return { type: "any" }; + } + + function peg$endExpectation() { + return { type: "end" }; + } + + function peg$otherExpectation(description) { + return { type: "other", description: description }; + } + + function peg$computePosDetails(pos) { + var details = peg$posDetailsCache[pos], p; + + if (details) { + return details; + } else { + p = pos - 1; + while (!peg$posDetailsCache[p]) { + p--; + } + + details = peg$posDetailsCache[p]; + details = { + line: details.line, + column: details.column + }; + + while (p < pos) { + if (input.charCodeAt(p) === 10) { + details.line++; + details.column = 1; + } else { + details.column++; } - (h = ""), (d = ""), (w = !0); + + p++; + } + + peg$posDetailsCache[pos] = details; + return details; + } + } + + function peg$computeLocation(startPos, endPos) { + var startPosDetails = peg$computePosDetails(startPos), + endPosDetails = peg$computePosDetails(endPos); + + return { + start: { + offset: startPos, + line: startPosDetails.line, + column: startPosDetails.column + }, + end: { + offset: endPos, + line: endPosDetails.line, + column: endPosDetails.column + } }; - do { - switch (p) { - case " ": - w ? h && (h += p) : d && (d += p); - case "\t": - case "\r": - continue; - case "#": - (t$1 = e.indexOf("\n", t$1 + 1) - 1), -2 == t$1 && (t$1 = 1 / 0); - continue; - case '"': - case "'": - if (!w && d) { - d += p; - continue; - } - let n = e[t$1 + 1] == p && e[t$1 + 2] == p; - if (((l = s(e, t$1, !0)), w)) { - if (h) - throw r("Unexpected " + p); - (h += n ? e.slice(t$1 + 2, l - 2) : e.slice(t$1, l)), (t$1 = l); - } - else - (d = e.slice(t$1, l)), (t$1 = l), n && ((d = d.slice(2, -2)), "\n" == d[1] ? (d = d[0] + d.slice(2)) : "\r" == d[1] && "\n" == d[2] && (d = d[0] + d.slice(3))); - if (((t$1 = i$2(e, t$1)), (p = e[t$1]), p && "," != p && "\n" != p && "#" != p && "}" != p && "]" != p && "=" != p)) - throw r("Unexpected character after end of string"); - t$1--; - continue; - case "\n": - case ",": - case void 0: - g(); - continue; - case "[": - case "{": - if (((u = "[" == p ? "]" : "}"), w && !f.length)) { - if (h) - throw r("Unexpected " + p); - if (((l = s(e, t$1)), "[" == p && "[" == e[t$1 + 1])) { - if ("]" != e[l - 2]) - throw r("Missing ]]"); - c.useArray(e.slice(t$1 + 2, l - 2)); - } - else - c.use(e.slice(t$1 + 1, l - 1)); - t$1 = l; - } - else if (w) { - if (h) - throw r("Unexpected " + p); - c.enterArray("[" == p ? [] : {}), f.push(u); - } - else { - if (d) - throw r("Unexpected " + p); - c.enter(h.trimEnd(), "[" == p ? [] : {}), f.push(u), (h = ""), (w = !0); - } - continue; - case "]": - case "}": - if ((h && g(), f.pop() != p)) - throw r("Unexpected " + p); - if ((c.exit(), (t$1 = i$2(e, t$1 + 1)), (p = e[t$1]), p && "," != p && "\n" != p && "#" != p && "}" != p && "]" != p)) - throw r("Unexpected character after end of scope"); - t$1--; - continue; - case "=": - if (!w) - throw r("Unexpected " + p); - if (!h) - throw r("Missing key before " + p); - w = !1; - continue; - default: - w ? (h += p) : (d += p); - } - } while ((p = e[++t$1]) || h); - if (f.length) - throw r("Missing " + f.pop()); - return c.root; - } - function h() { - let e = ""; - for (let t of arguments) - e += "string" == typeof t ? t : t[0]; - return f(e); - } - const toml = ((h.parse = f), - h); + } - const allKeys = { - "string": ["name", "description", "version", "type", "author_name", "author_email", "license"], - "number": ["schema_version"], - "boolean": ["autoclose_loader"], - "array": ["runtimes", "packages", "paths", "plugins"] - }; - const defaultConfig$1 = { - "schema_version": 1, - "type": "app", - "autoclose_loader": true, - "runtimes": [{ - "src": "https://cdn.jsdelivr.net/pyodide/v0.21.2/full/pyodide.js", - "name": "pyodide-0.21.2", - "lang": "python" - }], - "packages": [], - "paths": [], - "plugins": [] - }; - function addClasses(element, classes) { - for (const entry of classes) { - element.classList.add(entry); + function peg$fail(expected) { + if (peg$currPos < peg$maxFailPos) { return; } + + if (peg$currPos > peg$maxFailPos) { + peg$maxFailPos = peg$currPos; + peg$maxFailExpected = []; } - } - function removeClasses(element, classes) { - for (const entry of classes) { - element.classList.remove(entry); + + peg$maxFailExpected.push(expected); + } + + function peg$buildSimpleError(message, location) { + return new peg$SyntaxError(message, null, null, location); + } + + function peg$buildStructuredError(expected, found, location) { + return new peg$SyntaxError( + peg$SyntaxError.buildMessage(expected, found), + expected, + found, + location + ); + } + + function peg$parseExpressions() { + var s0, s1, s2, s3, s4, s5, s6, s7; + + s0 = peg$currPos; + s1 = []; + s2 = peg$parseWhitespace(); + if (s2 === peg$FAILED) { + s2 = peg$parseNewline(); + if (s2 === peg$FAILED) { + s2 = peg$parseComment(); + } } - } - function getLastPath(str) { - return str.split('\\').pop().split('/').pop(); - } - function escape(str) { - return str.replace(/</g, "<").replace(/>/g, ">"); - } - function htmlDecode(input) { - const doc = new DOMParser().parseFromString(ltrim(escape(input)), 'text/html'); - return doc.documentElement.textContent; - } - function ltrim(code) { - const lines = code.split('\n'); - if (lines.length == 0) - return code; - const lengths = lines - .filter(line => line.trim().length != 0) - .map(line => { - const [prefix] = line.match(/^\s*/); - return prefix.length; - }); - const k = Math.min(...lengths); - return k != 0 ? lines.map(line => line.substring(k)).join('\n') - : code; - } - function guidGenerator() { - const S4 = function () { - return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1); + while (s2 !== peg$FAILED) { + s1.push(s2); + s2 = peg$parseWhitespace(); + if (s2 === peg$FAILED) { + s2 = peg$parseNewline(); + if (s2 === peg$FAILED) { + s2 = peg$parseComment(); + } + } + } + if (s1 !== peg$FAILED) { + s2 = peg$currPos; + s3 = peg$parseExpression(); + if (s3 !== peg$FAILED) { + s4 = []; + s5 = peg$parseWhitespace(); + if (s5 === peg$FAILED) { + s5 = peg$parseComment(); + } + while (s5 !== peg$FAILED) { + s4.push(s5); + s5 = peg$parseWhitespace(); + if (s5 === peg$FAILED) { + s5 = peg$parseComment(); + } + } + if (s4 !== peg$FAILED) { + s5 = peg$currPos; + s6 = peg$parseNewline(); + if (s6 !== peg$FAILED) { + s7 = peg$parseExpressions(); + if (s7 !== peg$FAILED) { + s6 = [s6, s7]; + s5 = s6; + } else { + peg$currPos = s5; + s5 = peg$FAILED; + } + } else { + peg$currPos = s5; + s5 = peg$FAILED; + } + if (s5 === peg$FAILED) { + s5 = null; + } + if (s5 !== peg$FAILED) { + s3 = [s3, s4, s5]; + s2 = s3; + } else { + peg$currPos = s2; + s2 = peg$FAILED; + } + } else { + peg$currPos = s2; + s2 = peg$FAILED; + } + } else { + peg$currPos = s2; + s2 = peg$FAILED; + } + if (s2 === peg$FAILED) { + s2 = null; + } + if (s2 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c0(); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + + return s0; + } + + function peg$parseExpression() { + var s0, s1; + + s0 = peg$currPos; + s1 = peg$parseTableArrayHeader(); + if (s1 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c1(s1); + } + s0 = s1; + if (s0 === peg$FAILED) { + s0 = peg$currPos; + s1 = peg$parseTableHeader(); + if (s1 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c2(s1); + } + s0 = s1; + if (s0 === peg$FAILED) { + s0 = peg$currPos; + s1 = peg$parseKeyValue(); + if (s1 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c3(s1); + } + s0 = s1; + } + } + + return s0; + } + + function peg$parseNewline() { + var s0; + + peg$silentFails++; + if (input.charCodeAt(peg$currPos) === 10) { + s0 = peg$c5; + peg$currPos++; + } else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c6); } + } + if (s0 === peg$FAILED) { + if (input.substr(peg$currPos, 2) === peg$c7) { + s0 = peg$c7; + peg$currPos += 2; + } else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c8); } + } + } + peg$silentFails--; + if (s0 === peg$FAILED) { + if (peg$silentFails === 0) { peg$fail(peg$c4); } + } + + return s0; + } + + function peg$parseWhitespace() { + var s0; + + peg$silentFails++; + if (peg$c10.test(input.charAt(peg$currPos))) { + s0 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c11); } + } + peg$silentFails--; + if (s0 === peg$FAILED) { + if (peg$silentFails === 0) { peg$fail(peg$c9); } + } + + return s0; + } + + function peg$parseComment() { + var s0, s1, s2, s3, s4, s5; + + peg$silentFails++; + s0 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 35) { + s1 = peg$c13; + peg$currPos++; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c14); } + } + if (s1 !== peg$FAILED) { + s2 = []; + s3 = peg$currPos; + s4 = peg$currPos; + peg$silentFails++; + s5 = peg$parseNewline(); + peg$silentFails--; + if (s5 === peg$FAILED) { + s4 = void 0; + } else { + peg$currPos = s4; + s4 = peg$FAILED; + } + if (s4 !== peg$FAILED) { + if (input.length > peg$currPos) { + s5 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s5 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c15); } + } + if (s5 !== peg$FAILED) { + s4 = [s4, s5]; + s3 = s4; + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + while (s3 !== peg$FAILED) { + s2.push(s3); + s3 = peg$currPos; + s4 = peg$currPos; + peg$silentFails++; + s5 = peg$parseNewline(); + peg$silentFails--; + if (s5 === peg$FAILED) { + s4 = void 0; + } else { + peg$currPos = s4; + s4 = peg$FAILED; + } + if (s4 !== peg$FAILED) { + if (input.length > peg$currPos) { + s5 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s5 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c15); } + } + if (s5 !== peg$FAILED) { + s4 = [s4, s5]; + s3 = s4; + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } + if (s2 !== peg$FAILED) { + s1 = [s1, s2]; + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + peg$silentFails--; + if (s0 === peg$FAILED) { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c12); } + } + + return s0; + } + + function peg$parseKeyValue() { + var s0, s1, s2, s3, s4, s5; + + s0 = peg$currPos; + s1 = peg$parseKey(); + if (s1 !== peg$FAILED) { + s2 = []; + s3 = peg$parseWhitespace(); + while (s3 !== peg$FAILED) { + s2.push(s3); + s3 = peg$parseWhitespace(); + } + if (s2 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 61) { + s3 = peg$c16; + peg$currPos++; + } else { + s3 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c17); } + } + if (s3 !== peg$FAILED) { + s4 = []; + s5 = peg$parseWhitespace(); + while (s5 !== peg$FAILED) { + s4.push(s5); + s5 = peg$parseWhitespace(); + } + if (s4 !== peg$FAILED) { + s5 = peg$parseValue(); + if (s5 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c18(s1, s5); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + + return s0; + } + + function peg$parseKey() { + var s0; + + s0 = peg$parseBareKey(); + if (s0 === peg$FAILED) { + s0 = peg$parseQuotedKey(); + } + + return s0; + } + + function peg$parseBareKey() { + var s0, s1, s2; + + s0 = peg$currPos; + s1 = []; + s2 = peg$parseBareKeyCharacter(); + if (s2 !== peg$FAILED) { + while (s2 !== peg$FAILED) { + s1.push(s2); + s2 = peg$parseBareKeyCharacter(); + } + } else { + s1 = peg$FAILED; + } + if (s1 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c19(); + } + s0 = s1; + + return s0; + } + + function peg$parseBareKeyCharacter() { + var s0; + + peg$silentFails++; + if (peg$c21.test(input.charAt(peg$currPos))) { + s0 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c22); } + } + peg$silentFails--; + if (s0 === peg$FAILED) { + if (peg$silentFails === 0) { peg$fail(peg$c20); } + } + + return s0; + } + + function peg$parseQuotedKey() { + var s0, s1, s2, s3; + + s0 = peg$currPos; + s1 = peg$parseDoubleQuote(); + if (s1 !== peg$FAILED) { + s2 = []; + s3 = peg$parseBasicCharacter(); + if (s3 !== peg$FAILED) { + while (s3 !== peg$FAILED) { + s2.push(s3); + s3 = peg$parseBasicCharacter(); + } + } else { + s2 = peg$FAILED; + } + if (s2 !== peg$FAILED) { + s3 = peg$parseDoubleQuote(); + if (s3 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c23(s2); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + + return s0; + } + + function peg$parseDoubleQuote() { + var s0; + + peg$silentFails++; + if (input.charCodeAt(peg$currPos) === 34) { + s0 = peg$c25; + peg$currPos++; + } else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c26); } + } + peg$silentFails--; + if (s0 === peg$FAILED) { + if (peg$silentFails === 0) { peg$fail(peg$c24); } + } + + return s0; + } + + function peg$parseSingleQuote() { + var s0; + + peg$silentFails++; + if (input.charCodeAt(peg$currPos) === 39) { + s0 = peg$c28; + peg$currPos++; + } else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c29); } + } + peg$silentFails--; + if (s0 === peg$FAILED) { + if (peg$silentFails === 0) { peg$fail(peg$c27); } + } + + return s0; + } + + function peg$parseThreeDoubleQuotes() { + var s0; + + peg$silentFails++; + if (input.substr(peg$currPos, 3) === peg$c31) { + s0 = peg$c31; + peg$currPos += 3; + } else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c32); } + } + peg$silentFails--; + if (s0 === peg$FAILED) { + if (peg$silentFails === 0) { peg$fail(peg$c30); } + } + + return s0; + } + + function peg$parseThreeSingleQuotes() { + var s0; + + peg$silentFails++; + if (input.substr(peg$currPos, 3) === peg$c34) { + s0 = peg$c34; + peg$currPos += 3; + } else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c35); } + } + peg$silentFails--; + if (s0 === peg$FAILED) { + if (peg$silentFails === 0) { peg$fail(peg$c33); } + } + + return s0; + } + + function peg$parseValue() { + var s0; + + s0 = peg$parseString(); + if (s0 === peg$FAILED) { + s0 = peg$parseBoolean(); + if (s0 === peg$FAILED) { + s0 = peg$parseDateTime(); + if (s0 === peg$FAILED) { + s0 = peg$parseFloat(); + if (s0 === peg$FAILED) { + s0 = peg$parseInteger(); + if (s0 === peg$FAILED) { + s0 = peg$parseArray(); + if (s0 === peg$FAILED) { + s0 = peg$parseInlineTable(); + } + } + } + } + } + } + + return s0; + } + + function peg$parseString() { + var s0; + + s0 = peg$parseMultilineBasicString(); + if (s0 === peg$FAILED) { + s0 = peg$parseBasicString(); + if (s0 === peg$FAILED) { + s0 = peg$parseMultilineLiteralString(); + if (s0 === peg$FAILED) { + s0 = peg$parseLiteralString(); + } + } + } + + return s0; + } + + function peg$parseBasicString() { + var s0, s1, s2, s3; + + s0 = peg$currPos; + s1 = peg$parseDoubleQuote(); + if (s1 !== peg$FAILED) { + s2 = []; + s3 = peg$parseBasicCharacter(); + while (s3 !== peg$FAILED) { + s2.push(s3); + s3 = peg$parseBasicCharacter(); + } + if (s2 !== peg$FAILED) { + s3 = peg$parseDoubleQuote(); + if (s3 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c36(s2); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + + return s0; + } + + function peg$parseBasicCharacter() { + var s0; + + s0 = peg$parseNormalCharacter(); + if (s0 === peg$FAILED) { + s0 = peg$parseEscapedCharacter(); + } + + return s0; + } + + function peg$parseNormalCharacter() { + var s0, s1, s2; + + peg$silentFails++; + s0 = peg$currPos; + s1 = peg$currPos; + peg$silentFails++; + s2 = peg$parseNewline(); + peg$silentFails--; + if (s2 === peg$FAILED) { + s1 = void 0; + } else { + peg$currPos = s1; + s1 = peg$FAILED; + } + if (s1 !== peg$FAILED) { + if (peg$c38.test(input.charAt(peg$currPos))) { + s2 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c39); } + } + if (s2 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c19(); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + peg$silentFails--; + if (s0 === peg$FAILED) { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c37); } + } + + return s0; + } + + function peg$parseEscapedCharacter() { + var s0, s1, s2, s3, s4; + + s0 = peg$currPos; + s1 = peg$parseBackslash(); + if (s1 !== peg$FAILED) { + s2 = peg$parseControlCharacter(); + if (s2 === peg$FAILED) { + s2 = peg$parseDoubleQuote(); + if (s2 === peg$FAILED) { + s2 = peg$parseBackslash(); + if (s2 === peg$FAILED) { + s2 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 117) { + s3 = peg$c40; + peg$currPos++; + } else { + s3 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c41); } + } + if (s3 !== peg$FAILED) { + s4 = peg$parseFourHexadecimalDigits(); + if (s4 !== peg$FAILED) { + s3 = [s3, s4]; + s2 = s3; + } else { + peg$currPos = s2; + s2 = peg$FAILED; + } + } else { + peg$currPos = s2; + s2 = peg$FAILED; + } + if (s2 === peg$FAILED) { + s2 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 85) { + s3 = peg$c42; + peg$currPos++; + } else { + s3 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c43); } + } + if (s3 !== peg$FAILED) { + s4 = peg$parseEightHexadecimalDigits(); + if (s4 !== peg$FAILED) { + s3 = [s3, s4]; + s2 = s3; + } else { + peg$currPos = s2; + s2 = peg$FAILED; + } + } else { + peg$currPos = s2; + s2 = peg$FAILED; + } + } + } + } + } + if (s2 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c44(); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + + return s0; + } + + function peg$parseControlCharacter() { + var s0; + + peg$silentFails++; + if (peg$c46.test(input.charAt(peg$currPos))) { + s0 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c47); } + } + peg$silentFails--; + if (s0 === peg$FAILED) { + if (peg$silentFails === 0) { peg$fail(peg$c45); } + } + + return s0; + } + + function peg$parseBackslash() { + var s0; + + peg$silentFails++; + if (input.charCodeAt(peg$currPos) === 92) { + s0 = peg$c49; + peg$currPos++; + } else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c50); } + } + peg$silentFails--; + if (s0 === peg$FAILED) { + if (peg$silentFails === 0) { peg$fail(peg$c48); } + } + + return s0; + } + + function peg$parseFourHexadecimalDigits() { + var s0, s1, s2, s3, s4; + + peg$silentFails++; + s0 = peg$currPos; + s1 = peg$parseHexDigit(); + if (s1 !== peg$FAILED) { + s2 = peg$parseHexDigit(); + if (s2 !== peg$FAILED) { + s3 = peg$parseHexDigit(); + if (s3 !== peg$FAILED) { + s4 = peg$parseHexDigit(); + if (s4 !== peg$FAILED) { + s1 = [s1, s2, s3, s4]; + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + peg$silentFails--; + if (s0 === peg$FAILED) { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c51); } + } + + return s0; + } + + function peg$parseEightHexadecimalDigits() { + var s0, s1, s2, s3, s4, s5, s6, s7, s8; + + peg$silentFails++; + s0 = peg$currPos; + s1 = peg$parseHexDigit(); + if (s1 !== peg$FAILED) { + s2 = peg$parseHexDigit(); + if (s2 !== peg$FAILED) { + s3 = peg$parseHexDigit(); + if (s3 !== peg$FAILED) { + s4 = peg$parseHexDigit(); + if (s4 !== peg$FAILED) { + s5 = peg$parseHexDigit(); + if (s5 !== peg$FAILED) { + s6 = peg$parseHexDigit(); + if (s6 !== peg$FAILED) { + s7 = peg$parseHexDigit(); + if (s7 !== peg$FAILED) { + s8 = peg$parseHexDigit(); + if (s8 !== peg$FAILED) { + s1 = [s1, s2, s3, s4, s5, s6, s7, s8]; + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + peg$silentFails--; + if (s0 === peg$FAILED) { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c52); } + } + + return s0; + } + + function peg$parseHexDigit() { + var s0; + + if (peg$c53.test(input.charAt(peg$currPos))) { + s0 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c54); } + } + + return s0; + } + + function peg$parseLiteralString() { + var s0, s1, s2, s3; + + s0 = peg$currPos; + s1 = peg$parseSingleQuote(); + if (s1 !== peg$FAILED) { + s2 = []; + s3 = peg$parseLiteralCharacter(); + while (s3 !== peg$FAILED) { + s2.push(s3); + s3 = peg$parseLiteralCharacter(); + } + if (s2 !== peg$FAILED) { + s3 = peg$parseSingleQuote(); + if (s3 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c55(); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + + return s0; + } + + function peg$parseLiteralCharacter() { + var s0, s1, s2; + + peg$silentFails++; + s0 = peg$currPos; + s1 = peg$currPos; + peg$silentFails++; + s2 = peg$parseNewline(); + peg$silentFails--; + if (s2 === peg$FAILED) { + s1 = void 0; + } else { + peg$currPos = s1; + s1 = peg$FAILED; + } + if (s1 !== peg$FAILED) { + if (peg$c56.test(input.charAt(peg$currPos))) { + s2 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c57); } + } + if (s2 !== peg$FAILED) { + s1 = [s1, s2]; + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + peg$silentFails--; + if (s0 === peg$FAILED) { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c37); } + } + + return s0; + } + + function peg$parseMultilineBasicString() { + var s0, s1, s2, s3, s4; + + s0 = peg$currPos; + s1 = peg$parseThreeDoubleQuotes(); + if (s1 !== peg$FAILED) { + s2 = peg$parseNewline(); + if (s2 === peg$FAILED) { + s2 = null; + } + if (s2 !== peg$FAILED) { + s3 = []; + s4 = peg$parseMultilineBasicText(); + while (s4 !== peg$FAILED) { + s3.push(s4); + s4 = peg$parseMultilineBasicText(); + } + if (s3 !== peg$FAILED) { + s4 = peg$parseThreeDoubleQuotes(); + if (s4 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c58(s3); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + + return s0; + } + + function peg$parseMultilineBasicText() { + var s0, s1, s2; + + s0 = peg$parseMultilineBasicCharacter(); + if (s0 === peg$FAILED) { + s0 = peg$currPos; + s1 = peg$parseBackslash(); + if (s1 !== peg$FAILED) { + s2 = peg$parseNewline(); + if (s2 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c19(); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + if (s0 === peg$FAILED) { + s0 = peg$parseNewline(); + } + } + + return s0; + } + + function peg$parseMultilineBasicCharacter() { + var s0, s1, s2; + + s0 = peg$currPos; + s1 = peg$currPos; + peg$silentFails++; + s2 = peg$parseThreeDoubleQuotes(); + peg$silentFails--; + if (s2 === peg$FAILED) { + s1 = void 0; + } else { + peg$currPos = s1; + s1 = peg$FAILED; + } + if (s1 !== peg$FAILED) { + s2 = peg$parseMultilineNormalCharacter(); + if (s2 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c19(); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + if (s0 === peg$FAILED) { + s0 = peg$parseEscapedCharacter(); + } + + return s0; + } + + function peg$parseMultilineNormalCharacter() { + var s0, s1, s2; + + peg$silentFails++; + s0 = peg$currPos; + s1 = peg$currPos; + peg$silentFails++; + s2 = peg$parseNewline(); + peg$silentFails--; + if (s2 === peg$FAILED) { + s1 = void 0; + } else { + peg$currPos = s1; + s1 = peg$FAILED; + } + if (s1 !== peg$FAILED) { + if (peg$c59.test(input.charAt(peg$currPos))) { + s2 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c60); } + } + if (s2 !== peg$FAILED) { + s1 = [s1, s2]; + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + peg$silentFails--; + if (s0 === peg$FAILED) { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c37); } + } + + return s0; + } + + function peg$parseMultilineLiteralString() { + var s0, s1, s2, s3, s4; + + s0 = peg$currPos; + s1 = peg$parseThreeSingleQuotes(); + if (s1 !== peg$FAILED) { + s2 = peg$parseNewline(); + if (s2 === peg$FAILED) { + s2 = null; + } + if (s2 !== peg$FAILED) { + s3 = []; + s4 = peg$parseMultilineLiteralText(); + while (s4 !== peg$FAILED) { + s3.push(s4); + s4 = peg$parseMultilineLiteralText(); + } + if (s3 !== peg$FAILED) { + s4 = peg$parseThreeSingleQuotes(); + if (s4 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c36(s3); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + + return s0; + } + + function peg$parseMultilineLiteralText() { + var s0, s1, s2; + + s0 = peg$currPos; + s1 = peg$currPos; + peg$silentFails++; + if (input.substr(peg$currPos, 3) === peg$c34) { + s2 = peg$c34; + peg$currPos += 3; + } else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c35); } + } + peg$silentFails--; + if (s2 === peg$FAILED) { + s1 = void 0; + } else { + peg$currPos = s1; + s1 = peg$FAILED; + } + if (s1 !== peg$FAILED) { + s2 = peg$parseMultilineLiteralCharacter(); + if (s2 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c19(); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + if (s0 === peg$FAILED) { + s0 = peg$parseNewline(); + } + + return s0; + } + + function peg$parseMultilineLiteralCharacter() { + var s0, s1, s2; + + peg$silentFails++; + s0 = peg$currPos; + s1 = peg$currPos; + peg$silentFails++; + s2 = peg$parseNewline(); + peg$silentFails--; + if (s2 === peg$FAILED) { + s1 = void 0; + } else { + peg$currPos = s1; + s1 = peg$FAILED; + } + if (s1 !== peg$FAILED) { + if (peg$c62.test(input.charAt(peg$currPos))) { + s2 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c63); } + } + if (s2 !== peg$FAILED) { + s1 = [s1, s2]; + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + peg$silentFails--; + if (s0 === peg$FAILED) { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c61); } + } + + return s0; + } + + function peg$parseBoolean() { + var s0, s1; + + s0 = peg$currPos; + if (input.substr(peg$currPos, 4) === peg$c64) { + s1 = peg$c64; + peg$currPos += 4; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c65); } + } + if (s1 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c66(); + } + s0 = s1; + if (s0 === peg$FAILED) { + s0 = peg$currPos; + if (input.substr(peg$currPos, 5) === peg$c67) { + s1 = peg$c67; + peg$currPos += 5; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c68); } + } + if (s1 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c69(); + } + s0 = s1; + } + + return s0; + } + + function peg$parseFloat() { + var s0, s1, s2, s3, s4; + + s0 = peg$currPos; + s1 = peg$parseInteger(); + if (s1 !== peg$FAILED) { + s2 = peg$currPos; + s3 = peg$parseFraction(); + if (s3 !== peg$FAILED) { + s4 = peg$parseExponent(); + if (s4 === peg$FAILED) { + s4 = null; + } + if (s4 !== peg$FAILED) { + s3 = [s3, s4]; + s2 = s3; + } else { + peg$currPos = s2; + s2 = peg$FAILED; + } + } else { + peg$currPos = s2; + s2 = peg$FAILED; + } + if (s2 === peg$FAILED) { + s2 = peg$parseExponent(); + } + if (s2 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c70(); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + + return s0; + } + + function peg$parseFraction() { + var s0, s1, s2, s3, s4, s5, s6; + + s0 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 46) { + s1 = peg$c71; + peg$currPos++; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c72); } + } + if (s1 !== peg$FAILED) { + s2 = peg$parseDigit(); + if (s2 !== peg$FAILED) { + s3 = []; + s4 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 95) { + s5 = peg$c73; + peg$currPos++; + } else { + s5 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c74); } + } + if (s5 === peg$FAILED) { + s5 = null; + } + if (s5 !== peg$FAILED) { + s6 = peg$parseDigit(); + if (s6 !== peg$FAILED) { + s5 = [s5, s6]; + s4 = s5; + } else { + peg$currPos = s4; + s4 = peg$FAILED; + } + } else { + peg$currPos = s4; + s4 = peg$FAILED; + } + while (s4 !== peg$FAILED) { + s3.push(s4); + s4 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 95) { + s5 = peg$c73; + peg$currPos++; + } else { + s5 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c74); } + } + if (s5 === peg$FAILED) { + s5 = null; + } + if (s5 !== peg$FAILED) { + s6 = peg$parseDigit(); + if (s6 !== peg$FAILED) { + s5 = [s5, s6]; + s4 = s5; + } else { + peg$currPos = s4; + s4 = peg$FAILED; + } + } else { + peg$currPos = s4; + s4 = peg$FAILED; + } + } + if (s3 !== peg$FAILED) { + s1 = [s1, s2, s3]; + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + + return s0; + } + + function peg$parseExponent() { + var s0, s1, s2; + + s0 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 101) { + s1 = peg$c75; + peg$currPos++; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c76); } + } + if (s1 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 69) { + s1 = peg$c77; + peg$currPos++; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c78); } + } + } + if (s1 !== peg$FAILED) { + s2 = peg$parseInteger(); + if (s2 !== peg$FAILED) { + s1 = [s1, s2]; + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + + return s0; + } + + function peg$parseInteger() { + var s0, s1, s2; + + s0 = peg$currPos; + s1 = peg$parseSign(); + if (s1 === peg$FAILED) { + s1 = null; + } + if (s1 !== peg$FAILED) { + s2 = peg$parseIntDigits(); + if (s2 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c79(); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + + return s0; + } + + function peg$parseSign() { + var s0; + + if (input.charCodeAt(peg$currPos) === 43) { + s0 = peg$c80; + peg$currPos++; + } else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c81); } + } + if (s0 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 45) { + s0 = peg$c82; + peg$currPos++; + } else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c83); } + } + } + + return s0; + } + + function peg$parseIntDigits() { + var s0, s1, s2, s3, s4, s5; + + s0 = peg$currPos; + s1 = peg$parseDigit_1to9(); + if (s1 !== peg$FAILED) { + s2 = []; + s3 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 95) { + s4 = peg$c73; + peg$currPos++; + } else { + s4 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c74); } + } + if (s4 === peg$FAILED) { + s4 = null; + } + if (s4 !== peg$FAILED) { + s5 = peg$parseDigit(); + if (s5 !== peg$FAILED) { + s4 = [s4, s5]; + s3 = s4; + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + if (s3 !== peg$FAILED) { + while (s3 !== peg$FAILED) { + s2.push(s3); + s3 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 95) { + s4 = peg$c73; + peg$currPos++; + } else { + s4 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c74); } + } + if (s4 === peg$FAILED) { + s4 = null; + } + if (s4 !== peg$FAILED) { + s5 = peg$parseDigit(); + if (s5 !== peg$FAILED) { + s4 = [s4, s5]; + s3 = s4; + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } + } else { + s2 = peg$FAILED; + } + if (s2 !== peg$FAILED) { + s1 = [s1, s2]; + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + if (s0 === peg$FAILED) { + s0 = peg$parseDigit(); + } + + return s0; + } + + function peg$parseDigit_1to9() { + var s0; + + if (peg$c84.test(input.charAt(peg$currPos))) { + s0 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c85); } + } + + return s0; + } + + function peg$parseDigit() { + var s0; + + if (peg$c86.test(input.charAt(peg$currPos))) { + s0 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c87); } + } + + return s0; + } + + function peg$parseDateTime() { + var s0, s1, s2, s3; + + s0 = peg$currPos; + s1 = peg$parseFullDate(); + if (s1 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 84) { + s2 = peg$c88; + peg$currPos++; + } else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c89); } + } + if (s2 !== peg$FAILED) { + s3 = peg$parseFullTime(); + if (s3 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c90(); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + + return s0; + } + + function peg$parseFullDate() { + var s0, s1, s2, s3, s4, s5; + + peg$silentFails++; + s0 = peg$currPos; + s1 = peg$parseYear(); + if (s1 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 45) { + s2 = peg$c82; + peg$currPos++; + } else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c83); } + } + if (s2 !== peg$FAILED) { + s3 = peg$parseMonth(); + if (s3 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 45) { + s4 = peg$c82; + peg$currPos++; + } else { + s4 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c83); } + } + if (s4 !== peg$FAILED) { + s5 = peg$parseMDay(); + if (s5 !== peg$FAILED) { + s1 = [s1, s2, s3, s4, s5]; + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + peg$silentFails--; + if (s0 === peg$FAILED) { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c91); } + } + + return s0; + } + + function peg$parseYear() { + var s0, s1, s2, s3, s4; + + s0 = peg$currPos; + s1 = peg$parseDigit(); + if (s1 !== peg$FAILED) { + s2 = peg$parseDigit(); + if (s2 !== peg$FAILED) { + s3 = peg$parseDigit(); + if (s3 !== peg$FAILED) { + s4 = peg$parseDigit(); + if (s4 !== peg$FAILED) { + s1 = [s1, s2, s3, s4]; + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + + return s0; + } + + function peg$parseMonth() { + var s0, s1, s2; + + s0 = peg$currPos; + s1 = peg$parseDigit(); + if (s1 !== peg$FAILED) { + s2 = peg$parseDigit(); + if (s2 !== peg$FAILED) { + s1 = [s1, s2]; + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + + return s0; + } + + function peg$parseMDay() { + var s0, s1, s2; + + s0 = peg$currPos; + s1 = peg$parseDigit(); + if (s1 !== peg$FAILED) { + s2 = peg$parseDigit(); + if (s2 !== peg$FAILED) { + s1 = [s1, s2]; + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + + return s0; + } + + function peg$parseFullTime() { + var s0, s1, s2; + + s0 = peg$currPos; + s1 = peg$parseTime(); + if (s1 !== peg$FAILED) { + s2 = peg$parseTimeOffset(); + if (s2 !== peg$FAILED) { + s1 = [s1, s2]; + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + + return s0; + } + + function peg$parseTime() { + var s0, s1, s2, s3, s4, s5, s6; + + s0 = peg$currPos; + s1 = peg$parseHour(); + if (s1 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 58) { + s2 = peg$c92; + peg$currPos++; + } else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c93); } + } + if (s2 !== peg$FAILED) { + s3 = peg$parseMinute(); + if (s3 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 58) { + s4 = peg$c92; + peg$currPos++; + } else { + s4 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c93); } + } + if (s4 !== peg$FAILED) { + s5 = peg$parseSecond(); + if (s5 !== peg$FAILED) { + s6 = peg$parseSecondFraction(); + if (s6 === peg$FAILED) { + s6 = null; + } + if (s6 !== peg$FAILED) { + s1 = [s1, s2, s3, s4, s5, s6]; + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + + return s0; + } + + function peg$parseHour() { + var s0, s1, s2; + + peg$silentFails++; + s0 = peg$currPos; + s1 = peg$parseDigit(); + if (s1 !== peg$FAILED) { + s2 = peg$parseDigit(); + if (s2 !== peg$FAILED) { + s1 = [s1, s2]; + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + peg$silentFails--; + if (s0 === peg$FAILED) { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c94); } + } + + return s0; + } + + function peg$parseMinute() { + var s0, s1, s2; + + peg$silentFails++; + s0 = peg$currPos; + s1 = peg$parseDigit(); + if (s1 !== peg$FAILED) { + s2 = peg$parseDigit(); + if (s2 !== peg$FAILED) { + s1 = [s1, s2]; + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + peg$silentFails--; + if (s0 === peg$FAILED) { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c95); } + } + + return s0; + } + + function peg$parseSecond() { + var s0, s1, s2; + + peg$silentFails++; + s0 = peg$currPos; + s1 = peg$parseDigit(); + if (s1 !== peg$FAILED) { + s2 = peg$parseDigit(); + if (s2 !== peg$FAILED) { + s1 = [s1, s2]; + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + peg$silentFails--; + if (s0 === peg$FAILED) { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c96); } + } + + return s0; + } + + function peg$parseSecondFraction() { + var s0, s1, s2, s3; + + s0 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 46) { + s1 = peg$c71; + peg$currPos++; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c72); } + } + if (s1 !== peg$FAILED) { + s2 = []; + s3 = peg$parseDigit(); + if (s3 !== peg$FAILED) { + while (s3 !== peg$FAILED) { + s2.push(s3); + s3 = peg$parseDigit(); + } + } else { + s2 = peg$FAILED; + } + if (s2 !== peg$FAILED) { + s1 = [s1, s2]; + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + + return s0; + } + + function peg$parseTimeOffset() { + var s0, s1, s2, s3, s4; + + peg$silentFails++; + if (input.charCodeAt(peg$currPos) === 90) { + s0 = peg$c98; + peg$currPos++; + } else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c99); } + } + if (s0 === peg$FAILED) { + s0 = peg$currPos; + s1 = peg$parseSign(); + if (s1 !== peg$FAILED) { + s2 = peg$parseHour(); + if (s2 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 58) { + s3 = peg$c92; + peg$currPos++; + } else { + s3 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c93); } + } + if (s3 !== peg$FAILED) { + s4 = peg$parseMinute(); + if (s4 !== peg$FAILED) { + s1 = [s1, s2, s3, s4]; + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + peg$silentFails--; + if (s0 === peg$FAILED) { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c97); } + } + + return s0; + } + + function peg$parseArray() { + var s0, s1, s2, s3, s4, s5, s6, s7, s8, s9; + + s0 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 91) { + s1 = peg$c100; + peg$currPos++; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c101); } + } + if (s1 !== peg$FAILED) { + s2 = []; + s3 = peg$parseArraySpace(); + while (s3 !== peg$FAILED) { + s2.push(s3); + s3 = peg$parseArraySpace(); + } + if (s2 !== peg$FAILED) { + s3 = peg$currPos; + s4 = peg$parseArrayValue(); + if (s4 !== peg$FAILED) { + s5 = []; + s6 = peg$parseArraySpace(); + while (s6 !== peg$FAILED) { + s5.push(s6); + s6 = peg$parseArraySpace(); + } + if (s5 !== peg$FAILED) { + s6 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 44) { + s7 = peg$c102; + peg$currPos++; + } else { + s7 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c103); } + } + if (s7 !== peg$FAILED) { + s8 = []; + s9 = peg$parseArraySpace(); + while (s9 !== peg$FAILED) { + s8.push(s9); + s9 = peg$parseArraySpace(); + } + if (s8 !== peg$FAILED) { + s7 = [s7, s8]; + s6 = s7; + } else { + peg$currPos = s6; + s6 = peg$FAILED; + } + } else { + peg$currPos = s6; + s6 = peg$FAILED; + } + if (s6 === peg$FAILED) { + s6 = null; + } + if (s6 !== peg$FAILED) { + s4 = [s4, s5, s6]; + s3 = s4; + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + if (s3 === peg$FAILED) { + s3 = null; + } + if (s3 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 93) { + s4 = peg$c104; + peg$currPos++; + } else { + s4 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c105); } + } + if (s4 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c106(s3); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + + return s0; + } + + function peg$parseArrayValue() { + var s0, s1, s2, s3, s4, s5, s6; + + s0 = peg$currPos; + s1 = peg$parseValue(); + if (s1 !== peg$FAILED) { + s2 = peg$currPos; + s3 = []; + s4 = peg$parseArraySpace(); + while (s4 !== peg$FAILED) { + s3.push(s4); + s4 = peg$parseArraySpace(); + } + if (s3 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 44) { + s4 = peg$c102; + peg$currPos++; + } else { + s4 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c103); } + } + if (s4 !== peg$FAILED) { + s5 = []; + s6 = peg$parseArraySpace(); + while (s6 !== peg$FAILED) { + s5.push(s6); + s6 = peg$parseArraySpace(); + } + if (s5 !== peg$FAILED) { + s6 = peg$parseArrayValue(); + if (s6 !== peg$FAILED) { + s3 = [s3, s4, s5, s6]; + s2 = s3; + } else { + peg$currPos = s2; + s2 = peg$FAILED; + } + } else { + peg$currPos = s2; + s2 = peg$FAILED; + } + } else { + peg$currPos = s2; + s2 = peg$FAILED; + } + } else { + peg$currPos = s2; + s2 = peg$FAILED; + } + if (s2 === peg$FAILED) { + s2 = null; + } + if (s2 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c107(s1, s2); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + + return s0; + } + + function peg$parseArraySpace() { + var s0; + + s0 = peg$parseWhitespace(); + if (s0 === peg$FAILED) { + s0 = peg$parseNewline(); + if (s0 === peg$FAILED) { + s0 = peg$parseComment(); + } + } + + return s0; + } + + function peg$parseInlineTable() { + var s0, s1, s2, s3, s4, s5, s6, s7, s8, s9, s10; + + s0 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 123) { + s1 = peg$c108; + peg$currPos++; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c109); } + } + if (s1 !== peg$FAILED) { + s2 = []; + s3 = peg$parseWhitespace(); + while (s3 !== peg$FAILED) { + s2.push(s3); + s3 = peg$parseWhitespace(); + } + if (s2 !== peg$FAILED) { + s3 = peg$currPos; + s4 = peg$parseKeyValue(); + if (s4 !== peg$FAILED) { + s5 = []; + s6 = peg$currPos; + s7 = []; + s8 = peg$parseWhitespace(); + while (s8 !== peg$FAILED) { + s7.push(s8); + s8 = peg$parseWhitespace(); + } + if (s7 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 44) { + s8 = peg$c102; + peg$currPos++; + } else { + s8 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c103); } + } + if (s8 !== peg$FAILED) { + s9 = []; + s10 = peg$parseWhitespace(); + while (s10 !== peg$FAILED) { + s9.push(s10); + s10 = peg$parseWhitespace(); + } + if (s9 !== peg$FAILED) { + s10 = peg$parseKeyValue(); + if (s10 !== peg$FAILED) { + s7 = [s7, s8, s9, s10]; + s6 = s7; + } else { + peg$currPos = s6; + s6 = peg$FAILED; + } + } else { + peg$currPos = s6; + s6 = peg$FAILED; + } + } else { + peg$currPos = s6; + s6 = peg$FAILED; + } + } else { + peg$currPos = s6; + s6 = peg$FAILED; + } + while (s6 !== peg$FAILED) { + s5.push(s6); + s6 = peg$currPos; + s7 = []; + s8 = peg$parseWhitespace(); + while (s8 !== peg$FAILED) { + s7.push(s8); + s8 = peg$parseWhitespace(); + } + if (s7 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 44) { + s8 = peg$c102; + peg$currPos++; + } else { + s8 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c103); } + } + if (s8 !== peg$FAILED) { + s9 = []; + s10 = peg$parseWhitespace(); + while (s10 !== peg$FAILED) { + s9.push(s10); + s10 = peg$parseWhitespace(); + } + if (s9 !== peg$FAILED) { + s10 = peg$parseKeyValue(); + if (s10 !== peg$FAILED) { + s7 = [s7, s8, s9, s10]; + s6 = s7; + } else { + peg$currPos = s6; + s6 = peg$FAILED; + } + } else { + peg$currPos = s6; + s6 = peg$FAILED; + } + } else { + peg$currPos = s6; + s6 = peg$FAILED; + } + } else { + peg$currPos = s6; + s6 = peg$FAILED; + } + } + if (s5 !== peg$FAILED) { + s6 = []; + s7 = peg$parseWhitespace(); + while (s7 !== peg$FAILED) { + s6.push(s7); + s7 = peg$parseWhitespace(); + } + if (s6 !== peg$FAILED) { + s4 = [s4, s5, s6]; + s3 = s4; + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + if (s3 === peg$FAILED) { + s3 = null; + } + if (s3 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 125) { + s4 = peg$c110; + peg$currPos++; + } else { + s4 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c111); } + } + if (s4 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c112(s3); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + + return s0; + } + + function peg$parseTableArrayHeader() { + var s0, s1, s2, s3; + + s0 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 91) { + s1 = peg$c100; + peg$currPos++; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c101); } + } + if (s1 !== peg$FAILED) { + s2 = peg$parseTableHeader(); + if (s2 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 93) { + s3 = peg$c104; + peg$currPos++; + } else { + s3 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c105); } + } + if (s3 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c113(s2); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + + return s0; + } + + function peg$parseTableHeader() { + var s0, s1, s2, s3, s4, s5, s6, s7, s8, s9; + + s0 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 91) { + s1 = peg$c100; + peg$currPos++; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c101); } + } + if (s1 !== peg$FAILED) { + s2 = []; + s3 = peg$parseWhitespace(); + while (s3 !== peg$FAILED) { + s2.push(s3); + s3 = peg$parseWhitespace(); + } + if (s2 !== peg$FAILED) { + s3 = peg$parseKey(); + if (s3 !== peg$FAILED) { + s4 = []; + s5 = peg$currPos; + s6 = []; + s7 = peg$parseWhitespace(); + while (s7 !== peg$FAILED) { + s6.push(s7); + s7 = peg$parseWhitespace(); + } + if (s6 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 46) { + s7 = peg$c71; + peg$currPos++; + } else { + s7 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c72); } + } + if (s7 !== peg$FAILED) { + s8 = []; + s9 = peg$parseWhitespace(); + while (s9 !== peg$FAILED) { + s8.push(s9); + s9 = peg$parseWhitespace(); + } + if (s8 !== peg$FAILED) { + s9 = peg$parseKey(); + if (s9 !== peg$FAILED) { + s6 = [s6, s7, s8, s9]; + s5 = s6; + } else { + peg$currPos = s5; + s5 = peg$FAILED; + } + } else { + peg$currPos = s5; + s5 = peg$FAILED; + } + } else { + peg$currPos = s5; + s5 = peg$FAILED; + } + } else { + peg$currPos = s5; + s5 = peg$FAILED; + } + while (s5 !== peg$FAILED) { + s4.push(s5); + s5 = peg$currPos; + s6 = []; + s7 = peg$parseWhitespace(); + while (s7 !== peg$FAILED) { + s6.push(s7); + s7 = peg$parseWhitespace(); + } + if (s6 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 46) { + s7 = peg$c71; + peg$currPos++; + } else { + s7 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c72); } + } + if (s7 !== peg$FAILED) { + s8 = []; + s9 = peg$parseWhitespace(); + while (s9 !== peg$FAILED) { + s8.push(s9); + s9 = peg$parseWhitespace(); + } + if (s8 !== peg$FAILED) { + s9 = peg$parseKey(); + if (s9 !== peg$FAILED) { + s6 = [s6, s7, s8, s9]; + s5 = s6; + } else { + peg$currPos = s5; + s5 = peg$FAILED; + } + } else { + peg$currPos = s5; + s5 = peg$FAILED; + } + } else { + peg$currPos = s5; + s5 = peg$FAILED; + } + } else { + peg$currPos = s5; + s5 = peg$FAILED; + } + } + if (s4 !== peg$FAILED) { + s5 = []; + s6 = peg$parseWhitespace(); + while (s6 !== peg$FAILED) { + s5.push(s6); + s6 = peg$parseWhitespace(); + } + if (s5 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 93) { + s6 = peg$c104; + peg$currPos++; + } else { + s6 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c105); } + } + if (s6 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c114(s3, s4); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + + return s0; + } + + + var genMsgRedefined, isFiniteNumber, isArray, hasOwnProperty, stringify, + unescape, fromCodePoint, checkTableKey, findContext; + + genMsgRedefined = function (key) { + return ('Value for ' + key + ' should not be redefined in the same table.'); }; - return S4() + S4() + '-' + S4() + '-' + S4() + '-' + S4() + '-' + S4() + S4() + S4(); + + isFiniteNumber = Number.isFinite || function (n) { + return typeof n === 'number' && isFinite(n); + }; + + isArray = Array.isArray || function (obj) { + return Object.prototype.toString.call(obj) === '[object Array]'; + }; + + hasOwnProperty = function (obj, key) { + return Object.prototype.hasOwnProperty.call(obj, key); + }; + + stringify = typeof JSON === 'object' && JSON ? JSON.stringify : function (o) { + return '"' + String(o).replace(/[\x00-\x1F"\\]/g, function (c) { + switch (c) { + case '"': case '\\': return '\\' + c; + case '\t': return '\\t'; + case '\n': return '\\n'; + case '\r': return '\\r'; + case '\b': return '\\b'; + case '\f': return '\\f'; + default: + var hex = c.charCodeAt(0).toString(16); + return '\\u' + '0000'.substr(hex.length) + hex; + } + }) + '"'; + }; + + unescape = function (c) { + switch (c) { + case '"': case '\\': return c; + case 't': return '\t'; + case 'n': return '\n'; + case 'r': return '\r'; + case 'b': return '\b'; + case 'f': return '\f'; + default: error(stringify(c) + ' cannot be escaped.'); + } + }; + + fromCodePoint = function (codepoint) { + if (!isFiniteNumber(codepoint) || codepoint < 0 || codepoint > 0x10FFFF) { + error('U+' + codepoint.toString(16) + + ' is not a valid Unicode code point.'); + } + if (String.fromCodePoint) { + return String.fromCodePoint(codepoint); + } + // See: punnycode.ucs2.encode from https://github.com/bestiejs/punycode.js + var c = ''; + if (codepoint > 0xFFFF) { + codepoint -= 0x10000; + c += String.fromCharCode((codepoint >>> 10) & 0x3FF | 0xD800); + codepoint = 0xDC00 | codepoint & 0x3FF; + } + c += String.fromCharCode(codepoint); + return c; + }; + + checkTableKey = function (table, k) { + if (hasOwnProperty(table, k)) { + error(genMsgRedefined(stringify(k))); + } + }; + + findContext = function (table, isTableArray, path) { + var s = ''; + for (var i = 0, l = path.length; i < l; i++) { + var k = path[i]; + s += (s ? '.' : '') + stringify(k); + if (!hasOwnProperty(table, k)) { + if (isTableArray && i + 1 === l) { + var t = {}; + table[k] = [t]; + table = t; + g_table_arrays[s] = true; + } else { + table = table[k] = {}; + g_tables[s] = true; + } + } else { + if (isTableArray) { + if (isArray(table[k])) { + if (!g_table_arrays[s]) { + error(genMsgRedefined(s)); + } + if (i + 1 === l) { + var t = {}; + table[k].push(t); + table = t; + } else { + s += '.' + stringify(table[k].length - 1); + table = table[k][table[k].length-1]; + } + } else { + if (!g_tables[s]) { + error(genMsgRedefined(s)); + } + table = table[k]; + } + } else { + if (isArray(table[k])) { + if (!g_table_arrays[s] || i + 1 === l) { + error(genMsgRedefined(s)); + } + s += '.' + stringify(table[k].length - 1); + table = table[k][table[k].length-1]; + } else { + if (!g_tables[s]) { + error(genMsgRedefined(s)); + } + table = table[k]; + } + } + } + } + if (isTableArray) { + if (!g_table_arrays[s]) { + error(genMsgRedefined(s)); + } + } else { + if (g_defined_tables[s] || g_table_arrays[s]) { + error(genMsgRedefined(s)); + } + g_defined_tables[s] = true; + } + return { + table: table, + path: path + }; + }; + + var g_root = {}; // TOML table + var g_context = { // current context + table: g_root, + path: [] + }; + var g_tables = {}; // paths to tables + var g_defined_tables = {}; // paths to tables directly defined + var g_table_arrays = {}; // paths to table arrays + + + peg$result = peg$startRuleFunction(); + + if (peg$result !== peg$FAILED && peg$currPos === input.length) { + return peg$result; + } else { + if (peg$result !== peg$FAILED && peg$currPos < input.length) { + peg$fail(peg$endExpectation()); + } + + throw peg$buildStructuredError( + peg$maxFailExpected, + peg$maxFailPos < input.length ? input.charAt(peg$maxFailPos) : null, + peg$maxFailPos < input.length + ? peg$computeLocation(peg$maxFailPos, peg$maxFailPos + 1) + : peg$computeLocation(peg$maxFailPos, peg$maxFailPos) + ); + } } - /* - * Display a page-wide error message to show that something has gone wrong with - * PyScript or Pyodide during loading. Probably not be used for issues that occur within - * Python scripts, since stderr can be routed to somewhere in the DOM - */ - function showError(msg) { - const warning = document.createElement('div'); - warning.style.backgroundColor = 'LightCoral'; - warning.style.alignContent = 'center'; - warning.style.margin = '4px'; - warning.style.padding = '4px'; - warning.innerHTML = msg; - document.body.prepend(warning); + + return { + SyntaxError: peg$SyntaxError, + parse: peg$parse + }; + })(); + + function subclass(child, parent) { + function ctor() { + this.constructor = child; } - function handleFetchError(e, singleFile) { - //Should we still export full error contents to console? - console.warn(`Caught an error in loadPaths:\r\n ${e.toString()}`); - let errorContent; - if (e.message.includes('TypeError: Failed to fetch')) { - errorContent = `<p>PyScript: Access to local files - (using "Paths:" in <py-env>) + ctor.prototype = parent.prototype; + child.prototype = new ctor(); + } + + function TomlSyntaxError(message, offset, line, column) { + this.message = message; + this.offset = offset; + this.line = line; + this.column = column; + } + + subclass(TomlSyntaxError, SyntaxError); + + var parser$1 = parser$2; + var toml = { + parse: function (src) { + try { + return parser$1.parse(src); + } catch (err) { + if (err instanceof parser$1.SyntaxError) { + err.line = err.location.start.line; + err.column = err.location.start.column; + err.offset = err.location.start.offset; + throw new TomlSyntaxError( + err.message, + err.location.start.offset, + err.location.start.line, + err.location.start.column); + } else { + throw err; + } + } + }, + SyntaxError: TomlSyntaxError + }; + + var toml_1 = toml; + + /* Very simple logger interface. + + Each module is expected to create its own logger by doing e.g.: + + const logger = getLogger('my-prefix'); + + and then use it instead of console: + + logger.info('hello', 'world'); + logger.warn('...'); + logger.error('...'); + + The logger automatically adds the prefix "[my-prefix]" to all logs. + E.g., the above call would print: + + [my-prefix] hello world + + logger.log is intentionally omitted. The idea is that PyScript should not + write anything to console.log, to leave it free for the user. + + Currently, the logger does not to anything more than that. In the future, + we might want to add additional features such as the ability to + enable/disable logs on a global or per-module basis. + */ + const _cache = new Map(); + function getLogger(prefix) { + let logger = _cache.get(prefix); + if (logger === undefined) { + logger = _makeLogger(prefix); + _cache.set(prefix, logger); + } + return logger; + } + function _makeLogger(prefix) { + prefix = `[${prefix}] `; + function make(level) { + const out_fn = console[level].bind(console); + function fn(fmt, ...args) { + out_fn(prefix + fmt, ...args); + } + return fn; + } + // 'log' is intentionally omitted + const debug = make('debug'); + const info = make('info'); + const warn = make('warn'); + const error = make('error'); + return { debug, info, warn, error }; + } + + /** + * @fileoverview Version of pyscript + * The version is based on calver which contains YEAR.MONTH.DAY.MODIFIER. + * The Modifier can be an optional text tag, such as "dev", "rc", etc. + * + * We are adding this file because we can't add version in main.js due to + * circular imports. + */ + const version = '2022.12.1.dev'; + + const CLOSEBUTTON = `<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 16 16' fill="currentColor" width="12px"><path d='M.293.293a1 1 0 011.414 0L8 6.586 14.293.293a1 1 0 111.414 1.414L9.414 8l6.293 6.293a1 1 0 01-1.414 1.414L8 9.414l-6.293 6.293a1 1 0 01-1.414-1.414L6.586 8 .293 1.707a1 1 0 010-1.414z'/></svg>`; + /* + These error codes are used to identify the type of error that occurred. + The convention is: + * PY0 - errors that occur when fetching + * PY1 - errors that occur in config + * Py2 - errors that occur in plugins + * PY9 - Deprecation errors + */ + var ErrorCode; + (function (ErrorCode) { + ErrorCode["GENERIC"] = "PY0000"; + ErrorCode["FETCH_ERROR"] = "PY0001"; + ErrorCode["FETCH_NAME_ERROR"] = "PY0002"; + // Currently these are created depending on error code received from fetching + ErrorCode["FETCH_UNAUTHORIZED_ERROR"] = "PY0401"; + ErrorCode["FETCH_FORBIDDEN_ERROR"] = "PY0403"; + ErrorCode["FETCH_NOT_FOUND_ERROR"] = "PY0404"; + ErrorCode["FETCH_SERVER_ERROR"] = "PY0500"; + ErrorCode["FETCH_UNAVAILABLE_ERROR"] = "PY0503"; + ErrorCode["BAD_CONFIG"] = "PY1000"; + ErrorCode["MICROPIP_INSTALL_ERROR"] = "PY1001"; + ErrorCode["BAD_PLUGIN_FILE_EXTENSION"] = "PY2000"; + ErrorCode["NO_DEFAULT_EXPORT"] = "PY2001"; + ErrorCode["TOP_LEVEL_AWAIT"] = "PY9000"; + })(ErrorCode || (ErrorCode = {})); + class UserError extends Error { + constructor(errorCode, message, t = 'text') { + super(message); + this.errorCode = errorCode; + this.name = 'UserError'; + this.messageType = t; + this.message = `(${errorCode}): ${message}`; + } + } + class FetchError extends UserError { + constructor(errorCode, message) { + super(errorCode, message); + this.name = 'FetchError'; + } + } + class InstallError extends UserError { + constructor(errorCode, message) { + super(errorCode, message); + this.name = 'InstallError'; + } + } + function _createAlertBanner(message, level = 'error', messageType = 'text', logMessage = true) { + // eslint-disable-next-line @typescript-eslint/restrict-template-expressions + switch (`log-${level}-${logMessage}`) { + case 'log-error-true': + console.error(message); + break; + case 'log-warning-true': + console.warn(message); + break; + } + const banner = document.createElement('div'); + banner.className = `alert-banner py-${level}`; + if (messageType === 'html') { + banner.innerHTML = message; + } + else { + banner.textContent = message; + } + if (level === 'warning') { + const closeButton = document.createElement('button'); + closeButton.id = 'alert-close-button'; + closeButton.addEventListener('click', () => { + banner.remove(); + }); + closeButton.innerHTML = CLOSEBUTTON; + banner.appendChild(closeButton); + } + document.body.prepend(banner); + } + + function escape(str) { + return str.replace(/</g, '<').replace(/>/g, '>'); + } + function htmlDecode(input) { + const doc = new DOMParser().parseFromString(ltrim(escape(input)), 'text/html'); + return doc.documentElement.textContent; + } + function ltrim(code) { + const lines = code.split('\n'); + if (lines.length == 0) + return code; + const lengths = lines + .filter(line => line.trim().length != 0) + .map(line => { + return line.match(/^\s*/)?.pop()?.length; + }); + const k = Math.min(...lengths); + return k != 0 ? lines.map(line => line.substring(k)).join('\n') : code; + } + let _uniqueIdCounter = 0; + function ensureUniqueId(el) { + if (el.id === '') + el.id = `py-internal-${_uniqueIdCounter++}`; + } + function showWarning(msg, messageType = 'text') { + _createAlertBanner(msg, 'warning', messageType); + } + function readTextFromPath(path) { + const request = new XMLHttpRequest(); + request.open('GET', path, false); + request.send(); + const returnValue = request.responseText; + return returnValue; + } + function globalExport(name, obj) { + // attach the given object to the global object, so that it is globally + // visible everywhere. Should be used very sparingly! + globalThis[name] = obj; + } + function getAttribute(el, attr) { + if (el.hasAttribute(attr)) { + const value = el.getAttribute(attr); + if (value) { + return value; + } + } + return null; + } + function joinPaths(parts, separator = '/') { + const res = parts + .map(function (part) { + return part.trim().replace(/(^[/]*|[/]*$)/g, ''); + }) + .filter(p => p !== '') + .join(separator || '/'); + if (parts[0].startsWith('/')) { + return '/' + res; + } + return res; + } + function createDeprecationWarning(msg, elementName) { + createSingularWarning(msg, elementName); + } + /** Adds a warning banner with content {msg} at the top of the page if + * and only if no banner containing the {sentinelText} already exists. + * If sentinelText is null, the full text of {msg} is used instead + * + * @param msg {string} The full text content of the warning banner to be displayed + * @param sentinelText {string} [null] The text to match against existing warning banners. + * If null, the full text of 'msg' is used instead. + */ + function createSingularWarning(msg, sentinelText = null) { + const banners = document.getElementsByClassName('alert-banner py-warning'); + let bannerCount = 0; + for (const banner of banners) { + if (banner.innerHTML.includes(sentinelText ? sentinelText : msg)) { + bannerCount++; + } + } + if (bannerCount == 0) { + _createAlertBanner(msg, 'warning'); + } + } + /** + * @returns A new asynchronous lock + * @private + */ + function createLock() { + // This is a promise that is resolved when the lock is open, not resolved when lock is held. + let _lock = Promise.resolve(); + /** + * Acquire the async lock + * @returns A zero argument function that releases the lock. + * @private + */ + async function acquireLock() { + const old_lock = _lock; + let releaseLock; + _lock = new Promise(resolve => (releaseLock = resolve)); + await old_lock; + return releaseLock; + } + return acquireLock; + } + + const logger$b = getLogger('py-config'); + const allKeys = { + string: ['name', 'description', 'version', 'type', 'author_name', 'author_email', 'license'], + number: ['schema_version'], + array: ['runtimes', 'interpreters', 'packages', 'fetch', 'plugins'], + }; + const defaultConfig$1 = { + schema_version: 1, + type: 'app', + interpreters: [ + { + src: 'https://cdn.jsdelivr.net/pyodide/v0.22.1/full/pyodide.js', + name: 'pyodide-0.22.1', + lang: 'python', + }, + ], + // This is for backward compatibility, we need to remove it in the future + runtimes: [], + packages: [], + fetch: [], + plugins: [], + }; + function loadConfigFromElement(el) { + let srcConfig; + let inlineConfig; + if (el === null) { + srcConfig = {}; + inlineConfig = {}; + } + else { + const configType = getAttribute(el, 'type') || 'toml'; + srcConfig = extractFromSrc(el, configType); + inlineConfig = extractFromInline(el, configType); + } + srcConfig = mergeConfig(srcConfig, defaultConfig$1); + const result = mergeConfig(inlineConfig, srcConfig); + result.pyscript = { + version, + time: new Date().toISOString(), + }; + return result; + } + function extractFromSrc(el, configType) { + const src = getAttribute(el, 'src'); + if (src) { + logger$b.info('loading ', src); + return validateConfig(readTextFromPath(src), configType); + } + return {}; + } + function extractFromInline(el, configType) { + if (el.innerHTML !== '') { + logger$b.info('loading <py-config> content'); + return validateConfig(htmlDecode(el.innerHTML), configType); + } + return {}; + } + function fillUserData(inputConfig, resultConfig) { + for (const key in inputConfig) { + // fill in all extra keys ignored by the validator + if (!(key in defaultConfig$1)) { + resultConfig[key] = inputConfig[key]; + } + } + return resultConfig; + } + function mergeConfig(inlineConfig, externalConfig) { + if (Object.keys(inlineConfig).length === 0 && Object.keys(externalConfig).length === 0) { + return defaultConfig$1; + } + else if (Object.keys(inlineConfig).length === 0) { + return externalConfig; + } + else if (Object.keys(externalConfig).length === 0) { + return inlineConfig; + } + else { + let merged = {}; + for (const keyType in allKeys) { + const keys = allKeys[keyType]; + keys.forEach(function (item) { + if (keyType === 'boolean') { + merged[item] = + typeof inlineConfig[item] !== 'undefined' ? inlineConfig[item] : externalConfig[item]; + } + else { + merged[item] = inlineConfig[item] || externalConfig[item]; + } + }); + } + // fill extra keys from external first + // they will be overridden by inline if extra keys also clash + merged = fillUserData(externalConfig, merged); + merged = fillUserData(inlineConfig, merged); + return merged; + } + } + function parseConfig(configText, configType = 'toml') { + if (configType === 'toml') { + // TOML parser is soft and can parse even JSON strings, this additional check prevents it. + if (configText.trim()[0] === '{') { + throw new UserError(ErrorCode.BAD_CONFIG, `The config supplied: ${configText} is an invalid TOML and cannot be parsed`); + } + try { + return toml_1.parse(configText); + } + catch (err) { + const errMessage = err.toString(); + throw new UserError(ErrorCode.BAD_CONFIG, `The config supplied: ${configText} is an invalid TOML and cannot be parsed: ${errMessage}`); + } + } + else if (configType === 'json') { + try { + return JSON.parse(configText); + } + catch (err) { + const errMessage = err.toString(); + throw new UserError(ErrorCode.BAD_CONFIG, `The config supplied: ${configText} is an invalid JSON and cannot be parsed: ${errMessage}`); + } + } + else { + throw new UserError(ErrorCode.BAD_CONFIG, `The type of config supplied '${configType}' is not supported, supported values are ["toml", "json"]`); + } + } + function validateConfig(configText, configType = 'toml') { + const config = parseConfig(configText, configType); + const finalConfig = {}; + for (const keyType in allKeys) { + const keys = allKeys[keyType]; + keys.forEach(function (item) { + if (validateParamInConfig(item, keyType, config)) { + if (item === 'interpreters') { + finalConfig[item] = []; + const interpreters = config[item]; + interpreters.forEach(function (eachInterpreter) { + const interpreterConfig = {}; + for (const eachInterpreterParam in eachInterpreter) { + if (validateParamInConfig(eachInterpreterParam, 'string', eachInterpreter)) { + interpreterConfig[eachInterpreterParam] = eachInterpreter[eachInterpreterParam]; + } + } + finalConfig[item].push(interpreterConfig); + }); + } + else if (item === 'runtimes') { + // This code is a bit of a mess, but it's used for backwards + // compatibility with the old runtimes config. It should be + // removed when we remove support for the old config. + // We also need the warning here since we are pushing + // runtimes to `interpreter` and we can't show the warning + // in main.js + createDeprecationWarning('The configuration option `config.runtimes` is deprecated. ' + + 'Please use `config.interpreters` instead.', ''); + finalConfig['interpreters'] = []; + const interpreters = config[item]; + interpreters.forEach(function (eachInterpreter) { + const interpreterConfig = {}; + for (const eachInterpreterParam in eachInterpreter) { + if (validateParamInConfig(eachInterpreterParam, 'string', eachInterpreter)) { + interpreterConfig[eachInterpreterParam] = eachInterpreter[eachInterpreterParam]; + } + } + finalConfig['interpreters'].push(interpreterConfig); + }); + } + else if (item === 'fetch') { + finalConfig[item] = []; + const fetchList = config[item]; + fetchList.forEach(function (eachFetch) { + const eachFetchConfig = {}; + for (const eachFetchConfigParam in eachFetch) { + const targetType = eachFetchConfigParam === 'files' ? 'array' : 'string'; + if (validateParamInConfig(eachFetchConfigParam, targetType, eachFetch)) { + eachFetchConfig[eachFetchConfigParam] = eachFetch[eachFetchConfigParam]; + } + } + finalConfig[item].push(eachFetchConfig); + }); + } + else { + finalConfig[item] = config[item]; + } + } + }); + } + return fillUserData(config, finalConfig); + } + function validateParamInConfig(paramName, paramType, config) { + if (paramName in config) { + return paramType === 'array' ? Array.isArray(config[paramName]) : typeof config[paramName] === paramType; + } + return false; + } + + /** + * This is a fetch wrapper that handles any non 200 responses and throws a + * FetchError with the right ErrorCode. This is useful because our FetchError + * will automatically create an alert banner. + * + * @param url - URL to fetch + * @param options - options to pass to fetch + * @returns Response + */ + async function robustFetch(url, options) { + let response; + // Note: We need to wrap fetch into a try/catch block because fetch + // throws a TypeError if the URL is invalid such as http://blah.blah + try { + response = await fetch(url, options); + } + catch (err) { + const error = err; + let errMsg; + if (url.startsWith('http')) { + errMsg = + `Fetching from URL ${url} failed with error ` + + `'${error.message}'. Are your filename and path correct?`; + } + else { + errMsg = `PyScript: Access to local files + (using "Paths:" in <py-config>) is not available when directly opening a HTML file; you must use a webserver to serve the additional files. See <a style="text-decoration: underline;" href="https://github.com/pyscript/pyscript/issues/257#issuecomment-1119595062">this reference</a> - on starting a simple webserver with Python.</p>`; - } - else if (e.message.includes('404')) { - errorContent = - `<p>PyScript: Loading from file <u>` + - singleFile + - `</u> failed with error 404 (File not Found). Are your filename and path are correct?</p>`; - } - else { - errorContent = '<p>PyScript encountered an error while loading from file: ' + e.message + '</p>'; - } - showError(errorContent); - } - function readTextFromPath(path) { - const request = new XMLHttpRequest(); - request.open("GET", path, false); - request.send(); - const returnValue = request.responseText; - return returnValue; - } - function fillUserData(inputConfig, resultConfig) { - for (const key in inputConfig) { - // fill in all extra keys ignored by the validator - if (!(key in defaultConfig$1)) { - resultConfig[key] = inputConfig[key]; - } - } - return resultConfig; - } - function mergeConfig(inlineConfig, externalConfig) { - if (Object.keys(inlineConfig).length === 0 && Object.keys(externalConfig).length === 0) { - return defaultConfig$1; - } - else if (Object.keys(inlineConfig).length === 0) { - return externalConfig; - } - else if (Object.keys(externalConfig).length === 0) { - return inlineConfig; - } - else { - let merged = {}; - for (const keyType in allKeys) { - const keys = allKeys[keyType]; - keys.forEach(function (item) { - if (keyType === "boolean") { - merged[item] = (typeof inlineConfig[item] !== "undefined") ? inlineConfig[item] : externalConfig[item]; - } - else { - merged[item] = inlineConfig[item] || externalConfig[item]; - } - }); - } - // fill extra keys from external first - // they will be overridden by inline if extra keys also clash - merged = fillUserData(externalConfig, merged); - merged = fillUserData(inlineConfig, merged); - return merged; - } - } - function parseConfig(configText, configType = "toml") { - let config; - if (configType === "toml") { - try { - // TOML parser is soft and can parse even JSON strings, this additional check prevents it. - if (configText.trim()[0] === "{") { - const errMessage = `config supplied: ${configText} is an invalid TOML and cannot be parsed`; - showError(`<p>${errMessage}</p>`); - throw Error(errMessage); - } - config = toml.parse(configText); - } - catch (err) { - const errMessage = err.toString(); - showError(`<p>config supplied: ${configText} is an invalid TOML and cannot be parsed: ${errMessage}</p>`); - throw err; - } - } - else if (configType === "json") { - try { - config = JSON.parse(configText); - } - catch (err) { - const errMessage = err.toString(); - showError(`<p>config supplied: ${configText} is an invalid JSON and cannot be parsed: ${errMessage}</p>`); - throw err; - } - } - else { - showError(`<p>type of config supplied is: ${configType}, supported values are ["toml", "json"].</p>`); - } - return config; - } - function validateConfig(configText, configType = "toml") { - const config = parseConfig(configText, configType); - const finalConfig = {}; - for (const keyType in allKeys) { - const keys = allKeys[keyType]; - keys.forEach(function (item) { - if (validateParamInConfig(item, keyType, config)) { - if (item === "runtimes") { - finalConfig[item] = []; - const runtimes = config[item]; - runtimes.forEach(function (eachRuntime) { - const runtimeConfig = {}; - for (const eachRuntimeParam in eachRuntime) { - if (validateParamInConfig(eachRuntimeParam, "string", eachRuntime)) { - runtimeConfig[eachRuntimeParam] = eachRuntime[eachRuntimeParam]; - } - } - finalConfig[item].push(runtimeConfig); - }); - } - else { - finalConfig[item] = config[item]; - } - } - }); - } - return fillUserData(config, finalConfig); - } - function validateParamInConfig(paramName, paramType, config) { - if (paramName in config) { - return paramType === "array" ? Array.isArray(config[paramName]) : typeof config[paramName] === paramType; - } - return false; - } + on starting a simple webserver with Python. + `; + } + throw new FetchError(ErrorCode.FETCH_ERROR, errMsg); + } + // Note that response.ok is true for 200-299 responses + if (!response.ok) { + const errorMsg = `Fetching from URL ${url} failed with error ${response.status} (${response.statusText}). Are your filename and path correct?`; + switch (response.status) { + case 404: + throw new FetchError(ErrorCode.FETCH_NOT_FOUND_ERROR, errorMsg); + case 401: + throw new FetchError(ErrorCode.FETCH_UNAUTHORIZED_ERROR, errorMsg); + case 403: + throw new FetchError(ErrorCode.FETCH_FORBIDDEN_ERROR, errorMsg); + case 500: + throw new FetchError(ErrorCode.FETCH_SERVER_ERROR, errorMsg); + case 503: + throw new FetchError(ErrorCode.FETCH_UNAVAILABLE_ERROR, errorMsg); + default: + throw new FetchError(ErrorCode.FETCH_ERROR, errorMsg); + } + } + return response; + } - const logger$b = getLogger('pyscript/base'); - // Global `Runtime` that implements the generic runtimes API - let runtime$2; - let Element; - runtimeLoaded.subscribe(value => { - runtime$2 = value; - }); - class BaseEvalElement extends HTMLElement { - shadow; - wrapper; - code; - source; - btnConfig; - btnRun; - outputElement; - errorElement; - theme; - appendOutput; - constructor() { - super(); - // attach shadow so we can preserve the element original innerHtml content - this.shadow = this.attachShadow({ mode: 'open' }); - this.wrapper = document.createElement('slot'); - this.shadow.appendChild(this.wrapper); - this.setOutputMode("append"); - } - addToOutput(s) { - this.outputElement.innerHTML += '<div>' + s + '</div>'; - this.outputElement.hidden = false; - } - setOutputMode(defaultMode = "append") { - const mode = this.hasAttribute('output-mode') ? this.getAttribute('output-mode') : defaultMode; - switch (mode) { - case "append": - this.appendOutput = true; - break; - case "replace": - this.appendOutput = false; - break; - default: - logger$b.warn(`${this.id}: custom output-modes are currently not implemented`); - } - } - // subclasses should overwrite this method to define custom logic - // before code gets evaluated - preEvaluate() { - return null; - } - // subclasses should overwrite this method to define custom logic - // after code has been evaluated - postEvaluate() { - return null; - } - checkId() { - if (!this.id) - this.id = 'py-' + guidGenerator(); - } - getSourceFromElement() { - return ''; - } - async getSourceFromFile(s) { - const response = await fetch(s); - this.code = await response.text(); - return this.code; - } - async _register_esm(runtime) { - const imports = {}; - const nodes = document.querySelectorAll("script[type='importmap']"); - const importmaps = []; - nodes.forEach(node => { - let importmap; - try { - importmap = JSON.parse(node.textContent); - if (importmap?.imports == null) - return; - importmaps.push(importmap); - } - catch { - return; - } - }); - for (const importmap of importmaps) { - for (const [name, url] of Object.entries(importmap.imports)) { - if (typeof name != 'string' || typeof url != 'string') - continue; - try { - // XXX: pyodide doesn't like Module(), failing with - // "can't read 'name' of undefined" at import time - imports[name] = { ...(await import(url)) }; - } - catch { - logger$b.error(`failed to fetch '${url}' for '${name}'`); - } - } - } - runtime.registerJsModule('esm', imports); - } - async evaluate() { - this.preEvaluate(); - let source; - let output; - try { - source = this.source ? await this.getSourceFromFile(this.source) - : this.getSourceFromElement(); - this._register_esm(runtime$2); - await runtime$2.run(`output_manager.change(out="${this.outputElement.id}", err="${this.errorElement.id}", append=${this.appendOutput ? 'True' : 'False'})`); - output = await runtime$2.run(source); - if (output !== undefined) { - if (Element === undefined) { - Element = runtime$2.globals.get('Element'); - } - const out = Element(this.outputElement.id); - out.write.callKwargs(output, { append: this.appendOutput }); - this.outputElement.hidden = false; - this.outputElement.style.display = 'block'; - } - await runtime$2.run(`output_manager.revert()`); - // check if this REPL contains errors, delete them and remove error classes - const errorElements = document.querySelectorAll(`div[id^='${this.errorElement.id}'][error]`); - if (errorElements.length > 0) { - errorElements.forEach(errorElement => { - errorElement.classList.add('hidden'); - if (this.hasAttribute('std-err')) { - this.errorElement.hidden = true; - this.errorElement.style.removeProperty('display'); - } - }); - } - removeClasses(this.errorElement, ['bg-red-200', 'p-2']); - this.postEvaluate(); - } - catch (err) { - logger$b.error(err); - try { - if (Element === undefined) { - Element = runtime$2.globals.get('Element'); - } - const out = Element(this.errorElement.id); - addClasses(this.errorElement, ['bg-red-200', 'p-2']); - out.write.callKwargs(err.toString(), { append: this.appendOutput }); - if (this.errorElement.children.length === 0) { - this.errorElement.setAttribute('error', ''); - } - else { - this.errorElement.children[this.errorElement.children.length - 1].setAttribute('error', ''); - } - this.errorElement.hidden = false; - this.errorElement.style.display = 'block'; - this.errorElement.style.visibility = 'visible'; - } - catch (internalErr) { - logger$b.error("Unnable to write error to error element in page."); - } - } - } // end evaluate - async eval(source) { - try { - const output = await runtime$2.run(source); - if (output !== undefined) { - logger$b.info(output); - } - } - catch (err) { - logger$b.error(err); - } - } // end eval - runAfterRuntimeInitialized(callback) { - runtimeLoaded.subscribe(value => { - if ('run' in value) { - setTimeout(() => { - void callback(); - }, 100); - } - }); - } - } - function createWidget(name, code, klass) { - class CustomWidget extends HTMLElement { - shadow; - wrapper; - name = name; - klass = klass; - code = code; - proxy; - proxyClass; - constructor() { - super(); - // attach shadow so we can preserve the element original innerHtml content - this.shadow = this.attachShadow({ mode: 'open' }); - this.wrapper = document.createElement('slot'); - this.shadow.appendChild(this.wrapper); - } - connectedCallback() { - // TODO: we are calling with a 2secs delay to allow pyodide to load - // ideally we can just wait for it to load and then run. To do - // so we need to replace using the promise and actually using - // the interpreter after it loads completely - // setTimeout(() => { - // void (async () => { - // await this.eval(this.code); - // this.proxy = this.proxyClass(this); - // console.log('proxy', this.proxy); - // this.proxy.connect(); - // this.registerWidget(); - // })(); - // }, 2000); - runtimeLoaded.subscribe(value => { - if ('run' in value) { - runtime$2 = value; - setTimeout(() => { - void (async () => { - await this.eval(this.code); - this.proxy = this.proxyClass(this); - this.proxy.connect(); - this.registerWidget(); - })(); - }, 1000); - } - }); - } - registerWidget() { - logger$b.info('new widget registered:', this.name); - runtime$2.globals.set(this.id, this.proxy); - } - async eval(source) { - try { - const output = await runtime$2.run(source); - this.proxyClass = runtime$2.globals.get(this.klass); - if (output !== undefined) { - logger$b.info('CustomWidget.eval: ', output); - } - } - catch (err) { - logger$b.error('CustomWidget.eval: ', err); - } - } - } - customElements.define(name, CustomWidget); - } - class PyWidget extends HTMLElement { - shadow; - name; - klass; - outputElement; - errorElement; - wrapper; - theme; - source; - code; - constructor() { - super(); - // attach shadow so we can preserve the element original innerHtml content - this.shadow = this.attachShadow({ mode: 'open' }); - this.wrapper = document.createElement('slot'); - this.shadow.appendChild(this.wrapper); - this.addAttributes('src', 'name', 'klass'); - } - addAttributes(...attrs) { - for (const each of attrs) { - const property = each === "src" ? "source" : each; - if (this.hasAttribute(each)) { - this[property] = this.getAttribute(each); - } - } - } - async connectedCallback() { - if (this.id === undefined) { - throw new ReferenceError(`No id specified for component. Components must have an explicit id. Please use id="" to specify your component id.`); - } - const mainDiv = document.createElement('div'); - mainDiv.id = this.id + '-main'; - this.appendChild(mainDiv); - logger$b.debug('PyWidget: reading source', this.source); - this.code = await this.getSourceFromFile(this.source); - createWidget(this.name, this.code, this.klass); - } - initOutErr() { - if (this.hasAttribute('output')) { - this.errorElement = this.outputElement = document.getElementById(this.getAttribute('output')); - // in this case, the default output-mode is append, if hasn't been specified - if (!this.hasAttribute('output-mode')) { - this.setAttribute('output-mode', 'append'); - } - } - else { - if (this.hasAttribute('std-out')) { - this.outputElement = document.getElementById(this.getAttribute('std-out')); - } - else { - // In this case neither output or std-out have been provided so we need - // to create a new output div to output to - this.outputElement = document.createElement('div'); - this.outputElement.classList.add('output'); - this.outputElement.hidden = true; - this.outputElement.id = this.id + '-' + this.getAttribute('exec-id'); - } - if (this.hasAttribute('std-err')) { - this.errorElement = document.getElementById(this.getAttribute('std-err')); - } - else { - this.errorElement = this.outputElement; - } - } - } - async getSourceFromFile(s) { - const response = await fetch(s); - return await response.text(); - } - async eval(source) { - try { - const output = await runtime$2.run(source); - if (output !== undefined) { - logger$b.info('PyWidget.eval: ', output); - } - } - catch (err) { - logger$b.error('PyWidget.eval: ', err); - } - } - } + const logger$a = getLogger('pyscript/pyodide'); + /* + RemoteInterpreter class is responsible to process requests from the + `InterpreterClient` class -- these can be requests for installation of + a package, executing code, etc. - const logger$a = getLogger('py-script'); - // Premise used to connect to the first available runtime (can be pyodide or others) - let runtime$1; - runtimeLoaded.subscribe(value => { - runtime$1 = value; - }); - loadedEnvironments.subscribe(value => { - }); - class PyScript extends BaseEvalElement { - constructor() { - super(); - // add an extra div where we can attach the codemirror editor - this.shadow.appendChild(this.wrapper); - } - connectedCallback() { - this.checkId(); - this.code = htmlDecode(this.innerHTML); - this.innerHTML = ''; - const mainDiv = document.createElement('div'); - addClasses(mainDiv, ['output']); - // add Editor to main PyScript div - if (this.hasAttribute('output')) { - this.errorElement = this.outputElement = document.getElementById(this.getAttribute('output')); - // in this case, the default output-mode is append, if hasn't been specified - if (!this.hasAttribute('output-mode')) { - this.setAttribute('output-mode', 'append'); - } - } - else { - if (this.hasAttribute('std-out')) { - this.outputElement = document.getElementById(this.getAttribute('std-out')); - } - else { - // In this case neither output or std-out have been provided so we need - // to create a new output div to output to - // Let's check if we have an id first and create one if not - this.outputElement = document.createElement('div'); - const exec_id = this.getAttribute('exec-id'); - this.outputElement.id = this.id + (exec_id ? '-' + exec_id : ''); - // add the output div id if there's not output pre-defined - mainDiv.appendChild(this.outputElement); - } - if (this.hasAttribute('std-err')) { - this.errorElement = document.getElementById(this.getAttribute('std-err')); - } - else { - this.errorElement = this.outputElement; - } - } - this.appendChild(mainDiv); - addToScriptsQueue(this); - if (this.hasAttribute('src')) { - this.source = this.getAttribute('src'); - } - } - async _register_esm(runtime) { - for (const node of document.querySelectorAll("script[type='importmap']")) { - const importmap = (() => { - try { - return JSON.parse(node.textContent); - } - catch { - return null; - } - })(); - if (importmap?.imports == null) - continue; - for (const [name, url] of Object.entries(importmap.imports)) { - if (typeof name != 'string' || typeof url != 'string') - continue; - let exports; - try { - // XXX: pyodide doesn't like Module(), failing with - // "can't read 'name' of undefined" at import time - exports = { ...(await import(url)) }; - } - catch { - logger$a.warn(`failed to fetch '${url}' for '${name}'`); - continue; - } - runtime.registerJsModule(name, exports); - } - } - } - getSourceFromElement() { - return htmlDecode(this.code); - } - } - /** Defines all possible py-on* and their corresponding event types */ - const pyAttributeToEvent = new Map([ - // Leaving pys-onClick and pys-onKeyDown for backward compatibility - ["pys-onClick", "click"], - ["pys-onKeyDown", "keydown"], - ["py-onClick", "click"], - ["py-onKeyDown", "keydown"], - // Window Events - ["py-afterprint", "afterprint"], - ["py-beforeprint", "beforeprint"], - ["py-beforeunload", "beforeunload"], - ["py-error", "error"], - ["py-hashchange", "hashchange"], - ["py-load", "load"], - ["py-message", "message"], - ["py-offline", "offline"], - ["py-online", "online"], - ["py-pagehide", "pagehide"], - ["py-pageshow", "pageshow"], - ["py-popstate", "popstate"], - ["py-resize", "resize"], - ["py-storage", "storage"], - ["py-unload", "unload"], - // Form Events - ["py-blur", "blur"], - ["py-change", "change"], - ["py-contextmenu", "contextmenu"], - ["py-focus", "focus"], - ["py-input", "input"], - ["py-invalid", "invalid"], - ["py-reset", "reset"], - ["py-search", "search"], - ["py-select", "select"], - ["py-submit", "submit"], - // Keyboard Events - ["py-keydown", "keydown"], - ["py-keypress", "keypress"], - ["py-keyup", "keyup"], - // Mouse Events - ["py-click", "click"], - ["py-dblclick", "dblclick"], - ["py-mousedown", "mousedown"], - ["py-mousemove", "mousemove"], - ["py-mouseout", "mouseout"], - ["py-mouseover", "mouseover"], - ["py-mouseup", "mouseup"], - ["py-mousewheel", "mousewheel"], - ["py-wheel", "wheel"], - // Drag Events - ["py-drag", "drag"], - ["py-dragend", "dragend"], - ["py-dragenter", "dragenter"], - ["py-dragleave", "dragleave"], - ["py-dragover", "dragover"], - ["py-dragstart", "dragstart"], - ["py-drop", "drop"], - ["py-scroll", "scroll"], - // Clipboard Events - ["py-copy", "copy"], - ["py-cut", "cut"], - ["py-paste", "paste"], - // Media Events - ["py-abort", "abort"], - ["py-canplay", "canplay"], - ["py-canplaythrough", "canplaythrough"], - ["py-cuechange", "cuechange"], - ["py-durationchange", "durationchange"], - ["py-emptied", "emptied"], - ["py-ended", "ended"], - ["py-loadeddata", "loadeddata"], - ["py-loadedmetadata", "loadedmetadata"], - ["py-loadstart", "loadstart"], - ["py-pause", "pause"], - ["py-play", "play"], - ["py-playing", "playing"], - ["py-progress", "progress"], - ["py-ratechange", "ratechange"], - ["py-seeked", "seeked"], - ["py-seeking", "seeking"], - ["py-stalled", "stalled"], - ["py-suspend", "suspend"], - ["py-timeupdate", "timeupdate"], - ["py-volumechange", "volumechange"], - ["py-waiting", "waiting"], - // Misc Events - ["py-toggle", "toggle"], - ]); - /** Initialize all elements with py-* handlers attributes */ - async function initHandlers() { - logger$a.debug('Initializing py-* event handlers...'); - for (const pyAttribute of pyAttributeToEvent.keys()) { - await createElementsWithEventListeners(runtime$1, pyAttribute); - } - } - /** Initializes an element with the given py-on* attribute and its handler */ - async function createElementsWithEventListeners(runtime, pyAttribute) { - const matches = document.querySelectorAll(`[${pyAttribute}]`); - for (const el of matches) { - if (el.id.length === 0) { - throw new TypeError(`<${el.tagName.toLowerCase()}> must have an id attribute, when using the ${pyAttribute} attribute`); - } - const handlerCode = el.getAttribute(pyAttribute); - const event = pyAttributeToEvent.get(pyAttribute); - if (pyAttribute === 'pys-onClick' || pyAttribute === 'pys-onKeyDown') { - console.warn("Use of pys-onClick and pys-onKeyDown attributes is deprecated in favor of py-onClick() and py-onKeyDown(). pys-on* attributes will be deprecated in a future version of PyScript."); - const source = ` + Currently, the only interpreter available is Pyodide as indicated by the + `InterpreterInterface` type above. This serves as a Union of types of + different interpreters which will be added in near future. + + Methods available handle loading of the interpreter, initialization, + running code, loading and installation of packages, loading from files etc. + + The class will be turned `abstract` in future, to support more runtimes + such as MicroPython. + */ + class RemoteInterpreter extends Object { + constructor(src = 'https://cdn.jsdelivr.net/pyodide/v0.22.1/full/pyodide.js') { + super(); + this.src = src; + } + /** + * loads the interface for the interpreter and saves an instance of it + * in the `this.interface` property along with calling of other + * additional convenience functions. + * */ + /** + * Although `loadPyodide` is used below, + * notice that it is not imported i.e. + * import { loadPyodide } from 'pyodide'; + * is not used at the top of this file. + * + * This is because, if it's used, loadPyodide + * behaves mischievously i.e. it tries to load + * `pyodide.asm.js` and `pyodide_py.tar` but + * with paths that are wrong such as: + * + * http://127.0.0.1:8080/build/pyodide_py.tar + * which results in a 404 since `build` doesn't + * contain these files and is clearly the wrong + * path. + */ + async loadInterpreter(config, stdio) { + this.interface = await loadPyodide({ + stdout: (msg) => { + stdio.stdout_writeline(msg); + }, + stderr: (msg) => { + stdio.stderr_writeline(msg); + }, + fullStdLib: false, + }); + // TODO: Remove this once `runtimes` is removed! + this.interpreter = this.interface; + this.globals = this.interface.globals; + if (config.packages) { + logger$a.info('Found packages in configuration to install. Loading micropip...'); + await this.loadPackage('micropip'); + } + logger$a.info('pyodide loaded and initialized'); + await this.run('print("Python initialization complete")'); + } + /* eslint-disable */ + async run(code) { + /** + * eslint wants `await` keyword to be used i.e. + * { result: await this.interface.runPython(code) } + * However, `await` is not a no-op (no-operation) i.e. + * `await 42` is NOT the same as `42` i.e. if the awaited + * thing is not a promise, it is wrapped inside a promise and + * that promise is awaited. Thus, it changes the execution order. + * See https://stackoverflow.com/questions/55262996/does-awaiting-a-non-promise-have-any-detectable-effect + * Thus, `eslint` is disabled for this block / snippet. + */ + /** + * The output of `runPython` is wrapped inside an object + * since an object is not thennable and avoids return of + * a coroutine directly. This is so we do not `await` the results + * of the underlying python execution, even if it's an + * awaitable object (Future, Task, etc.) + */ + return { result: this.interface.runPython(code) }; + } + /* eslint-enable */ + /** + * delegates the registration of JS modules to + * the underlying interface. + * */ + registerJsModule(name, module) { + this.interface.registerJsModule(name, module); + } + /** + * delegates the loading of packages to + * the underlying interface. + * */ + async loadPackage(names) { + logger$a.info(`pyodide.loadPackage: ${names.toString()}`); + // the new way in v0.22.1 is to pass it as a dict of options i.e. + // { messageCallback: logger.info.bind(logger), errorCallback: logger.info.bind(logger) } + // but one of our tests tries to use a locally downloaded older version of pyodide + // for which the signature of `loadPackage` accepts the above params as args i.e. + // the call uses `logger.info.bind(logger), logger.info.bind(logger)`. + const pyodide_version = (await this.run("import sys; sys.modules['pyodide'].__version__")).result.toString(); + if (pyodide_version.startsWith('0.22')) { + await this.interface.loadPackage(names, { + messageCallback: logger$a.info.bind(logger$a), + errorCallback: logger$a.info.bind(logger$a), + }); + } + else { + await this.interface.loadPackage(names, logger$a.info.bind(logger$a), logger$a.info.bind(logger$a)); + } + } + /** + * delegates the installation of packages + * (using a package manager, which can be specific to + * the interface) to the underlying interface. + * + * For Pyodide, we use `micropip` + * */ + async installPackage(package_name) { + if (package_name.length > 0) { + logger$a.info(`micropip install ${package_name.toString()}`); + const micropip = this.interface.pyimport('micropip'); + try { + await micropip.install(package_name); + micropip.destroy(); + } + catch (e) { + let exceptionMessage = `Unable to install package(s) '` + package_name + `'.`; + // If we can't fetch `package_name` micropip.install throws a huge + // Python traceback in `e.message` this logic is to handle the + // error and throw a more sensible error message instead of the + // huge traceback. + if (e.message.includes("Can't find a pure Python 3 wheel")) { + exceptionMessage += + ` Reason: Can't find a pure Python 3 Wheel for package(s) '` + + package_name + + `'. See: https://pyodide.org/en/stable/usage/faq.html#micropip-can-t-find-a-pure-python-wheel ` + + `for more information.`; + } + else if (e.message.includes("Can't fetch metadata")) { + exceptionMessage += + ' Unable to find package in PyPI. ' + + 'Please make sure you have entered a correct package name.'; + } + else { + exceptionMessage += + ` Reason: ${e.message}. Please open an issue at ` + + `https://github.com/pyscript/pyscript/issues/new if you require help or ` + + `you think it's a bug.`; + } + logger$a.error(e); + throw new InstallError(ErrorCode.MICROPIP_INSTALL_ERROR, exceptionMessage); + } + } + } + /** + * + * @param path : the path in the filesystem + * @param fetch_path : the path to be fetched + * + * Given a file available at `fetch_path` URL (eg: + * `http://dummy.com/hi.py`), the function downloads the file and saves it + * to the `path` (eg: `a/b/c/foo.py`) on the FS. + * + * Example usage: await loadFromFile(`a/b/c/foo.py`, + * `http://dummy.com/hi.py`) + * + * Write content of `http://dummy.com/hi.py` to `a/b/c/foo.py` + * + * NOTE: The `path` parameter expects to have the `filename` in it i.e. + * `a/b/c/foo.py` is valid while `a/b/c` (i.e. only the folders) are + * incorrect. + * + * The path will be resolved relative to the current working directory, + * which is initially `/home/pyodide`. So by default `a/b.py` will be placed + * in `/home/pyodide/a/b.py`, `../a/b.py` will be placed into `/home/a/b.py` + * and `/a/b.py` will be placed into `/a/b.py`. + */ + async loadFromFile(path, fetch_path) { + // eslint-disable-next-line @typescript-eslint/ban-ts-comment + // @ts-ignore + path = this.interface._module.PATH_FS.resolve(path); + // eslint-disable-next-line @typescript-eslint/ban-ts-comment + // @ts-ignore + const dir = this.interface._module.PATH.dirname(path); + this.interface.FS.mkdirTree(dir); + // `robustFetch` checks for failures in getting a response + const response = await robustFetch(fetch_path); + const buffer = await response.arrayBuffer(); + const data = new Uint8Array(buffer); + this.interface.FS.writeFile(path, data, { canOwn: true }); + } + /** + * delegates clearing importlib's module path + * caches to the underlying interface + */ + invalidate_module_path_cache() { + const importlib = this.interface.pyimport('importlib'); + importlib.invalidate_caches(); + } + } + + const logger$9 = getLogger('pyscript/interpreter'); + /* + InterpreterClient class is responsible to request code execution + (among other things) from a `RemoteInterpreter` + */ + class InterpreterClient extends Object { + constructor(config, stdio) { + super(); + this.config = config; + this._remote = new RemoteInterpreter(this.config.interpreters[0].src); + this.stdio = stdio; + } + /** + * initializes the remote interpreter, which further loads the underlying + * interface. + * */ + async initializeRemote() { + await this._remote.loadInterpreter(this.config, this.stdio); + this.globals = this._remote.globals; + } + /** + * delegates the code to be run to the underlying interface of + * the remote interpreter. + * Python exceptions are turned into JS exceptions. + * */ + async run(code) { + return await this._remote.run(code); + } + /** + * Same as run, but Python exceptions are not propagated: instead, they + * are logged to the console. + * + * This is a bad API and should be killed/refactored/changed eventually, + * but for now we have code which relies on it. + * */ + async runButDontRaise(code) { + let result; + try { + result = (await this.run(code)).result; + } + catch (error) { + logger$9.error('Error:', error); + } + return result; + } + } + + const logger$8 = getLogger('plugin'); + class Plugin { + /** Validate the configuration of the plugin and handle default values. + * + * Individual plugins are expected to check that the config keys/sections + * which are relevant to them contains valid values, and to raise an error + * if they contains unknown keys. + * + * This is also a good place where set default values for those keys which + * are not specified by the user. + * + * This hook should **NOT** contain expensive operations, else it delays + * the download of the python interpreter which is initiated later. + */ + configure(config) { } + /** The preliminary initialization phase is complete and we are about to + * download and launch the Python interpreter. + * + * We can assume that the page is already shown to the user and that the + * DOM content has been loaded. This is a good place where to add tags to + * the DOM, if needed. + * + * This hook should **NOT** contain expensive operations, else it delays + * the download of the python interpreter which is initiated later. + */ + beforeLaunch(config) { } + /** The Python interpreter has been launched, the virtualenv has been + * installed and we are ready to execute user code. + * + * The <py-script> tags will be executed after this hook. + */ + afterSetup(interpreter) { } + /** The source of a <py-script>> tag has been fetched, and we're about + * to evaluate that source using the provided interpreter. + * + * @param options.interpreter The Interpreter object that will be used to evaluated the Python source code + * @param options.src {string} The Python source code to be evaluated + * @param options.pyScriptTag The <py-script> HTML tag that originated the evaluation + */ + beforePyScriptExec(options) { } + /** The Python in a <py-script> has just been evaluated, but control + * has not been ceded back to the JavaScript event loop yet + * + * @param options.interpreter The Interpreter object that will be used to evaluated the Python source code + * @param options.src {string} The Python source code to be evaluated + * @param options.pyScriptTag The <py-script> HTML tag that originated the evaluation + * @param options.result The returned result of evaluating the Python (if any) + */ + afterPyScriptExec(options) { } + /** Startup complete. The interpreter is initialized and ready, user + * scripts have been executed: the main initialization logic ends here and + * the page is ready to accept user interactions. + */ + afterStartup(interpreter) { } + /** Called when an UserError is raised + */ + onUserError(error) { } + } + class PluginManager { + constructor() { + this._plugins = []; + this._pythonPlugins = []; + } + add(...plugins) { + for (const p of plugins) + this._plugins.push(p); + } + addPythonPlugin(plugin) { + this._pythonPlugins.push(plugin); + } + configure(config) { + for (const p of this._plugins) + p.configure?.(config); + for (const p of this._pythonPlugins) + p.configure?.(config); + } + beforeLaunch(config) { + for (const p of this._plugins) { + try { + p?.beforeLaunch?.(config); + } + catch (e) { + logger$8.error(`Error while calling beforeLaunch hook of plugin ${p.constructor.name}`, e); + } + } + } + afterSetup(interpreter) { + for (const p of this._plugins) { + try { + p.afterSetup?.(interpreter); + } + catch (e) { + logger$8.error(`Error while calling afterSetup hook of plugin ${p.constructor.name}`, e); + } + } + for (const p of this._pythonPlugins) + p.afterSetup?.(interpreter); + } + afterStartup(interpreter) { + for (const p of this._plugins) + p.afterStartup?.(interpreter); + for (const p of this._pythonPlugins) + p.afterStartup?.(interpreter); + } + beforePyScriptExec(options) { + for (const p of this._plugins) + p.beforePyScriptExec?.(options); + for (const p of this._pythonPlugins) + p.beforePyScriptExec?.callKwargs(options); + } + afterPyScriptExec(options) { + for (const p of this._plugins) + p.afterPyScriptExec?.(options); + for (const p of this._pythonPlugins) + p.afterPyScriptExec?.callKwargs(options); + } + onUserError(error) { + for (const p of this._plugins) + p.onUserError?.(error); + for (const p of this._pythonPlugins) + p.onUserError?.(error); + } + } + /** + * Defines a new CustomElement (via customElement.defines) with `tag`, + * where the new CustomElement is a proxy that delegates the logic to + * pyPluginClass. + * + * @param tag - tag that will be used to define the new CustomElement (i.e: "py-script") + * @param pyPluginClass - class that will be used to create instance to be + * used as CustomElement logic handler. Any DOM event + * received by the newly created CustomElement will be + * delegated to that instance. + */ + function define_custom_element(tag, pyPluginClass) { + logger$8.info(`creating plugin: ${tag}`); + class ProxyCustomElement extends HTMLElement { + constructor() { + logger$8.debug(`creating ${tag} plugin instance`); + super(); + this.shadow = this.attachShadow({ mode: 'open' }); + this.wrapper = document.createElement('slot'); + this.shadow.appendChild(this.wrapper); + this.originalInnerHTML = this.innerHTML; + this.pyPluginInstance = pyPluginClass(this); + } + connectedCallback() { + const innerHTML = this.pyPluginInstance.connect(); + if (typeof innerHTML === 'string') + this.innerHTML = innerHTML; + } + } + customElements.define(tag, ProxyCustomElement); + } + + const logger$7 = getLogger('pyexec'); + async function pyExec(interpreter, pysrc, outElem) { + //This is pyscript.py + const pyscript_py = interpreter._remote.interface.pyimport('pyscript'); + ensureUniqueId(outElem); + pyscript_py.set_current_display_target(outElem.id); + try { + try { + if (pyscript_py.uses_top_level_await(pysrc)) { + throw new UserError(ErrorCode.TOP_LEVEL_AWAIT, 'The use of top-level "await", "async for", and ' + + '"async with" has been removed.' + + '\nPlease write a coroutine containing ' + + 'your code and schedule it using asyncio.ensure_future() or similar.' + + '\nSee https://docs.pyscript.net/latest/guides/asyncio.html for more information.'); + } + return await interpreter.run(pysrc); + } + catch (err) { + // XXX: currently we display exceptions in the same position as + // the output. But we probably need a better way to do that, + // e.g. allowing plugins to intercept exceptions and display them + // in a configurable way. + displayPyException(err, outElem); + return { result: undefined }; + } + } + finally { + pyscript_py.set_current_display_target(undefined); + pyscript_py.destroy(); + } + } + /** + * Javascript API to call the python display() function + * + * Expected usage: + * pyDisplay(interpreter, obj); + * pyDisplay(interpreter, obj, { target: targetID }); + */ + function pyDisplay(interpreter, obj, kwargs) { + const display = interpreter.globals.get('display'); + if (kwargs === undefined) + display(obj); + else { + display.callKwargs(obj, kwargs); + } + } + function displayPyException(err, errElem) { + //addClasses(errElem, ['py-error']) + const pre = document.createElement('pre'); + pre.className = 'py-error'; + if (err.name === 'PythonError') { + // err.message contains the python-level traceback (i.e. a string + // starting with: "Traceback (most recent call last) ..." + logger$7.error('Python exception:\n' + err.message); + pre.innerText = err.message; + } + else { + // this is very likely a normal JS exception. The best we can do is to + // display it as is. + logger$7.error('Non-python exception:\n' + err); + pre.innerText = err; + } + errElem.appendChild(pre); + } + + const logger$6 = getLogger('py-script'); + function make_PyScript(interpreter, app) { + class PyScript extends HTMLElement { + async connectedCallback() { + /** + * Since connectedCallback is async, multiple py-script tags can be executed in + * an order which is not particularly sequential. The locking mechanism here ensures + * a sequential execution of multiple py-script tags present in one page. + * + * Concurrent access to the multiple py-script tags is thus avoided. + */ + let releaseLock; + try { + releaseLock = await app.tagExecutionLock(); + ensureUniqueId(this); + // Save innerHTML information in srcCode so we can access it later + // once we clean innerHTML (which is required since we don't want + // source code to be rendered on the screen) + this.srcCode = this.innerHTML; + const pySrc = await this.getPySrc(); + this.innerHTML = ''; + app.plugins.beforePyScriptExec({ interpreter: interpreter, src: pySrc, pyScriptTag: this }); + const result = (await pyExec(interpreter, pySrc, this)).result; + app.plugins.afterPyScriptExec({ + interpreter: interpreter, + src: pySrc, + pyScriptTag: this, + result: result, + }); + } + finally { + releaseLock(); + } + } + async getPySrc() { + if (this.hasAttribute('src')) { + const url = this.getAttribute('src'); + try { + const response = await robustFetch(url); + return await response.text(); + } + catch (e) { + _createAlertBanner(e.message); + this.innerHTML = ''; + throw e; + } + } + else { + return htmlDecode(this.srcCode); + } + } + } + return PyScript; + } + /** Defines all possible py-on* and their corresponding event types */ + const pyAttributeToEvent = new Map([ + // Leaving pys-onClick and pys-onKeyDown for backward compatibility + ['pys-onClick', 'click'], + ['pys-onKeyDown', 'keydown'], + ['py-onClick', 'click'], + ['py-onKeyDown', 'keydown'], + // Window Events + ['py-afterprint', 'afterprint'], + ['py-beforeprint', 'beforeprint'], + ['py-beforeunload', 'beforeunload'], + ['py-error', 'error'], + ['py-hashchange', 'hashchange'], + ['py-load', 'load'], + ['py-message', 'message'], + ['py-offline', 'offline'], + ['py-online', 'online'], + ['py-pagehide', 'pagehide'], + ['py-pageshow', 'pageshow'], + ['py-popstate', 'popstate'], + ['py-resize', 'resize'], + ['py-storage', 'storage'], + ['py-unload', 'unload'], + // Form Events + ['py-blur', 'blur'], + ['py-change', 'change'], + ['py-contextmenu', 'contextmenu'], + ['py-focus', 'focus'], + ['py-input', 'input'], + ['py-invalid', 'invalid'], + ['py-reset', 'reset'], + ['py-search', 'search'], + ['py-select', 'select'], + ['py-submit', 'submit'], + // Keyboard Events + ['py-keydown', 'keydown'], + ['py-keypress', 'keypress'], + ['py-keyup', 'keyup'], + // Mouse Events + ['py-click', 'click'], + ['py-dblclick', 'dblclick'], + ['py-mousedown', 'mousedown'], + ['py-mousemove', 'mousemove'], + ['py-mouseout', 'mouseout'], + ['py-mouseover', 'mouseover'], + ['py-mouseup', 'mouseup'], + ['py-mousewheel', 'mousewheel'], + ['py-wheel', 'wheel'], + // Drag Events + ['py-drag', 'drag'], + ['py-dragend', 'dragend'], + ['py-dragenter', 'dragenter'], + ['py-dragleave', 'dragleave'], + ['py-dragover', 'dragover'], + ['py-dragstart', 'dragstart'], + ['py-drop', 'drop'], + ['py-scroll', 'scroll'], + // Clipboard Events + ['py-copy', 'copy'], + ['py-cut', 'cut'], + ['py-paste', 'paste'], + // Media Events + ['py-abort', 'abort'], + ['py-canplay', 'canplay'], + ['py-canplaythrough', 'canplaythrough'], + ['py-cuechange', 'cuechange'], + ['py-durationchange', 'durationchange'], + ['py-emptied', 'emptied'], + ['py-ended', 'ended'], + ['py-loadeddata', 'loadeddata'], + ['py-loadedmetadata', 'loadedmetadata'], + ['py-loadstart', 'loadstart'], + ['py-pause', 'pause'], + ['py-play', 'play'], + ['py-playing', 'playing'], + ['py-progress', 'progress'], + ['py-ratechange', 'ratechange'], + ['py-seeked', 'seeked'], + ['py-seeking', 'seeking'], + ['py-stalled', 'stalled'], + ['py-suspend', 'suspend'], + ['py-timeupdate', 'timeupdate'], + ['py-volumechange', 'volumechange'], + ['py-waiting', 'waiting'], + // Misc Events + ['py-toggle', 'toggle'], + ]); + /** Initialize all elements with py-* handlers attributes */ + function initHandlers(interpreter) { + logger$6.debug('Initializing py-* event handlers...'); + for (const pyAttribute of pyAttributeToEvent.keys()) { + createElementsWithEventListeners(interpreter, pyAttribute); + } + } + /** Initializes an element with the given py-on* attribute and its handler */ + function createElementsWithEventListeners(interpreter, pyAttribute) { + const matches = document.querySelectorAll(`[${pyAttribute}]`); + for (const el of matches) { + // If the element doesn't have an id, let's add one automatically! + if (el.id.length === 0) { + ensureUniqueId(el); + } + const handlerCode = el.getAttribute(pyAttribute); + const event = pyAttributeToEvent.get(pyAttribute); + if (pyAttribute === 'pys-onClick' || pyAttribute === 'pys-onKeyDown') { + const msg = `The attribute 'pys-onClick' and 'pys-onKeyDown' are deprecated. Please 'py-click="myFunction()"' ` + + ` or 'py-keydown="myFunction()"' instead.`; + createDeprecationWarning(msg, msg); + const source = ` from pyodide.ffi import create_proxy Element("${el.id}").element.addEventListener("${event}", create_proxy(${handlerCode})) `; - await runtime.run(source); - } - else { - el.addEventListener(event, () => { - (async () => { await runtime.run(handlerCode); })(); - }); - } - // TODO: Should we actually map handlers in JS instead of Python? - // el.onclick = (evt: any) => { - // console.log("click"); - // new Promise((resolve, reject) => { - // setTimeout(() => { - // console.log('Inside') - // }, 300); - // }).then(() => { - // console.log("resolved") - // }); - // // let handlerCode = el.getAttribute('py-onClick'); - // // pyodide.runPython(handlerCode); - // } - } - } - /** Mount all elements with attribute py-mount into the Python namespace */ - async function mountElements() { - const matches = document.querySelectorAll('[py-mount]'); - logger$a.info(`py-mount: found ${matches.length} elements`); - let source = ''; - for (const el of matches) { - const mountName = el.getAttribute('py-mount') || el.id.split('-').join('_'); - source += `\n${mountName} = Element("${el.id}")`; - } - await runtime$1.run(source); - } - addInitializer(mountElements); - addPostInitializer(initHandlers); - - /*! js-yaml 4.1.0 https://github.com/nodeca/js-yaml @license MIT */ - function isNothing(subject) { - return (typeof subject === 'undefined') || (subject === null); - } - - - function isObject(subject) { - return (typeof subject === 'object') && (subject !== null); - } - - - function toArray(sequence) { - if (Array.isArray(sequence)) return sequence; - else if (isNothing(sequence)) return []; - - return [ sequence ]; - } - - - function extend$1(target, source) { - var index, length, key, sourceKeys; - - if (source) { - sourceKeys = Object.keys(source); - - for (index = 0, length = sourceKeys.length; index < length; index += 1) { - key = sourceKeys[index]; - target[key] = source[key]; - } + // We meed to run the source code in a try/catch block, because + // the source code may contain a syntax error, which will cause + // the splashscreen to not be removed. + try { + interpreter.run(source); + } + catch (e) { + logger$6.error(e.message); + } + } + else { + el.addEventListener(event, () => { + void (async () => { + try { + await interpreter.run(handlerCode); + } + catch (err) { + displayPyException(err, el.parentElement); + } + })(); + }); + } + // TODO: Should we actually map handlers in JS instead of Python? + // el.onclick = (evt: any) => { + // console.log("click"); + // new Promise((resolve, reject) => { + // setTimeout(() => { + // console.log('Inside') + // }, 300); + // }).then(() => { + // console.log("resolved") + // }); + // // let handlerCode = el.getAttribute('py-onClick'); + // // pyodide.runPython(handlerCode); + // } } + } + /** Mount all elements with attribute py-mount into the Python namespace */ + async function mountElements(interpreter) { + const matches = document.querySelectorAll('[py-mount]'); + logger$6.info(`py-mount: found ${matches.length} elements`); + let source = ''; + for (const el of matches) { + const mountName = el.getAttribute('py-mount') || el.id.split('-').join('_'); + source += `\n${mountName} = Element("${el.id}")`; + } + await interpreter.run(source); + } + function calculatePaths(fetch_cfg) { + const fetchPaths = []; + const paths = []; + fetch_cfg.forEach(function (each_fetch_cfg) { + const from = each_fetch_cfg.from || ''; + const to_folder = each_fetch_cfg.to_folder || '.'; + const to_file = each_fetch_cfg.to_file; + const files = each_fetch_cfg.files; + if (files !== undefined) { + if (to_file !== undefined) { + throw new UserError(ErrorCode.BAD_CONFIG, `Cannot use 'to_file' and 'files' parameters together!`); + } + for (const each_f of files) { + const each_fetch_path = joinPaths([from, each_f]); + fetchPaths.push(each_fetch_path); + const each_path = joinPaths([to_folder, each_f]); + paths.push(each_path); + } + } + else { + fetchPaths.push(from); + const filename = to_file || from.split('/').pop(); + if (filename === '') { + throw new UserError(ErrorCode.BAD_CONFIG, `Couldn't determine the filename from the path ${from}, please supply 'to_file' parameter.`); + } + else { + paths.push(joinPaths([to_folder, filename])); + } + } + }); + return [paths, fetchPaths]; + } + + /** + The data structure for documents. @nonabstract + */ + class Text { + /** + @internal + */ + constructor() { } + /** + Get the line description around the given position. + */ + lineAt(pos) { + if (pos < 0 || pos > this.length) + throw new RangeError(`Invalid position ${pos} in document of length ${this.length}`); + return this.lineInner(pos, false, 1, 0); + } + /** + Get the description for the given (1-based) line number. + */ + line(n) { + if (n < 1 || n > this.lines) + throw new RangeError(`Invalid line number ${n} in ${this.lines}-line document`); + return this.lineInner(n, true, 1, 0); + } + /** + Replace a range of the text with the given content. + */ + replace(from, to, text) { + let parts = []; + this.decompose(0, from, parts, 2 /* Open.To */); + if (text.length) + text.decompose(0, text.length, parts, 1 /* Open.From */ | 2 /* Open.To */); + this.decompose(to, this.length, parts, 1 /* Open.From */); + return TextNode.from(parts, this.length - (to - from) + text.length); + } + /** + Append another document to this one. + */ + append(other) { + return this.replace(this.length, this.length, other); + } + /** + Retrieve the text between the given points. + */ + slice(from, to = this.length) { + let parts = []; + this.decompose(from, to, parts, 0); + return TextNode.from(parts, to - from); + } + /** + Test whether this text is equal to another instance. + */ + eq(other) { + if (other == this) + return true; + if (other.length != this.length || other.lines != this.lines) + return false; + let start = this.scanIdentical(other, 1), end = this.length - this.scanIdentical(other, -1); + let a = new RawTextCursor(this), b = new RawTextCursor(other); + for (let skip = start, pos = start;;) { + a.next(skip); + b.next(skip); + skip = 0; + if (a.lineBreak != b.lineBreak || a.done != b.done || a.value != b.value) + return false; + pos += a.value.length; + if (a.done || pos >= end) + return true; + } + } + /** + Iterate over the text. When `dir` is `-1`, iteration happens + from end to start. This will return lines and the breaks between + them as separate strings. + */ + iter(dir = 1) { return new RawTextCursor(this, dir); } + /** + Iterate over a range of the text. When `from` > `to`, the + iterator will run in reverse. + */ + iterRange(from, to = this.length) { return new PartialTextCursor(this, from, to); } + /** + Return a cursor that iterates over the given range of lines, + _without_ returning the line breaks between, and yielding empty + strings for empty lines. + + When `from` and `to` are given, they should be 1-based line numbers. + */ + iterLines(from, to) { + let inner; + if (from == null) { + inner = this.iter(); + } + else { + if (to == null) + to = this.lines + 1; + let start = this.line(from).from; + inner = this.iterRange(start, Math.max(start, to == this.lines + 1 ? this.length : to <= 1 ? 0 : this.line(to - 1).to)); + } + return new LineCursor(inner); + } + /** + @internal + */ + toString() { return this.sliceString(0); } + /** + Convert the document to an array of lines (which can be + deserialized again via [`Text.of`](https://codemirror.net/6/docs/ref/#state.Text^of)). + */ + toJSON() { + let lines = []; + this.flatten(lines); + return lines; + } + /** + Create a `Text` instance for the given array of lines. + */ + static of(text) { + if (text.length == 0) + throw new RangeError("A document must have at least one line"); + if (text.length == 1 && !text[0]) + return Text.empty; + return text.length <= 32 /* Tree.Branch */ ? new TextLeaf(text) : TextNode.from(TextLeaf.split(text, [])); + } + } + // Leaves store an array of line strings. There are always line breaks + // between these strings. Leaves are limited in size and have to be + // contained in TextNode instances for bigger documents. + class TextLeaf extends Text { + constructor(text, length = textLength(text)) { + super(); + this.text = text; + this.length = length; + } + get lines() { return this.text.length; } + get children() { return null; } + lineInner(target, isLine, line, offset) { + for (let i = 0;; i++) { + let string = this.text[i], end = offset + string.length; + if ((isLine ? line : end) >= target) + return new Line(offset, end, line, string); + offset = end + 1; + line++; + } + } + decompose(from, to, target, open) { + let text = from <= 0 && to >= this.length ? this + : new TextLeaf(sliceText(this.text, from, to), Math.min(to, this.length) - Math.max(0, from)); + if (open & 1 /* Open.From */) { + let prev = target.pop(); + let joined = appendText(text.text, prev.text.slice(), 0, text.length); + if (joined.length <= 32 /* Tree.Branch */) { + target.push(new TextLeaf(joined, prev.length + text.length)); + } + else { + let mid = joined.length >> 1; + target.push(new TextLeaf(joined.slice(0, mid)), new TextLeaf(joined.slice(mid))); + } + } + else { + target.push(text); + } + } + replace(from, to, text) { + if (!(text instanceof TextLeaf)) + return super.replace(from, to, text); + let lines = appendText(this.text, appendText(text.text, sliceText(this.text, 0, from)), to); + let newLen = this.length + text.length - (to - from); + if (lines.length <= 32 /* Tree.Branch */) + return new TextLeaf(lines, newLen); + return TextNode.from(TextLeaf.split(lines, []), newLen); + } + sliceString(from, to = this.length, lineSep = "\n") { + let result = ""; + for (let pos = 0, i = 0; pos <= to && i < this.text.length; i++) { + let line = this.text[i], end = pos + line.length; + if (pos > from && i) + result += lineSep; + if (from < end && to > pos) + result += line.slice(Math.max(0, from - pos), to - pos); + pos = end + 1; + } + return result; + } + flatten(target) { + for (let line of this.text) + target.push(line); + } + scanIdentical() { return 0; } + static split(text, target) { + let part = [], len = -1; + for (let line of text) { + part.push(line); + len += line.length + 1; + if (part.length == 32 /* Tree.Branch */) { + target.push(new TextLeaf(part, len)); + part = []; + len = -1; + } + } + if (len > -1) + target.push(new TextLeaf(part, len)); + return target; + } + } + // Nodes provide the tree structure of the `Text` type. They store a + // number of other nodes or leaves, taking care to balance themselves + // on changes. There are implied line breaks _between_ the children of + // a node (but not before the first or after the last child). + class TextNode extends Text { + constructor(children, length) { + super(); + this.children = children; + this.length = length; + this.lines = 0; + for (let child of children) + this.lines += child.lines; + } + lineInner(target, isLine, line, offset) { + for (let i = 0;; i++) { + let child = this.children[i], end = offset + child.length, endLine = line + child.lines - 1; + if ((isLine ? endLine : end) >= target) + return child.lineInner(target, isLine, line, offset); + offset = end + 1; + line = endLine + 1; + } + } + decompose(from, to, target, open) { + for (let i = 0, pos = 0; pos <= to && i < this.children.length; i++) { + let child = this.children[i], end = pos + child.length; + if (from <= end && to >= pos) { + let childOpen = open & ((pos <= from ? 1 /* Open.From */ : 0) | (end >= to ? 2 /* Open.To */ : 0)); + if (pos >= from && end <= to && !childOpen) + target.push(child); + else + child.decompose(from - pos, to - pos, target, childOpen); + } + pos = end + 1; + } + } + replace(from, to, text) { + if (text.lines < this.lines) + for (let i = 0, pos = 0; i < this.children.length; i++) { + let child = this.children[i], end = pos + child.length; + // Fast path: if the change only affects one child and the + // child's size remains in the acceptable range, only update + // that child + if (from >= pos && to <= end) { + let updated = child.replace(from - pos, to - pos, text); + let totalLines = this.lines - child.lines + updated.lines; + if (updated.lines < (totalLines >> (5 /* Tree.BranchShift */ - 1)) && + updated.lines > (totalLines >> (5 /* Tree.BranchShift */ + 1))) { + let copy = this.children.slice(); + copy[i] = updated; + return new TextNode(copy, this.length - (to - from) + text.length); + } + return super.replace(pos, end, updated); + } + pos = end + 1; + } + return super.replace(from, to, text); + } + sliceString(from, to = this.length, lineSep = "\n") { + let result = ""; + for (let i = 0, pos = 0; i < this.children.length && pos <= to; i++) { + let child = this.children[i], end = pos + child.length; + if (pos > from && i) + result += lineSep; + if (from < end && to > pos) + result += child.sliceString(from - pos, to - pos, lineSep); + pos = end + 1; + } + return result; + } + flatten(target) { + for (let child of this.children) + child.flatten(target); + } + scanIdentical(other, dir) { + if (!(other instanceof TextNode)) + return 0; + let length = 0; + let [iA, iB, eA, eB] = dir > 0 ? [0, 0, this.children.length, other.children.length] + : [this.children.length - 1, other.children.length - 1, -1, -1]; + for (;; iA += dir, iB += dir) { + if (iA == eA || iB == eB) + return length; + let chA = this.children[iA], chB = other.children[iB]; + if (chA != chB) + return length + chA.scanIdentical(chB, dir); + length += chA.length + 1; + } + } + static from(children, length = children.reduce((l, ch) => l + ch.length + 1, -1)) { + let lines = 0; + for (let ch of children) + lines += ch.lines; + if (lines < 32 /* Tree.Branch */) { + let flat = []; + for (let ch of children) + ch.flatten(flat); + return new TextLeaf(flat, length); + } + let chunk = Math.max(32 /* Tree.Branch */, lines >> 5 /* Tree.BranchShift */), maxChunk = chunk << 1, minChunk = chunk >> 1; + let chunked = [], currentLines = 0, currentLen = -1, currentChunk = []; + function add(child) { + let last; + if (child.lines > maxChunk && child instanceof TextNode) { + for (let node of child.children) + add(node); + } + else if (child.lines > minChunk && (currentLines > minChunk || !currentLines)) { + flush(); + chunked.push(child); + } + else if (child instanceof TextLeaf && currentLines && + (last = currentChunk[currentChunk.length - 1]) instanceof TextLeaf && + child.lines + last.lines <= 32 /* Tree.Branch */) { + currentLines += child.lines; + currentLen += child.length + 1; + currentChunk[currentChunk.length - 1] = new TextLeaf(last.text.concat(child.text), last.length + 1 + child.length); + } + else { + if (currentLines + child.lines > chunk) + flush(); + currentLines += child.lines; + currentLen += child.length + 1; + currentChunk.push(child); + } + } + function flush() { + if (currentLines == 0) + return; + chunked.push(currentChunk.length == 1 ? currentChunk[0] : TextNode.from(currentChunk, currentLen)); + currentLen = -1; + currentLines = currentChunk.length = 0; + } + for (let child of children) + add(child); + flush(); + return chunked.length == 1 ? chunked[0] : new TextNode(chunked, length); + } + } + Text.empty = /*@__PURE__*/new TextLeaf([""], 0); + function textLength(text) { + let length = -1; + for (let line of text) + length += line.length + 1; + return length; + } + function appendText(text, target, from = 0, to = 1e9) { + for (let pos = 0, i = 0, first = true; i < text.length && pos <= to; i++) { + let line = text[i], end = pos + line.length; + if (end >= from) { + if (end > to) + line = line.slice(0, to - pos); + if (pos < from) + line = line.slice(from - pos); + if (first) { + target[target.length - 1] += line; + first = false; + } + else + target.push(line); + } + pos = end + 1; + } return target; - } - - - function repeat(string, count) { - var result = '', cycle; - - for (cycle = 0; cycle < count; cycle += 1) { - result += string; + } + function sliceText(text, from, to) { + return appendText(text, [""], from, to); + } + class RawTextCursor { + constructor(text, dir = 1) { + this.dir = dir; + this.done = false; + this.lineBreak = false; + this.value = ""; + this.nodes = [text]; + this.offsets = [dir > 0 ? 1 : (text instanceof TextLeaf ? text.text.length : text.children.length) << 1]; } - - return result; - } - - - function isNegativeZero(number) { - return (number === 0) && (Number.NEGATIVE_INFINITY === 1 / number); - } - - - var isNothing_1 = isNothing; - var isObject_1 = isObject; - var toArray_1 = toArray; - var repeat_1 = repeat; - var isNegativeZero_1 = isNegativeZero; - var extend_1 = extend$1; - - var common = { - isNothing: isNothing_1, - isObject: isObject_1, - toArray: toArray_1, - repeat: repeat_1, - isNegativeZero: isNegativeZero_1, - extend: extend_1 - }; - - // YAML error class. http://stackoverflow.com/questions/8458984 - - - function formatError(exception, compact) { - var where = '', message = exception.reason || '(unknown reason)'; - - if (!exception.mark) return message; - - if (exception.mark.name) { - where += 'in "' + exception.mark.name + '" '; - } - - where += '(' + (exception.mark.line + 1) + ':' + (exception.mark.column + 1) + ')'; - - if (!compact && exception.mark.snippet) { - where += '\n\n' + exception.mark.snippet; - } - - return message + ' ' + where; - } - - - function YAMLException$1(reason, mark) { - // Super constructor - Error.call(this); - - this.name = 'YAMLException'; - this.reason = reason; - this.mark = mark; - this.message = formatError(this, false); - - // Include stack trace in error object - if (Error.captureStackTrace) { - // Chrome and NodeJS - Error.captureStackTrace(this, this.constructor); - } else { - // FF, IE 10+ and Safari 6+. Fallback for others - this.stack = (new Error()).stack || ''; - } - } - - - // Inherit from Error - YAMLException$1.prototype = Object.create(Error.prototype); - YAMLException$1.prototype.constructor = YAMLException$1; - - - YAMLException$1.prototype.toString = function toString(compact) { - return this.name + ': ' + formatError(this, compact); - }; - - - var exception = YAMLException$1; - - // get snippet for a single line, respecting maxLength - function getLine(buffer, lineStart, lineEnd, position, maxLineLength) { - var head = ''; - var tail = ''; - var maxHalfLength = Math.floor(maxLineLength / 2) - 1; - - if (position - lineStart > maxHalfLength) { - head = ' ... '; - lineStart = position - maxHalfLength + head.length; - } - - if (lineEnd - position > maxHalfLength) { - tail = ' ...'; - lineEnd = position + maxHalfLength - tail.length; - } - - return { - str: head + buffer.slice(lineStart, lineEnd).replace(/\t/g, '→') + tail, - pos: position - lineStart + head.length // relative position - }; - } - - - function padStart(string, max) { - return common.repeat(' ', max - string.length) + string; - } - - - function makeSnippet(mark, options) { - options = Object.create(options || null); - - if (!mark.buffer) return null; - - if (!options.maxLength) options.maxLength = 79; - if (typeof options.indent !== 'number') options.indent = 1; - if (typeof options.linesBefore !== 'number') options.linesBefore = 3; - if (typeof options.linesAfter !== 'number') options.linesAfter = 2; - - var re = /\r?\n|\r|\0/g; - var lineStarts = [ 0 ]; - var lineEnds = []; - var match; - var foundLineNo = -1; - - while ((match = re.exec(mark.buffer))) { - lineEnds.push(match.index); - lineStarts.push(match.index + match[0].length); - - if (mark.position <= match.index && foundLineNo < 0) { - foundLineNo = lineStarts.length - 2; - } - } - - if (foundLineNo < 0) foundLineNo = lineStarts.length - 1; - - var result = '', i, line; - var lineNoLength = Math.min(mark.line + options.linesAfter, lineEnds.length).toString().length; - var maxLineLength = options.maxLength - (options.indent + lineNoLength + 3); - - for (i = 1; i <= options.linesBefore; i++) { - if (foundLineNo - i < 0) break; - line = getLine( - mark.buffer, - lineStarts[foundLineNo - i], - lineEnds[foundLineNo - i], - mark.position - (lineStarts[foundLineNo] - lineStarts[foundLineNo - i]), - maxLineLength - ); - result = common.repeat(' ', options.indent) + padStart((mark.line - i + 1).toString(), lineNoLength) + - ' | ' + line.str + '\n' + result; - } - - line = getLine(mark.buffer, lineStarts[foundLineNo], lineEnds[foundLineNo], mark.position, maxLineLength); - result += common.repeat(' ', options.indent) + padStart((mark.line + 1).toString(), lineNoLength) + - ' | ' + line.str + '\n'; - result += common.repeat('-', options.indent + lineNoLength + 3 + line.pos) + '^' + '\n'; - - for (i = 1; i <= options.linesAfter; i++) { - if (foundLineNo + i >= lineEnds.length) break; - line = getLine( - mark.buffer, - lineStarts[foundLineNo + i], - lineEnds[foundLineNo + i], - mark.position - (lineStarts[foundLineNo] - lineStarts[foundLineNo + i]), - maxLineLength - ); - result += common.repeat(' ', options.indent) + padStart((mark.line + i + 1).toString(), lineNoLength) + - ' | ' + line.str + '\n'; - } - - return result.replace(/\n$/, ''); - } - - - var snippet = makeSnippet; - - var TYPE_CONSTRUCTOR_OPTIONS = [ - 'kind', - 'multi', - 'resolve', - 'construct', - 'instanceOf', - 'predicate', - 'represent', - 'representName', - 'defaultStyle', - 'styleAliases' - ]; - - var YAML_NODE_KINDS = [ - 'scalar', - 'sequence', - 'mapping' - ]; - - function compileStyleAliases(map) { - var result = {}; - - if (map !== null) { - Object.keys(map).forEach(function (style) { - map[style].forEach(function (alias) { - result[String(alias)] = style; - }); - }); - } - - return result; - } - - function Type$1(tag, options) { - options = options || {}; - - Object.keys(options).forEach(function (name) { - if (TYPE_CONSTRUCTOR_OPTIONS.indexOf(name) === -1) { - throw new exception('Unknown option "' + name + '" is met in definition of "' + tag + '" YAML type.'); - } - }); - - // TODO: Add tag format check. - this.options = options; // keep original options in case user wants to extend this type later - this.tag = tag; - this.kind = options['kind'] || null; - this.resolve = options['resolve'] || function () { return true; }; - this.construct = options['construct'] || function (data) { return data; }; - this.instanceOf = options['instanceOf'] || null; - this.predicate = options['predicate'] || null; - this.represent = options['represent'] || null; - this.representName = options['representName'] || null; - this.defaultStyle = options['defaultStyle'] || null; - this.multi = options['multi'] || false; - this.styleAliases = compileStyleAliases(options['styleAliases'] || null); - - if (YAML_NODE_KINDS.indexOf(this.kind) === -1) { - throw new exception('Unknown kind "' + this.kind + '" is specified for "' + tag + '" YAML type.'); - } - } - - var type = Type$1; - - /*eslint-disable max-len*/ - - - - - - function compileList(schema, name) { - var result = []; - - schema[name].forEach(function (currentType) { - var newIndex = result.length; - - result.forEach(function (previousType, previousIndex) { - if (previousType.tag === currentType.tag && - previousType.kind === currentType.kind && - previousType.multi === currentType.multi) { - - newIndex = previousIndex; + nextInner(skip, dir) { + this.done = this.lineBreak = false; + for (;;) { + let last = this.nodes.length - 1; + let top = this.nodes[last], offsetValue = this.offsets[last], offset = offsetValue >> 1; + let size = top instanceof TextLeaf ? top.text.length : top.children.length; + if (offset == (dir > 0 ? size : 0)) { + if (last == 0) { + this.done = true; + this.value = ""; + return this; + } + if (dir > 0) + this.offsets[last - 1]++; + this.nodes.pop(); + this.offsets.pop(); + } + else if ((offsetValue & 1) == (dir > 0 ? 0 : 1)) { + this.offsets[last] += dir; + if (skip == 0) { + this.lineBreak = true; + this.value = "\n"; + return this; + } + skip--; + } + else if (top instanceof TextLeaf) { + // Move to the next string + let next = top.text[offset + (dir < 0 ? -1 : 0)]; + this.offsets[last] += dir; + if (next.length > Math.max(0, skip)) { + this.value = skip == 0 ? next : dir > 0 ? next.slice(skip) : next.slice(0, next.length - skip); + return this; + } + skip -= next.length; + } + else { + let next = top.children[offset + (dir < 0 ? -1 : 0)]; + if (skip > next.length) { + skip -= next.length; + this.offsets[last] += dir; + } + else { + if (dir < 0) + this.offsets[last]--; + this.nodes.push(next); + this.offsets.push(dir > 0 ? 1 : (next instanceof TextLeaf ? next.text.length : next.children.length) << 1); + } + } } - }); - - result[newIndex] = currentType; - }); - - return result; - } - - - function compileMap(/* lists... */) { - var result = { - scalar: {}, - sequence: {}, - mapping: {}, - fallback: {}, - multi: { - scalar: [], - sequence: [], - mapping: [], - fallback: [] - } - }, index, length; - - function collectType(type) { - if (type.multi) { - result.multi[type.kind].push(type); - result.multi['fallback'].push(type); - } else { - result[type.kind][type.tag] = result['fallback'][type.tag] = type; - } } - - for (index = 0, length = arguments.length; index < length; index += 1) { - arguments[index].forEach(collectType); - } - return result; - } - - - function Schema$1(definition) { - return this.extend(definition); - } - - - Schema$1.prototype.extend = function extend(definition) { - var implicit = []; - var explicit = []; - - if (definition instanceof type) { - // Schema.extend(type) - explicit.push(definition); - - } else if (Array.isArray(definition)) { - // Schema.extend([ type1, type2, ... ]) - explicit = explicit.concat(definition); - - } else if (definition && (Array.isArray(definition.implicit) || Array.isArray(definition.explicit))) { - // Schema.extend({ explicit: [ type1, type2, ... ], implicit: [ type1, type2, ... ] }) - if (definition.implicit) implicit = implicit.concat(definition.implicit); - if (definition.explicit) explicit = explicit.concat(definition.explicit); - - } else { - throw new exception('Schema.extend argument should be a Type, [ Type ], ' + - 'or a schema definition ({ implicit: [...], explicit: [...] })'); - } - - implicit.forEach(function (type$1) { - if (!(type$1 instanceof type)) { - throw new exception('Specified list of YAML types (or a single Type object) contains a non-Type object.'); - } - - if (type$1.loadKind && type$1.loadKind !== 'scalar') { - throw new exception('There is a non-scalar type in the implicit list of a schema. Implicit resolving of such types is not supported.'); - } - - if (type$1.multi) { - throw new exception('There is a multi type in the implicit list of a schema. Multi tags can only be listed as explicit.'); - } - }); - - explicit.forEach(function (type$1) { - if (!(type$1 instanceof type)) { - throw new exception('Specified list of YAML types (or a single Type object) contains a non-Type object.'); - } - }); - - var result = Object.create(Schema$1.prototype); - - result.implicit = (this.implicit || []).concat(implicit); - result.explicit = (this.explicit || []).concat(explicit); - - result.compiledImplicit = compileList(result, 'implicit'); - result.compiledExplicit = compileList(result, 'explicit'); - result.compiledTypeMap = compileMap(result.compiledImplicit, result.compiledExplicit); - - return result; - }; - - - var schema = Schema$1; - - var str = new type('tag:yaml.org,2002:str', { - kind: 'scalar', - construct: function (data) { return data !== null ? data : ''; } - }); - - var seq = new type('tag:yaml.org,2002:seq', { - kind: 'sequence', - construct: function (data) { return data !== null ? data : []; } - }); - - var map = new type('tag:yaml.org,2002:map', { - kind: 'mapping', - construct: function (data) { return data !== null ? data : {}; } - }); - - var failsafe = new schema({ - explicit: [ - str, - seq, - map - ] - }); - - function resolveYamlNull(data) { - if (data === null) return true; - - var max = data.length; - - return (max === 1 && data === '~') || - (max === 4 && (data === 'null' || data === 'Null' || data === 'NULL')); - } - - function constructYamlNull() { - return null; - } - - function isNull(object) { - return object === null; - } - - var _null = new type('tag:yaml.org,2002:null', { - kind: 'scalar', - resolve: resolveYamlNull, - construct: constructYamlNull, - predicate: isNull, - represent: { - canonical: function () { return '~'; }, - lowercase: function () { return 'null'; }, - uppercase: function () { return 'NULL'; }, - camelcase: function () { return 'Null'; }, - empty: function () { return ''; } - }, - defaultStyle: 'lowercase' - }); - - function resolveYamlBoolean(data) { - if (data === null) return false; - - var max = data.length; - - return (max === 4 && (data === 'true' || data === 'True' || data === 'TRUE')) || - (max === 5 && (data === 'false' || data === 'False' || data === 'FALSE')); - } - - function constructYamlBoolean(data) { - return data === 'true' || - data === 'True' || - data === 'TRUE'; - } - - function isBoolean(object) { - return Object.prototype.toString.call(object) === '[object Boolean]'; - } - - var bool = new type('tag:yaml.org,2002:bool', { - kind: 'scalar', - resolve: resolveYamlBoolean, - construct: constructYamlBoolean, - predicate: isBoolean, - represent: { - lowercase: function (object) { return object ? 'true' : 'false'; }, - uppercase: function (object) { return object ? 'TRUE' : 'FALSE'; }, - camelcase: function (object) { return object ? 'True' : 'False'; } - }, - defaultStyle: 'lowercase' - }); - - function isHexCode(c) { - return ((0x30/* 0 */ <= c) && (c <= 0x39/* 9 */)) || - ((0x41/* A */ <= c) && (c <= 0x46/* F */)) || - ((0x61/* a */ <= c) && (c <= 0x66/* f */)); - } - - function isOctCode(c) { - return ((0x30/* 0 */ <= c) && (c <= 0x37/* 7 */)); - } - - function isDecCode(c) { - return ((0x30/* 0 */ <= c) && (c <= 0x39/* 9 */)); - } - - function resolveYamlInteger(data) { - if (data === null) return false; - - var max = data.length, - index = 0, - hasDigits = false, - ch; - - if (!max) return false; - - ch = data[index]; - - // sign - if (ch === '-' || ch === '+') { - ch = data[++index]; - } - - if (ch === '0') { - // 0 - if (index + 1 === max) return true; - ch = data[++index]; - - // base 2, base 8, base 16 - - if (ch === 'b') { - // base 2 - index++; - - for (; index < max; index++) { - ch = data[index]; - if (ch === '_') continue; - if (ch !== '0' && ch !== '1') return false; - hasDigits = true; + next(skip = 0) { + if (skip < 0) { + this.nextInner(-skip, (-this.dir)); + skip = this.value.length; } - return hasDigits && ch !== '_'; - } - - - if (ch === 'x') { - // base 16 - index++; - - for (; index < max; index++) { - ch = data[index]; - if (ch === '_') continue; - if (!isHexCode(data.charCodeAt(index))) return false; - hasDigits = true; + return this.nextInner(skip, this.dir); + } + } + class PartialTextCursor { + constructor(text, start, end) { + this.value = ""; + this.done = false; + this.cursor = new RawTextCursor(text, start > end ? -1 : 1); + this.pos = start > end ? text.length : 0; + this.from = Math.min(start, end); + this.to = Math.max(start, end); + } + nextInner(skip, dir) { + if (dir < 0 ? this.pos <= this.from : this.pos >= this.to) { + this.value = ""; + this.done = true; + return this; } - return hasDigits && ch !== '_'; - } - - - if (ch === 'o') { - // base 8 - index++; - - for (; index < max; index++) { - ch = data[index]; - if (ch === '_') continue; - if (!isOctCode(data.charCodeAt(index))) return false; - hasDigits = true; + skip += Math.max(0, dir < 0 ? this.pos - this.to : this.from - this.pos); + let limit = dir < 0 ? this.pos - this.from : this.to - this.pos; + if (skip > limit) + skip = limit; + limit -= skip; + let { value } = this.cursor.next(skip); + this.pos += (value.length + skip) * dir; + this.value = value.length <= limit ? value : dir < 0 ? value.slice(value.length - limit) : value.slice(0, limit); + this.done = !this.value; + return this; + } + next(skip = 0) { + if (skip < 0) + skip = Math.max(skip, this.from - this.pos); + else if (skip > 0) + skip = Math.min(skip, this.to - this.pos); + return this.nextInner(skip, this.cursor.dir); + } + get lineBreak() { return this.cursor.lineBreak && this.value != ""; } + } + class LineCursor { + constructor(inner) { + this.inner = inner; + this.afterBreak = true; + this.value = ""; + this.done = false; + } + next(skip = 0) { + let { done, lineBreak, value } = this.inner.next(skip); + if (done) { + this.done = true; + this.value = ""; } - return hasDigits && ch !== '_'; - } + else if (lineBreak) { + if (this.afterBreak) { + this.value = ""; + } + else { + this.afterBreak = true; + this.next(); + } + } + else { + this.value = value; + this.afterBreak = false; + } + return this; } - - // base 10 (except 0) - - // value should not start with `_`; - if (ch === '_') return false; - - for (; index < max; index++) { - ch = data[index]; - if (ch === '_') continue; - if (!isDecCode(data.charCodeAt(index))) { - return false; - } - hasDigits = true; + get lineBreak() { return false; } + } + if (typeof Symbol != "undefined") { + Text.prototype[Symbol.iterator] = function () { return this.iter(); }; + RawTextCursor.prototype[Symbol.iterator] = PartialTextCursor.prototype[Symbol.iterator] = + LineCursor.prototype[Symbol.iterator] = function () { return this; }; + } + /** + This type describes a line in the document. It is created + on-demand when lines are [queried](https://codemirror.net/6/docs/ref/#state.Text.lineAt). + */ + class Line { + /** + @internal + */ + constructor( + /** + The position of the start of the line. + */ + from, + /** + The position at the end of the line (_before_ the line break, + or at the end of document for the last line). + */ + to, + /** + This line's line number (1-based). + */ + number, + /** + The line's content. + */ + text) { + this.from = from; + this.to = to; + this.number = number; + this.text = text; } + /** + The length of the line (not including any line break after it). + */ + get length() { return this.to - this.from; } + } - // Should have digits and should not end with `_` - if (!hasDigits || ch === '_') return false; - - return true; - } - - function constructYamlInteger(data) { - var value = data, sign = 1, ch; - - if (value.indexOf('_') !== -1) { - value = value.replace(/_/g, ''); - } - - ch = value[0]; - - if (ch === '-' || ch === '+') { - if (ch === '-') sign = -1; - value = value.slice(1); - ch = value[0]; - } - - if (value === '0') return 0; - - if (ch === '0') { - if (value[1] === 'b') return sign * parseInt(value.slice(2), 2); - if (value[1] === 'x') return sign * parseInt(value.slice(2), 16); - if (value[1] === 'o') return sign * parseInt(value.slice(2), 8); - } - - return sign * parseInt(value, 10); - } - - function isInteger(object) { - return (Object.prototype.toString.call(object)) === '[object Number]' && - (object % 1 === 0 && !common.isNegativeZero(object)); - } - - var int = new type('tag:yaml.org,2002:int', { - kind: 'scalar', - resolve: resolveYamlInteger, - construct: constructYamlInteger, - predicate: isInteger, - represent: { - binary: function (obj) { return obj >= 0 ? '0b' + obj.toString(2) : '-0b' + obj.toString(2).slice(1); }, - octal: function (obj) { return obj >= 0 ? '0o' + obj.toString(8) : '-0o' + obj.toString(8).slice(1); }, - decimal: function (obj) { return obj.toString(10); }, - /* eslint-disable max-len */ - hexadecimal: function (obj) { return obj >= 0 ? '0x' + obj.toString(16).toUpperCase() : '-0x' + obj.toString(16).toUpperCase().slice(1); } - }, - defaultStyle: 'decimal', - styleAliases: { - binary: [ 2, 'bin' ], - octal: [ 8, 'oct' ], - decimal: [ 10, 'dec' ], - hexadecimal: [ 16, 'hex' ] - } - }); - - var YAML_FLOAT_PATTERN = new RegExp( - // 2.5e4, 2.5 and integers - '^(?:[-+]?(?:[0-9][0-9_]*)(?:\\.[0-9_]*)?(?:[eE][-+]?[0-9]+)?' + - // .2e4, .2 - // special case, seems not from spec - '|\\.[0-9_]+(?:[eE][-+]?[0-9]+)?' + - // .inf - '|[-+]?\\.(?:inf|Inf|INF)' + - // .nan - '|\\.(?:nan|NaN|NAN))$'); - - function resolveYamlFloat(data) { - if (data === null) return false; - - if (!YAML_FLOAT_PATTERN.test(data) || - // Quick hack to not allow integers end with `_` - // Probably should update regexp & check speed - data[data.length - 1] === '_') { - return false; - } - - return true; - } - - function constructYamlFloat(data) { - var value, sign; - - value = data.replace(/_/g, '').toLowerCase(); - sign = value[0] === '-' ? -1 : 1; - - if ('+-'.indexOf(value[0]) >= 0) { - value = value.slice(1); - } - - if (value === '.inf') { - return (sign === 1) ? Number.POSITIVE_INFINITY : Number.NEGATIVE_INFINITY; - - } else if (value === '.nan') { - return NaN; - } - return sign * parseFloat(value, 10); - } - - - var SCIENTIFIC_WITHOUT_DOT = /^[-+]?[0-9]+e/; - - function representYamlFloat(object, style) { - var res; - - if (isNaN(object)) { - switch (style) { - case 'lowercase': return '.nan'; - case 'uppercase': return '.NAN'; - case 'camelcase': return '.NaN'; - } - } else if (Number.POSITIVE_INFINITY === object) { - switch (style) { - case 'lowercase': return '.inf'; - case 'uppercase': return '.INF'; - case 'camelcase': return '.Inf'; - } - } else if (Number.NEGATIVE_INFINITY === object) { - switch (style) { - case 'lowercase': return '-.inf'; - case 'uppercase': return '-.INF'; - case 'camelcase': return '-.Inf'; - } - } else if (common.isNegativeZero(object)) { - return '-0.0'; - } - - res = object.toString(10); - - // JS stringifier can build scientific format without dots: 5e-100, - // while YAML requres dot: 5.e-100. Fix it with simple hack - - return SCIENTIFIC_WITHOUT_DOT.test(res) ? res.replace('e', '.e') : res; - } - - function isFloat(object) { - return (Object.prototype.toString.call(object) === '[object Number]') && - (object % 1 !== 0 || common.isNegativeZero(object)); - } - - var float = new type('tag:yaml.org,2002:float', { - kind: 'scalar', - resolve: resolveYamlFloat, - construct: constructYamlFloat, - predicate: isFloat, - represent: representYamlFloat, - defaultStyle: 'lowercase' - }); - - var json = failsafe.extend({ - implicit: [ - _null, - bool, - int, - float - ] - }); - - var core = json; - - var YAML_DATE_REGEXP = new RegExp( - '^([0-9][0-9][0-9][0-9])' + // [1] year - '-([0-9][0-9])' + // [2] month - '-([0-9][0-9])$'); // [3] day - - var YAML_TIMESTAMP_REGEXP = new RegExp( - '^([0-9][0-9][0-9][0-9])' + // [1] year - '-([0-9][0-9]?)' + // [2] month - '-([0-9][0-9]?)' + // [3] day - '(?:[Tt]|[ \\t]+)' + // ... - '([0-9][0-9]?)' + // [4] hour - ':([0-9][0-9])' + // [5] minute - ':([0-9][0-9])' + // [6] second - '(?:\\.([0-9]*))?' + // [7] fraction - '(?:[ \\t]*(Z|([-+])([0-9][0-9]?)' + // [8] tz [9] tz_sign [10] tz_hour - '(?::([0-9][0-9]))?))?$'); // [11] tz_minute - - function resolveYamlTimestamp(data) { - if (data === null) return false; - if (YAML_DATE_REGEXP.exec(data) !== null) return true; - if (YAML_TIMESTAMP_REGEXP.exec(data) !== null) return true; + // Compressed representation of the Grapheme_Cluster_Break=Extend + // information from + // http://www.unicode.org/Public/13.0.0/ucd/auxiliary/GraphemeBreakProperty.txt. + // Each pair of elements represents a range, as an offet from the + // previous range and a length. Numbers are in base-36, with the empty + // string being a shorthand for 1. + let extend = /*@__PURE__*/"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(s => s ? parseInt(s, 36) : 1); + // Convert offsets into absolute values + for (let i = 1; i < extend.length; i++) + extend[i] += extend[i - 1]; + function isExtendingChar(code) { + for (let i = 1; i < extend.length; i += 2) + if (extend[i] > code) + return extend[i - 1] <= code; return false; - } - - function constructYamlTimestamp(data) { - var match, year, month, day, hour, minute, second, fraction = 0, - delta = null, tz_hour, tz_minute, date; - - match = YAML_DATE_REGEXP.exec(data); - if (match === null) match = YAML_TIMESTAMP_REGEXP.exec(data); - - if (match === null) throw new Error('Date resolve error'); - - // match: [1] year [2] month [3] day - - year = +(match[1]); - month = +(match[2]) - 1; // JS month starts with 0 - day = +(match[3]); - - if (!match[4]) { // no hour - return new Date(Date.UTC(year, month, day)); - } - - // match: [4] hour [5] minute [6] second [7] fraction - - hour = +(match[4]); - minute = +(match[5]); - second = +(match[6]); - - if (match[7]) { - fraction = match[7].slice(0, 3); - while (fraction.length < 3) { // milli-seconds - fraction += '0'; - } - fraction = +fraction; - } - - // match: [8] tz [9] tz_sign [10] tz_hour [11] tz_minute - - if (match[9]) { - tz_hour = +(match[10]); - tz_minute = +(match[11] || 0); - delta = (tz_hour * 60 + tz_minute) * 60000; // delta in mili-seconds - if (match[9] === '-') delta = -delta; - } - - date = new Date(Date.UTC(year, month, day, hour, minute, second, fraction)); - - if (delta) date.setTime(date.getTime() - delta); - - return date; - } - - function representYamlTimestamp(object /*, style*/) { - return object.toISOString(); - } - - var timestamp = new type('tag:yaml.org,2002:timestamp', { - kind: 'scalar', - resolve: resolveYamlTimestamp, - construct: constructYamlTimestamp, - instanceOf: Date, - represent: representYamlTimestamp - }); - - function resolveYamlMerge(data) { - return data === '<<' || data === null; - } - - var merge = new type('tag:yaml.org,2002:merge', { - kind: 'scalar', - resolve: resolveYamlMerge - }); - - /*eslint-disable no-bitwise*/ - - - - - - // [ 64, 65, 66 ] -> [ padding, CR, LF ] - var BASE64_MAP = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=\n\r'; - - - function resolveYamlBinary(data) { - if (data === null) return false; - - var code, idx, bitlen = 0, max = data.length, map = BASE64_MAP; - - // Convert one by one. - for (idx = 0; idx < max; idx++) { - code = map.indexOf(data.charAt(idx)); - - // Skip CR/LF - if (code > 64) continue; - - // Fail on illegal characters - if (code < 0) return false; - - bitlen += 6; - } - - // If there are any bits left, source was corrupted - return (bitlen % 8) === 0; - } - - function constructYamlBinary(data) { - var idx, tailbits, - input = data.replace(/[\r\n=]/g, ''), // remove CR/LF & padding to simplify scan - max = input.length, - map = BASE64_MAP, - bits = 0, - result = []; - - // Collect by 6*4 bits (3 bytes) - - for (idx = 0; idx < max; idx++) { - if ((idx % 4 === 0) && idx) { - result.push((bits >> 16) & 0xFF); - result.push((bits >> 8) & 0xFF); - result.push(bits & 0xFF); - } - - bits = (bits << 6) | map.indexOf(input.charAt(idx)); - } - - // Dump tail - - tailbits = (max % 4) * 6; - - if (tailbits === 0) { - result.push((bits >> 16) & 0xFF); - result.push((bits >> 8) & 0xFF); - result.push(bits & 0xFF); - } else if (tailbits === 18) { - result.push((bits >> 10) & 0xFF); - result.push((bits >> 2) & 0xFF); - } else if (tailbits === 12) { - result.push((bits >> 4) & 0xFF); - } - - return new Uint8Array(result); - } - - function representYamlBinary(object /*, style*/) { - var result = '', bits = 0, idx, tail, - max = object.length, - map = BASE64_MAP; - - // Convert every three bytes to 4 ASCII characters. - - for (idx = 0; idx < max; idx++) { - if ((idx % 3 === 0) && idx) { - result += map[(bits >> 18) & 0x3F]; - result += map[(bits >> 12) & 0x3F]; - result += map[(bits >> 6) & 0x3F]; - result += map[bits & 0x3F]; - } - - bits = (bits << 8) + object[idx]; - } - - // Dump tail - - tail = max % 3; - - if (tail === 0) { - result += map[(bits >> 18) & 0x3F]; - result += map[(bits >> 12) & 0x3F]; - result += map[(bits >> 6) & 0x3F]; - result += map[bits & 0x3F]; - } else if (tail === 2) { - result += map[(bits >> 10) & 0x3F]; - result += map[(bits >> 4) & 0x3F]; - result += map[(bits << 2) & 0x3F]; - result += map[64]; - } else if (tail === 1) { - result += map[(bits >> 2) & 0x3F]; - result += map[(bits << 4) & 0x3F]; - result += map[64]; - result += map[64]; - } - - return result; - } - - function isBinary(obj) { - return Object.prototype.toString.call(obj) === '[object Uint8Array]'; - } - - var binary = new type('tag:yaml.org,2002:binary', { - kind: 'scalar', - resolve: resolveYamlBinary, - construct: constructYamlBinary, - predicate: isBinary, - represent: representYamlBinary - }); - - var _hasOwnProperty$3 = Object.prototype.hasOwnProperty; - var _toString$2 = Object.prototype.toString; - - function resolveYamlOmap(data) { - if (data === null) return true; - - var objectKeys = [], index, length, pair, pairKey, pairHasKey, - object = data; - - for (index = 0, length = object.length; index < length; index += 1) { - pair = object[index]; - pairHasKey = false; - - if (_toString$2.call(pair) !== '[object Object]') return false; - - for (pairKey in pair) { - if (_hasOwnProperty$3.call(pair, pairKey)) { - if (!pairHasKey) pairHasKey = true; - else return false; + } + function isRegionalIndicator(code) { + return code >= 0x1F1E6 && code <= 0x1F1FF; + } + const ZWJ = 0x200d; + /** + Returns a next grapheme cluster break _after_ (not equal to) + `pos`, if `forward` is true, or before otherwise. Returns `pos` + itself if no further cluster break is available in the string. + Moves across surrogate pairs, extending characters (when + `includeExtending` is true), characters joined with zero-width + joiners, and flag emoji. + */ + function findClusterBreak(str, pos, forward = true, includeExtending = true) { + return (forward ? nextClusterBreak : prevClusterBreak)(str, pos, includeExtending); + } + function nextClusterBreak(str, pos, includeExtending) { + if (pos == str.length) + return pos; + // If pos is in the middle of a surrogate pair, move to its start + if (pos && surrogateLow(str.charCodeAt(pos)) && surrogateHigh(str.charCodeAt(pos - 1))) + pos--; + let prev = codePointAt(str, pos); + pos += codePointSize(prev); + while (pos < str.length) { + let next = codePointAt(str, pos); + if (prev == ZWJ || next == ZWJ || includeExtending && isExtendingChar(next)) { + pos += codePointSize(next); + prev = next; } - } - - if (!pairHasKey) return false; - - if (objectKeys.indexOf(pairKey) === -1) objectKeys.push(pairKey); - else return false; - } - - return true; - } - - function constructYamlOmap(data) { - return data !== null ? data : []; - } - - var omap = new type('tag:yaml.org,2002:omap', { - kind: 'sequence', - resolve: resolveYamlOmap, - construct: constructYamlOmap - }); - - var _toString$1 = Object.prototype.toString; - - function resolveYamlPairs(data) { - if (data === null) return true; - - var index, length, pair, keys, result, - object = data; - - result = new Array(object.length); - - for (index = 0, length = object.length; index < length; index += 1) { - pair = object[index]; - - if (_toString$1.call(pair) !== '[object Object]') return false; - - keys = Object.keys(pair); - - if (keys.length !== 1) return false; - - result[index] = [ keys[0], pair[keys[0]] ]; - } - - return true; - } - - function constructYamlPairs(data) { - if (data === null) return []; - - var index, length, pair, keys, result, - object = data; - - result = new Array(object.length); - - for (index = 0, length = object.length; index < length; index += 1) { - pair = object[index]; - - keys = Object.keys(pair); - - result[index] = [ keys[0], pair[keys[0]] ]; - } - - return result; - } - - var pairs = new type('tag:yaml.org,2002:pairs', { - kind: 'sequence', - resolve: resolveYamlPairs, - construct: constructYamlPairs - }); - - var _hasOwnProperty$2 = Object.prototype.hasOwnProperty; - - function resolveYamlSet(data) { - if (data === null) return true; - - var key, object = data; - - for (key in object) { - if (_hasOwnProperty$2.call(object, key)) { - if (object[key] !== null) return false; - } - } - - return true; - } - - function constructYamlSet(data) { - return data !== null ? data : {}; - } - - var set = new type('tag:yaml.org,2002:set', { - kind: 'mapping', - resolve: resolveYamlSet, - construct: constructYamlSet - }); - - var _default = core.extend({ - implicit: [ - timestamp, - merge - ], - explicit: [ - binary, - omap, - pairs, - set - ] - }); - - /*eslint-disable max-len,no-use-before-define*/ - - - - - - - - var _hasOwnProperty$1 = Object.prototype.hasOwnProperty; - - - var CONTEXT_FLOW_IN = 1; - var CONTEXT_FLOW_OUT = 2; - var CONTEXT_BLOCK_IN = 3; - var CONTEXT_BLOCK_OUT = 4; - - - var CHOMPING_CLIP = 1; - var CHOMPING_STRIP = 2; - var CHOMPING_KEEP = 3; - - - var PATTERN_NON_PRINTABLE = /[\x00-\x08\x0B\x0C\x0E-\x1F\x7F-\x84\x86-\x9F\uFFFE\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]/; - var PATTERN_NON_ASCII_LINE_BREAKS = /[\x85\u2028\u2029]/; - var PATTERN_FLOW_INDICATORS = /[,\[\]\{\}]/; - var PATTERN_TAG_HANDLE = /^(?:!|!!|![a-z\-]+!)$/i; - var PATTERN_TAG_URI = /^(?:!|[^,\[\]\{\}])(?:%[0-9a-f]{2}|[0-9a-z\-#;\/\?:@&=\+\$,_\.!~\*'\(\)\[\]])*$/i; - - - function _class(obj) { return Object.prototype.toString.call(obj); } - - function is_EOL(c) { - return (c === 0x0A/* LF */) || (c === 0x0D/* CR */); - } - - function is_WHITE_SPACE(c) { - return (c === 0x09/* Tab */) || (c === 0x20/* Space */); - } - - function is_WS_OR_EOL(c) { - return (c === 0x09/* Tab */) || - (c === 0x20/* Space */) || - (c === 0x0A/* LF */) || - (c === 0x0D/* CR */); - } - - function is_FLOW_INDICATOR(c) { - return c === 0x2C/* , */ || - c === 0x5B/* [ */ || - c === 0x5D/* ] */ || - c === 0x7B/* { */ || - c === 0x7D/* } */; - } - - function fromHexCode(c) { - var lc; - - if ((0x30/* 0 */ <= c) && (c <= 0x39/* 9 */)) { - return c - 0x30; - } - - /*eslint-disable no-bitwise*/ - lc = c | 0x20; - - if ((0x61/* a */ <= lc) && (lc <= 0x66/* f */)) { - return lc - 0x61 + 10; - } - - return -1; - } - - function escapedHexLen(c) { - if (c === 0x78/* x */) { return 2; } - if (c === 0x75/* u */) { return 4; } - if (c === 0x55/* U */) { return 8; } - return 0; - } - - function fromDecimalCode(c) { - if ((0x30/* 0 */ <= c) && (c <= 0x39/* 9 */)) { - return c - 0x30; - } - - return -1; - } - - function simpleEscapeSequence(c) { - /* eslint-disable indent */ - return (c === 0x30/* 0 */) ? '\x00' : - (c === 0x61/* a */) ? '\x07' : - (c === 0x62/* b */) ? '\x08' : - (c === 0x74/* t */) ? '\x09' : - (c === 0x09/* Tab */) ? '\x09' : - (c === 0x6E/* n */) ? '\x0A' : - (c === 0x76/* v */) ? '\x0B' : - (c === 0x66/* f */) ? '\x0C' : - (c === 0x72/* r */) ? '\x0D' : - (c === 0x65/* e */) ? '\x1B' : - (c === 0x20/* Space */) ? ' ' : - (c === 0x22/* " */) ? '\x22' : - (c === 0x2F/* / */) ? '/' : - (c === 0x5C/* \ */) ? '\x5C' : - (c === 0x4E/* N */) ? '\x85' : - (c === 0x5F/* _ */) ? '\xA0' : - (c === 0x4C/* L */) ? '\u2028' : - (c === 0x50/* P */) ? '\u2029' : ''; - } - - function charFromCodepoint(c) { - if (c <= 0xFFFF) { - return String.fromCharCode(c); - } - // Encode UTF-16 surrogate pair - // https://en.wikipedia.org/wiki/UTF-16#Code_points_U.2B010000_to_U.2B10FFFF - return String.fromCharCode( - ((c - 0x010000) >> 10) + 0xD800, - ((c - 0x010000) & 0x03FF) + 0xDC00 - ); - } - - var simpleEscapeCheck = new Array(256); // integer, for fast access - var simpleEscapeMap = new Array(256); - for (var i$1 = 0; i$1 < 256; i$1++) { - simpleEscapeCheck[i$1] = simpleEscapeSequence(i$1) ? 1 : 0; - simpleEscapeMap[i$1] = simpleEscapeSequence(i$1); - } - - - function State$1(input, options) { - this.input = input; - - this.filename = options['filename'] || null; - this.schema = options['schema'] || _default; - this.onWarning = options['onWarning'] || null; - // (Hidden) Remove? makes the loader to expect YAML 1.1 documents - // if such documents have no explicit %YAML directive - this.legacy = options['legacy'] || false; - - this.json = options['json'] || false; - this.listener = options['listener'] || null; - - this.implicitTypes = this.schema.compiledImplicit; - this.typeMap = this.schema.compiledTypeMap; - - this.length = input.length; - this.position = 0; - this.line = 0; - this.lineStart = 0; - this.lineIndent = 0; - - // position of first leading tab in the current line, - // used to make sure there are no tabs in the indentation - this.firstTabInLine = -1; - - this.documents = []; - - /* - this.version; - this.checkLineBreaks; - this.tagMap; - this.anchorMap; - this.tag; - this.anchor; - this.kind; - this.result;*/ - - } - - - function generateError(state, message) { - var mark = { - name: state.filename, - buffer: state.input.slice(0, -1), // omit trailing \0 - position: state.position, - line: state.line, - column: state.position - state.lineStart - }; - - mark.snippet = snippet(mark); - - return new exception(message, mark); - } - - function throwError(state, message) { - throw generateError(state, message); - } - - function throwWarning(state, message) { - if (state.onWarning) { - state.onWarning.call(null, generateError(state, message)); - } - } - - - var directiveHandlers = { - - YAML: function handleYamlDirective(state, name, args) { - - var match, major, minor; - - if (state.version !== null) { - throwError(state, 'duplication of %YAML directive'); - } - - if (args.length !== 1) { - throwError(state, 'YAML directive accepts exactly one argument'); - } - - match = /^([0-9]+)\.([0-9]+)$/.exec(args[0]); - - if (match === null) { - throwError(state, 'ill-formed argument of the YAML directive'); - } - - major = parseInt(match[1], 10); - minor = parseInt(match[2], 10); - - if (major !== 1) { - throwError(state, 'unacceptable YAML version of the document'); - } - - state.version = args[0]; - state.checkLineBreaks = (minor < 2); - - if (minor !== 1 && minor !== 2) { - throwWarning(state, 'unsupported YAML version of the document'); - } - }, - - TAG: function handleTagDirective(state, name, args) { - - var handle, prefix; - - if (args.length !== 2) { - throwError(state, 'TAG directive accepts exactly two arguments'); - } - - handle = args[0]; - prefix = args[1]; - - if (!PATTERN_TAG_HANDLE.test(handle)) { - throwError(state, 'ill-formed tag handle (first argument) of the TAG directive'); - } - - if (_hasOwnProperty$1.call(state.tagMap, handle)) { - throwError(state, 'there is a previously declared suffix for "' + handle + '" tag handle'); - } - - if (!PATTERN_TAG_URI.test(prefix)) { - throwError(state, 'ill-formed tag prefix (second argument) of the TAG directive'); - } - - try { - prefix = decodeURIComponent(prefix); - } catch (err) { - throwError(state, 'tag prefix is malformed: ' + prefix); - } - - state.tagMap[handle] = prefix; - } - }; - - - function captureSegment(state, start, end, checkJson) { - var _position, _length, _character, _result; - - if (start < end) { - _result = state.input.slice(start, end); - - if (checkJson) { - for (_position = 0, _length = _result.length; _position < _length; _position += 1) { - _character = _result.charCodeAt(_position); - if (!(_character === 0x09 || - (0x20 <= _character && _character <= 0x10FFFF))) { - throwError(state, 'expected valid JSON character'); - } - } - } else if (PATTERN_NON_PRINTABLE.test(_result)) { - throwError(state, 'the stream contains non-printable characters'); - } - - state.result += _result; - } - } - - function mergeMappings(state, destination, source, overridableKeys) { - var sourceKeys, key, index, quantity; - - if (!common.isObject(source)) { - throwError(state, 'cannot merge mappings; the provided source object is unacceptable'); - } - - sourceKeys = Object.keys(source); - - for (index = 0, quantity = sourceKeys.length; index < quantity; index += 1) { - key = sourceKeys[index]; - - if (!_hasOwnProperty$1.call(destination, key)) { - destination[key] = source[key]; - overridableKeys[key] = true; - } - } - } - - function storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, valueNode, - startLine, startLineStart, startPos) { - - var index, quantity; - - // The output is a plain object here, so keys can only be strings. - // We need to convert keyNode to a string, but doing so can hang the process - // (deeply nested arrays that explode exponentially using aliases). - if (Array.isArray(keyNode)) { - keyNode = Array.prototype.slice.call(keyNode); - - for (index = 0, quantity = keyNode.length; index < quantity; index += 1) { - if (Array.isArray(keyNode[index])) { - throwError(state, 'nested arrays are not supported inside keys'); - } - - if (typeof keyNode === 'object' && _class(keyNode[index]) === '[object Object]') { - keyNode[index] = '[object Object]'; - } - } - } - - // Avoid code execution in load() via toString property - // (still use its own toString for arrays, timestamps, - // and whatever user schema extensions happen to have @@toStringTag) - if (typeof keyNode === 'object' && _class(keyNode) === '[object Object]') { - keyNode = '[object Object]'; - } - - - keyNode = String(keyNode); - - if (_result === null) { - _result = {}; - } - - if (keyTag === 'tag:yaml.org,2002:merge') { - if (Array.isArray(valueNode)) { - for (index = 0, quantity = valueNode.length; index < quantity; index += 1) { - mergeMappings(state, _result, valueNode[index], overridableKeys); - } - } else { - mergeMappings(state, _result, valueNode, overridableKeys); - } - } else { - if (!state.json && - !_hasOwnProperty$1.call(overridableKeys, keyNode) && - _hasOwnProperty$1.call(_result, keyNode)) { - state.line = startLine || state.line; - state.lineStart = startLineStart || state.lineStart; - state.position = startPos || state.position; - throwError(state, 'duplicated mapping key'); - } - - // used for this specific key only because Object.defineProperty is slow - if (keyNode === '__proto__') { - Object.defineProperty(_result, keyNode, { - configurable: true, - enumerable: true, - writable: true, - value: valueNode - }); - } else { - _result[keyNode] = valueNode; - } - delete overridableKeys[keyNode]; - } - - return _result; - } - - function readLineBreak(state) { - var ch; - - ch = state.input.charCodeAt(state.position); - - if (ch === 0x0A/* LF */) { - state.position++; - } else if (ch === 0x0D/* CR */) { - state.position++; - if (state.input.charCodeAt(state.position) === 0x0A/* LF */) { - state.position++; - } - } else { - throwError(state, 'a line break is expected'); - } - - state.line += 1; - state.lineStart = state.position; - state.firstTabInLine = -1; - } - - function skipSeparationSpace(state, allowComments, checkIndent) { - var lineBreaks = 0, - ch = state.input.charCodeAt(state.position); - - while (ch !== 0) { - while (is_WHITE_SPACE(ch)) { - if (ch === 0x09/* Tab */ && state.firstTabInLine === -1) { - state.firstTabInLine = state.position; - } - ch = state.input.charCodeAt(++state.position); - } - - if (allowComments && ch === 0x23/* # */) { - do { - ch = state.input.charCodeAt(++state.position); - } while (ch !== 0x0A/* LF */ && ch !== 0x0D/* CR */ && ch !== 0); - } - - if (is_EOL(ch)) { - readLineBreak(state); - - ch = state.input.charCodeAt(state.position); - lineBreaks++; - state.lineIndent = 0; - - while (ch === 0x20/* Space */) { - state.lineIndent++; - ch = state.input.charCodeAt(++state.position); - } - } else { - break; - } - } - - if (checkIndent !== -1 && lineBreaks !== 0 && state.lineIndent < checkIndent) { - throwWarning(state, 'deficient indentation'); - } - - return lineBreaks; - } - - function testDocumentSeparator(state) { - var _position = state.position, - ch; - - ch = state.input.charCodeAt(_position); - - // Condition state.position === state.lineStart is tested - // in parent on each call, for efficiency. No needs to test here again. - if ((ch === 0x2D/* - */ || ch === 0x2E/* . */) && - ch === state.input.charCodeAt(_position + 1) && - ch === state.input.charCodeAt(_position + 2)) { - - _position += 3; - - ch = state.input.charCodeAt(_position); - - if (ch === 0 || is_WS_OR_EOL(ch)) { - return true; - } - } - - return false; - } - - function writeFoldedLines(state, count) { - if (count === 1) { - state.result += ' '; - } else if (count > 1) { - state.result += common.repeat('\n', count - 1); - } - } - - - function readPlainScalar(state, nodeIndent, withinFlowCollection) { - var preceding, - following, - captureStart, - captureEnd, - hasPendingContent, - _line, - _lineStart, - _lineIndent, - _kind = state.kind, - _result = state.result, - ch; - - ch = state.input.charCodeAt(state.position); - - if (is_WS_OR_EOL(ch) || - is_FLOW_INDICATOR(ch) || - ch === 0x23/* # */ || - ch === 0x26/* & */ || - ch === 0x2A/* * */ || - ch === 0x21/* ! */ || - ch === 0x7C/* | */ || - ch === 0x3E/* > */ || - ch === 0x27/* ' */ || - ch === 0x22/* " */ || - ch === 0x25/* % */ || - ch === 0x40/* @ */ || - ch === 0x60/* ` */) { - return false; - } - - if (ch === 0x3F/* ? */ || ch === 0x2D/* - */) { - following = state.input.charCodeAt(state.position + 1); - - if (is_WS_OR_EOL(following) || - withinFlowCollection && is_FLOW_INDICATOR(following)) { - return false; - } - } - - state.kind = 'scalar'; - state.result = ''; - captureStart = captureEnd = state.position; - hasPendingContent = false; - - while (ch !== 0) { - if (ch === 0x3A/* : */) { - following = state.input.charCodeAt(state.position + 1); - - if (is_WS_OR_EOL(following) || - withinFlowCollection && is_FLOW_INDICATOR(following)) { - break; - } - - } else if (ch === 0x23/* # */) { - preceding = state.input.charCodeAt(state.position - 1); - - if (is_WS_OR_EOL(preceding)) { - break; - } - - } else if ((state.position === state.lineStart && testDocumentSeparator(state)) || - withinFlowCollection && is_FLOW_INDICATOR(ch)) { - break; - - } else if (is_EOL(ch)) { - _line = state.line; - _lineStart = state.lineStart; - _lineIndent = state.lineIndent; - skipSeparationSpace(state, false, -1); - - if (state.lineIndent >= nodeIndent) { - hasPendingContent = true; - ch = state.input.charCodeAt(state.position); - continue; - } else { - state.position = captureEnd; - state.line = _line; - state.lineStart = _lineStart; - state.lineIndent = _lineIndent; - break; - } - } - - if (hasPendingContent) { - captureSegment(state, captureStart, captureEnd, false); - writeFoldedLines(state, state.line - _line); - captureStart = captureEnd = state.position; - hasPendingContent = false; - } - - if (!is_WHITE_SPACE(ch)) { - captureEnd = state.position + 1; - } - - ch = state.input.charCodeAt(++state.position); - } - - captureSegment(state, captureStart, captureEnd, false); - - if (state.result) { - return true; - } - - state.kind = _kind; - state.result = _result; - return false; - } - - function readSingleQuotedScalar(state, nodeIndent) { - var ch, - captureStart, captureEnd; - - ch = state.input.charCodeAt(state.position); - - if (ch !== 0x27/* ' */) { - return false; - } - - state.kind = 'scalar'; - state.result = ''; - state.position++; - captureStart = captureEnd = state.position; - - while ((ch = state.input.charCodeAt(state.position)) !== 0) { - if (ch === 0x27/* ' */) { - captureSegment(state, captureStart, state.position, true); - ch = state.input.charCodeAt(++state.position); - - if (ch === 0x27/* ' */) { - captureStart = state.position; - state.position++; - captureEnd = state.position; - } else { - return true; - } - - } else if (is_EOL(ch)) { - captureSegment(state, captureStart, captureEnd, true); - writeFoldedLines(state, skipSeparationSpace(state, false, nodeIndent)); - captureStart = captureEnd = state.position; - - } else if (state.position === state.lineStart && testDocumentSeparator(state)) { - throwError(state, 'unexpected end of the document within a single quoted scalar'); - - } else { - state.position++; - captureEnd = state.position; - } - } - - throwError(state, 'unexpected end of the stream within a single quoted scalar'); - } - - function readDoubleQuotedScalar(state, nodeIndent) { - var captureStart, - captureEnd, - hexLength, - hexResult, - tmp, - ch; - - ch = state.input.charCodeAt(state.position); - - if (ch !== 0x22/* " */) { - return false; - } - - state.kind = 'scalar'; - state.result = ''; - state.position++; - captureStart = captureEnd = state.position; - - while ((ch = state.input.charCodeAt(state.position)) !== 0) { - if (ch === 0x22/* " */) { - captureSegment(state, captureStart, state.position, true); - state.position++; - return true; - - } else if (ch === 0x5C/* \ */) { - captureSegment(state, captureStart, state.position, true); - ch = state.input.charCodeAt(++state.position); - - if (is_EOL(ch)) { - skipSeparationSpace(state, false, nodeIndent); - - // TODO: rework to inline fn with no type cast? - } else if (ch < 256 && simpleEscapeCheck[ch]) { - state.result += simpleEscapeMap[ch]; - state.position++; - - } else if ((tmp = escapedHexLen(ch)) > 0) { - hexLength = tmp; - hexResult = 0; - - for (; hexLength > 0; hexLength--) { - ch = state.input.charCodeAt(++state.position); - - if ((tmp = fromHexCode(ch)) >= 0) { - hexResult = (hexResult << 4) + tmp; - - } else { - throwError(state, 'expected hexadecimal character'); + else if (isRegionalIndicator(next)) { + let countBefore = 0, i = pos - 2; + while (i >= 0 && isRegionalIndicator(codePointAt(str, i))) { + countBefore++; + i -= 2; } - } - - state.result += charFromCodepoint(hexResult); - - state.position++; - - } else { - throwError(state, 'unknown escape sequence'); + if (countBefore % 2 == 0) + break; + else + pos += 2; } - - captureStart = captureEnd = state.position; - - } else if (is_EOL(ch)) { - captureSegment(state, captureStart, captureEnd, true); - writeFoldedLines(state, skipSeparationSpace(state, false, nodeIndent)); - captureStart = captureEnd = state.position; - - } else if (state.position === state.lineStart && testDocumentSeparator(state)) { - throwError(state, 'unexpected end of the document within a double quoted scalar'); - - } else { - state.position++; - captureEnd = state.position; - } - } - - throwError(state, 'unexpected end of the stream within a double quoted scalar'); - } - - function readFlowCollection(state, nodeIndent) { - var readNext = true, - _line, - _lineStart, - _pos, - _tag = state.tag, - _result, - _anchor = state.anchor, - following, - terminator, - isPair, - isExplicitPair, - isMapping, - overridableKeys = Object.create(null), - keyNode, - keyTag, - valueNode, - ch; - - ch = state.input.charCodeAt(state.position); - - if (ch === 0x5B/* [ */) { - terminator = 0x5D;/* ] */ - isMapping = false; - _result = []; - } else if (ch === 0x7B/* { */) { - terminator = 0x7D;/* } */ - isMapping = true; - _result = {}; - } else { - return false; - } - - if (state.anchor !== null) { - state.anchorMap[state.anchor] = _result; - } - - ch = state.input.charCodeAt(++state.position); - - while (ch !== 0) { - skipSeparationSpace(state, true, nodeIndent); - - ch = state.input.charCodeAt(state.position); - - if (ch === terminator) { - state.position++; - state.tag = _tag; - state.anchor = _anchor; - state.kind = isMapping ? 'mapping' : 'sequence'; - state.result = _result; - return true; - } else if (!readNext) { - throwError(state, 'missed comma between flow collection entries'); - } else if (ch === 0x2C/* , */) { - // "flow collection entries can never be completely empty", as per YAML 1.2, section 7.4 - throwError(state, "expected the node content, but found ','"); - } - - keyTag = keyNode = valueNode = null; - isPair = isExplicitPair = false; - - if (ch === 0x3F/* ? */) { - following = state.input.charCodeAt(state.position + 1); - - if (is_WS_OR_EOL(following)) { - isPair = isExplicitPair = true; - state.position++; - skipSeparationSpace(state, true, nodeIndent); - } - } - - _line = state.line; // Save the current line. - _lineStart = state.lineStart; - _pos = state.position; - composeNode(state, nodeIndent, CONTEXT_FLOW_IN, false, true); - keyTag = state.tag; - keyNode = state.result; - skipSeparationSpace(state, true, nodeIndent); - - ch = state.input.charCodeAt(state.position); - - if ((isExplicitPair || state.line === _line) && ch === 0x3A/* : */) { - isPair = true; - ch = state.input.charCodeAt(++state.position); - skipSeparationSpace(state, true, nodeIndent); - composeNode(state, nodeIndent, CONTEXT_FLOW_IN, false, true); - valueNode = state.result; - } - - if (isMapping) { - storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, valueNode, _line, _lineStart, _pos); - } else if (isPair) { - _result.push(storeMappingPair(state, null, overridableKeys, keyTag, keyNode, valueNode, _line, _lineStart, _pos)); - } else { - _result.push(keyNode); - } - - skipSeparationSpace(state, true, nodeIndent); - - ch = state.input.charCodeAt(state.position); - - if (ch === 0x2C/* , */) { - readNext = true; - ch = state.input.charCodeAt(++state.position); - } else { - readNext = false; - } - } - - throwError(state, 'unexpected end of the stream within a flow collection'); - } - - function readBlockScalar(state, nodeIndent) { - var captureStart, - folding, - chomping = CHOMPING_CLIP, - didReadContent = false, - detectedIndent = false, - textIndent = nodeIndent, - emptyLines = 0, - atMoreIndented = false, - tmp, - ch; - - ch = state.input.charCodeAt(state.position); - - if (ch === 0x7C/* | */) { - folding = false; - } else if (ch === 0x3E/* > */) { - folding = true; - } else { - return false; - } - - state.kind = 'scalar'; - state.result = ''; - - while (ch !== 0) { - ch = state.input.charCodeAt(++state.position); - - if (ch === 0x2B/* + */ || ch === 0x2D/* - */) { - if (CHOMPING_CLIP === chomping) { - chomping = (ch === 0x2B/* + */) ? CHOMPING_KEEP : CHOMPING_STRIP; - } else { - throwError(state, 'repeat of a chomping mode identifier'); - } - - } else if ((tmp = fromDecimalCode(ch)) >= 0) { - if (tmp === 0) { - throwError(state, 'bad explicit indentation width of a block scalar; it cannot be less than one'); - } else if (!detectedIndent) { - textIndent = nodeIndent + tmp - 1; - detectedIndent = true; - } else { - throwError(state, 'repeat of an indentation width identifier'); - } - - } else { - break; - } - } - - if (is_WHITE_SPACE(ch)) { - do { ch = state.input.charCodeAt(++state.position); } - while (is_WHITE_SPACE(ch)); - - if (ch === 0x23/* # */) { - do { ch = state.input.charCodeAt(++state.position); } - while (!is_EOL(ch) && (ch !== 0)); - } - } - - while (ch !== 0) { - readLineBreak(state); - state.lineIndent = 0; - - ch = state.input.charCodeAt(state.position); - - while ((!detectedIndent || state.lineIndent < textIndent) && - (ch === 0x20/* Space */)) { - state.lineIndent++; - ch = state.input.charCodeAt(++state.position); - } - - if (!detectedIndent && state.lineIndent > textIndent) { - textIndent = state.lineIndent; - } - - if (is_EOL(ch)) { - emptyLines++; - continue; - } - - // End of the scalar. - if (state.lineIndent < textIndent) { - - // Perform the chomping. - if (chomping === CHOMPING_KEEP) { - state.result += common.repeat('\n', didReadContent ? 1 + emptyLines : emptyLines); - } else if (chomping === CHOMPING_CLIP) { - if (didReadContent) { // i.e. only if the scalar is not empty. - state.result += '\n'; - } - } - - // Break this `while` cycle and go to the funciton's epilogue. - break; - } - - // Folded style: use fancy rules to handle line breaks. - if (folding) { - - // Lines starting with white space characters (more-indented lines) are not folded. - if (is_WHITE_SPACE(ch)) { - atMoreIndented = true; - // except for the first content line (cf. Example 8.1) - state.result += common.repeat('\n', didReadContent ? 1 + emptyLines : emptyLines); - - // End of more-indented block. - } else if (atMoreIndented) { - atMoreIndented = false; - state.result += common.repeat('\n', emptyLines + 1); - - // Just one line break - perceive as the same line. - } else if (emptyLines === 0) { - if (didReadContent) { // i.e. only if we have already read some scalar content. - state.result += ' '; - } - - // Several line breaks - perceive as different lines. - } else { - state.result += common.repeat('\n', emptyLines); - } - - // Literal style: just add exact number of line breaks between content lines. - } else { - // Keep all line breaks except the header line break. - state.result += common.repeat('\n', didReadContent ? 1 + emptyLines : emptyLines); - } - - didReadContent = true; - detectedIndent = true; - emptyLines = 0; - captureStart = state.position; - - while (!is_EOL(ch) && (ch !== 0)) { - ch = state.input.charCodeAt(++state.position); - } - - captureSegment(state, captureStart, state.position, false); - } - - return true; - } - - function readBlockSequence(state, nodeIndent) { - var _line, - _tag = state.tag, - _anchor = state.anchor, - _result = [], - following, - detected = false, - ch; - - // there is a leading tab before this token, so it can't be a block sequence/mapping; - // it can still be flow sequence/mapping or a scalar - if (state.firstTabInLine !== -1) return false; - - if (state.anchor !== null) { - state.anchorMap[state.anchor] = _result; - } - - ch = state.input.charCodeAt(state.position); - - while (ch !== 0) { - if (state.firstTabInLine !== -1) { - state.position = state.firstTabInLine; - throwError(state, 'tab characters must not be used in indentation'); - } - - if (ch !== 0x2D/* - */) { - break; - } - - following = state.input.charCodeAt(state.position + 1); - - if (!is_WS_OR_EOL(following)) { - break; - } - - detected = true; - state.position++; - - if (skipSeparationSpace(state, true, -1)) { - if (state.lineIndent <= nodeIndent) { - _result.push(null); - ch = state.input.charCodeAt(state.position); - continue; - } - } - - _line = state.line; - composeNode(state, nodeIndent, CONTEXT_BLOCK_IN, false, true); - _result.push(state.result); - skipSeparationSpace(state, true, -1); - - ch = state.input.charCodeAt(state.position); - - if ((state.line === _line || state.lineIndent > nodeIndent) && (ch !== 0)) { - throwError(state, 'bad indentation of a sequence entry'); - } else if (state.lineIndent < nodeIndent) { - break; - } - } - - if (detected) { - state.tag = _tag; - state.anchor = _anchor; - state.kind = 'sequence'; - state.result = _result; - return true; - } - return false; - } - - function readBlockMapping(state, nodeIndent, flowIndent) { - var following, - allowCompact, - _line, - _keyLine, - _keyLineStart, - _keyPos, - _tag = state.tag, - _anchor = state.anchor, - _result = {}, - overridableKeys = Object.create(null), - keyTag = null, - keyNode = null, - valueNode = null, - atExplicitKey = false, - detected = false, - ch; - - // there is a leading tab before this token, so it can't be a block sequence/mapping; - // it can still be flow sequence/mapping or a scalar - if (state.firstTabInLine !== -1) return false; - - if (state.anchor !== null) { - state.anchorMap[state.anchor] = _result; - } - - ch = state.input.charCodeAt(state.position); - - while (ch !== 0) { - if (!atExplicitKey && state.firstTabInLine !== -1) { - state.position = state.firstTabInLine; - throwError(state, 'tab characters must not be used in indentation'); - } - - following = state.input.charCodeAt(state.position + 1); - _line = state.line; // Save the current line. - - // - // Explicit notation case. There are two separate blocks: - // first for the key (denoted by "?") and second for the value (denoted by ":") - // - if ((ch === 0x3F/* ? */ || ch === 0x3A/* : */) && is_WS_OR_EOL(following)) { - - if (ch === 0x3F/* ? */) { - if (atExplicitKey) { - storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, null, _keyLine, _keyLineStart, _keyPos); - keyTag = keyNode = valueNode = null; - } - - detected = true; - atExplicitKey = true; - allowCompact = true; - - } else if (atExplicitKey) { - // i.e. 0x3A/* : */ === character after the explicit key. - atExplicitKey = false; - allowCompact = true; - - } else { - throwError(state, 'incomplete explicit mapping pair; a key node is missed; or followed by a non-tabulated empty line'); - } - - state.position += 1; - ch = following; - - // - // Implicit notation case. Flow-style node as the key first, then ":", and the value. - // - } else { - _keyLine = state.line; - _keyLineStart = state.lineStart; - _keyPos = state.position; - - if (!composeNode(state, flowIndent, CONTEXT_FLOW_OUT, false, true)) { - // Neither implicit nor explicit notation. - // Reading is done. Go to the epilogue. - break; - } - - if (state.line === _line) { - ch = state.input.charCodeAt(state.position); - - while (is_WHITE_SPACE(ch)) { - ch = state.input.charCodeAt(++state.position); - } - - if (ch === 0x3A/* : */) { - ch = state.input.charCodeAt(++state.position); - - if (!is_WS_OR_EOL(ch)) { - throwError(state, 'a whitespace character is expected after the key-value separator within a block mapping'); - } - - if (atExplicitKey) { - storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, null, _keyLine, _keyLineStart, _keyPos); - keyTag = keyNode = valueNode = null; - } - - detected = true; - atExplicitKey = false; - allowCompact = false; - keyTag = state.tag; - keyNode = state.result; - - } else if (detected) { - throwError(state, 'can not read an implicit mapping pair; a colon is missed'); - - } else { - state.tag = _tag; - state.anchor = _anchor; - return true; // Keep the result of `composeNode`. - } - - } else if (detected) { - throwError(state, 'can not read a block mapping entry; a multiline key may not be an implicit key'); - - } else { - state.tag = _tag; - state.anchor = _anchor; - return true; // Keep the result of `composeNode`. - } - } - - // - // Common reading code for both explicit and implicit notations. - // - if (state.line === _line || state.lineIndent > nodeIndent) { - if (atExplicitKey) { - _keyLine = state.line; - _keyLineStart = state.lineStart; - _keyPos = state.position; - } - - if (composeNode(state, nodeIndent, CONTEXT_BLOCK_OUT, true, allowCompact)) { - if (atExplicitKey) { - keyNode = state.result; - } else { - valueNode = state.result; - } - } - - if (!atExplicitKey) { - storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, valueNode, _keyLine, _keyLineStart, _keyPos); - keyTag = keyNode = valueNode = null; - } - - skipSeparationSpace(state, true, -1); - ch = state.input.charCodeAt(state.position); - } - - if ((state.line === _line || state.lineIndent > nodeIndent) && (ch !== 0)) { - throwError(state, 'bad indentation of a mapping entry'); - } else if (state.lineIndent < nodeIndent) { - break; - } - } - - // - // Epilogue. - // - - // Special case: last mapping's node contains only the key in explicit notation. - if (atExplicitKey) { - storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, null, _keyLine, _keyLineStart, _keyPos); - } - - // Expose the resulting mapping. - if (detected) { - state.tag = _tag; - state.anchor = _anchor; - state.kind = 'mapping'; - state.result = _result; - } - - return detected; - } - - function readTagProperty(state) { - var _position, - isVerbatim = false, - isNamed = false, - tagHandle, - tagName, - ch; - - ch = state.input.charCodeAt(state.position); - - if (ch !== 0x21/* ! */) return false; - - if (state.tag !== null) { - throwError(state, 'duplication of a tag property'); - } - - ch = state.input.charCodeAt(++state.position); - - if (ch === 0x3C/* < */) { - isVerbatim = true; - ch = state.input.charCodeAt(++state.position); - - } else if (ch === 0x21/* ! */) { - isNamed = true; - tagHandle = '!!'; - ch = state.input.charCodeAt(++state.position); - - } else { - tagHandle = '!'; - } - - _position = state.position; - - if (isVerbatim) { - do { ch = state.input.charCodeAt(++state.position); } - while (ch !== 0 && ch !== 0x3E/* > */); - - if (state.position < state.length) { - tagName = state.input.slice(_position, state.position); - ch = state.input.charCodeAt(++state.position); - } else { - throwError(state, 'unexpected end of the stream within a verbatim tag'); - } - } else { - while (ch !== 0 && !is_WS_OR_EOL(ch)) { - - if (ch === 0x21/* ! */) { - if (!isNamed) { - tagHandle = state.input.slice(_position - 1, state.position + 1); - - if (!PATTERN_TAG_HANDLE.test(tagHandle)) { - throwError(state, 'named tag handle cannot contain such characters'); - } - - isNamed = true; - _position = state.position + 1; - } else { - throwError(state, 'tag suffix cannot contain exclamation marks'); - } - } - - ch = state.input.charCodeAt(++state.position); - } - - tagName = state.input.slice(_position, state.position); - - if (PATTERN_FLOW_INDICATORS.test(tagName)) { - throwError(state, 'tag suffix cannot contain flow indicator characters'); - } - } - - if (tagName && !PATTERN_TAG_URI.test(tagName)) { - throwError(state, 'tag name cannot contain such characters: ' + tagName); - } - - try { - tagName = decodeURIComponent(tagName); - } catch (err) { - throwError(state, 'tag name is malformed: ' + tagName); - } - - if (isVerbatim) { - state.tag = tagName; - - } else if (_hasOwnProperty$1.call(state.tagMap, tagHandle)) { - state.tag = state.tagMap[tagHandle] + tagName; - - } else if (tagHandle === '!') { - state.tag = '!' + tagName; - - } else if (tagHandle === '!!') { - state.tag = 'tag:yaml.org,2002:' + tagName; - - } else { - throwError(state, 'undeclared tag handle "' + tagHandle + '"'); - } - - return true; - } - - function readAnchorProperty(state) { - var _position, - ch; - - ch = state.input.charCodeAt(state.position); - - if (ch !== 0x26/* & */) return false; - - if (state.anchor !== null) { - throwError(state, 'duplication of an anchor property'); - } - - ch = state.input.charCodeAt(++state.position); - _position = state.position; - - while (ch !== 0 && !is_WS_OR_EOL(ch) && !is_FLOW_INDICATOR(ch)) { - ch = state.input.charCodeAt(++state.position); - } - - if (state.position === _position) { - throwError(state, 'name of an anchor node must contain at least one character'); - } - - state.anchor = state.input.slice(_position, state.position); - return true; - } - - function readAlias(state) { - var _position, alias, - ch; - - ch = state.input.charCodeAt(state.position); - - if (ch !== 0x2A/* * */) return false; - - ch = state.input.charCodeAt(++state.position); - _position = state.position; - - while (ch !== 0 && !is_WS_OR_EOL(ch) && !is_FLOW_INDICATOR(ch)) { - ch = state.input.charCodeAt(++state.position); - } - - if (state.position === _position) { - throwError(state, 'name of an alias node must contain at least one character'); - } - - alias = state.input.slice(_position, state.position); - - if (!_hasOwnProperty$1.call(state.anchorMap, alias)) { - throwError(state, 'unidentified alias "' + alias + '"'); - } - - state.result = state.anchorMap[alias]; - skipSeparationSpace(state, true, -1); - return true; - } - - function composeNode(state, parentIndent, nodeContext, allowToSeek, allowCompact) { - var allowBlockStyles, - allowBlockScalars, - allowBlockCollections, - indentStatus = 1, // 1: this>parent, 0: this=parent, -1: this<parent - atNewLine = false, - hasContent = false, - typeIndex, - typeQuantity, - typeList, - type, - flowIndent, - blockIndent; - - if (state.listener !== null) { - state.listener('open', state); - } - - state.tag = null; - state.anchor = null; - state.kind = null; - state.result = null; - - allowBlockStyles = allowBlockScalars = allowBlockCollections = - CONTEXT_BLOCK_OUT === nodeContext || - CONTEXT_BLOCK_IN === nodeContext; - - if (allowToSeek) { - if (skipSeparationSpace(state, true, -1)) { - atNewLine = true; - - if (state.lineIndent > parentIndent) { - indentStatus = 1; - } else if (state.lineIndent === parentIndent) { - indentStatus = 0; - } else if (state.lineIndent < parentIndent) { - indentStatus = -1; - } - } - } - - if (indentStatus === 1) { - while (readTagProperty(state) || readAnchorProperty(state)) { - if (skipSeparationSpace(state, true, -1)) { - atNewLine = true; - allowBlockCollections = allowBlockStyles; - - if (state.lineIndent > parentIndent) { - indentStatus = 1; - } else if (state.lineIndent === parentIndent) { - indentStatus = 0; - } else if (state.lineIndent < parentIndent) { - indentStatus = -1; - } - } else { - allowBlockCollections = false; - } - } - } - - if (allowBlockCollections) { - allowBlockCollections = atNewLine || allowCompact; - } - - if (indentStatus === 1 || CONTEXT_BLOCK_OUT === nodeContext) { - if (CONTEXT_FLOW_IN === nodeContext || CONTEXT_FLOW_OUT === nodeContext) { - flowIndent = parentIndent; - } else { - flowIndent = parentIndent + 1; - } - - blockIndent = state.position - state.lineStart; - - if (indentStatus === 1) { - if (allowBlockCollections && - (readBlockSequence(state, blockIndent) || - readBlockMapping(state, blockIndent, flowIndent)) || - readFlowCollection(state, flowIndent)) { - hasContent = true; - } else { - if ((allowBlockScalars && readBlockScalar(state, flowIndent)) || - readSingleQuotedScalar(state, flowIndent) || - readDoubleQuotedScalar(state, flowIndent)) { - hasContent = true; - - } else if (readAlias(state)) { - hasContent = true; - - if (state.tag !== null || state.anchor !== null) { - throwError(state, 'alias node should not have any properties'); - } - - } else if (readPlainScalar(state, flowIndent, CONTEXT_FLOW_IN === nodeContext)) { - hasContent = true; - - if (state.tag === null) { - state.tag = '?'; - } - } - - if (state.anchor !== null) { - state.anchorMap[state.anchor] = state.result; - } - } - } else if (indentStatus === 0) { - // Special case: block sequences are allowed to have same indentation level as the parent. - // http://www.yaml.org/spec/1.2/spec.html#id2799784 - hasContent = allowBlockCollections && readBlockSequence(state, blockIndent); - } - } - - if (state.tag === null) { - if (state.anchor !== null) { - state.anchorMap[state.anchor] = state.result; - } - - } else if (state.tag === '?') { - // Implicit resolving is not allowed for non-scalar types, and '?' - // non-specific tag is only automatically assigned to plain scalars. - // - // We only need to check kind conformity in case user explicitly assigns '?' - // tag, for example like this: "!<?> [0]" - // - if (state.result !== null && state.kind !== 'scalar') { - throwError(state, 'unacceptable node kind for !<?> tag; it should be "scalar", not "' + state.kind + '"'); - } - - for (typeIndex = 0, typeQuantity = state.implicitTypes.length; typeIndex < typeQuantity; typeIndex += 1) { - type = state.implicitTypes[typeIndex]; - - if (type.resolve(state.result)) { // `state.result` updated in resolver if matched - state.result = type.construct(state.result); - state.tag = type.tag; - if (state.anchor !== null) { - state.anchorMap[state.anchor] = state.result; - } - break; - } - } - } else if (state.tag !== '!') { - if (_hasOwnProperty$1.call(state.typeMap[state.kind || 'fallback'], state.tag)) { - type = state.typeMap[state.kind || 'fallback'][state.tag]; - } else { - // looking for multi type - type = null; - typeList = state.typeMap.multi[state.kind || 'fallback']; - - for (typeIndex = 0, typeQuantity = typeList.length; typeIndex < typeQuantity; typeIndex += 1) { - if (state.tag.slice(0, typeList[typeIndex].tag.length) === typeList[typeIndex].tag) { - type = typeList[typeIndex]; + else { break; - } + } + } + return pos; + } + function prevClusterBreak(str, pos, includeExtending) { + while (pos > 0) { + let found = nextClusterBreak(str, pos - 2, includeExtending); + if (found < pos) + return found; + pos--; + } + return 0; + } + function surrogateLow(ch) { return ch >= 0xDC00 && ch < 0xE000; } + function surrogateHigh(ch) { return ch >= 0xD800 && ch < 0xDC00; } + /** + Find the code point at the given position in a string (like the + [`codePointAt`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/codePointAt) + string method). + */ + function codePointAt(str, pos) { + let code0 = str.charCodeAt(pos); + if (!surrogateHigh(code0) || pos + 1 == str.length) + return code0; + let code1 = str.charCodeAt(pos + 1); + if (!surrogateLow(code1)) + return code0; + return ((code0 - 0xd800) << 10) + (code1 - 0xdc00) + 0x10000; + } + /** + Given a Unicode codepoint, return the JavaScript string that + respresents it (like + [`String.fromCodePoint`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/fromCodePoint)). + */ + function fromCodePoint(code) { + if (code <= 0xffff) + return String.fromCharCode(code); + code -= 0x10000; + return String.fromCharCode((code >> 10) + 0xd800, (code & 1023) + 0xdc00); + } + /** + The amount of positions a character takes up a JavaScript string. + */ + function codePointSize(code) { return code < 0x10000 ? 1 : 2; } + + const DefaultSplit = /\r\n?|\n/; + /** + Distinguishes different ways in which positions can be mapped. + */ + var MapMode = /*@__PURE__*/(function (MapMode) { + /** + Map a position to a valid new position, even when its context + was deleted. + */ + MapMode[MapMode["Simple"] = 0] = "Simple"; + /** + Return null if deletion happens across the position. + */ + MapMode[MapMode["TrackDel"] = 1] = "TrackDel"; + /** + Return null if the character _before_ the position is deleted. + */ + MapMode[MapMode["TrackBefore"] = 2] = "TrackBefore"; + /** + Return null if the character _after_ the position is deleted. + */ + MapMode[MapMode["TrackAfter"] = 3] = "TrackAfter"; + return MapMode})(MapMode || (MapMode = {})); + /** + A change description is a variant of [change set](https://codemirror.net/6/docs/ref/#state.ChangeSet) + that doesn't store the inserted text. As such, it can't be + applied, but is cheaper to store and manipulate. + */ + class ChangeDesc { + // Sections are encoded as pairs of integers. The first is the + // length in the current document, and the second is -1 for + // unaffected sections, and the length of the replacement content + // otherwise. So an insertion would be (0, n>0), a deletion (n>0, + // 0), and a replacement two positive numbers. + /** + @internal + */ + constructor( + /** + @internal + */ + sections) { + this.sections = sections; + } + /** + The length of the document before the change. + */ + get length() { + let result = 0; + for (let i = 0; i < this.sections.length; i += 2) + result += this.sections[i]; + return result; + } + /** + The length of the document after the change. + */ + get newLength() { + let result = 0; + for (let i = 0; i < this.sections.length; i += 2) { + let ins = this.sections[i + 1]; + result += ins < 0 ? this.sections[i] : ins; + } + return result; + } + /** + False when there are actual changes in this set. + */ + get empty() { return this.sections.length == 0 || this.sections.length == 2 && this.sections[1] < 0; } + /** + Iterate over the unchanged parts left by these changes. `posA` + provides the position of the range in the old document, `posB` + the new position in the changed document. + */ + iterGaps(f) { + for (let i = 0, posA = 0, posB = 0; i < this.sections.length;) { + let len = this.sections[i++], ins = this.sections[i++]; + if (ins < 0) { + f(posA, posB, len); + posB += len; + } + else { + posB += ins; + } + posA += len; + } + } + /** + Iterate over the ranges changed by these changes. (See + [`ChangeSet.iterChanges`](https://codemirror.net/6/docs/ref/#state.ChangeSet.iterChanges) for a + variant that also provides you with the inserted text.) + `fromA`/`toA` provides the extent of the change in the starting + document, `fromB`/`toB` the extent of the replacement in the + changed document. + + When `individual` is true, adjacent changes (which are kept + separate for [position mapping](https://codemirror.net/6/docs/ref/#state.ChangeDesc.mapPos)) are + reported separately. + */ + iterChangedRanges(f, individual = false) { + iterChanges(this, f, individual); + } + /** + Get a description of the inverted form of these changes. + */ + get invertedDesc() { + let sections = []; + for (let i = 0; i < this.sections.length;) { + let len = this.sections[i++], ins = this.sections[i++]; + if (ins < 0) + sections.push(len, ins); + else + sections.push(ins, len); + } + return new ChangeDesc(sections); + } + /** + Compute the combined effect of applying another set of changes + after this one. The length of the document after this set should + match the length before `other`. + */ + composeDesc(other) { return this.empty ? other : other.empty ? this : composeSets(this, other); } + /** + Map this description, which should start with the same document + as `other`, over another set of changes, so that it can be + applied after it. When `before` is true, map as if the changes + in `other` happened before the ones in `this`. + */ + mapDesc(other, before = false) { return other.empty ? this : mapSet(this, other, before); } + mapPos(pos, assoc = -1, mode = MapMode.Simple) { + let posA = 0, posB = 0; + for (let i = 0; i < this.sections.length;) { + let len = this.sections[i++], ins = this.sections[i++], endA = posA + len; + if (ins < 0) { + if (endA > pos) + return posB + (pos - posA); + posB += len; + } + else { + if (mode != MapMode.Simple && endA >= pos && + (mode == MapMode.TrackDel && posA < pos && endA > pos || + mode == MapMode.TrackBefore && posA < pos || + mode == MapMode.TrackAfter && endA > pos)) + return null; + if (endA > pos || endA == pos && assoc < 0 && !len) + return pos == posA || assoc < 0 ? posB : posB + ins; + posB += ins; + } + posA = endA; + } + if (pos > posA) + throw new RangeError(`Position ${pos} is out of range for changeset of length ${posA}`); + return posB; + } + /** + Check whether these changes touch a given range. When one of the + changes entirely covers the range, the string `"cover"` is + returned. + */ + touchesRange(from, to = from) { + for (let i = 0, pos = 0; i < this.sections.length && pos <= to;) { + let len = this.sections[i++], ins = this.sections[i++], end = pos + len; + if (ins >= 0 && pos <= to && end >= from) + return pos < from && end > to ? "cover" : true; + pos = end; + } + return false; + } + /** + @internal + */ + toString() { + let result = ""; + for (let i = 0; i < this.sections.length;) { + let len = this.sections[i++], ins = this.sections[i++]; + result += (result ? " " : "") + len + (ins >= 0 ? ":" + ins : ""); + } + return result; + } + /** + Serialize this change desc to a JSON-representable value. + */ + toJSON() { return this.sections; } + /** + Create a change desc from its JSON representation (as produced + by [`toJSON`](https://codemirror.net/6/docs/ref/#state.ChangeDesc.toJSON). + */ + static fromJSON(json) { + if (!Array.isArray(json) || json.length % 2 || json.some(a => typeof a != "number")) + throw new RangeError("Invalid JSON representation of ChangeDesc"); + return new ChangeDesc(json); + } + /** + @internal + */ + static create(sections) { return new ChangeDesc(sections); } + } + /** + A change set represents a group of modifications to a document. It + stores the document length, and can only be applied to documents + with exactly that length. + */ + class ChangeSet extends ChangeDesc { + constructor(sections, + /** + @internal + */ + inserted) { + super(sections); + this.inserted = inserted; + } + /** + Apply the changes to a document, returning the modified + document. + */ + apply(doc) { + if (this.length != doc.length) + throw new RangeError("Applying change set to a document with the wrong length"); + iterChanges(this, (fromA, toA, fromB, _toB, text) => doc = doc.replace(fromB, fromB + (toA - fromA), text), false); + return doc; + } + mapDesc(other, before = false) { return mapSet(this, other, before, true); } + /** + Given the document as it existed _before_ the changes, return a + change set that represents the inverse of this set, which could + be used to go from the document created by the changes back to + the document as it existed before the changes. + */ + invert(doc) { + let sections = this.sections.slice(), inserted = []; + for (let i = 0, pos = 0; i < sections.length; i += 2) { + let len = sections[i], ins = sections[i + 1]; + if (ins >= 0) { + sections[i] = ins; + sections[i + 1] = len; + let index = i >> 1; + while (inserted.length < index) + inserted.push(Text.empty); + inserted.push(len ? doc.slice(pos, pos + len) : Text.empty); + } + pos += len; + } + return new ChangeSet(sections, inserted); + } + /** + Combine two subsequent change sets into a single set. `other` + must start in the document produced by `this`. If `this` goes + `docA` → `docB` and `other` represents `docB` → `docC`, the + returned value will represent the change `docA` → `docC`. + */ + compose(other) { return this.empty ? other : other.empty ? this : composeSets(this, other, true); } + /** + Given another change set starting in the same document, maps this + change set over the other, producing a new change set that can be + applied to the document produced by applying `other`. When + `before` is `true`, order changes as if `this` comes before + `other`, otherwise (the default) treat `other` as coming first. + + Given two changes `A` and `B`, `A.compose(B.map(A))` and + `B.compose(A.map(B, true))` will produce the same document. This + provides a basic form of [operational + transformation](https://en.wikipedia.org/wiki/Operational_transformation), + and can be used for collaborative editing. + */ + map(other, before = false) { return other.empty ? this : mapSet(this, other, before, true); } + /** + Iterate over the changed ranges in the document, calling `f` for + each, with the range in the original document (`fromA`-`toA`) + and the range that replaces it in the new document + (`fromB`-`toB`). + + When `individual` is true, adjacent changes are reported + separately. + */ + iterChanges(f, individual = false) { + iterChanges(this, f, individual); + } + /** + Get a [change description](https://codemirror.net/6/docs/ref/#state.ChangeDesc) for this change + set. + */ + get desc() { return ChangeDesc.create(this.sections); } + /** + @internal + */ + filter(ranges) { + let resultSections = [], resultInserted = [], filteredSections = []; + let iter = new SectionIter(this); + done: for (let i = 0, pos = 0;;) { + let next = i == ranges.length ? 1e9 : ranges[i++]; + while (pos < next || pos == next && iter.len == 0) { + if (iter.done) + break done; + let len = Math.min(iter.len, next - pos); + addSection(filteredSections, len, -1); + let ins = iter.ins == -1 ? -1 : iter.off == 0 ? iter.ins : 0; + addSection(resultSections, len, ins); + if (ins > 0) + addInsert(resultInserted, resultSections, iter.text); + iter.forward(len); + pos += len; + } + let end = ranges[i++]; + while (pos < end) { + if (iter.done) + break done; + let len = Math.min(iter.len, end - pos); + addSection(resultSections, len, -1); + addSection(filteredSections, len, iter.ins == -1 ? -1 : iter.off == 0 ? iter.ins : 0); + iter.forward(len); + pos += len; + } + } + return { changes: new ChangeSet(resultSections, resultInserted), + filtered: ChangeDesc.create(filteredSections) }; + } + /** + Serialize this change set to a JSON-representable value. + */ + toJSON() { + let parts = []; + for (let i = 0; i < this.sections.length; i += 2) { + let len = this.sections[i], ins = this.sections[i + 1]; + if (ins < 0) + parts.push(len); + else if (ins == 0) + parts.push([len]); + else + parts.push([len].concat(this.inserted[i >> 1].toJSON())); + } + return parts; + } + /** + Create a change set for the given changes, for a document of the + given length, using `lineSep` as line separator. + */ + static of(changes, length, lineSep) { + let sections = [], inserted = [], pos = 0; + let total = null; + function flush(force = false) { + if (!force && !sections.length) + return; + if (pos < length) + addSection(sections, length - pos, -1); + let set = new ChangeSet(sections, inserted); + total = total ? total.compose(set.map(total)) : set; + sections = []; + inserted = []; + pos = 0; + } + function process(spec) { + if (Array.isArray(spec)) { + for (let sub of spec) + process(sub); + } + else if (spec instanceof ChangeSet) { + if (spec.length != length) + throw new RangeError(`Mismatched change set length (got ${spec.length}, expected ${length})`); + flush(); + total = total ? total.compose(spec.map(total)) : spec; + } + else { + let { from, to = from, insert } = spec; + if (from > to || from < 0 || to > length) + throw new RangeError(`Invalid change range ${from} to ${to} (in doc of length ${length})`); + let insText = !insert ? Text.empty : typeof insert == "string" ? Text.of(insert.split(lineSep || DefaultSplit)) : insert; + let insLen = insText.length; + if (from == to && insLen == 0) + return; + if (from < pos) + flush(); + if (from > pos) + addSection(sections, from - pos, -1); + addSection(sections, to - from, insLen); + addInsert(inserted, sections, insText); + pos = to; + } + } + process(changes); + flush(!total); + return total; + } + /** + Create an empty changeset of the given length. + */ + static empty(length) { + return new ChangeSet(length ? [length, -1] : [], []); + } + /** + Create a changeset from its JSON representation (as produced by + [`toJSON`](https://codemirror.net/6/docs/ref/#state.ChangeSet.toJSON). + */ + static fromJSON(json) { + if (!Array.isArray(json)) + throw new RangeError("Invalid JSON representation of ChangeSet"); + let sections = [], inserted = []; + for (let i = 0; i < json.length; i++) { + let part = json[i]; + if (typeof part == "number") { + sections.push(part, -1); + } + else if (!Array.isArray(part) || typeof part[0] != "number" || part.some((e, i) => i && typeof e != "string")) { + throw new RangeError("Invalid JSON representation of ChangeSet"); + } + else if (part.length == 1) { + sections.push(part[0], 0); + } + else { + while (inserted.length < i) + inserted.push(Text.empty); + inserted[i] = Text.of(part.slice(1)); + sections.push(part[0], inserted[i].length); + } + } + return new ChangeSet(sections, inserted); + } + /** + @internal + */ + static createSet(sections, inserted) { + return new ChangeSet(sections, inserted); + } + } + function addSection(sections, len, ins, forceJoin = false) { + if (len == 0 && ins <= 0) + return; + let last = sections.length - 2; + if (last >= 0 && ins <= 0 && ins == sections[last + 1]) + sections[last] += len; + else if (len == 0 && sections[last] == 0) + sections[last + 1] += ins; + else if (forceJoin) { + sections[last] += len; + sections[last + 1] += ins; + } + else + sections.push(len, ins); + } + function addInsert(values, sections, value) { + if (value.length == 0) + return; + let index = (sections.length - 2) >> 1; + if (index < values.length) { + values[values.length - 1] = values[values.length - 1].append(value); + } + else { + while (values.length < index) + values.push(Text.empty); + values.push(value); + } + } + function iterChanges(desc, f, individual) { + let inserted = desc.inserted; + for (let posA = 0, posB = 0, i = 0; i < desc.sections.length;) { + let len = desc.sections[i++], ins = desc.sections[i++]; + if (ins < 0) { + posA += len; + posB += len; + } + else { + let endA = posA, endB = posB, text = Text.empty; + for (;;) { + endA += len; + endB += ins; + if (ins && inserted) + text = text.append(inserted[(i - 2) >> 1]); + if (individual || i == desc.sections.length || desc.sections[i + 1] < 0) + break; + len = desc.sections[i++]; + ins = desc.sections[i++]; + } + f(posA, endA, posB, endB, text); + posA = endA; + posB = endB; + } + } + } + function mapSet(setA, setB, before, mkSet = false) { + // Produce a copy of setA that applies to the document after setB + // has been applied (assuming both start at the same document). + let sections = [], insert = mkSet ? [] : null; + let a = new SectionIter(setA), b = new SectionIter(setB); + // Iterate over both sets in parallel. inserted tracks, for changes + // in A that have to be processed piece-by-piece, whether their + // content has been inserted already, and refers to the section + // index. + for (let inserted = -1;;) { + if (a.ins == -1 && b.ins == -1) { + // Move across ranges skipped by both sets. + let len = Math.min(a.len, b.len); + addSection(sections, len, -1); + a.forward(len); + b.forward(len); + } + else if (b.ins >= 0 && (a.ins < 0 || inserted == a.i || a.off == 0 && (b.len < a.len || b.len == a.len && !before))) { + // If there's a change in B that comes before the next change in + // A (ordered by start pos, then len, then before flag), skip + // that (and process any changes in A it covers). + let len = b.len; + addSection(sections, b.ins, -1); + while (len) { + let piece = Math.min(a.len, len); + if (a.ins >= 0 && inserted < a.i && a.len <= piece) { + addSection(sections, 0, a.ins); + if (insert) + addInsert(insert, sections, a.text); + inserted = a.i; + } + a.forward(piece); + len -= piece; + } + b.next(); + } + else if (a.ins >= 0) { + // Process the part of a change in A up to the start of the next + // non-deletion change in B (if overlapping). + let len = 0, left = a.len; + while (left) { + if (b.ins == -1) { + let piece = Math.min(left, b.len); + len += piece; + left -= piece; + b.forward(piece); + } + else if (b.ins == 0 && b.len < left) { + left -= b.len; + b.next(); + } + else { + break; + } + } + addSection(sections, len, inserted < a.i ? a.ins : 0); + if (insert && inserted < a.i) + addInsert(insert, sections, a.text); + inserted = a.i; + a.forward(a.len - left); + } + else if (a.done && b.done) { + return insert ? ChangeSet.createSet(sections, insert) : ChangeDesc.create(sections); + } + else { + throw new Error("Mismatched change set lengths"); + } + } + } + function composeSets(setA, setB, mkSet = false) { + let sections = []; + let insert = mkSet ? [] : null; + let a = new SectionIter(setA), b = new SectionIter(setB); + for (let open = false;;) { + if (a.done && b.done) { + return insert ? ChangeSet.createSet(sections, insert) : ChangeDesc.create(sections); + } + else if (a.ins == 0) { // Deletion in A + addSection(sections, a.len, 0, open); + a.next(); + } + else if (b.len == 0 && !b.done) { // Insertion in B + addSection(sections, 0, b.ins, open); + if (insert) + addInsert(insert, sections, b.text); + b.next(); + } + else if (a.done || b.done) { + throw new Error("Mismatched change set lengths"); + } + else { + let len = Math.min(a.len2, b.len), sectionLen = sections.length; + if (a.ins == -1) { + let insB = b.ins == -1 ? -1 : b.off ? 0 : b.ins; + addSection(sections, len, insB, open); + if (insert && insB) + addInsert(insert, sections, b.text); + } + else if (b.ins == -1) { + addSection(sections, a.off ? 0 : a.len, len, open); + if (insert) + addInsert(insert, sections, a.textBit(len)); + } + else { + addSection(sections, a.off ? 0 : a.len, b.off ? 0 : b.ins, open); + if (insert && !b.off) + addInsert(insert, sections, b.text); + } + open = (a.ins > len || b.ins >= 0 && b.len > len) && (open || sections.length > sectionLen); + a.forward2(len); + b.forward(len); + } + } + } + class SectionIter { + constructor(set) { + this.set = set; + this.i = 0; + this.next(); + } + next() { + let { sections } = this.set; + if (this.i < sections.length) { + this.len = sections[this.i++]; + this.ins = sections[this.i++]; + } + else { + this.len = 0; + this.ins = -2; + } + this.off = 0; + } + get done() { return this.ins == -2; } + get len2() { return this.ins < 0 ? this.len : this.ins; } + get text() { + let { inserted } = this.set, index = (this.i - 2) >> 1; + return index >= inserted.length ? Text.empty : inserted[index]; + } + textBit(len) { + let { inserted } = this.set, index = (this.i - 2) >> 1; + return index >= inserted.length && !len ? Text.empty + : inserted[index].slice(this.off, len == null ? undefined : this.off + len); + } + forward(len) { + if (len == this.len) + this.next(); + else { + this.len -= len; + this.off += len; + } + } + forward2(len) { + if (this.ins == -1) + this.forward(len); + else if (len == this.ins) + this.next(); + else { + this.ins -= len; + this.off += len; + } + } + } + + /** + A single selection range. When + [`allowMultipleSelections`](https://codemirror.net/6/docs/ref/#state.EditorState^allowMultipleSelections) + is enabled, a [selection](https://codemirror.net/6/docs/ref/#state.EditorSelection) may hold + multiple ranges. By default, selections hold exactly one range. + */ + class SelectionRange { + constructor( + /** + The lower boundary of the range. + */ + from, + /** + The upper boundary of the range. + */ + to, flags) { + this.from = from; + this.to = to; + this.flags = flags; + } + /** + The anchor of the range—the side that doesn't move when you + extend it. + */ + get anchor() { return this.flags & 16 /* RangeFlag.Inverted */ ? this.to : this.from; } + /** + The head of the range, which is moved when the range is + [extended](https://codemirror.net/6/docs/ref/#state.SelectionRange.extend). + */ + get head() { return this.flags & 16 /* RangeFlag.Inverted */ ? this.from : this.to; } + /** + True when `anchor` and `head` are at the same position. + */ + get empty() { return this.from == this.to; } + /** + If this is a cursor that is explicitly associated with the + character on one of its sides, this returns the side. -1 means + the character before its position, 1 the character after, and 0 + means no association. + */ + get assoc() { return this.flags & 4 /* RangeFlag.AssocBefore */ ? -1 : this.flags & 8 /* RangeFlag.AssocAfter */ ? 1 : 0; } + /** + The bidirectional text level associated with this cursor, if + any. + */ + get bidiLevel() { + let level = this.flags & 3 /* RangeFlag.BidiLevelMask */; + return level == 3 ? null : level; + } + /** + The goal column (stored vertical offset) associated with a + cursor. This is used to preserve the vertical position when + [moving](https://codemirror.net/6/docs/ref/#view.EditorView.moveVertically) across + lines of different length. + */ + get goalColumn() { + let value = this.flags >> 5 /* RangeFlag.GoalColumnOffset */; + return value == 33554431 /* RangeFlag.NoGoalColumn */ ? undefined : value; + } + /** + Map this range through a change, producing a valid range in the + updated document. + */ + map(change, assoc = -1) { + let from, to; + if (this.empty) { + from = to = change.mapPos(this.from, assoc); + } + else { + from = change.mapPos(this.from, 1); + to = change.mapPos(this.to, -1); + } + return from == this.from && to == this.to ? this : new SelectionRange(from, to, this.flags); + } + /** + Extend this range to cover at least `from` to `to`. + */ + extend(from, to = from) { + if (from <= this.anchor && to >= this.anchor) + return EditorSelection.range(from, to); + let head = Math.abs(from - this.anchor) > Math.abs(to - this.anchor) ? from : to; + return EditorSelection.range(this.anchor, head); + } + /** + Compare this range to another range. + */ + eq(other) { + return this.anchor == other.anchor && this.head == other.head; + } + /** + Return a JSON-serializable object representing the range. + */ + toJSON() { return { anchor: this.anchor, head: this.head }; } + /** + Convert a JSON representation of a range to a `SelectionRange` + instance. + */ + static fromJSON(json) { + if (!json || typeof json.anchor != "number" || typeof json.head != "number") + throw new RangeError("Invalid JSON representation for SelectionRange"); + return EditorSelection.range(json.anchor, json.head); + } + /** + @internal + */ + static create(from, to, flags) { + return new SelectionRange(from, to, flags); + } + } + /** + An editor selection holds one or more selection ranges. + */ + class EditorSelection { + constructor( + /** + The ranges in the selection, sorted by position. Ranges cannot + overlap (but they may touch, if they aren't empty). + */ + ranges, + /** + The index of the _main_ range in the selection (which is + usually the range that was added last). + */ + mainIndex) { + this.ranges = ranges; + this.mainIndex = mainIndex; + } + /** + Map a selection through a change. Used to adjust the selection + position for changes. + */ + map(change, assoc = -1) { + if (change.empty) + return this; + return EditorSelection.create(this.ranges.map(r => r.map(change, assoc)), this.mainIndex); + } + /** + Compare this selection to another selection. + */ + eq(other) { + if (this.ranges.length != other.ranges.length || + this.mainIndex != other.mainIndex) + return false; + for (let i = 0; i < this.ranges.length; i++) + if (!this.ranges[i].eq(other.ranges[i])) + return false; + return true; + } + /** + Get the primary selection range. Usually, you should make sure + your code applies to _all_ ranges, by using methods like + [`changeByRange`](https://codemirror.net/6/docs/ref/#state.EditorState.changeByRange). + */ + get main() { return this.ranges[this.mainIndex]; } + /** + Make sure the selection only has one range. Returns a selection + holding only the main range from this selection. + */ + asSingle() { + return this.ranges.length == 1 ? this : new EditorSelection([this.main], 0); + } + /** + Extend this selection with an extra range. + */ + addRange(range, main = true) { + return EditorSelection.create([range].concat(this.ranges), main ? 0 : this.mainIndex + 1); + } + /** + Replace a given range with another range, and then normalize the + selection to merge and sort ranges if necessary. + */ + replaceRange(range, which = this.mainIndex) { + let ranges = this.ranges.slice(); + ranges[which] = range; + return EditorSelection.create(ranges, this.mainIndex); + } + /** + Convert this selection to an object that can be serialized to + JSON. + */ + toJSON() { + return { ranges: this.ranges.map(r => r.toJSON()), main: this.mainIndex }; + } + /** + Create a selection from a JSON representation. + */ + static fromJSON(json) { + if (!json || !Array.isArray(json.ranges) || typeof json.main != "number" || json.main >= json.ranges.length) + throw new RangeError("Invalid JSON representation for EditorSelection"); + return new EditorSelection(json.ranges.map((r) => SelectionRange.fromJSON(r)), json.main); + } + /** + Create a selection holding a single range. + */ + static single(anchor, head = anchor) { + return new EditorSelection([EditorSelection.range(anchor, head)], 0); + } + /** + Sort and merge the given set of ranges, creating a valid + selection. + */ + static create(ranges, mainIndex = 0) { + if (ranges.length == 0) + throw new RangeError("A selection needs at least one range"); + for (let pos = 0, i = 0; i < ranges.length; i++) { + let range = ranges[i]; + if (range.empty ? range.from <= pos : range.from < pos) + return EditorSelection.normalized(ranges.slice(), mainIndex); + pos = range.to; + } + return new EditorSelection(ranges, mainIndex); + } + /** + Create a cursor selection range at the given position. You can + safely ignore the optional arguments in most situations. + */ + static cursor(pos, assoc = 0, bidiLevel, goalColumn) { + return SelectionRange.create(pos, pos, (assoc == 0 ? 0 : assoc < 0 ? 4 /* RangeFlag.AssocBefore */ : 8 /* RangeFlag.AssocAfter */) | + (bidiLevel == null ? 3 : Math.min(2, bidiLevel)) | + ((goalColumn !== null && goalColumn !== void 0 ? goalColumn : 33554431 /* RangeFlag.NoGoalColumn */) << 5 /* RangeFlag.GoalColumnOffset */)); + } + /** + Create a selection range. + */ + static range(anchor, head, goalColumn) { + let goal = (goalColumn !== null && goalColumn !== void 0 ? goalColumn : 33554431 /* RangeFlag.NoGoalColumn */) << 5 /* RangeFlag.GoalColumnOffset */; + return head < anchor ? SelectionRange.create(head, anchor, 16 /* RangeFlag.Inverted */ | goal | 8 /* RangeFlag.AssocAfter */) + : SelectionRange.create(anchor, head, goal | (head > anchor ? 4 /* RangeFlag.AssocBefore */ : 0)); + } + /** + @internal + */ + static normalized(ranges, mainIndex = 0) { + let main = ranges[mainIndex]; + ranges.sort((a, b) => a.from - b.from); + mainIndex = ranges.indexOf(main); + for (let i = 1; i < ranges.length; i++) { + let range = ranges[i], prev = ranges[i - 1]; + if (range.empty ? range.from <= prev.to : range.from < prev.to) { + let from = prev.from, to = Math.max(range.to, prev.to); + if (i <= mainIndex) + mainIndex--; + ranges.splice(--i, 2, range.anchor > range.head ? EditorSelection.range(to, from) : EditorSelection.range(from, to)); + } + } + return new EditorSelection(ranges, mainIndex); + } + } + function checkSelection(selection, docLength) { + for (let range of selection.ranges) + if (range.to > docLength) + throw new RangeError("Selection points outside of document"); + } + + let nextID = 0; + /** + A facet is a labeled value that is associated with an editor + state. It takes inputs from any number of extensions, and combines + those into a single output value. + + Examples of uses of facets are the [tab + size](https://codemirror.net/6/docs/ref/#state.EditorState^tabSize), [editor + attributes](https://codemirror.net/6/docs/ref/#view.EditorView^editorAttributes), and [update + listeners](https://codemirror.net/6/docs/ref/#view.EditorView^updateListener). + */ + class Facet { + constructor( + /** + @internal + */ + combine, + /** + @internal + */ + compareInput, + /** + @internal + */ + compare, isStatic, enables) { + this.combine = combine; + this.compareInput = compareInput; + this.compare = compare; + this.isStatic = isStatic; + /** + @internal + */ + this.id = nextID++; + this.default = combine([]); + this.extensions = typeof enables == "function" ? enables(this) : enables; + } + /** + Define a new facet. + */ + static define(config = {}) { + return new Facet(config.combine || ((a) => a), config.compareInput || ((a, b) => a === b), config.compare || (!config.combine ? sameArray$1 : (a, b) => a === b), !!config.static, config.enables); + } + /** + Returns an extension that adds the given value to this facet. + */ + of(value) { + return new FacetProvider([], this, 0 /* Provider.Static */, value); + } + /** + Create an extension that computes a value for the facet from a + state. You must take care to declare the parts of the state that + this value depends on, since your function is only called again + for a new state when one of those parts changed. + + In cases where your value depends only on a single field, you'll + want to use the [`from`](https://codemirror.net/6/docs/ref/#state.Facet.from) method instead. + */ + compute(deps, get) { + if (this.isStatic) + throw new Error("Can't compute a static facet"); + return new FacetProvider(deps, this, 1 /* Provider.Single */, get); + } + /** + Create an extension that computes zero or more values for this + facet from a state. + */ + computeN(deps, get) { + if (this.isStatic) + throw new Error("Can't compute a static facet"); + return new FacetProvider(deps, this, 2 /* Provider.Multi */, get); + } + from(field, get) { + if (!get) + get = x => x; + return this.compute([field], state => get(state.field(field))); + } + } + function sameArray$1(a, b) { + return a == b || a.length == b.length && a.every((e, i) => e === b[i]); + } + class FacetProvider { + constructor(dependencies, facet, type, value) { + this.dependencies = dependencies; + this.facet = facet; + this.type = type; + this.value = value; + this.id = nextID++; + } + dynamicSlot(addresses) { + var _a; + let getter = this.value; + let compare = this.facet.compareInput; + let id = this.id, idx = addresses[id] >> 1, multi = this.type == 2 /* Provider.Multi */; + let depDoc = false, depSel = false, depAddrs = []; + for (let dep of this.dependencies) { + if (dep == "doc") + depDoc = true; + else if (dep == "selection") + depSel = true; + else if ((((_a = addresses[dep.id]) !== null && _a !== void 0 ? _a : 1) & 1) == 0) + depAddrs.push(addresses[dep.id]); + } + return { + create(state) { + state.values[idx] = getter(state); + return 1 /* SlotStatus.Changed */; + }, + update(state, tr) { + if ((depDoc && tr.docChanged) || (depSel && (tr.docChanged || tr.selection)) || ensureAll(state, depAddrs)) { + let newVal = getter(state); + if (multi ? !compareArray(newVal, state.values[idx], compare) : !compare(newVal, state.values[idx])) { + state.values[idx] = newVal; + return 1 /* SlotStatus.Changed */; + } + } + return 0; + }, + reconfigure: (state, oldState) => { + let newVal = getter(state); + let oldAddr = oldState.config.address[id]; + if (oldAddr != null) { + let oldVal = getAddr(oldState, oldAddr); + if (this.dependencies.every(dep => { + return dep instanceof Facet ? oldState.facet(dep) === state.facet(dep) : + dep instanceof StateField ? oldState.field(dep, false) == state.field(dep, false) : true; + }) || (multi ? compareArray(newVal, oldVal, compare) : compare(newVal, oldVal))) { + state.values[idx] = oldVal; + return 0; + } + } + state.values[idx] = newVal; + return 1 /* SlotStatus.Changed */; + } + }; + } + } + function compareArray(a, b, compare) { + if (a.length != b.length) + return false; + for (let i = 0; i < a.length; i++) + if (!compare(a[i], b[i])) + return false; + return true; + } + function ensureAll(state, addrs) { + let changed = false; + for (let addr of addrs) + if (ensureAddr(state, addr) & 1 /* SlotStatus.Changed */) + changed = true; + return changed; + } + function dynamicFacetSlot(addresses, facet, providers) { + let providerAddrs = providers.map(p => addresses[p.id]); + let providerTypes = providers.map(p => p.type); + let dynamic = providerAddrs.filter(p => !(p & 1)); + let idx = addresses[facet.id] >> 1; + function get(state) { + let values = []; + for (let i = 0; i < providerAddrs.length; i++) { + let value = getAddr(state, providerAddrs[i]); + if (providerTypes[i] == 2 /* Provider.Multi */) + for (let val of value) + values.push(val); + else + values.push(value); + } + return facet.combine(values); + } + return { + create(state) { + for (let addr of providerAddrs) + ensureAddr(state, addr); + state.values[idx] = get(state); + return 1 /* SlotStatus.Changed */; + }, + update(state, tr) { + if (!ensureAll(state, dynamic)) + return 0; + let value = get(state); + if (facet.compare(value, state.values[idx])) + return 0; + state.values[idx] = value; + return 1 /* SlotStatus.Changed */; + }, + reconfigure(state, oldState) { + let depChanged = ensureAll(state, providerAddrs); + let oldProviders = oldState.config.facets[facet.id], oldValue = oldState.facet(facet); + if (oldProviders && !depChanged && sameArray$1(providers, oldProviders)) { + state.values[idx] = oldValue; + return 0; + } + let value = get(state); + if (facet.compare(value, oldValue)) { + state.values[idx] = oldValue; + return 0; + } + state.values[idx] = value; + return 1 /* SlotStatus.Changed */; + } + }; + } + const initField = /*@__PURE__*/Facet.define({ static: true }); + /** + Fields can store additional information in an editor state, and + keep it in sync with the rest of the state. + */ + class StateField { + constructor( + /** + @internal + */ + id, createF, updateF, compareF, + /** + @internal + */ + spec) { + this.id = id; + this.createF = createF; + this.updateF = updateF; + this.compareF = compareF; + this.spec = spec; + /** + @internal + */ + this.provides = undefined; + } + /** + Define a state field. + */ + static define(config) { + let field = new StateField(nextID++, config.create, config.update, config.compare || ((a, b) => a === b), config); + if (config.provide) + field.provides = config.provide(field); + return field; + } + create(state) { + let init = state.facet(initField).find(i => i.field == this); + return ((init === null || init === void 0 ? void 0 : init.create) || this.createF)(state); + } + /** + @internal + */ + slot(addresses) { + let idx = addresses[this.id] >> 1; + return { + create: (state) => { + state.values[idx] = this.create(state); + return 1 /* SlotStatus.Changed */; + }, + update: (state, tr) => { + let oldVal = state.values[idx]; + let value = this.updateF(oldVal, tr); + if (this.compareF(oldVal, value)) + return 0; + state.values[idx] = value; + return 1 /* SlotStatus.Changed */; + }, + reconfigure: (state, oldState) => { + if (oldState.config.address[this.id] != null) { + state.values[idx] = oldState.field(this); + return 0; + } + state.values[idx] = this.create(state); + return 1 /* SlotStatus.Changed */; + } + }; + } + /** + Returns an extension that enables this field and overrides the + way it is initialized. Can be useful when you need to provide a + non-default starting value for the field. + */ + init(create) { + return [this, initField.of({ field: this, create })]; + } + /** + State field instances can be used as + [`Extension`](https://codemirror.net/6/docs/ref/#state.Extension) values to enable the field in a + given state. + */ + get extension() { return this; } + } + const Prec_ = { lowest: 4, low: 3, default: 2, high: 1, highest: 0 }; + function prec(value) { + return (ext) => new PrecExtension(ext, value); + } + /** + By default extensions are registered in the order they are found + in the flattened form of nested array that was provided. + Individual extension values can be assigned a precedence to + override this. Extensions that do not have a precedence set get + the precedence of the nearest parent with a precedence, or + [`default`](https://codemirror.net/6/docs/ref/#state.Prec.default) if there is no such parent. The + final ordering of extensions is determined by first sorting by + precedence and then by order within each precedence. + */ + const Prec = { + /** + The highest precedence level, for extensions that should end up + near the start of the precedence ordering. + */ + highest: /*@__PURE__*/prec(Prec_.highest), + /** + A higher-than-default precedence, for extensions that should + come before those with default precedence. + */ + high: /*@__PURE__*/prec(Prec_.high), + /** + The default precedence, which is also used for extensions + without an explicit precedence. + */ + default: /*@__PURE__*/prec(Prec_.default), + /** + A lower-than-default precedence. + */ + low: /*@__PURE__*/prec(Prec_.low), + /** + The lowest precedence level. Meant for things that should end up + near the end of the extension order. + */ + lowest: /*@__PURE__*/prec(Prec_.lowest) + }; + class PrecExtension { + constructor(inner, prec) { + this.inner = inner; + this.prec = prec; + } + } + /** + Extension compartments can be used to make a configuration + dynamic. By [wrapping](https://codemirror.net/6/docs/ref/#state.Compartment.of) part of your + configuration in a compartment, you can later + [replace](https://codemirror.net/6/docs/ref/#state.Compartment.reconfigure) that part through a + transaction. + */ + class Compartment { + /** + Create an instance of this compartment to add to your [state + configuration](https://codemirror.net/6/docs/ref/#state.EditorStateConfig.extensions). + */ + of(ext) { return new CompartmentInstance(this, ext); } + /** + Create an [effect](https://codemirror.net/6/docs/ref/#state.TransactionSpec.effects) that + reconfigures this compartment. + */ + reconfigure(content) { + return Compartment.reconfigure.of({ compartment: this, extension: content }); + } + /** + Get the current content of the compartment in the state, or + `undefined` if it isn't present. + */ + get(state) { + return state.config.compartments.get(this); + } + } + class CompartmentInstance { + constructor(compartment, inner) { + this.compartment = compartment; + this.inner = inner; + } + } + class Configuration { + constructor(base, compartments, dynamicSlots, address, staticValues, facets) { + this.base = base; + this.compartments = compartments; + this.dynamicSlots = dynamicSlots; + this.address = address; + this.staticValues = staticValues; + this.facets = facets; + this.statusTemplate = []; + while (this.statusTemplate.length < dynamicSlots.length) + this.statusTemplate.push(0 /* SlotStatus.Unresolved */); + } + staticFacet(facet) { + let addr = this.address[facet.id]; + return addr == null ? facet.default : this.staticValues[addr >> 1]; + } + static resolve(base, compartments, oldState) { + let fields = []; + let facets = Object.create(null); + let newCompartments = new Map(); + for (let ext of flatten(base, compartments, newCompartments)) { + if (ext instanceof StateField) + fields.push(ext); + else + (facets[ext.facet.id] || (facets[ext.facet.id] = [])).push(ext); + } + let address = Object.create(null); + let staticValues = []; + let dynamicSlots = []; + for (let field of fields) { + address[field.id] = dynamicSlots.length << 1; + dynamicSlots.push(a => field.slot(a)); + } + let oldFacets = oldState === null || oldState === void 0 ? void 0 : oldState.config.facets; + for (let id in facets) { + let providers = facets[id], facet = providers[0].facet; + let oldProviders = oldFacets && oldFacets[id] || []; + if (providers.every(p => p.type == 0 /* Provider.Static */)) { + address[facet.id] = (staticValues.length << 1) | 1; + if (sameArray$1(oldProviders, providers)) { + staticValues.push(oldState.facet(facet)); + } + else { + let value = facet.combine(providers.map(p => p.value)); + staticValues.push(oldState && facet.compare(value, oldState.facet(facet)) ? oldState.facet(facet) : value); + } + } + else { + for (let p of providers) { + if (p.type == 0 /* Provider.Static */) { + address[p.id] = (staticValues.length << 1) | 1; + staticValues.push(p.value); + } + else { + address[p.id] = dynamicSlots.length << 1; + dynamicSlots.push(a => p.dynamicSlot(a)); + } + } + address[facet.id] = dynamicSlots.length << 1; + dynamicSlots.push(a => dynamicFacetSlot(a, facet, providers)); + } + } + let dynamic = dynamicSlots.map(f => f(address)); + return new Configuration(base, newCompartments, dynamic, address, staticValues, facets); + } + } + function flatten(extension, compartments, newCompartments) { + let result = [[], [], [], [], []]; + let seen = new Map(); + function inner(ext, prec) { + let known = seen.get(ext); + if (known != null) { + if (known <= prec) + return; + let found = result[known].indexOf(ext); + if (found > -1) + result[known].splice(found, 1); + if (ext instanceof CompartmentInstance) + newCompartments.delete(ext.compartment); + } + seen.set(ext, prec); + if (Array.isArray(ext)) { + for (let e of ext) + inner(e, prec); + } + else if (ext instanceof CompartmentInstance) { + if (newCompartments.has(ext.compartment)) + throw new RangeError(`Duplicate use of compartment in extensions`); + let content = compartments.get(ext.compartment) || ext.inner; + newCompartments.set(ext.compartment, content); + inner(content, prec); + } + else if (ext instanceof PrecExtension) { + inner(ext.inner, ext.prec); + } + else if (ext instanceof StateField) { + result[prec].push(ext); + if (ext.provides) + inner(ext.provides, prec); + } + else if (ext instanceof FacetProvider) { + result[prec].push(ext); + if (ext.facet.extensions) + inner(ext.facet.extensions, Prec_.default); + } + else { + let content = ext.extension; + if (!content) + throw new Error(`Unrecognized extension value in extension set (${ext}). This sometimes happens because multiple instances of @codemirror/state are loaded, breaking instanceof checks.`); + inner(content, prec); + } + } + inner(extension, Prec_.default); + return result.reduce((a, b) => a.concat(b)); + } + function ensureAddr(state, addr) { + if (addr & 1) + return 2 /* SlotStatus.Computed */; + let idx = addr >> 1; + let status = state.status[idx]; + if (status == 4 /* SlotStatus.Computing */) + throw new Error("Cyclic dependency between fields and/or facets"); + if (status & 2 /* SlotStatus.Computed */) + return status; + state.status[idx] = 4 /* SlotStatus.Computing */; + let changed = state.computeSlot(state, state.config.dynamicSlots[idx]); + return state.status[idx] = 2 /* SlotStatus.Computed */ | changed; + } + function getAddr(state, addr) { + return addr & 1 ? state.config.staticValues[addr >> 1] : state.values[addr >> 1]; + } + + const languageData = /*@__PURE__*/Facet.define(); + const allowMultipleSelections = /*@__PURE__*/Facet.define({ + combine: values => values.some(v => v), + static: true + }); + const lineSeparator = /*@__PURE__*/Facet.define({ + combine: values => values.length ? values[0] : undefined, + static: true + }); + const changeFilter = /*@__PURE__*/Facet.define(); + const transactionFilter = /*@__PURE__*/Facet.define(); + const transactionExtender = /*@__PURE__*/Facet.define(); + const readOnly = /*@__PURE__*/Facet.define({ + combine: values => values.length ? values[0] : false + }); + + /** + Annotations are tagged values that are used to add metadata to + transactions in an extensible way. They should be used to model + things that effect the entire transaction (such as its [time + stamp](https://codemirror.net/6/docs/ref/#state.Transaction^time) or information about its + [origin](https://codemirror.net/6/docs/ref/#state.Transaction^userEvent)). For effects that happen + _alongside_ the other changes made by the transaction, [state + effects](https://codemirror.net/6/docs/ref/#state.StateEffect) are more appropriate. + */ + class Annotation { + /** + @internal + */ + constructor( + /** + The annotation type. + */ + type, + /** + The value of this annotation. + */ + value) { + this.type = type; + this.value = value; + } + /** + Define a new type of annotation. + */ + static define() { return new AnnotationType(); } + } + /** + Marker that identifies a type of [annotation](https://codemirror.net/6/docs/ref/#state.Annotation). + */ + class AnnotationType { + /** + Create an instance of this annotation. + */ + of(value) { return new Annotation(this, value); } + } + /** + Representation of a type of state effect. Defined with + [`StateEffect.define`](https://codemirror.net/6/docs/ref/#state.StateEffect^define). + */ + class StateEffectType { + /** + @internal + */ + constructor( + // The `any` types in these function types are there to work + // around TypeScript issue #37631, where the type guard on + // `StateEffect.is` mysteriously stops working when these properly + // have type `Value`. + /** + @internal + */ + map) { + this.map = map; + } + /** + Create a [state effect](https://codemirror.net/6/docs/ref/#state.StateEffect) instance of this + type. + */ + of(value) { return new StateEffect(this, value); } + } + /** + State effects can be used to represent additional effects + associated with a [transaction](https://codemirror.net/6/docs/ref/#state.Transaction.effects). They + are often useful to model changes to custom [state + fields](https://codemirror.net/6/docs/ref/#state.StateField), when those changes aren't implicit in + document or selection changes. + */ + class StateEffect { + /** + @internal + */ + constructor( + /** + @internal + */ + type, + /** + The value of this effect. + */ + value) { + this.type = type; + this.value = value; + } + /** + Map this effect through a position mapping. Will return + `undefined` when that ends up deleting the effect. + */ + map(mapping) { + let mapped = this.type.map(this.value, mapping); + return mapped === undefined ? undefined : mapped == this.value ? this : new StateEffect(this.type, mapped); + } + /** + Tells you whether this effect object is of a given + [type](https://codemirror.net/6/docs/ref/#state.StateEffectType). + */ + is(type) { return this.type == type; } + /** + Define a new effect type. The type parameter indicates the type + of values that his effect holds. + */ + static define(spec = {}) { + return new StateEffectType(spec.map || (v => v)); + } + /** + Map an array of effects through a change set. + */ + static mapEffects(effects, mapping) { + if (!effects.length) + return effects; + let result = []; + for (let effect of effects) { + let mapped = effect.map(mapping); + if (mapped) + result.push(mapped); + } + return result; + } + } + /** + This effect can be used to reconfigure the root extensions of + the editor. Doing this will discard any extensions + [appended](https://codemirror.net/6/docs/ref/#state.StateEffect^appendConfig), but does not reset + the content of [reconfigured](https://codemirror.net/6/docs/ref/#state.Compartment.reconfigure) + compartments. + */ + StateEffect.reconfigure = /*@__PURE__*/StateEffect.define(); + /** + Append extensions to the top-level configuration of the editor. + */ + StateEffect.appendConfig = /*@__PURE__*/StateEffect.define(); + /** + Changes to the editor state are grouped into transactions. + Typically, a user action creates a single transaction, which may + contain any number of document changes, may change the selection, + or have other effects. Create a transaction by calling + [`EditorState.update`](https://codemirror.net/6/docs/ref/#state.EditorState.update), or immediately + dispatch one by calling + [`EditorView.dispatch`](https://codemirror.net/6/docs/ref/#view.EditorView.dispatch). + */ + class Transaction { + constructor( + /** + The state from which the transaction starts. + */ + startState, + /** + The document changes made by this transaction. + */ + changes, + /** + The selection set by this transaction, or undefined if it + doesn't explicitly set a selection. + */ + selection, + /** + The effects added to the transaction. + */ + effects, + /** + @internal + */ + annotations, + /** + Whether the selection should be scrolled into view after this + transaction is dispatched. + */ + scrollIntoView) { + this.startState = startState; + this.changes = changes; + this.selection = selection; + this.effects = effects; + this.annotations = annotations; + this.scrollIntoView = scrollIntoView; + /** + @internal + */ + this._doc = null; + /** + @internal + */ + this._state = null; + if (selection) + checkSelection(selection, changes.newLength); + if (!annotations.some((a) => a.type == Transaction.time)) + this.annotations = annotations.concat(Transaction.time.of(Date.now())); + } + /** + @internal + */ + static create(startState, changes, selection, effects, annotations, scrollIntoView) { + return new Transaction(startState, changes, selection, effects, annotations, scrollIntoView); + } + /** + The new document produced by the transaction. Contrary to + [`.state`](https://codemirror.net/6/docs/ref/#state.Transaction.state)`.doc`, accessing this won't + force the entire new state to be computed right away, so it is + recommended that [transaction + filters](https://codemirror.net/6/docs/ref/#state.EditorState^transactionFilter) use this getter + when they need to look at the new document. + */ + get newDoc() { + return this._doc || (this._doc = this.changes.apply(this.startState.doc)); + } + /** + The new selection produced by the transaction. If + [`this.selection`](https://codemirror.net/6/docs/ref/#state.Transaction.selection) is undefined, + this will [map](https://codemirror.net/6/docs/ref/#state.EditorSelection.map) the start state's + current selection through the changes made by the transaction. + */ + get newSelection() { + return this.selection || this.startState.selection.map(this.changes); + } + /** + The new state created by the transaction. Computed on demand + (but retained for subsequent access), so it is recommended not to + access it in [transaction + filters](https://codemirror.net/6/docs/ref/#state.EditorState^transactionFilter) when possible. + */ + get state() { + if (!this._state) + this.startState.applyTransaction(this); + return this._state; + } + /** + Get the value of the given annotation type, if any. + */ + annotation(type) { + for (let ann of this.annotations) + if (ann.type == type) + return ann.value; + return undefined; + } + /** + Indicates whether the transaction changed the document. + */ + get docChanged() { return !this.changes.empty; } + /** + Indicates whether this transaction reconfigures the state + (through a [configuration compartment](https://codemirror.net/6/docs/ref/#state.Compartment) or + with a top-level configuration + [effect](https://codemirror.net/6/docs/ref/#state.StateEffect^reconfigure). + */ + get reconfigured() { return this.startState.config != this.state.config; } + /** + Returns true if the transaction has a [user + event](https://codemirror.net/6/docs/ref/#state.Transaction^userEvent) annotation that is equal to + or more specific than `event`. For example, if the transaction + has `"select.pointer"` as user event, `"select"` and + `"select.pointer"` will match it. + */ + isUserEvent(event) { + let e = this.annotation(Transaction.userEvent); + return !!(e && (e == event || e.length > event.length && e.slice(0, event.length) == event && e[event.length] == ".")); + } + } + /** + Annotation used to store transaction timestamps. Automatically + added to every transaction, holding `Date.now()`. + */ + Transaction.time = /*@__PURE__*/Annotation.define(); + /** + Annotation used to associate a transaction with a user interface + event. Holds a string identifying the event, using a + dot-separated format to support attaching more specific + information. The events used by the core libraries are: + + - `"input"` when content is entered + - `"input.type"` for typed input + - `"input.type.compose"` for composition + - `"input.paste"` for pasted input + - `"input.drop"` when adding content with drag-and-drop + - `"input.complete"` when autocompleting + - `"delete"` when the user deletes content + - `"delete.selection"` when deleting the selection + - `"delete.forward"` when deleting forward from the selection + - `"delete.backward"` when deleting backward from the selection + - `"delete.cut"` when cutting to the clipboard + - `"move"` when content is moved + - `"move.drop"` when content is moved within the editor through drag-and-drop + - `"select"` when explicitly changing the selection + - `"select.pointer"` when selecting with a mouse or other pointing device + - `"undo"` and `"redo"` for history actions + + Use [`isUserEvent`](https://codemirror.net/6/docs/ref/#state.Transaction.isUserEvent) to check + whether the annotation matches a given event. + */ + Transaction.userEvent = /*@__PURE__*/Annotation.define(); + /** + Annotation indicating whether a transaction should be added to + the undo history or not. + */ + Transaction.addToHistory = /*@__PURE__*/Annotation.define(); + /** + Annotation indicating (when present and true) that a transaction + represents a change made by some other actor, not the user. This + is used, for example, to tag other people's changes in + collaborative editing. + */ + Transaction.remote = /*@__PURE__*/Annotation.define(); + function joinRanges(a, b) { + let result = []; + for (let iA = 0, iB = 0;;) { + let from, to; + if (iA < a.length && (iB == b.length || b[iB] >= a[iA])) { + from = a[iA++]; + to = a[iA++]; + } + else if (iB < b.length) { + from = b[iB++]; + to = b[iB++]; + } + else + return result; + if (!result.length || result[result.length - 1] < from) + result.push(from, to); + else if (result[result.length - 1] < to) + result[result.length - 1] = to; + } + } + function mergeTransaction(a, b, sequential) { + var _a; + let mapForA, mapForB, changes; + if (sequential) { + mapForA = b.changes; + mapForB = ChangeSet.empty(b.changes.length); + changes = a.changes.compose(b.changes); + } + else { + mapForA = b.changes.map(a.changes); + mapForB = a.changes.mapDesc(b.changes, true); + changes = a.changes.compose(mapForA); + } + return { + changes, + selection: b.selection ? b.selection.map(mapForB) : (_a = a.selection) === null || _a === void 0 ? void 0 : _a.map(mapForA), + effects: StateEffect.mapEffects(a.effects, mapForA).concat(StateEffect.mapEffects(b.effects, mapForB)), + annotations: a.annotations.length ? a.annotations.concat(b.annotations) : b.annotations, + scrollIntoView: a.scrollIntoView || b.scrollIntoView + }; + } + function resolveTransactionInner(state, spec, docSize) { + let sel = spec.selection, annotations = asArray$1(spec.annotations); + if (spec.userEvent) + annotations = annotations.concat(Transaction.userEvent.of(spec.userEvent)); + return { + changes: spec.changes instanceof ChangeSet ? spec.changes + : ChangeSet.of(spec.changes || [], docSize, state.facet(lineSeparator)), + selection: sel && (sel instanceof EditorSelection ? sel : EditorSelection.single(sel.anchor, sel.head)), + effects: asArray$1(spec.effects), + annotations, + scrollIntoView: !!spec.scrollIntoView + }; + } + function resolveTransaction(state, specs, filter) { + let s = resolveTransactionInner(state, specs.length ? specs[0] : {}, state.doc.length); + if (specs.length && specs[0].filter === false) + filter = false; + for (let i = 1; i < specs.length; i++) { + if (specs[i].filter === false) + filter = false; + let seq = !!specs[i].sequential; + s = mergeTransaction(s, resolveTransactionInner(state, specs[i], seq ? s.changes.newLength : state.doc.length), seq); + } + let tr = Transaction.create(state, s.changes, s.selection, s.effects, s.annotations, s.scrollIntoView); + return extendTransaction(filter ? filterTransaction(tr) : tr); + } + // Finish a transaction by applying filters if necessary. + function filterTransaction(tr) { + let state = tr.startState; + // Change filters + let result = true; + for (let filter of state.facet(changeFilter)) { + let value = filter(tr); + if (value === false) { + result = false; + break; + } + if (Array.isArray(value)) + result = result === true ? value : joinRanges(result, value); + } + if (result !== true) { + let changes, back; + if (result === false) { + back = tr.changes.invertedDesc; + changes = ChangeSet.empty(state.doc.length); + } + else { + let filtered = tr.changes.filter(result); + changes = filtered.changes; + back = filtered.filtered.mapDesc(filtered.changes).invertedDesc; + } + tr = Transaction.create(state, changes, tr.selection && tr.selection.map(back), StateEffect.mapEffects(tr.effects, back), tr.annotations, tr.scrollIntoView); + } + // Transaction filters + let filters = state.facet(transactionFilter); + for (let i = filters.length - 1; i >= 0; i--) { + let filtered = filters[i](tr); + if (filtered instanceof Transaction) + tr = filtered; + else if (Array.isArray(filtered) && filtered.length == 1 && filtered[0] instanceof Transaction) + tr = filtered[0]; + else + tr = resolveTransaction(state, asArray$1(filtered), false); + } + return tr; + } + function extendTransaction(tr) { + let state = tr.startState, extenders = state.facet(transactionExtender), spec = tr; + for (let i = extenders.length - 1; i >= 0; i--) { + let extension = extenders[i](tr); + if (extension && Object.keys(extension).length) + spec = mergeTransaction(spec, resolveTransactionInner(state, extension, tr.changes.newLength), true); + } + return spec == tr ? tr : Transaction.create(state, tr.changes, tr.selection, spec.effects, spec.annotations, spec.scrollIntoView); + } + const none$2 = []; + function asArray$1(value) { + return value == null ? none$2 : Array.isArray(value) ? value : [value]; + } + + /** + The categories produced by a [character + categorizer](https://codemirror.net/6/docs/ref/#state.EditorState.charCategorizer). These are used + do things like selecting by word. + */ + var CharCategory = /*@__PURE__*/(function (CharCategory) { + /** + Word characters. + */ + CharCategory[CharCategory["Word"] = 0] = "Word"; + /** + Whitespace. + */ + CharCategory[CharCategory["Space"] = 1] = "Space"; + /** + Anything else. + */ + CharCategory[CharCategory["Other"] = 2] = "Other"; + return CharCategory})(CharCategory || (CharCategory = {})); + const nonASCIISingleCaseWordChar = /[\u00df\u0587\u0590-\u05f4\u0600-\u06ff\u3040-\u309f\u30a0-\u30ff\u3400-\u4db5\u4e00-\u9fcc\uac00-\ud7af]/; + let wordChar; + try { + wordChar = /*@__PURE__*/new RegExp("[\\p{Alphabetic}\\p{Number}_]", "u"); + } + catch (_) { } + function hasWordChar(str) { + if (wordChar) + return wordChar.test(str); + for (let i = 0; i < str.length; i++) { + let ch = str[i]; + if (/\w/.test(ch) || ch > "\x80" && (ch.toUpperCase() != ch.toLowerCase() || nonASCIISingleCaseWordChar.test(ch))) + return true; + } + return false; + } + function makeCategorizer(wordChars) { + return (char) => { + if (!/\S/.test(char)) + return CharCategory.Space; + if (hasWordChar(char)) + return CharCategory.Word; + for (let i = 0; i < wordChars.length; i++) + if (char.indexOf(wordChars[i]) > -1) + return CharCategory.Word; + return CharCategory.Other; + }; + } + + /** + The editor state class is a persistent (immutable) data structure. + To update a state, you [create](https://codemirror.net/6/docs/ref/#state.EditorState.update) a + [transaction](https://codemirror.net/6/docs/ref/#state.Transaction), which produces a _new_ state + instance, without modifying the original object. + + As such, _never_ mutate properties of a state directly. That'll + just break things. + */ + class EditorState { + constructor( + /** + @internal + */ + config, + /** + The current document. + */ + doc, + /** + The current selection. + */ + selection, + /** + @internal + */ + values, computeSlot, tr) { + this.config = config; + this.doc = doc; + this.selection = selection; + this.values = values; + this.status = config.statusTemplate.slice(); + this.computeSlot = computeSlot; + // Fill in the computed state immediately, so that further queries + // for it made during the update return this state + if (tr) + tr._state = this; + for (let i = 0; i < this.config.dynamicSlots.length; i++) + ensureAddr(this, i << 1); + this.computeSlot = null; + } + field(field, require = true) { + let addr = this.config.address[field.id]; + if (addr == null) { + if (require) + throw new RangeError("Field is not present in this state"); + return undefined; + } + ensureAddr(this, addr); + return getAddr(this, addr); + } + /** + Create a [transaction](https://codemirror.net/6/docs/ref/#state.Transaction) that updates this + state. Any number of [transaction specs](https://codemirror.net/6/docs/ref/#state.TransactionSpec) + can be passed. Unless + [`sequential`](https://codemirror.net/6/docs/ref/#state.TransactionSpec.sequential) is set, the + [changes](https://codemirror.net/6/docs/ref/#state.TransactionSpec.changes) (if any) of each spec + are assumed to start in the _current_ document (not the document + produced by previous specs), and its + [selection](https://codemirror.net/6/docs/ref/#state.TransactionSpec.selection) and + [effects](https://codemirror.net/6/docs/ref/#state.TransactionSpec.effects) are assumed to refer + to the document created by its _own_ changes. The resulting + transaction contains the combined effect of all the different + specs. For [selection](https://codemirror.net/6/docs/ref/#state.TransactionSpec.selection), later + specs take precedence over earlier ones. + */ + update(...specs) { + return resolveTransaction(this, specs, true); + } + /** + @internal + */ + applyTransaction(tr) { + let conf = this.config, { base, compartments } = conf; + for (let effect of tr.effects) { + if (effect.is(Compartment.reconfigure)) { + if (conf) { + compartments = new Map; + conf.compartments.forEach((val, key) => compartments.set(key, val)); + conf = null; + } + compartments.set(effect.value.compartment, effect.value.extension); + } + else if (effect.is(StateEffect.reconfigure)) { + conf = null; + base = effect.value; + } + else if (effect.is(StateEffect.appendConfig)) { + conf = null; + base = asArray$1(base).concat(effect.value); + } + } + let startValues; + if (!conf) { + conf = Configuration.resolve(base, compartments, this); + let intermediateState = new EditorState(conf, this.doc, this.selection, conf.dynamicSlots.map(() => null), (state, slot) => slot.reconfigure(state, this), null); + startValues = intermediateState.values; + } + else { + startValues = tr.startState.values.slice(); + } + new EditorState(conf, tr.newDoc, tr.newSelection, startValues, (state, slot) => slot.update(state, tr), tr); + } + /** + Create a [transaction spec](https://codemirror.net/6/docs/ref/#state.TransactionSpec) that + replaces every selection range with the given content. + */ + replaceSelection(text) { + if (typeof text == "string") + text = this.toText(text); + return this.changeByRange(range => ({ changes: { from: range.from, to: range.to, insert: text }, + range: EditorSelection.cursor(range.from + text.length) })); + } + /** + Create a set of changes and a new selection by running the given + function for each range in the active selection. The function + can return an optional set of changes (in the coordinate space + of the start document), plus an updated range (in the coordinate + space of the document produced by the call's own changes). This + method will merge all the changes and ranges into a single + changeset and selection, and return it as a [transaction + spec](https://codemirror.net/6/docs/ref/#state.TransactionSpec), which can be passed to + [`update`](https://codemirror.net/6/docs/ref/#state.EditorState.update). + */ + changeByRange(f) { + let sel = this.selection; + let result1 = f(sel.ranges[0]); + let changes = this.changes(result1.changes), ranges = [result1.range]; + let effects = asArray$1(result1.effects); + for (let i = 1; i < sel.ranges.length; i++) { + let result = f(sel.ranges[i]); + let newChanges = this.changes(result.changes), newMapped = newChanges.map(changes); + for (let j = 0; j < i; j++) + ranges[j] = ranges[j].map(newMapped); + let mapBy = changes.mapDesc(newChanges, true); + ranges.push(result.range.map(mapBy)); + changes = changes.compose(newMapped); + effects = StateEffect.mapEffects(effects, newMapped).concat(StateEffect.mapEffects(asArray$1(result.effects), mapBy)); + } + return { + changes, + selection: EditorSelection.create(ranges, sel.mainIndex), + effects + }; + } + /** + Create a [change set](https://codemirror.net/6/docs/ref/#state.ChangeSet) from the given change + description, taking the state's document length and line + separator into account. + */ + changes(spec = []) { + if (spec instanceof ChangeSet) + return spec; + return ChangeSet.of(spec, this.doc.length, this.facet(EditorState.lineSeparator)); + } + /** + Using the state's [line + separator](https://codemirror.net/6/docs/ref/#state.EditorState^lineSeparator), create a + [`Text`](https://codemirror.net/6/docs/ref/#state.Text) instance from the given string. + */ + toText(string) { + return Text.of(string.split(this.facet(EditorState.lineSeparator) || DefaultSplit)); + } + /** + Return the given range of the document as a string. + */ + sliceDoc(from = 0, to = this.doc.length) { + return this.doc.sliceString(from, to, this.lineBreak); + } + /** + Get the value of a state [facet](https://codemirror.net/6/docs/ref/#state.Facet). + */ + facet(facet) { + let addr = this.config.address[facet.id]; + if (addr == null) + return facet.default; + ensureAddr(this, addr); + return getAddr(this, addr); + } + /** + Convert this state to a JSON-serializable object. When custom + fields should be serialized, you can pass them in as an object + mapping property names (in the resulting object, which should + not use `doc` or `selection`) to fields. + */ + toJSON(fields) { + let result = { + doc: this.sliceDoc(), + selection: this.selection.toJSON() + }; + if (fields) + for (let prop in fields) { + let value = fields[prop]; + if (value instanceof StateField && this.config.address[value.id] != null) + result[prop] = value.spec.toJSON(this.field(fields[prop]), this); + } + return result; + } + /** + Deserialize a state from its JSON representation. When custom + fields should be deserialized, pass the same object you passed + to [`toJSON`](https://codemirror.net/6/docs/ref/#state.EditorState.toJSON) when serializing as + third argument. + */ + static fromJSON(json, config = {}, fields) { + if (!json || typeof json.doc != "string") + throw new RangeError("Invalid JSON representation for EditorState"); + let fieldInit = []; + if (fields) + for (let prop in fields) { + if (Object.prototype.hasOwnProperty.call(json, prop)) { + let field = fields[prop], value = json[prop]; + fieldInit.push(field.init(state => field.spec.fromJSON(value, state))); + } + } + return EditorState.create({ + doc: json.doc, + selection: EditorSelection.fromJSON(json.selection), + extensions: config.extensions ? fieldInit.concat([config.extensions]) : fieldInit + }); + } + /** + Create a new state. You'll usually only need this when + initializing an editor—updated states are created by applying + transactions. + */ + static create(config = {}) { + let configuration = Configuration.resolve(config.extensions || [], new Map); + let doc = config.doc instanceof Text ? config.doc + : Text.of((config.doc || "").split(configuration.staticFacet(EditorState.lineSeparator) || DefaultSplit)); + let selection = !config.selection ? EditorSelection.single(0) + : config.selection instanceof EditorSelection ? config.selection + : EditorSelection.single(config.selection.anchor, config.selection.head); + checkSelection(selection, doc.length); + if (!configuration.staticFacet(allowMultipleSelections)) + selection = selection.asSingle(); + return new EditorState(configuration, doc, selection, configuration.dynamicSlots.map(() => null), (state, slot) => slot.create(state), null); + } + /** + The size (in columns) of a tab in the document, determined by + the [`tabSize`](https://codemirror.net/6/docs/ref/#state.EditorState^tabSize) facet. + */ + get tabSize() { return this.facet(EditorState.tabSize); } + /** + Get the proper [line-break](https://codemirror.net/6/docs/ref/#state.EditorState^lineSeparator) + string for this state. + */ + get lineBreak() { return this.facet(EditorState.lineSeparator) || "\n"; } + /** + Returns true when the editor is + [configured](https://codemirror.net/6/docs/ref/#state.EditorState^readOnly) to be read-only. + */ + get readOnly() { return this.facet(readOnly); } + /** + Look up a translation for the given phrase (via the + [`phrases`](https://codemirror.net/6/docs/ref/#state.EditorState^phrases) facet), or return the + original string if no translation is found. + + If additional arguments are passed, they will be inserted in + place of markers like `$1` (for the first value) and `$2`, etc. + A single `$` is equivalent to `$1`, and `$$` will produce a + literal dollar sign. + */ + phrase(phrase, ...insert) { + for (let map of this.facet(EditorState.phrases)) + if (Object.prototype.hasOwnProperty.call(map, phrase)) { + phrase = map[phrase]; + break; + } + if (insert.length) + phrase = phrase.replace(/\$(\$|\d*)/g, (m, i) => { + if (i == "$") + return "$"; + let n = +(i || 1); + return !n || n > insert.length ? m : insert[n - 1]; + }); + return phrase; + } + /** + Find the values for a given language data field, provided by the + the [`languageData`](https://codemirror.net/6/docs/ref/#state.EditorState^languageData) facet. + */ + languageDataAt(name, pos, side = -1) { + let values = []; + for (let provider of this.facet(languageData)) { + for (let result of provider(this, pos, side)) { + if (Object.prototype.hasOwnProperty.call(result, name)) + values.push(result[name]); + } + } + return values; + } + /** + Return a function that can categorize strings (expected to + represent a single [grapheme cluster](https://codemirror.net/6/docs/ref/#state.findClusterBreak)) + into one of: + + - Word (contains an alphanumeric character or a character + explicitly listed in the local language's `"wordChars"` + language data, which should be a string) + - Space (contains only whitespace) + - Other (anything else) + */ + charCategorizer(at) { + return makeCategorizer(this.languageDataAt("wordChars", at).join("")); + } + /** + Find the word at the given position, meaning the range + containing all [word](https://codemirror.net/6/docs/ref/#state.CharCategory.Word) characters + around it. If no word characters are adjacent to the position, + this returns null. + */ + wordAt(pos) { + let { text, from, length } = this.doc.lineAt(pos); + let cat = this.charCategorizer(pos); + let start = pos - from, end = pos - from; + while (start > 0) { + let prev = findClusterBreak(text, start, false); + if (cat(text.slice(prev, start)) != CharCategory.Word) + break; + start = prev; + } + while (end < length) { + let next = findClusterBreak(text, end); + if (cat(text.slice(end, next)) != CharCategory.Word) + break; + end = next; + } + return start == end ? null : EditorSelection.range(start + from, end + from); + } + } + /** + A facet that, when enabled, causes the editor to allow multiple + ranges to be selected. Be careful though, because by default the + editor relies on the native DOM selection, which cannot handle + multiple selections. An extension like + [`drawSelection`](https://codemirror.net/6/docs/ref/#view.drawSelection) can be used to make + secondary selections visible to the user. + */ + EditorState.allowMultipleSelections = allowMultipleSelections; + /** + Configures the tab size to use in this state. The first + (highest-precedence) value of the facet is used. If no value is + given, this defaults to 4. + */ + EditorState.tabSize = /*@__PURE__*/Facet.define({ + combine: values => values.length ? values[0] : 4 + }); + /** + The line separator to use. By default, any of `"\n"`, `"\r\n"` + and `"\r"` is treated as a separator when splitting lines, and + lines are joined with `"\n"`. + + When you configure a value here, only that precise separator + will be used, allowing you to round-trip documents through the + editor without normalizing line separators. + */ + EditorState.lineSeparator = lineSeparator; + /** + This facet controls the value of the + [`readOnly`](https://codemirror.net/6/docs/ref/#state.EditorState.readOnly) getter, which is + consulted by commands and extensions that implement editing + functionality to determine whether they should apply. It + defaults to false, but when its highest-precedence value is + `true`, such functionality disables itself. + + Not to be confused with + [`EditorView.editable`](https://codemirror.net/6/docs/ref/#view.EditorView^editable), which + controls whether the editor's DOM is set to be editable (and + thus focusable). + */ + EditorState.readOnly = readOnly; + /** + Registers translation phrases. The + [`phrase`](https://codemirror.net/6/docs/ref/#state.EditorState.phrase) method will look through + all objects registered with this facet to find translations for + its argument. + */ + EditorState.phrases = /*@__PURE__*/Facet.define({ + compare(a, b) { + let kA = Object.keys(a), kB = Object.keys(b); + return kA.length == kB.length && kA.every(k => a[k] == b[k]); + } + }); + /** + A facet used to register [language + data](https://codemirror.net/6/docs/ref/#state.EditorState.languageDataAt) providers. + */ + EditorState.languageData = languageData; + /** + Facet used to register change filters, which are called for each + transaction (unless explicitly + [disabled](https://codemirror.net/6/docs/ref/#state.TransactionSpec.filter)), and can suppress + part of the transaction's changes. + + Such a function can return `true` to indicate that it doesn't + want to do anything, `false` to completely stop the changes in + the transaction, or a set of ranges in which changes should be + suppressed. Such ranges are represented as an array of numbers, + with each pair of two numbers indicating the start and end of a + range. So for example `[10, 20, 100, 110]` suppresses changes + between 10 and 20, and between 100 and 110. + */ + EditorState.changeFilter = changeFilter; + /** + Facet used to register a hook that gets a chance to update or + replace transaction specs before they are applied. This will + only be applied for transactions that don't have + [`filter`](https://codemirror.net/6/docs/ref/#state.TransactionSpec.filter) set to `false`. You + can either return a single transaction spec (possibly the input + transaction), or an array of specs (which will be combined in + the same way as the arguments to + [`EditorState.update`](https://codemirror.net/6/docs/ref/#state.EditorState.update)). + + When possible, it is recommended to avoid accessing + [`Transaction.state`](https://codemirror.net/6/docs/ref/#state.Transaction.state) in a filter, + since it will force creation of a state that will then be + discarded again, if the transaction is actually filtered. + + (This functionality should be used with care. Indiscriminately + modifying transaction is likely to break something or degrade + the user experience.) + */ + EditorState.transactionFilter = transactionFilter; + /** + This is a more limited form of + [`transactionFilter`](https://codemirror.net/6/docs/ref/#state.EditorState^transactionFilter), + which can only add + [annotations](https://codemirror.net/6/docs/ref/#state.TransactionSpec.annotations) and + [effects](https://codemirror.net/6/docs/ref/#state.TransactionSpec.effects). _But_, this type + of filter runs even if the transaction has disabled regular + [filtering](https://codemirror.net/6/docs/ref/#state.TransactionSpec.filter), making it suitable + for effects that don't need to touch the changes or selection, + but do want to process every transaction. + + Extenders run _after_ filters, when both are present. + */ + EditorState.transactionExtender = transactionExtender; + Compartment.reconfigure = /*@__PURE__*/StateEffect.define(); + + /** + Utility function for combining behaviors to fill in a config + object from an array of provided configs. `defaults` should hold + default values for all optional fields in `Config`. + + The function will, by default, error + when a field gets two values that aren't `===`-equal, but you can + provide combine functions per field to do something else. + */ + function combineConfig(configs, defaults, // Should hold only the optional properties of Config, but I haven't managed to express that + combine = {}) { + let result = {}; + for (let config of configs) + for (let key of Object.keys(config)) { + let value = config[key], current = result[key]; + if (current === undefined) + result[key] = value; + else if (current === value || value === undefined) ; // No conflict + else if (Object.hasOwnProperty.call(combine, key)) + result[key] = combine[key](current, value); + else + throw new Error("Config merge conflict for field " + key); + } + for (let key in defaults) + if (result[key] === undefined) + result[key] = defaults[key]; + return result; + } + + /** + Each range is associated with a value, which must inherit from + this class. + */ + class RangeValue { + /** + Compare this value with another value. Used when comparing + rangesets. The default implementation compares by identity. + Unless you are only creating a fixed number of unique instances + of your value type, it is a good idea to implement this + properly. + */ + eq(other) { return this == other; } + /** + Create a [range](https://codemirror.net/6/docs/ref/#state.Range) with this value. + */ + range(from, to = from) { return Range$1.create(from, to, this); } + } + RangeValue.prototype.startSide = RangeValue.prototype.endSide = 0; + RangeValue.prototype.point = false; + RangeValue.prototype.mapMode = MapMode.TrackDel; + /** + A range associates a value with a range of positions. + */ + class Range$1 { + constructor( + /** + The range's start position. + */ + from, + /** + Its end position. + */ + to, + /** + The value associated with this range. + */ + value) { + this.from = from; + this.to = to; + this.value = value; + } + /** + @internal + */ + static create(from, to, value) { + return new Range$1(from, to, value); + } + } + function cmpRange(a, b) { + return a.from - b.from || a.value.startSide - b.value.startSide; + } + class Chunk { + constructor(from, to, value, + // Chunks are marked with the largest point that occurs + // in them (or -1 for no points), so that scans that are + // only interested in points (such as the + // heightmap-related logic) can skip range-only chunks. + maxPoint) { + this.from = from; + this.to = to; + this.value = value; + this.maxPoint = maxPoint; + } + get length() { return this.to[this.to.length - 1]; } + // Find the index of the given position and side. Use the ranges' + // `from` pos when `end == false`, `to` when `end == true`. + findIndex(pos, side, end, startAt = 0) { + let arr = end ? this.to : this.from; + for (let lo = startAt, hi = arr.length;;) { + if (lo == hi) + return lo; + let mid = (lo + hi) >> 1; + let diff = arr[mid] - pos || (end ? this.value[mid].endSide : this.value[mid].startSide) - side; + if (mid == lo) + return diff >= 0 ? lo : hi; + if (diff >= 0) + hi = mid; + else + lo = mid + 1; + } + } + between(offset, from, to, f) { + for (let i = this.findIndex(from, -1000000000 /* C.Far */, true), e = this.findIndex(to, 1000000000 /* C.Far */, false, i); i < e; i++) + if (f(this.from[i] + offset, this.to[i] + offset, this.value[i]) === false) + return false; + } + map(offset, changes) { + let value = [], from = [], to = [], newPos = -1, maxPoint = -1; + for (let i = 0; i < this.value.length; i++) { + let val = this.value[i], curFrom = this.from[i] + offset, curTo = this.to[i] + offset, newFrom, newTo; + if (curFrom == curTo) { + let mapped = changes.mapPos(curFrom, val.startSide, val.mapMode); + if (mapped == null) + continue; + newFrom = newTo = mapped; + if (val.startSide != val.endSide) { + newTo = changes.mapPos(curFrom, val.endSide); + if (newTo < newFrom) + continue; + } + } + else { + newFrom = changes.mapPos(curFrom, val.startSide); + newTo = changes.mapPos(curTo, val.endSide); + if (newFrom > newTo || newFrom == newTo && val.startSide > 0 && val.endSide <= 0) + continue; + } + if ((newTo - newFrom || val.endSide - val.startSide) < 0) + continue; + if (newPos < 0) + newPos = newFrom; + if (val.point) + maxPoint = Math.max(maxPoint, newTo - newFrom); + value.push(val); + from.push(newFrom - newPos); + to.push(newTo - newPos); + } + return { mapped: value.length ? new Chunk(from, to, value, maxPoint) : null, pos: newPos }; + } + } + /** + A range set stores a collection of [ranges](https://codemirror.net/6/docs/ref/#state.Range) in a + way that makes them efficient to [map](https://codemirror.net/6/docs/ref/#state.RangeSet.map) and + [update](https://codemirror.net/6/docs/ref/#state.RangeSet.update). This is an immutable data + structure. + */ + class RangeSet { + constructor( + /** + @internal + */ + chunkPos, + /** + @internal + */ + chunk, + /** + @internal + */ + nextLayer, + /** + @internal + */ + maxPoint) { + this.chunkPos = chunkPos; + this.chunk = chunk; + this.nextLayer = nextLayer; + this.maxPoint = maxPoint; + } + /** + @internal + */ + static create(chunkPos, chunk, nextLayer, maxPoint) { + return new RangeSet(chunkPos, chunk, nextLayer, maxPoint); + } + /** + @internal + */ + get length() { + let last = this.chunk.length - 1; + return last < 0 ? 0 : Math.max(this.chunkEnd(last), this.nextLayer.length); + } + /** + The number of ranges in the set. + */ + get size() { + if (this.isEmpty) + return 0; + let size = this.nextLayer.size; + for (let chunk of this.chunk) + size += chunk.value.length; + return size; + } + /** + @internal + */ + chunkEnd(index) { + return this.chunkPos[index] + this.chunk[index].length; + } + /** + Update the range set, optionally adding new ranges or filtering + out existing ones. + + (Note: The type parameter is just there as a kludge to work + around TypeScript variance issues that prevented `RangeSet<X>` + from being a subtype of `RangeSet<Y>` when `X` is a subtype of + `Y`.) + */ + update(updateSpec) { + let { add = [], sort = false, filterFrom = 0, filterTo = this.length } = updateSpec; + let filter = updateSpec.filter; + if (add.length == 0 && !filter) + return this; + if (sort) + add = add.slice().sort(cmpRange); + if (this.isEmpty) + return add.length ? RangeSet.of(add) : this; + let cur = new LayerCursor(this, null, -1).goto(0), i = 0, spill = []; + let builder = new RangeSetBuilder(); + while (cur.value || i < add.length) { + if (i < add.length && (cur.from - add[i].from || cur.startSide - add[i].value.startSide) >= 0) { + let range = add[i++]; + if (!builder.addInner(range.from, range.to, range.value)) + spill.push(range); + } + else if (cur.rangeIndex == 1 && cur.chunkIndex < this.chunk.length && + (i == add.length || this.chunkEnd(cur.chunkIndex) < add[i].from) && + (!filter || filterFrom > this.chunkEnd(cur.chunkIndex) || filterTo < this.chunkPos[cur.chunkIndex]) && + builder.addChunk(this.chunkPos[cur.chunkIndex], this.chunk[cur.chunkIndex])) { + cur.nextChunk(); + } + else { + if (!filter || filterFrom > cur.to || filterTo < cur.from || filter(cur.from, cur.to, cur.value)) { + if (!builder.addInner(cur.from, cur.to, cur.value)) + spill.push(Range$1.create(cur.from, cur.to, cur.value)); + } + cur.next(); + } + } + return builder.finishInner(this.nextLayer.isEmpty && !spill.length ? RangeSet.empty + : this.nextLayer.update({ add: spill, filter, filterFrom, filterTo })); + } + /** + Map this range set through a set of changes, return the new set. + */ + map(changes) { + if (changes.empty || this.isEmpty) + return this; + let chunks = [], chunkPos = [], maxPoint = -1; + for (let i = 0; i < this.chunk.length; i++) { + let start = this.chunkPos[i], chunk = this.chunk[i]; + let touch = changes.touchesRange(start, start + chunk.length); + if (touch === false) { + maxPoint = Math.max(maxPoint, chunk.maxPoint); + chunks.push(chunk); + chunkPos.push(changes.mapPos(start)); + } + else if (touch === true) { + let { mapped, pos } = chunk.map(start, changes); + if (mapped) { + maxPoint = Math.max(maxPoint, mapped.maxPoint); + chunks.push(mapped); + chunkPos.push(pos); + } + } + } + let next = this.nextLayer.map(changes); + return chunks.length == 0 ? next : new RangeSet(chunkPos, chunks, next || RangeSet.empty, maxPoint); + } + /** + Iterate over the ranges that touch the region `from` to `to`, + calling `f` for each. There is no guarantee that the ranges will + be reported in any specific order. When the callback returns + `false`, iteration stops. + */ + between(from, to, f) { + if (this.isEmpty) + return; + for (let i = 0; i < this.chunk.length; i++) { + let start = this.chunkPos[i], chunk = this.chunk[i]; + if (to >= start && from <= start + chunk.length && + chunk.between(start, from - start, to - start, f) === false) + return; + } + this.nextLayer.between(from, to, f); + } + /** + Iterate over the ranges in this set, in order, including all + ranges that end at or after `from`. + */ + iter(from = 0) { + return HeapCursor.from([this]).goto(from); + } + /** + @internal + */ + get isEmpty() { return this.nextLayer == this; } + /** + Iterate over the ranges in a collection of sets, in order, + starting from `from`. + */ + static iter(sets, from = 0) { + return HeapCursor.from(sets).goto(from); + } + /** + Iterate over two groups of sets, calling methods on `comparator` + to notify it of possible differences. + */ + static compare(oldSets, newSets, + /** + This indicates how the underlying data changed between these + ranges, and is needed to synchronize the iteration. `from` and + `to` are coordinates in the _new_ space, after these changes. + */ + textDiff, comparator, + /** + Can be used to ignore all non-point ranges, and points below + the given size. When -1, all ranges are compared. + */ + minPointSize = -1) { + let a = oldSets.filter(set => set.maxPoint > 0 || !set.isEmpty && set.maxPoint >= minPointSize); + let b = newSets.filter(set => set.maxPoint > 0 || !set.isEmpty && set.maxPoint >= minPointSize); + let sharedChunks = findSharedChunks(a, b, textDiff); + let sideA = new SpanCursor(a, sharedChunks, minPointSize); + let sideB = new SpanCursor(b, sharedChunks, minPointSize); + textDiff.iterGaps((fromA, fromB, length) => compare(sideA, fromA, sideB, fromB, length, comparator)); + if (textDiff.empty && textDiff.length == 0) + compare(sideA, 0, sideB, 0, 0, comparator); + } + /** + Compare the contents of two groups of range sets, returning true + if they are equivalent in the given range. + */ + static eq(oldSets, newSets, from = 0, to) { + if (to == null) + to = 1000000000 /* C.Far */; + let a = oldSets.filter(set => !set.isEmpty && newSets.indexOf(set) < 0); + let b = newSets.filter(set => !set.isEmpty && oldSets.indexOf(set) < 0); + if (a.length != b.length) + return false; + if (!a.length) + return true; + let sharedChunks = findSharedChunks(a, b); + let sideA = new SpanCursor(a, sharedChunks, 0).goto(from), sideB = new SpanCursor(b, sharedChunks, 0).goto(from); + for (;;) { + if (sideA.to != sideB.to || + !sameValues(sideA.active, sideB.active) || + sideA.point && (!sideB.point || !sideA.point.eq(sideB.point))) + return false; + if (sideA.to > to) + return true; + sideA.next(); + sideB.next(); + } + } + /** + Iterate over a group of range sets at the same time, notifying + the iterator about the ranges covering every given piece of + content. Returns the open count (see + [`SpanIterator.span`](https://codemirror.net/6/docs/ref/#state.SpanIterator.span)) at the end + of the iteration. + */ + static spans(sets, from, to, iterator, + /** + When given and greater than -1, only points of at least this + size are taken into account. + */ + minPointSize = -1) { + let cursor = new SpanCursor(sets, null, minPointSize).goto(from), pos = from; + let open = cursor.openStart; + for (;;) { + let curTo = Math.min(cursor.to, to); + if (cursor.point) { + iterator.point(pos, curTo, cursor.point, cursor.activeForPoint(cursor.to), open, cursor.pointRank); + open = cursor.openEnd(curTo) + (cursor.to > curTo ? 1 : 0); + } + else if (curTo > pos) { + iterator.span(pos, curTo, cursor.active, open); + open = cursor.openEnd(curTo); + } + if (cursor.to > to) + break; + pos = cursor.to; + cursor.next(); + } + return open; + } + /** + Create a range set for the given range or array of ranges. By + default, this expects the ranges to be _sorted_ (by start + position and, if two start at the same position, + `value.startSide`). You can pass `true` as second argument to + cause the method to sort them. + */ + static of(ranges, sort = false) { + let build = new RangeSetBuilder(); + for (let range of ranges instanceof Range$1 ? [ranges] : sort ? lazySort(ranges) : ranges) + build.add(range.from, range.to, range.value); + return build.finish(); + } + } + /** + The empty set of ranges. + */ + RangeSet.empty = /*@__PURE__*/new RangeSet([], [], null, -1); + function lazySort(ranges) { + if (ranges.length > 1) + for (let prev = ranges[0], i = 1; i < ranges.length; i++) { + let cur = ranges[i]; + if (cmpRange(prev, cur) > 0) + return ranges.slice().sort(cmpRange); + prev = cur; + } + return ranges; + } + RangeSet.empty.nextLayer = RangeSet.empty; + /** + A range set builder is a data structure that helps build up a + [range set](https://codemirror.net/6/docs/ref/#state.RangeSet) directly, without first allocating + an array of [`Range`](https://codemirror.net/6/docs/ref/#state.Range) objects. + */ + class RangeSetBuilder { + /** + Create an empty builder. + */ + constructor() { + this.chunks = []; + this.chunkPos = []; + this.chunkStart = -1; + this.last = null; + this.lastFrom = -1000000000 /* C.Far */; + this.lastTo = -1000000000 /* C.Far */; + this.from = []; + this.to = []; + this.value = []; + this.maxPoint = -1; + this.setMaxPoint = -1; + this.nextLayer = null; + } + finishChunk(newArrays) { + this.chunks.push(new Chunk(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; + if (newArrays) { + this.from = []; + this.to = []; + this.value = []; + } + } + /** + Add a range. Ranges should be added in sorted (by `from` and + `value.startSide`) order. + */ + add(from, to, value) { + if (!this.addInner(from, to, value)) + (this.nextLayer || (this.nextLayer = new RangeSetBuilder)).add(from, to, value); + } + /** + @internal + */ + addInner(from, to, value) { + let diff = from - this.lastTo || value.startSide - this.last.endSide; + if (diff <= 0 && (from - this.lastFrom || value.startSide - this.last.startSide) < 0) + throw new Error("Ranges must be added sorted by `from` position and `startSide`"); + if (diff < 0) + return false; + if (this.from.length == 250 /* C.ChunkSize */) + this.finishChunk(true); + if (this.chunkStart < 0) + this.chunkStart = from; + this.from.push(from - this.chunkStart); + this.to.push(to - this.chunkStart); + this.last = value; + this.lastFrom = from; + this.lastTo = to; + this.value.push(value); + if (value.point) + this.maxPoint = Math.max(this.maxPoint, to - from); + return true; + } + /** + @internal + */ + addChunk(from, chunk) { + if ((from - this.lastTo || chunk.value[0].startSide - this.last.endSide) < 0) + return false; + if (this.from.length) + this.finishChunk(true); + this.setMaxPoint = Math.max(this.setMaxPoint, chunk.maxPoint); + this.chunks.push(chunk); + this.chunkPos.push(from); + let last = chunk.value.length - 1; + this.last = chunk.value[last]; + this.lastFrom = chunk.from[last] + from; + this.lastTo = chunk.to[last] + from; + return true; + } + /** + Finish the range set. Returns the new set. The builder can't be + used anymore after this has been called. + */ + finish() { return this.finishInner(RangeSet.empty); } + /** + @internal + */ + finishInner(next) { + if (this.from.length) + this.finishChunk(false); + if (this.chunks.length == 0) + return next; + let result = RangeSet.create(this.chunkPos, this.chunks, this.nextLayer ? this.nextLayer.finishInner(next) : next, this.setMaxPoint); + this.from = null; // Make sure further `add` calls produce errors + return result; + } + } + function findSharedChunks(a, b, textDiff) { + let inA = new Map(); + for (let set of a) + for (let i = 0; i < set.chunk.length; i++) + if (set.chunk[i].maxPoint <= 0) + inA.set(set.chunk[i], set.chunkPos[i]); + let shared = new Set(); + for (let set of b) + for (let i = 0; i < set.chunk.length; i++) { + let known = inA.get(set.chunk[i]); + if (known != null && (textDiff ? textDiff.mapPos(known) : known) == set.chunkPos[i] && + !(textDiff === null || textDiff === void 0 ? void 0 : textDiff.touchesRange(known, known + set.chunk[i].length))) + shared.add(set.chunk[i]); + } + return shared; + } + class LayerCursor { + constructor(layer, skip, minPoint, rank = 0) { + this.layer = layer; + this.skip = skip; + this.minPoint = minPoint; + this.rank = rank; + } + get startSide() { return this.value ? this.value.startSide : 0; } + get endSide() { return this.value ? this.value.endSide : 0; } + goto(pos, side = -1000000000 /* C.Far */) { + this.chunkIndex = this.rangeIndex = 0; + this.gotoInner(pos, side, false); + return this; + } + gotoInner(pos, side, forward) { + while (this.chunkIndex < this.layer.chunk.length) { + let next = this.layer.chunk[this.chunkIndex]; + if (!(this.skip && this.skip.has(next) || + this.layer.chunkEnd(this.chunkIndex) < pos || + next.maxPoint < this.minPoint)) + break; + this.chunkIndex++; + forward = false; + } + if (this.chunkIndex < this.layer.chunk.length) { + let rangeIndex = this.layer.chunk[this.chunkIndex].findIndex(pos - this.layer.chunkPos[this.chunkIndex], side, true); + if (!forward || this.rangeIndex < rangeIndex) + this.setRangeIndex(rangeIndex); + } + this.next(); + } + forward(pos, side) { + if ((this.to - pos || this.endSide - side) < 0) + this.gotoInner(pos, side, true); + } + next() { + for (;;) { + if (this.chunkIndex == this.layer.chunk.length) { + this.from = this.to = 1000000000 /* C.Far */; + this.value = null; + break; + } + else { + let chunkPos = this.layer.chunkPos[this.chunkIndex], chunk = this.layer.chunk[this.chunkIndex]; + let from = chunkPos + chunk.from[this.rangeIndex]; + this.from = from; + this.to = chunkPos + chunk.to[this.rangeIndex]; + this.value = chunk.value[this.rangeIndex]; + this.setRangeIndex(this.rangeIndex + 1); + if (this.minPoint < 0 || this.value.point && this.to - this.from >= this.minPoint) + break; + } + } + } + setRangeIndex(index) { + if (index == this.layer.chunk[this.chunkIndex].value.length) { + this.chunkIndex++; + if (this.skip) { + while (this.chunkIndex < this.layer.chunk.length && this.skip.has(this.layer.chunk[this.chunkIndex])) + this.chunkIndex++; + } + this.rangeIndex = 0; + } + else { + this.rangeIndex = index; + } + } + nextChunk() { + this.chunkIndex++; + this.rangeIndex = 0; + this.next(); + } + compare(other) { + return this.from - other.from || this.startSide - other.startSide || this.rank - other.rank || + this.to - other.to || this.endSide - other.endSide; + } + } + class HeapCursor { + constructor(heap) { + this.heap = heap; + } + static from(sets, skip = null, minPoint = -1) { + let heap = []; + for (let i = 0; i < sets.length; i++) { + for (let cur = sets[i]; !cur.isEmpty; cur = cur.nextLayer) { + if (cur.maxPoint >= minPoint) + heap.push(new LayerCursor(cur, skip, minPoint, i)); + } + } + return heap.length == 1 ? heap[0] : new HeapCursor(heap); + } + get startSide() { return this.value ? this.value.startSide : 0; } + goto(pos, side = -1000000000 /* C.Far */) { + for (let cur of this.heap) + cur.goto(pos, side); + for (let i = this.heap.length >> 1; i >= 0; i--) + heapBubble(this.heap, i); + this.next(); + return this; + } + forward(pos, side) { + for (let cur of this.heap) + cur.forward(pos, side); + for (let i = this.heap.length >> 1; i >= 0; i--) + heapBubble(this.heap, i); + if ((this.to - pos || this.value.endSide - side) < 0) + this.next(); + } + next() { + if (this.heap.length == 0) { + this.from = this.to = 1000000000 /* C.Far */; + this.value = null; + this.rank = -1; + } + else { + let top = this.heap[0]; + this.from = top.from; + this.to = top.to; + this.value = top.value; + this.rank = top.rank; + if (top.value) + top.next(); + heapBubble(this.heap, 0); + } + } + } + function heapBubble(heap, index) { + for (let cur = heap[index];;) { + let childIndex = (index << 1) + 1; + if (childIndex >= heap.length) + break; + let child = heap[childIndex]; + if (childIndex + 1 < heap.length && child.compare(heap[childIndex + 1]) >= 0) { + child = heap[childIndex + 1]; + childIndex++; + } + if (cur.compare(child) < 0) + break; + heap[childIndex] = cur; + heap[index] = child; + index = childIndex; + } + } + class SpanCursor { + constructor(sets, skip, minPoint) { + this.minPoint = minPoint; + this.active = []; + this.activeTo = []; + this.activeRank = []; + this.minActive = -1; + // A currently active point range, if any + this.point = null; + this.pointFrom = 0; + this.pointRank = 0; + this.to = -1000000000 /* C.Far */; + this.endSide = 0; + this.openStart = -1; + this.cursor = HeapCursor.from(sets, skip, minPoint); + } + goto(pos, side = -1000000000 /* C.Far */) { + this.cursor.goto(pos, side); + this.active.length = this.activeTo.length = this.activeRank.length = 0; + this.minActive = -1; + this.to = pos; + this.endSide = side; + this.openStart = -1; + this.next(); + return this; + } + forward(pos, side) { + while (this.minActive > -1 && (this.activeTo[this.minActive] - pos || this.active[this.minActive].endSide - side) < 0) + this.removeActive(this.minActive); + this.cursor.forward(pos, side); + } + removeActive(index) { + remove(this.active, index); + remove(this.activeTo, index); + remove(this.activeRank, index); + this.minActive = findMinIndex(this.active, this.activeTo); + } + addActive(trackOpen) { + let i = 0, { value, to, rank } = this.cursor; + while (i < this.activeRank.length && this.activeRank[i] <= rank) + i++; + insert(this.active, i, value); + insert(this.activeTo, i, to); + insert(this.activeRank, i, rank); + if (trackOpen) + insert(trackOpen, i, this.cursor.from); + this.minActive = findMinIndex(this.active, this.activeTo); + } + // After calling this, if `this.point` != null, the next range is a + // point. Otherwise, it's a regular range, covered by `this.active`. + next() { + let from = this.to, wasPoint = this.point; + this.point = null; + let trackOpen = this.openStart < 0 ? [] : null, trackExtra = 0; + for (;;) { + let a = this.minActive; + if (a > -1 && (this.activeTo[a] - this.cursor.from || this.active[a].endSide - this.cursor.startSide) < 0) { + if (this.activeTo[a] > from) { + this.to = this.activeTo[a]; + this.endSide = this.active[a].endSide; + break; + } + this.removeActive(a); + if (trackOpen) + remove(trackOpen, a); + } + else if (!this.cursor.value) { + this.to = this.endSide = 1000000000 /* C.Far */; + break; + } + else if (this.cursor.from > from) { + this.to = this.cursor.from; + this.endSide = this.cursor.startSide; + break; + } + else { + let nextVal = this.cursor.value; + if (!nextVal.point) { // Opening a range + this.addActive(trackOpen); + if (this.cursor.from < from && this.cursor.to > from) + trackExtra++; + this.cursor.next(); + } + else if (wasPoint && this.cursor.to == this.to && this.cursor.from < this.cursor.to) { + // Ignore any non-empty points that end precisely at the end of the prev point + this.cursor.next(); + } + else { // New point + this.point = nextVal; + this.pointFrom = this.cursor.from; + this.pointRank = this.cursor.rank; + this.to = this.cursor.to; + this.endSide = nextVal.endSide; + if (this.cursor.from < from) + trackExtra = 1; + this.cursor.next(); + this.forward(this.to, this.endSide); + break; + } + } + } + if (trackOpen) { + let openStart = 0; + while (openStart < trackOpen.length && trackOpen[openStart] < from) + openStart++; + this.openStart = openStart + trackExtra; + } + } + activeForPoint(to) { + if (!this.active.length) + return this.active; + let active = []; + for (let i = this.active.length - 1; i >= 0; i--) { + if (this.activeRank[i] < this.pointRank) + break; + if (this.activeTo[i] > to || this.activeTo[i] == to && this.active[i].endSide >= this.point.endSide) + active.push(this.active[i]); + } + return active.reverse(); + } + openEnd(to) { + let open = 0; + for (let i = this.activeTo.length - 1; i >= 0 && this.activeTo[i] > to; i--) + open++; + return open; + } + } + function compare(a, startA, b, startB, length, comparator) { + a.goto(startA); + b.goto(startB); + let endB = startB + length; + let pos = startB, dPos = startB - startA; + for (;;) { + let diff = (a.to + dPos) - b.to || a.endSide - b.endSide; + let end = diff < 0 ? a.to + dPos : b.to, clipEnd = Math.min(end, endB); + if (a.point || b.point) { + if (!(a.point && b.point && (a.point == b.point || a.point.eq(b.point)) && + sameValues(a.activeForPoint(a.to + dPos), b.activeForPoint(b.to)))) + comparator.comparePoint(pos, clipEnd, a.point, b.point); + } + else { + if (clipEnd > pos && !sameValues(a.active, b.active)) + comparator.compareRange(pos, clipEnd, a.active, b.active); + } + if (end > endB) + break; + pos = end; + if (diff <= 0) + a.next(); + if (diff >= 0) + b.next(); + } + } + function sameValues(a, b) { + if (a.length != b.length) + return false; + for (let i = 0; i < a.length; i++) + if (a[i] != b[i] && !a[i].eq(b[i])) + return false; + return true; + } + function remove(array, index) { + for (let i = index, e = array.length - 1; i < e; i++) + array[i] = array[i + 1]; + array.pop(); + } + function insert(array, index, value) { + for (let i = array.length - 1; i >= index; i--) + array[i + 1] = array[i]; + array[index] = value; + } + function findMinIndex(value, array) { + let found = -1, foundPos = 1000000000 /* C.Far */; + for (let i = 0; i < array.length; i++) + if ((array[i] - foundPos || value[i].endSide - value[found].endSide) < 0) { + found = i; + foundPos = array[i]; + } + return found; + } + + /** + Count the column position at the given offset into the string, + taking extending characters and tab size into account. + */ + function countColumn(string, tabSize, to = string.length) { + let n = 0; + for (let i = 0; i < to;) { + if (string.charCodeAt(i) == 9) { + n += tabSize - (n % tabSize); + i++; + } + else { + n++; + i = findClusterBreak(string, i); + } + } + return n; + } + /** + Find the offset that corresponds to the given column position in a + string, taking extending characters and tab size into account. By + default, the string length is returned when it is too short to + reach the column. Pass `strict` true to make it return -1 in that + situation. + */ + function findColumn(string, col, tabSize, strict) { + for (let i = 0, n = 0;;) { + if (n >= col) + return i; + if (i == string.length) + break; + n += string.charCodeAt(i) == 9 ? tabSize - (n % tabSize) : 1; + i = findClusterBreak(string, i); + } + return strict === true ? -1 : string.length; + } + + const C = "\u037c"; + const COUNT = typeof Symbol == "undefined" ? "__" + C : Symbol.for(C); + const SET = typeof Symbol == "undefined" ? "__styleSet" + Math.floor(Math.random() * 1e8) : Symbol("styleSet"); + const top = typeof globalThis != "undefined" ? globalThis : typeof window != "undefined" ? window : {}; + + // :: - Style modules encapsulate a set of CSS rules defined from + // JavaScript. Their definitions are only available in a given DOM + // root after it has been _mounted_ there with `StyleModule.mount`. + // + // Style modules should be created once and stored somewhere, as + // opposed to re-creating them every time you need them. The amount of + // CSS rules generated for a given DOM root is bounded by the amount + // of style modules that were used. So to avoid leaking rules, don't + // create these dynamically, but treat them as one-time allocations. + class StyleModule { + // :: (Object<Style>, ?{finish: ?(string) → string}) + // Create a style module from the given spec. + // + // When `finish` is given, it is called on regular (non-`@`) + // selectors (after `&` expansion) to compute the final selector. + constructor(spec, options) { + this.rules = []; + let {finish} = options || {}; + + function splitSelector(selector) { + return /^@/.test(selector) ? [selector] : selector.split(/,\s*/) + } + + function render(selectors, spec, target, isKeyframes) { + let local = [], isAt = /^@(\w+)\b/.exec(selectors[0]), keyframes = isAt && isAt[1] == "keyframes"; + if (isAt && spec == null) return target.push(selectors[0] + ";") + for (let prop in spec) { + let value = spec[prop]; + if (/&/.test(prop)) { + render(prop.split(/,\s*/).map(part => selectors.map(sel => part.replace(/&/, sel))).reduce((a, b) => a.concat(b)), + value, target); + } else if (value && typeof value == "object") { + if (!isAt) throw new RangeError("The value of a property (" + prop + ") should be a primitive value.") + render(splitSelector(prop), value, local, keyframes); + } else if (value != null) { + local.push(prop.replace(/_.*/, "").replace(/[A-Z]/g, l => "-" + l.toLowerCase()) + ": " + value + ";"); } } - - if (!type) { - throwError(state, 'unknown tag !<' + state.tag + '>'); - } - - if (state.result !== null && type.kind !== state.kind) { - throwError(state, 'unacceptable node kind for !<' + state.tag + '> tag; it should be "' + type.kind + '", not "' + state.kind + '"'); - } - - if (!type.resolve(state.result, state.tag)) { // `state.result` updated in resolver if matched - throwError(state, 'cannot resolve a node with !<' + state.tag + '> explicit tag'); - } else { - state.result = type.construct(state.result, state.tag); - if (state.anchor !== null) { - state.anchorMap[state.anchor] = state.result; - } + if (local.length || keyframes) { + target.push((finish && !isAt && !isKeyframes ? selectors.map(finish) : selectors).join(", ") + + " {" + local.join(" ") + "}"); } } - if (state.listener !== null) { - state.listener('close', state); - } - return state.tag !== null || state.anchor !== null || hasContent; + for (let prop in spec) render(splitSelector(prop), spec[prop], this.rules); } - function readDocument(state) { - var documentStart = state.position, - _position, - directiveName, - directiveArgs, - hasDirectives = false, - ch; + // :: () → string + // Returns a string containing the module's CSS rules. + getRules() { return this.rules.join("\n") } - state.version = null; - state.checkLineBreaks = state.legacy; - state.tagMap = Object.create(null); - state.anchorMap = Object.create(null); + // :: () → string + // Generate a new unique CSS class name. + static newName() { + let id = top[COUNT] || 1; + top[COUNT] = id + 1; + return C + id.toString(36) + } - while ((ch = state.input.charCodeAt(state.position)) !== 0) { - skipSeparationSpace(state, true, -1); + // :: (union<Document, ShadowRoot>, union<[StyleModule], StyleModule>) + // + // Mount the given set of modules in the given DOM root, which ensures + // that the CSS rules defined by the module are available in that + // context. + // + // Rules are only added to the document once per root. + // + // Rule order will follow the order of the modules, so that rules from + // modules later in the array take precedence of those from earlier + // modules. If you call this function multiple times for the same root + // in a way that changes the order of already mounted modules, the old + // order will be changed. + static mount(root, modules) { + (root[SET] || new StyleSet(root)).mount(Array.isArray(modules) ? modules : [modules]); + } + } - ch = state.input.charCodeAt(state.position); + let adoptedSet = null; - if (state.lineIndent > 0 || ch !== 0x25/* % */) { - break; + class StyleSet { + constructor(root) { + if (!root.head && root.adoptedStyleSheets && typeof CSSStyleSheet != "undefined") { + if (adoptedSet) { + root.adoptedStyleSheets = [adoptedSet.sheet].concat(root.adoptedStyleSheets); + return root[SET] = adoptedSet } - - hasDirectives = true; - ch = state.input.charCodeAt(++state.position); - _position = state.position; - - while (ch !== 0 && !is_WS_OR_EOL(ch)) { - ch = state.input.charCodeAt(++state.position); - } - - directiveName = state.input.slice(_position, state.position); - directiveArgs = []; - - if (directiveName.length < 1) { - throwError(state, 'directive name must not be less than one character in length'); - } - - while (ch !== 0) { - while (is_WHITE_SPACE(ch)) { - ch = state.input.charCodeAt(++state.position); - } - - if (ch === 0x23/* # */) { - do { ch = state.input.charCodeAt(++state.position); } - while (ch !== 0 && !is_EOL(ch)); - break; - } - - if (is_EOL(ch)) break; - - _position = state.position; - - while (ch !== 0 && !is_WS_OR_EOL(ch)) { - ch = state.input.charCodeAt(++state.position); - } - - directiveArgs.push(state.input.slice(_position, state.position)); - } - - if (ch !== 0) readLineBreak(state); - - if (_hasOwnProperty$1.call(directiveHandlers, directiveName)) { - directiveHandlers[directiveName](state, directiveName, directiveArgs); - } else { - throwWarning(state, 'unknown document directive "' + directiveName + '"'); - } - } - - skipSeparationSpace(state, true, -1); - - if (state.lineIndent === 0 && - state.input.charCodeAt(state.position) === 0x2D/* - */ && - state.input.charCodeAt(state.position + 1) === 0x2D/* - */ && - state.input.charCodeAt(state.position + 2) === 0x2D/* - */) { - state.position += 3; - skipSeparationSpace(state, true, -1); - - } else if (hasDirectives) { - throwError(state, 'directives end mark is expected'); - } - - composeNode(state, state.lineIndent - 1, CONTEXT_BLOCK_OUT, false, true); - skipSeparationSpace(state, true, -1); - - if (state.checkLineBreaks && - PATTERN_NON_ASCII_LINE_BREAKS.test(state.input.slice(documentStart, state.position))) { - throwWarning(state, 'non-ASCII line breaks are interpreted as content'); - } - - state.documents.push(state.result); - - if (state.position === state.lineStart && testDocumentSeparator(state)) { - - if (state.input.charCodeAt(state.position) === 0x2E/* . */) { - state.position += 3; - skipSeparationSpace(state, true, -1); - } - return; - } - - if (state.position < (state.length - 1)) { - throwError(state, 'end of the stream or a document separator is expected'); + this.sheet = new CSSStyleSheet; + root.adoptedStyleSheets = [this.sheet].concat(root.adoptedStyleSheets); + adoptedSet = this; } else { - return; + this.styleTag = (root.ownerDocument || root).createElement("style"); + let target = root.head || root; + target.insertBefore(this.styleTag, target.firstChild); } + this.modules = []; + root[SET] = this; } - - function loadDocuments(input, options) { - input = String(input); - options = options || {}; - - if (input.length !== 0) { - - // Add tailing `\n` if not exists - if (input.charCodeAt(input.length - 1) !== 0x0A/* LF */ && - input.charCodeAt(input.length - 1) !== 0x0D/* CR */) { - input += '\n'; + mount(modules) { + let sheet = this.sheet; + let pos = 0 /* Current rule offset */, j = 0; /* Index into this.modules */ + for (let i = 0; i < modules.length; i++) { + let mod = modules[i], index = this.modules.indexOf(mod); + if (index < j && index > -1) { // Ordering conflict + this.modules.splice(index, 1); + j--; + index = -1; } - - // Strip BOM - if (input.charCodeAt(0) === 0xFEFF) { - input = input.slice(1); + if (index == -1) { + this.modules.splice(j++, 0, mod); + if (sheet) for (let k = 0; k < mod.rules.length; k++) + sheet.insertRule(mod.rules[k], pos++); + } else { + while (j < index) pos += this.modules[j++].rules.length; + pos += mod.rules.length; + j++; } } - var state = new State$1(input, options); - - var nullpos = input.indexOf('\0'); - - if (nullpos !== -1) { - state.position = nullpos; - throwError(state, 'null byte is not allowed in input'); - } - - // Use 0 as string terminator. That significantly simplifies bounds check. - state.input += '\0'; - - while (state.input.charCodeAt(state.position) === 0x20/* Space */) { - state.lineIndent += 1; - state.position += 1; - } - - while (state.position < (state.length - 1)) { - readDocument(state); - } - - return state.documents; - } - - - function loadAll$1(input, iterator, options) { - if (iterator !== null && typeof iterator === 'object' && typeof options === 'undefined') { - options = iterator; - iterator = null; - } - - var documents = loadDocuments(input, options); - - if (typeof iterator !== 'function') { - return documents; - } - - for (var index = 0, length = documents.length; index < length; index += 1) { - iterator(documents[index]); + if (!sheet) { + let text = ""; + for (let i = 0; i < this.modules.length; i++) + text += this.modules[i].getRules() + "\n"; + this.styleTag.textContent = text; } } + } + // Style::Object<union<Style,string>> + // + // A style is an object that, in the simple case, maps CSS property + // names to strings holding their values, as in `{color: "red", + // fontWeight: "bold"}`. The property names can be given in + // camel-case—the library will insert a dash before capital letters + // when converting them to CSS. + // + // If you include an underscore in a property name, it and everything + // after it will be removed from the output, which can be useful when + // providing a property multiple times, for browser compatibility + // reasons. + // + // A property in a style object can also be a sub-selector, which + // extends the current context to add a pseudo-selector or a child + // selector. Such a property should contain a `&` character, which + // will be replaced by the current selector. For example `{"&:before": + // {content: '"hi"'}}`. Sub-selectors and regular properties can + // freely be mixed in a given object. Any property containing a `&` is + // assumed to be a sub-selector. + // + // Finally, a property can specify an @-block to be wrapped around the + // styles defined inside the object that's the property's value. For + // example to create a media query you can do `{"@media screen and + // (min-width: 400px)": {...}}`. - function load$1(input, options) { - var documents = loadDocuments(input, options); + var base = { + 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: "'" + }; - if (documents.length === 0) { - /*eslint-disable no-undefined*/ - return undefined; - } else if (documents.length === 1) { - return documents[0]; + var shift = { + 48: ")", + 49: "!", + 50: "@", + 51: "#", + 52: "$", + 53: "%", + 54: "^", + 55: "&", + 56: "*", + 57: "(", + 59: ":", + 61: "+", + 173: "_", + 186: ":", + 187: "+", + 188: "<", + 189: "_", + 190: ">", + 191: "?", + 192: "~", + 219: "{", + 220: "|", + 221: "}", + 222: "\"" + }; + + var chrome$1 = typeof navigator != "undefined" && /Chrome\/(\d+)/.exec(navigator.userAgent); + typeof navigator != "undefined" && /Gecko\/\d+/.test(navigator.userAgent); + var mac = typeof navigator != "undefined" && /Mac/.test(navigator.platform); + var ie$1 = typeof navigator != "undefined" && /MSIE \d|Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(navigator.userAgent); + var brokenModifierNames = mac || chrome$1 && +chrome$1[1] < 57; + + // Fill in the digit keys + for (var i = 0; i < 10; i++) base[48 + i] = base[96 + i] = String(i); + + // The function keys + for (var i = 1; i <= 24; i++) base[i + 111] = "F" + i; + + // And the alphabetic keys + for (var i = 65; i <= 90; i++) { + base[i] = String.fromCharCode(i + 32); + shift[i] = String.fromCharCode(i); + } + + // For each code that doesn't have a shift-equivalent, copy the base name + for (var code in base) if (!shift.hasOwnProperty(code)) shift[code] = base[code]; + + function keyName(event) { + var ignoreKey = brokenModifierNames && (event.ctrlKey || event.altKey || event.metaKey) || + ie$1 && event.shiftKey && event.key && event.key.length == 1 || + event.key == "Unidentified"; + var name = (!ignoreKey && event.key) || + (event.shiftKey ? shift : base)[event.keyCode] || + event.key || "Unidentified"; + // Edge sometimes produces wrong names (Issue #3) + if (name == "Esc") name = "Escape"; + if (name == "Del") name = "Delete"; + // https://developer.microsoft.com/en-us/microsoft-edge/platform/issues/8860571/ + if (name == "Left") name = "ArrowLeft"; + if (name == "Up") name = "ArrowUp"; + if (name == "Right") name = "ArrowRight"; + if (name == "Down") name = "ArrowDown"; + return name + } + + function getSelection(root) { + let target; + // Browsers differ on whether shadow roots have a getSelection + // method. If it exists, use that, otherwise, call it on the + // document. + if (root.nodeType == 11) { // Shadow root + target = root.getSelection ? root : root.ownerDocument; } - throw new exception('expected a single document in the stream, but found more'); + else { + target = root; + } + return target.getSelection(); + } + function contains(dom, node) { + return node ? dom == node || dom.contains(node.nodeType != 1 ? node.parentNode : node) : false; + } + function deepActiveElement(doc) { + let elt = doc.activeElement; + while (elt && elt.shadowRoot) + elt = elt.shadowRoot.activeElement; + return elt; + } + function hasSelection(dom, selection) { + if (!selection.anchorNode) + return false; + try { + // Firefox will raise 'permission denied' errors when accessing + // properties of `sel.anchorNode` when it's in a generated CSS + // element. + return contains(dom, selection.anchorNode); + } + catch (_) { + return false; + } + } + function clientRectsFor(dom) { + if (dom.nodeType == 3) + return textRange(dom, 0, dom.nodeValue.length).getClientRects(); + else if (dom.nodeType == 1) + return dom.getClientRects(); + else + return []; + } + // Scans forward and backward through DOM positions equivalent to the + // given one to see if the two are in the same place (i.e. after a + // text node vs at the end of that text node) + function isEquivalentPosition(node, off, targetNode, targetOff) { + return targetNode ? (scanFor(node, off, targetNode, targetOff, -1) || + scanFor(node, off, targetNode, targetOff, 1)) : false; + } + function domIndex(node) { + for (var index = 0;; index++) { + node = node.previousSibling; + if (!node) + return index; + } + } + function scanFor(node, off, targetNode, targetOff, dir) { + for (;;) { + if (node == targetNode && off == targetOff) + return true; + if (off == (dir < 0 ? 0 : maxOffset(node))) { + if (node.nodeName == "DIV") + return false; + let parent = node.parentNode; + if (!parent || parent.nodeType != 1) + return false; + off = domIndex(node) + (dir < 0 ? 0 : 1); + node = parent; + } + else if (node.nodeType == 1) { + node = node.childNodes[off + (dir < 0 ? -1 : 0)]; + if (node.nodeType == 1 && node.contentEditable == "false") + return false; + off = dir < 0 ? maxOffset(node) : 0; + } + else { + return false; + } + } + } + function maxOffset(node) { + return node.nodeType == 3 ? node.nodeValue.length : node.childNodes.length; + } + const Rect0 = { left: 0, right: 0, top: 0, bottom: 0 }; + function flattenRect(rect, left) { + let x = left ? rect.left : rect.right; + return { left: x, right: x, top: rect.top, bottom: rect.bottom }; + } + function windowRect(win) { + return { left: 0, right: win.innerWidth, + top: 0, bottom: win.innerHeight }; + } + function scrollRectIntoView(dom, rect, side, x, y, xMargin, yMargin, ltr) { + let doc = dom.ownerDocument, win = doc.defaultView || window; + for (let cur = dom; cur;) { + if (cur.nodeType == 1) { // Element + let bounding, top = cur == doc.body; + if (top) { + bounding = windowRect(win); + } + else { + if (cur.scrollHeight <= cur.clientHeight && cur.scrollWidth <= cur.clientWidth) { + cur = cur.assignedSlot || cur.parentNode; + continue; + } + let rect = cur.getBoundingClientRect(); + // Make sure scrollbar width isn't included in the rectangle + bounding = { left: rect.left, right: rect.left + cur.clientWidth, + top: rect.top, bottom: rect.top + cur.clientHeight }; + } + let moveX = 0, moveY = 0; + if (y == "nearest") { + if (rect.top < bounding.top) { + moveY = -(bounding.top - rect.top + yMargin); + if (side > 0 && rect.bottom > bounding.bottom + moveY) + moveY = rect.bottom - bounding.bottom + moveY + yMargin; + } + else if (rect.bottom > bounding.bottom) { + moveY = rect.bottom - bounding.bottom + yMargin; + if (side < 0 && (rect.top - moveY) < bounding.top) + moveY = -(bounding.top + moveY - rect.top + yMargin); + } + } + else { + let rectHeight = rect.bottom - rect.top, boundingHeight = bounding.bottom - bounding.top; + let targetTop = y == "center" && rectHeight <= boundingHeight ? rect.top + rectHeight / 2 - boundingHeight / 2 : + y == "start" || y == "center" && side < 0 ? rect.top - yMargin : + rect.bottom - boundingHeight + yMargin; + moveY = targetTop - bounding.top; + } + if (x == "nearest") { + if (rect.left < bounding.left) { + moveX = -(bounding.left - rect.left + xMargin); + if (side > 0 && rect.right > bounding.right + moveX) + moveX = rect.right - bounding.right + moveX + xMargin; + } + else if (rect.right > bounding.right) { + moveX = rect.right - bounding.right + xMargin; + if (side < 0 && rect.left < bounding.left + moveX) + moveX = -(bounding.left + moveX - rect.left + xMargin); + } + } + else { + let targetLeft = x == "center" ? rect.left + (rect.right - rect.left) / 2 - (bounding.right - bounding.left) / 2 : + (x == "start") == ltr ? rect.left - xMargin : + rect.right - (bounding.right - bounding.left) + xMargin; + moveX = targetLeft - bounding.left; + } + if (moveX || moveY) { + if (top) { + win.scrollBy(moveX, moveY); + } + else { + let movedX = 0, movedY = 0; + if (moveY) { + let start = cur.scrollTop; + cur.scrollTop += moveY; + movedY = cur.scrollTop - start; + } + if (moveX) { + let start = cur.scrollLeft; + cur.scrollLeft += moveX; + movedX = cur.scrollLeft - start; + } + rect = { left: rect.left - movedX, top: rect.top - movedY, + right: rect.right - movedX, bottom: rect.bottom - movedY }; + if (movedX && Math.abs(movedX - moveX) < 1) + x = "nearest"; + if (movedY && Math.abs(movedY - moveY) < 1) + y = "nearest"; + } + } + if (top) + break; + cur = cur.assignedSlot || cur.parentNode; + } + else if (cur.nodeType == 11) { // A shadow root + cur = cur.host; + } + else { + break; + } + } + } + class DOMSelectionState { + constructor() { + this.anchorNode = null; + this.anchorOffset = 0; + this.focusNode = null; + this.focusOffset = 0; + } + eq(domSel) { + return this.anchorNode == domSel.anchorNode && this.anchorOffset == domSel.anchorOffset && + this.focusNode == domSel.focusNode && this.focusOffset == domSel.focusOffset; + } + setRange(range) { + this.set(range.anchorNode, range.anchorOffset, range.focusNode, range.focusOffset); + } + set(anchorNode, anchorOffset, focusNode, focusOffset) { + this.anchorNode = anchorNode; + this.anchorOffset = anchorOffset; + this.focusNode = focusNode; + this.focusOffset = focusOffset; + } + } + let preventScrollSupported = null; + // Feature-detects support for .focus({preventScroll: true}), and uses + // a fallback kludge when not supported. + function focusPreventScroll(dom) { + if (dom.setActive) + return dom.setActive(); // in IE + if (preventScrollSupported) + return dom.focus(preventScrollSupported); + let stack = []; + for (let cur = dom; cur; cur = cur.parentNode) { + stack.push(cur, cur.scrollTop, cur.scrollLeft); + if (cur == cur.ownerDocument) + break; + } + dom.focus(preventScrollSupported == null ? { + get preventScroll() { + preventScrollSupported = { preventScroll: true }; + return true; + } + } : undefined); + if (!preventScrollSupported) { + preventScrollSupported = false; + for (let i = 0; i < stack.length;) { + let elt = stack[i++], top = stack[i++], left = stack[i++]; + if (elt.scrollTop != top) + elt.scrollTop = top; + if (elt.scrollLeft != left) + elt.scrollLeft = left; + } + } + } + let scratchRange; + function textRange(node, from, to = from) { + let range = scratchRange || (scratchRange = document.createRange()); + range.setEnd(node, to); + range.setStart(node, from); + return range; + } + function dispatchKey(elt, name, code) { + let options = { key: name, code: name, keyCode: code, which: code, cancelable: true }; + let down = new KeyboardEvent("keydown", options); + down.synthetic = true; + elt.dispatchEvent(down); + let up = new KeyboardEvent("keyup", options); + up.synthetic = true; + elt.dispatchEvent(up); + return down.defaultPrevented || up.defaultPrevented; + } + function getRoot(node) { + while (node) { + if (node && (node.nodeType == 9 || node.nodeType == 11 && node.host)) + return node; + node = node.assignedSlot || node.parentNode; + } + return null; + } + function clearAttributes(node) { + while (node.attributes.length) + node.removeAttributeNode(node.attributes[0]); + } + function atElementStart(doc, selection) { + let node = selection.focusNode, offset = selection.focusOffset; + if (!node || selection.anchorNode != node || selection.anchorOffset != offset) + return false; + for (;;) { + if (offset) { + if (node.nodeType != 1) + return false; + let prev = node.childNodes[offset - 1]; + if (prev.contentEditable == "false") + offset--; + else { + node = prev; + offset = maxOffset(node); + } + } + else if (node == doc) { + return true; + } + else { + offset = domIndex(node); + node = node.parentNode; + } + } + } + + class DOMPos { + constructor(node, offset, precise = true) { + this.node = node; + this.offset = offset; + this.precise = precise; + } + static before(dom, precise) { return new DOMPos(dom.parentNode, domIndex(dom), precise); } + static after(dom, precise) { return new DOMPos(dom.parentNode, domIndex(dom) + 1, precise); } + } + const noChildren = []; + class ContentView { + constructor() { + this.parent = null; + this.dom = null; + this.dirty = 2 /* Dirty.Node */; + } + get editorView() { + if (!this.parent) + throw new Error("Accessing view in orphan content view"); + return this.parent.editorView; + } + get overrideDOMText() { return null; } + get posAtStart() { + return this.parent ? this.parent.posBefore(this) : 0; + } + get posAtEnd() { + return this.posAtStart + this.length; + } + posBefore(view) { + let pos = this.posAtStart; + for (let child of this.children) { + if (child == view) + return pos; + pos += child.length + child.breakAfter; + } + throw new RangeError("Invalid child in posBefore"); + } + posAfter(view) { + return this.posBefore(view) + view.length; + } + // Will return a rectangle directly before (when side < 0), after + // (side > 0) or directly on (when the browser supports it) the + // given position. + coordsAt(_pos, _side) { return null; } + sync(track) { + if (this.dirty & 2 /* Dirty.Node */) { + let parent = this.dom; + let prev = null, next; + for (let child of this.children) { + if (child.dirty) { + if (!child.dom && (next = prev ? prev.nextSibling : parent.firstChild)) { + let contentView = ContentView.get(next); + if (!contentView || !contentView.parent && contentView.canReuseDOM(child)) + child.reuseDOM(next); + } + child.sync(track); + child.dirty = 0 /* Dirty.Not */; + } + next = prev ? prev.nextSibling : parent.firstChild; + if (track && !track.written && track.node == parent && next != child.dom) + track.written = true; + if (child.dom.parentNode == parent) { + while (next && next != child.dom) + next = rm$1(next); + } + else { + parent.insertBefore(child.dom, next); + } + prev = child.dom; + } + next = prev ? prev.nextSibling : parent.firstChild; + if (next && track && track.node == parent) + track.written = true; + while (next) + next = rm$1(next); + } + else if (this.dirty & 1 /* Dirty.Child */) { + for (let child of this.children) + if (child.dirty) { + child.sync(track); + child.dirty = 0 /* Dirty.Not */; + } + } + } + reuseDOM(_dom) { } + localPosFromDOM(node, offset) { + let after; + if (node == this.dom) { + after = this.dom.childNodes[offset]; + } + else { + let bias = maxOffset(node) == 0 ? 0 : offset == 0 ? -1 : 1; + for (;;) { + let parent = node.parentNode; + if (parent == this.dom) + break; + if (bias == 0 && parent.firstChild != parent.lastChild) { + if (node == parent.firstChild) + bias = -1; + else + bias = 1; + } + node = parent; + } + if (bias < 0) + after = node; + else + after = node.nextSibling; + } + if (after == this.dom.firstChild) + return 0; + while (after && !ContentView.get(after)) + after = after.nextSibling; + if (!after) + return this.length; + for (let i = 0, pos = 0;; i++) { + let child = this.children[i]; + if (child.dom == after) + return pos; + pos += child.length + child.breakAfter; + } + } + domBoundsAround(from, to, offset = 0) { + let fromI = -1, fromStart = -1, toI = -1, toEnd = -1; + for (let i = 0, pos = offset, prevEnd = offset; i < this.children.length; i++) { + let child = this.children[i], end = pos + child.length; + if (pos < from && end > to) + return child.domBoundsAround(from, to, pos); + if (end >= from && fromI == -1) { + fromI = i; + fromStart = pos; + } + if (pos > to && child.dom.parentNode == this.dom) { + toI = i; + toEnd = prevEnd; + break; + } + prevEnd = end; + pos = end + child.breakAfter; + } + return { from: fromStart, to: toEnd < 0 ? offset + this.length : toEnd, + startDOM: (fromI ? this.children[fromI - 1].dom.nextSibling : null) || this.dom.firstChild, + endDOM: toI < this.children.length && toI >= 0 ? this.children[toI].dom : null }; + } + markDirty(andParent = false) { + this.dirty |= 2 /* Dirty.Node */; + this.markParentsDirty(andParent); + } + markParentsDirty(childList) { + for (let parent = this.parent; parent; parent = parent.parent) { + if (childList) + parent.dirty |= 2 /* Dirty.Node */; + if (parent.dirty & 1 /* Dirty.Child */) + return; + parent.dirty |= 1 /* Dirty.Child */; + childList = false; + } + } + setParent(parent) { + if (this.parent != parent) { + this.parent = parent; + if (this.dirty) + this.markParentsDirty(true); + } + } + setDOM(dom) { + if (this.dom) + this.dom.cmView = null; + this.dom = dom; + dom.cmView = this; + } + get rootView() { + for (let v = this;;) { + let parent = v.parent; + if (!parent) + return v; + v = parent; + } + } + replaceChildren(from, to, children = noChildren) { + this.markDirty(); + for (let i = from; i < to; i++) { + let child = this.children[i]; + if (child.parent == this) + child.destroy(); + } + this.children.splice(from, to - from, ...children); + for (let i = 0; i < children.length; i++) + children[i].setParent(this); + } + ignoreMutation(_rec) { return false; } + ignoreEvent(_event) { return false; } + childCursor(pos = this.length) { + return new ChildCursor(this.children, pos, this.children.length); + } + childPos(pos, bias = 1) { + return this.childCursor().findPos(pos, bias); + } + toString() { + let name = this.constructor.name.replace("View", ""); + return name + (this.children.length ? "(" + this.children.join() + ")" : + this.length ? "[" + (name == "Text" ? this.text : this.length) + "]" : "") + + (this.breakAfter ? "#" : ""); + } + static get(node) { return node.cmView; } + get isEditable() { return true; } + merge(from, to, source, hasStart, openStart, openEnd) { + return false; + } + become(other) { return false; } + canReuseDOM(other) { return other.constructor == this.constructor; } + // When this is a zero-length view with a side, this should return a + // number <= 0 to indicate it is before its position, or a + // number > 0 when after its position. + getSide() { return 0; } + destroy() { + this.parent = null; + } + } + ContentView.prototype.breakAfter = 0; + // Remove a DOM node and return its next sibling. + function rm$1(dom) { + let next = dom.nextSibling; + dom.parentNode.removeChild(dom); + return next; + } + class ChildCursor { + constructor(children, pos, i) { + this.children = children; + this.pos = pos; + this.i = i; + this.off = 0; + } + findPos(pos, bias = 1) { + for (;;) { + if (pos > this.pos || pos == this.pos && + (bias > 0 || this.i == 0 || this.children[this.i - 1].breakAfter)) { + this.off = pos - this.pos; + return this; + } + let next = this.children[--this.i]; + this.pos -= next.length + next.breakAfter; + } + } + } + function replaceRange(parent, fromI, fromOff, toI, toOff, insert, breakAtStart, openStart, openEnd) { + let { children } = parent; + let before = children.length ? children[fromI] : null; + let last = insert.length ? insert[insert.length - 1] : null; + let breakAtEnd = last ? last.breakAfter : breakAtStart; + // Change within a single child + if (fromI == toI && before && !breakAtStart && !breakAtEnd && insert.length < 2 && + before.merge(fromOff, toOff, insert.length ? last : null, fromOff == 0, openStart, openEnd)) + return; + if (toI < children.length) { + let after = children[toI]; + // Make sure the end of the child after the update is preserved in `after` + if (after && toOff < after.length) { + // If we're splitting a child, separate part of it to avoid that + // being mangled when updating the child before the update. + if (fromI == toI) { + after = after.split(toOff); + toOff = 0; + } + // If the element after the replacement should be merged with + // the last replacing element, update `content` + if (!breakAtEnd && last && after.merge(0, toOff, last, true, 0, openEnd)) { + insert[insert.length - 1] = after; + } + else { + // Remove the start of the after element, if necessary, and + // add it to `content`. + if (toOff) + after.merge(0, toOff, null, false, 0, openEnd); + insert.push(after); + } + } + else if (after === null || after === void 0 ? void 0 : after.breakAfter) { + // The element at `toI` is entirely covered by this range. + // Preserve its line break, if any. + if (last) + last.breakAfter = 1; + else + breakAtStart = 1; + } + // Since we've handled the next element from the current elements + // now, make sure `toI` points after that. + toI++; + } + if (before) { + before.breakAfter = breakAtStart; + if (fromOff > 0) { + if (!breakAtStart && insert.length && before.merge(fromOff, before.length, insert[0], false, openStart, 0)) { + before.breakAfter = insert.shift().breakAfter; + } + else if (fromOff < before.length || before.children.length && before.children[before.children.length - 1].length == 0) { + before.merge(fromOff, before.length, null, false, openStart, 0); + } + fromI++; + } + } + // Try to merge widgets on the boundaries of the replacement + while (fromI < toI && insert.length) { + if (children[toI - 1].become(insert[insert.length - 1])) { + toI--; + insert.pop(); + openEnd = insert.length ? 0 : openStart; + } + else if (children[fromI].become(insert[0])) { + fromI++; + insert.shift(); + openStart = insert.length ? 0 : openEnd; + } + else { + break; + } + } + if (!insert.length && fromI && toI < children.length && !children[fromI - 1].breakAfter && + children[toI].merge(0, 0, children[fromI - 1], false, openStart, openEnd)) + fromI--; + if (fromI < toI || insert.length) + parent.replaceChildren(fromI, toI, insert); + } + function mergeChildrenInto(parent, from, to, insert, openStart, openEnd) { + let cur = parent.childCursor(); + let { i: toI, off: toOff } = cur.findPos(to, 1); + let { i: fromI, off: fromOff } = cur.findPos(from, -1); + let dLen = from - to; + for (let view of insert) + dLen += view.length; + parent.length += dLen; + replaceRange(parent, fromI, fromOff, toI, toOff, insert, 0, openStart, openEnd); + } + + let nav = typeof navigator != "undefined" ? navigator : { userAgent: "", vendor: "", platform: "" }; + let doc = typeof document != "undefined" ? document : { documentElement: { style: {} } }; + const ie_edge = /*@__PURE__*//Edge\/(\d+)/.exec(nav.userAgent); + const ie_upto10 = /*@__PURE__*//MSIE \d/.test(nav.userAgent); + const ie_11up = /*@__PURE__*//Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(nav.userAgent); + const ie = !!(ie_upto10 || ie_11up || ie_edge); + const gecko = !ie && /*@__PURE__*//gecko\/(\d+)/i.test(nav.userAgent); + const chrome = !ie && /*@__PURE__*//Chrome\/(\d+)/.exec(nav.userAgent); + const webkit = "webkitFontSmoothing" in doc.documentElement.style; + const safari = !ie && /*@__PURE__*//Apple Computer/.test(nav.vendor); + const ios = safari && (/*@__PURE__*//Mobile\/\w+/.test(nav.userAgent) || nav.maxTouchPoints > 2); + var browser = { + mac: ios || /*@__PURE__*//Mac/.test(nav.platform), + windows: /*@__PURE__*//Win/.test(nav.platform), + linux: /*@__PURE__*//Linux|X11/.test(nav.platform), + ie, + ie_version: ie_upto10 ? doc.documentMode || 6 : ie_11up ? +ie_11up[1] : ie_edge ? +ie_edge[1] : 0, + gecko, + gecko_version: gecko ? +(/*@__PURE__*//Firefox\/(\d+)/.exec(nav.userAgent) || [0, 0])[1] : 0, + chrome: !!chrome, + chrome_version: chrome ? +chrome[1] : 0, + ios, + android: /*@__PURE__*//Android\b/.test(nav.userAgent), + webkit, + safari, + webkit_version: webkit ? +(/*@__PURE__*//\bAppleWebKit\/(\d+)/.exec(navigator.userAgent) || [0, 0])[1] : 0, + tabSize: doc.documentElement.style.tabSize != null ? "tab-size" : "-moz-tab-size" + }; + + const MaxJoinLen = 256; + class TextView extends ContentView { + constructor(text) { + super(); + this.text = text; + } + get length() { return this.text.length; } + createDOM(textDOM) { + this.setDOM(textDOM || document.createTextNode(this.text)); + } + sync(track) { + if (!this.dom) + this.createDOM(); + if (this.dom.nodeValue != this.text) { + if (track && track.node == this.dom) + track.written = true; + this.dom.nodeValue = this.text; + } + } + reuseDOM(dom) { + if (dom.nodeType == 3) + this.createDOM(dom); + } + merge(from, to, source) { + if (source && (!(source instanceof TextView) || this.length - (to - from) + source.length > MaxJoinLen)) + return false; + this.text = this.text.slice(0, from) + (source ? source.text : "") + this.text.slice(to); + this.markDirty(); + return true; + } + split(from) { + let result = new TextView(this.text.slice(from)); + this.text = this.text.slice(0, from); + this.markDirty(); + return result; + } + localPosFromDOM(node, offset) { + return node == this.dom ? offset : offset ? this.text.length : 0; + } + domAtPos(pos) { return new DOMPos(this.dom, pos); } + domBoundsAround(_from, _to, offset) { + return { from: offset, to: offset + this.length, startDOM: this.dom, endDOM: this.dom.nextSibling }; + } + coordsAt(pos, side) { + return textCoords(this.dom, pos, side); + } + } + class MarkView extends ContentView { + constructor(mark, children = [], length = 0) { + super(); + this.mark = mark; + this.children = children; + this.length = length; + for (let ch of children) + ch.setParent(this); + } + setAttrs(dom) { + clearAttributes(dom); + if (this.mark.class) + dom.className = this.mark.class; + if (this.mark.attrs) + for (let name in this.mark.attrs) + dom.setAttribute(name, this.mark.attrs[name]); + return dom; + } + reuseDOM(node) { + if (node.nodeName == this.mark.tagName.toUpperCase()) { + this.setDOM(node); + this.dirty |= 4 /* Dirty.Attrs */ | 2 /* Dirty.Node */; + } + } + sync(track) { + if (!this.dom) + this.setDOM(this.setAttrs(document.createElement(this.mark.tagName))); + else if (this.dirty & 4 /* Dirty.Attrs */) + this.setAttrs(this.dom); + super.sync(track); + } + merge(from, to, source, _hasStart, openStart, openEnd) { + if (source && (!(source instanceof MarkView && source.mark.eq(this.mark)) || + (from && openStart <= 0) || (to < this.length && openEnd <= 0))) + return false; + mergeChildrenInto(this, from, to, source ? source.children : [], openStart - 1, openEnd - 1); + this.markDirty(); + return true; + } + split(from) { + let result = [], off = 0, detachFrom = -1, i = 0; + for (let elt of this.children) { + let end = off + elt.length; + if (end > from) + result.push(off < from ? elt.split(from - off) : elt); + if (detachFrom < 0 && off >= from) + detachFrom = i; + off = end; + i++; + } + let length = this.length - from; + this.length = from; + if (detachFrom > -1) { + this.children.length = detachFrom; + this.markDirty(); + } + return new MarkView(this.mark, result, length); + } + domAtPos(pos) { + return inlineDOMAtPos(this, pos); + } + coordsAt(pos, side) { + return coordsInChildren(this, pos, side); + } + } + function textCoords(text, pos, side) { + let length = text.nodeValue.length; + if (pos > length) + pos = length; + let from = pos, to = pos, flatten = 0; + if (pos == 0 && side < 0 || pos == length && side >= 0) { + if (!(browser.chrome || browser.gecko)) { // These browsers reliably return valid rectangles for empty ranges + if (pos) { + from--; + flatten = 1; + } // FIXME this is wrong in RTL text + else if (to < length) { + to++; + flatten = -1; + } + } + } + else { + if (side < 0) + from--; + else if (to < length) + to++; + } + let rects = textRange(text, from, to).getClientRects(); + if (!rects.length) + return Rect0; + let rect = rects[(flatten ? flatten < 0 : side >= 0) ? 0 : rects.length - 1]; + if (browser.safari && !flatten && rect.width == 0) + rect = Array.prototype.find.call(rects, r => r.width) || rect; + return flatten ? flattenRect(rect, flatten < 0) : rect || null; + } + // Also used for collapsed ranges that don't have a placeholder widget! + class WidgetView extends ContentView { + constructor(widget, length, side) { + super(); + this.widget = widget; + this.length = length; + this.side = side; + this.prevWidget = null; + } + static create(widget, length, side) { + return new (widget.customView || WidgetView)(widget, length, side); + } + split(from) { + let result = WidgetView.create(this.widget, this.length - from, this.side); + this.length -= from; + return result; + } + sync() { + if (!this.dom || !this.widget.updateDOM(this.dom)) { + if (this.dom && this.prevWidget) + this.prevWidget.destroy(this.dom); + this.prevWidget = null; + this.setDOM(this.widget.toDOM(this.editorView)); + this.dom.contentEditable = "false"; + } + } + getSide() { return this.side; } + merge(from, to, source, hasStart, openStart, openEnd) { + if (source && (!(source instanceof WidgetView) || !this.widget.compare(source.widget) || + from > 0 && openStart <= 0 || to < this.length && openEnd <= 0)) + return false; + this.length = from + (source ? source.length : 0) + (this.length - to); + return true; + } + become(other) { + if (other.length == this.length && other instanceof WidgetView && other.side == this.side) { + if (this.widget.constructor == other.widget.constructor) { + if (!this.widget.eq(other.widget)) + this.markDirty(true); + if (this.dom && !this.prevWidget) + this.prevWidget = this.widget; + this.widget = other.widget; + return true; + } + } + return false; + } + ignoreMutation() { return true; } + ignoreEvent(event) { return this.widget.ignoreEvent(event); } + get overrideDOMText() { + if (this.length == 0) + return Text.empty; + let top = this; + while (top.parent) + top = top.parent; + let view = top.editorView, text = view && view.state.doc, start = this.posAtStart; + return text ? text.slice(start, start + this.length) : Text.empty; + } + domAtPos(pos) { + return pos == 0 ? DOMPos.before(this.dom) : DOMPos.after(this.dom, pos == this.length); + } + domBoundsAround() { return null; } + coordsAt(pos, side) { + let rects = this.dom.getClientRects(), rect = null; + if (!rects.length) + return Rect0; + for (let i = pos > 0 ? rects.length - 1 : 0;; i += (pos > 0 ? -1 : 1)) { + rect = rects[i]; + if (pos > 0 ? i == 0 : i == rects.length - 1 || rect.top < rect.bottom) + break; + } + return (pos == 0 && side > 0 || pos == this.length && side <= 0) ? rect : flattenRect(rect, pos == 0); + } + get isEditable() { return false; } + destroy() { + super.destroy(); + if (this.dom) + this.widget.destroy(this.dom); + } + } + class CompositionView extends WidgetView { + domAtPos(pos) { + let { topView, text } = this.widget; + if (!topView) + return new DOMPos(text, Math.min(pos, text.nodeValue.length)); + return scanCompositionTree(pos, 0, topView, text, (v, p) => v.domAtPos(p), p => new DOMPos(text, Math.min(p, text.nodeValue.length))); + } + sync() { this.setDOM(this.widget.toDOM()); } + localPosFromDOM(node, offset) { + let { topView, text } = this.widget; + if (!topView) + return Math.min(offset, this.length); + return posFromDOMInCompositionTree(node, offset, topView, text); + } + ignoreMutation() { return false; } + get overrideDOMText() { return null; } + coordsAt(pos, side) { + let { topView, text } = this.widget; + if (!topView) + return textCoords(text, pos, side); + return scanCompositionTree(pos, side, topView, text, (v, pos, side) => v.coordsAt(pos, side), (pos, side) => textCoords(text, pos, side)); + } + destroy() { + var _a; + super.destroy(); + (_a = this.widget.topView) === null || _a === void 0 ? void 0 : _a.destroy(); + } + get isEditable() { return true; } + canReuseDOM() { return true; } + } + // Uses the old structure of a chunk of content view frozen for + // composition to try and find a reasonable DOM location for the given + // offset. + function scanCompositionTree(pos, side, view, text, enterView, fromText) { + if (view instanceof MarkView) { + for (let child = view.dom.firstChild; child; child = child.nextSibling) { + let desc = ContentView.get(child); + if (!desc) + return fromText(pos, side); + let hasComp = contains(child, text); + let len = desc.length + (hasComp ? text.nodeValue.length : 0); + if (pos < len || pos == len && desc.getSide() <= 0) + return hasComp ? scanCompositionTree(pos, side, desc, text, enterView, fromText) : enterView(desc, pos, side); + pos -= len; + } + return enterView(view, view.length, -1); + } + else if (view.dom == text) { + return fromText(pos, side); + } + else { + return enterView(view, pos, side); + } + } + function posFromDOMInCompositionTree(node, offset, view, text) { + if (view instanceof MarkView) { + for (let child of view.children) { + let pos = 0, hasComp = contains(child.dom, text); + if (contains(child.dom, node)) + return pos + (hasComp ? posFromDOMInCompositionTree(node, offset, child, text) : child.localPosFromDOM(node, offset)); + pos += hasComp ? text.nodeValue.length : child.length; + } + } + else if (view.dom == text) { + return Math.min(offset, text.nodeValue.length); + } + return view.localPosFromDOM(node, offset); + } + // These are drawn around uneditable widgets to avoid a number of + // browser bugs that show up when the cursor is directly next to + // uneditable inline content. + class WidgetBufferView extends ContentView { + constructor(side) { + super(); + this.side = side; + } + get length() { return 0; } + merge() { return false; } + become(other) { + return other instanceof WidgetBufferView && other.side == this.side; + } + split() { return new WidgetBufferView(this.side); } + sync() { + if (!this.dom) { + let dom = document.createElement("img"); + dom.className = "cm-widgetBuffer"; + dom.setAttribute("aria-hidden", "true"); + this.setDOM(dom); + } + } + getSide() { return this.side; } + domAtPos(pos) { return DOMPos.before(this.dom); } + localPosFromDOM() { return 0; } + domBoundsAround() { return null; } + coordsAt(pos) { + let imgRect = this.dom.getBoundingClientRect(); + // Since the <img> height doesn't correspond to text height, try + // to borrow the height from some sibling node. + let siblingRect = inlineSiblingRect(this, this.side > 0 ? -1 : 1); + return siblingRect && siblingRect.top < imgRect.bottom && siblingRect.bottom > imgRect.top + ? { left: imgRect.left, right: imgRect.right, top: siblingRect.top, bottom: siblingRect.bottom } : imgRect; + } + get overrideDOMText() { + return Text.empty; + } + } + TextView.prototype.children = WidgetView.prototype.children = WidgetBufferView.prototype.children = noChildren; + function inlineSiblingRect(view, side) { + let parent = view.parent, index = parent ? parent.children.indexOf(view) : -1; + while (parent && index >= 0) { + if (side < 0 ? index > 0 : index < parent.children.length) { + let next = parent.children[index + side]; + if (next instanceof TextView) { + let nextRect = next.coordsAt(side < 0 ? next.length : 0, side); + if (nextRect) + return nextRect; + } + index += side; + } + else if (parent instanceof MarkView && parent.parent) { + index = parent.parent.children.indexOf(parent) + (side < 0 ? 0 : 1); + parent = parent.parent; + } + else { + let last = parent.dom.lastChild; + if (last && last.nodeName == "BR") + return last.getClientRects()[0]; + break; + } + } + return undefined; + } + function inlineDOMAtPos(parent, pos) { + let dom = parent.dom, { children } = parent, i = 0; + for (let off = 0; i < children.length; i++) { + let child = children[i], end = off + child.length; + if (end == off && child.getSide() <= 0) + continue; + if (pos > off && pos < end && child.dom.parentNode == dom) + return child.domAtPos(pos - off); + if (pos <= off) + break; + off = end; + } + // if (i) return DOMPos.after(children[i - 1].dom!) + for (let j = i; j > 0; j--) { + let prev = children[j - 1]; + if (prev.dom.parentNode == dom) + return prev.domAtPos(prev.length); + } + for (let j = i; j < children.length; j++) { + let next = children[j]; + if (next.dom.parentNode == dom) + return next.domAtPos(0); + } + return new DOMPos(dom, 0); + } + // Assumes `view`, if a mark view, has precisely 1 child. + function joinInlineInto(parent, view, open) { + let last, { children } = parent; + if (open > 0 && view instanceof MarkView && children.length && + (last = children[children.length - 1]) instanceof MarkView && last.mark.eq(view.mark)) { + joinInlineInto(last, view.children[0], open - 1); + } + else { + children.push(view); + view.setParent(parent); + } + parent.length += view.length; + } + function coordsInChildren(view, pos, side) { + for (let off = 0, i = 0; i < view.children.length; i++) { + let child = view.children[i], end = off + child.length, next; + if ((side <= 0 || end == view.length || child.getSide() > 0 ? end >= pos : end > pos) && + (pos < end || i + 1 == view.children.length || (next = view.children[i + 1]).length || next.getSide() > 0)) { + let flatten = 0; + if (end == off) { + if (child.getSide() <= 0) + continue; + flatten = side = -child.getSide(); + } + let rect = child.coordsAt(Math.max(0, pos - off), side); + return flatten && rect ? flattenRect(rect, side < 0) : rect; + } + off = end; + } + let last = view.dom.lastChild; + if (!last) + return view.dom.getBoundingClientRect(); + let rects = clientRectsFor(last); + return rects[rects.length - 1] || null; + } + + function combineAttrs(source, target) { + for (let name in source) { + if (name == "class" && target.class) + target.class += " " + source.class; + else if (name == "style" && target.style) + target.style += ";" + source.style; + else + target[name] = source[name]; + } + return target; + } + function attrsEq(a, b) { + if (a == b) + return true; + if (!a || !b) + return false; + let keysA = Object.keys(a), keysB = Object.keys(b); + if (keysA.length != keysB.length) + return false; + for (let key of keysA) { + if (keysB.indexOf(key) == -1 || a[key] !== b[key]) + return false; + } + return true; + } + function updateAttrs(dom, prev, attrs) { + let changed = null; + if (prev) + for (let name in prev) + if (!(attrs && name in attrs)) + dom.removeAttribute(changed = name); + if (attrs) + for (let name in attrs) + if (!(prev && prev[name] == attrs[name])) + dom.setAttribute(changed = name, attrs[name]); + return !!changed; + } + + /** + Widgets added to the content are described by subclasses of this + class. Using a description object like that makes it possible to + delay creating of the DOM structure for a widget until it is + needed, and to avoid redrawing widgets even if the decorations + that define them are recreated. + */ + class WidgetType { + /** + Compare this instance to another instance of the same type. + (TypeScript can't express this, but only instances of the same + specific class will be passed to this method.) This is used to + avoid redrawing widgets when they are replaced by a new + decoration of the same type. The default implementation just + returns `false`, which will cause new instances of the widget to + always be redrawn. + */ + eq(widget) { return false; } + /** + Update a DOM element created by a widget of the same type (but + different, non-`eq` content) to reflect this widget. May return + true to indicate that it could update, false to indicate it + couldn't (in which case the widget will be redrawn). The default + implementation just returns false. + */ + updateDOM(dom) { return false; } + /** + @internal + */ + compare(other) { + return this == other || this.constructor == other.constructor && this.eq(other); + } + /** + The estimated height this widget will have, to be used when + estimating the height of content that hasn't been drawn. May + return -1 to indicate you don't know. The default implementation + returns -1. + */ + get estimatedHeight() { return -1; } + /** + Can be used to configure which kinds of events inside the widget + should be ignored by the editor. The default is to ignore all + events. + */ + ignoreEvent(event) { return true; } + /** + @internal + */ + get customView() { return null; } + /** + This is called when the an instance of the widget is removed + from the editor view. + */ + destroy(dom) { } + } + /** + The different types of blocks that can occur in an editor view. + */ + var BlockType = /*@__PURE__*/(function (BlockType) { + /** + A line of text. + */ + BlockType[BlockType["Text"] = 0] = "Text"; + /** + A block widget associated with the position after it. + */ + BlockType[BlockType["WidgetBefore"] = 1] = "WidgetBefore"; + /** + A block widget associated with the position before it. + */ + BlockType[BlockType["WidgetAfter"] = 2] = "WidgetAfter"; + /** + A block widget [replacing](https://codemirror.net/6/docs/ref/#view.Decoration^replace) a range of content. + */ + BlockType[BlockType["WidgetRange"] = 3] = "WidgetRange"; + return BlockType})(BlockType || (BlockType = {})); + /** + A decoration provides information on how to draw or style a piece + of content. You'll usually use it wrapped in a + [`Range`](https://codemirror.net/6/docs/ref/#state.Range), which adds a start and end position. + @nonabstract + */ + class Decoration extends RangeValue { + constructor( + /** + @internal + */ + startSide, + /** + @internal + */ + endSide, + /** + @internal + */ + widget, + /** + The config object used to create this decoration. You can + include additional properties in there to store metadata about + your decoration. + */ + spec) { + super(); + this.startSide = startSide; + this.endSide = endSide; + this.widget = widget; + this.spec = spec; + } + /** + @internal + */ + get heightRelevant() { return false; } + /** + Create a mark decoration, which influences the styling of the + content in its range. Nested mark decorations will cause nested + DOM elements to be created. Nesting order is determined by + precedence of the [facet](https://codemirror.net/6/docs/ref/#view.EditorView^decorations), with + the higher-precedence decorations creating the inner DOM nodes. + Such elements are split on line boundaries and on the boundaries + of lower-precedence decorations. + */ + static mark(spec) { + return new MarkDecoration(spec); + } + /** + Create a widget decoration, which displays a DOM element at the + given position. + */ + static widget(spec) { + let side = spec.side || 0, block = !!spec.block; + side += block ? (side > 0 ? 300000000 /* Side.BlockAfter */ : -400000000 /* Side.BlockBefore */) : (side > 0 ? 100000000 /* Side.InlineAfter */ : -100000000 /* Side.InlineBefore */); + return new PointDecoration(spec, side, side, block, spec.widget || null, false); + } + /** + Create a replace decoration which replaces the given range with + a widget, or simply hides it. + */ + static replace(spec) { + let block = !!spec.block, startSide, endSide; + if (spec.isBlockGap) { + startSide = -500000000 /* Side.GapStart */; + endSide = 400000000 /* Side.GapEnd */; + } + else { + let { start, end } = getInclusive(spec, block); + startSide = (start ? (block ? -300000000 /* Side.BlockIncStart */ : -1 /* Side.InlineIncStart */) : 500000000 /* Side.NonIncStart */) - 1; + endSide = (end ? (block ? 200000000 /* Side.BlockIncEnd */ : 1 /* Side.InlineIncEnd */) : -600000000 /* Side.NonIncEnd */) + 1; + } + return new PointDecoration(spec, startSide, endSide, block, spec.widget || null, true); + } + /** + Create a line decoration, which can add DOM attributes to the + line starting at the given position. + */ + static line(spec) { + return new LineDecoration(spec); + } + /** + Build a [`DecorationSet`](https://codemirror.net/6/docs/ref/#view.DecorationSet) from the given + decorated range or ranges. If the ranges aren't already sorted, + pass `true` for `sort` to make the library sort them for you. + */ + static set(of, sort = false) { + return RangeSet.of(of, sort); + } + /** + @internal + */ + hasHeight() { return this.widget ? this.widget.estimatedHeight > -1 : false; } + } + /** + The empty set of decorations. + */ + Decoration.none = RangeSet.empty; + class MarkDecoration extends Decoration { + constructor(spec) { + let { start, end } = getInclusive(spec); + super(start ? -1 /* Side.InlineIncStart */ : 500000000 /* Side.NonIncStart */, end ? 1 /* Side.InlineIncEnd */ : -600000000 /* Side.NonIncEnd */, null, spec); + this.tagName = spec.tagName || "span"; + this.class = spec.class || ""; + this.attrs = spec.attributes || null; + } + eq(other) { + return this == other || + other instanceof MarkDecoration && + this.tagName == other.tagName && + this.class == other.class && + attrsEq(this.attrs, other.attrs); + } + range(from, to = from) { + if (from >= to) + throw new RangeError("Mark decorations may not be empty"); + return super.range(from, to); + } + } + MarkDecoration.prototype.point = false; + class LineDecoration extends Decoration { + constructor(spec) { + super(-200000000 /* Side.Line */, -200000000 /* Side.Line */, null, spec); + } + eq(other) { + return other instanceof LineDecoration && attrsEq(this.spec.attributes, other.spec.attributes); + } + range(from, to = from) { + if (to != from) + throw new RangeError("Line decoration ranges must be zero-length"); + return super.range(from, to); + } + } + LineDecoration.prototype.mapMode = MapMode.TrackBefore; + LineDecoration.prototype.point = true; + class PointDecoration extends Decoration { + constructor(spec, startSide, endSide, block, widget, isReplace) { + super(startSide, endSide, widget, spec); + this.block = block; + this.isReplace = isReplace; + this.mapMode = !block ? MapMode.TrackDel : startSide <= 0 ? MapMode.TrackBefore : MapMode.TrackAfter; + } + // Only relevant when this.block == true + get type() { + return this.startSide < this.endSide ? BlockType.WidgetRange + : this.startSide <= 0 ? BlockType.WidgetBefore : BlockType.WidgetAfter; + } + get heightRelevant() { return this.block || !!this.widget && this.widget.estimatedHeight >= 5; } + eq(other) { + return other instanceof PointDecoration && + widgetsEq(this.widget, other.widget) && + this.block == other.block && + this.startSide == other.startSide && this.endSide == other.endSide; + } + range(from, to = from) { + if (this.isReplace && (from > to || (from == to && this.startSide > 0 && this.endSide <= 0))) + throw new RangeError("Invalid range for replacement decoration"); + if (!this.isReplace && to != from) + throw new RangeError("Widget decorations can only have zero-length ranges"); + return super.range(from, to); + } + } + PointDecoration.prototype.point = true; + function getInclusive(spec, block = false) { + let { inclusiveStart: start, inclusiveEnd: end } = spec; + if (start == null) + start = spec.inclusive; + if (end == null) + end = spec.inclusive; + return { start: start !== null && start !== void 0 ? start : block, end: end !== null && end !== void 0 ? end : block }; + } + function widgetsEq(a, b) { + return a == b || !!(a && b && a.compare(b)); + } + function addRange(from, to, ranges, margin = 0) { + let last = ranges.length - 1; + if (last >= 0 && ranges[last] + margin >= from) + ranges[last] = Math.max(ranges[last], to); + else + ranges.push(from, to); + } + + class LineView extends ContentView { + constructor() { + super(...arguments); + this.children = []; + this.length = 0; + this.prevAttrs = undefined; + this.attrs = null; + this.breakAfter = 0; + } + // Consumes source + merge(from, to, source, hasStart, openStart, openEnd) { + if (source) { + if (!(source instanceof LineView)) + return false; + if (!this.dom) + source.transferDOM(this); // Reuse source.dom when appropriate + } + if (hasStart) + this.setDeco(source ? source.attrs : null); + mergeChildrenInto(this, from, to, source ? source.children : [], openStart, openEnd); + return true; + } + split(at) { + let end = new LineView; + end.breakAfter = this.breakAfter; + if (this.length == 0) + return end; + let { i, off } = this.childPos(at); + if (off) { + end.append(this.children[i].split(off), 0); + this.children[i].merge(off, this.children[i].length, null, false, 0, 0); + i++; + } + for (let j = i; j < this.children.length; j++) + end.append(this.children[j], 0); + while (i > 0 && this.children[i - 1].length == 0) + this.children[--i].destroy(); + this.children.length = i; + this.markDirty(); + this.length = at; + return end; + } + transferDOM(other) { + if (!this.dom) + return; + this.markDirty(); + other.setDOM(this.dom); + other.prevAttrs = this.prevAttrs === undefined ? this.attrs : this.prevAttrs; + this.prevAttrs = undefined; + this.dom = null; + } + setDeco(attrs) { + if (!attrsEq(this.attrs, attrs)) { + if (this.dom) { + this.prevAttrs = this.attrs; + this.markDirty(); + } + this.attrs = attrs; + } + } + append(child, openStart) { + joinInlineInto(this, child, openStart); + } + // Only called when building a line view in ContentBuilder + addLineDeco(deco) { + let attrs = deco.spec.attributes, cls = deco.spec.class; + if (attrs) + this.attrs = combineAttrs(attrs, this.attrs || {}); + if (cls) + this.attrs = combineAttrs({ class: cls }, this.attrs || {}); + } + domAtPos(pos) { + return inlineDOMAtPos(this, pos); + } + reuseDOM(node) { + if (node.nodeName == "DIV") { + this.setDOM(node); + this.dirty |= 4 /* Dirty.Attrs */ | 2 /* Dirty.Node */; + } + } + sync(track) { + var _a; + if (!this.dom) { + this.setDOM(document.createElement("div")); + this.dom.className = "cm-line"; + this.prevAttrs = this.attrs ? null : undefined; + } + else if (this.dirty & 4 /* Dirty.Attrs */) { + clearAttributes(this.dom); + this.dom.className = "cm-line"; + this.prevAttrs = this.attrs ? null : undefined; + } + if (this.prevAttrs !== undefined) { + updateAttrs(this.dom, this.prevAttrs, this.attrs); + this.dom.classList.add("cm-line"); + this.prevAttrs = undefined; + } + super.sync(track); + let last = this.dom.lastChild; + while (last && ContentView.get(last) instanceof MarkView) + last = last.lastChild; + if (!last || !this.length || + last.nodeName != "BR" && ((_a = ContentView.get(last)) === null || _a === void 0 ? void 0 : _a.isEditable) == false && + (!browser.ios || !this.children.some(ch => ch instanceof TextView))) { + let hack = document.createElement("BR"); + hack.cmIgnore = true; + this.dom.appendChild(hack); + } + } + measureTextSize() { + if (this.children.length == 0 || this.length > 20) + return null; + let totalWidth = 0; + for (let child of this.children) { + if (!(child instanceof TextView) || /[^ -~]/.test(child.text)) + return null; + let rects = clientRectsFor(child.dom); + if (rects.length != 1) + return null; + totalWidth += rects[0].width; + } + return !totalWidth ? null : { + lineHeight: this.dom.getBoundingClientRect().height, + charWidth: totalWidth / this.length + }; + } + coordsAt(pos, side) { + return coordsInChildren(this, pos, side); + } + become(_other) { return false; } + get type() { return BlockType.Text; } + static find(docView, pos) { + for (let i = 0, off = 0; i < docView.children.length; i++) { + let block = docView.children[i], end = off + block.length; + if (end >= pos) { + if (block instanceof LineView) + return block; + if (end > pos) + break; + } + off = end + block.breakAfter; + } + return null; + } + } + class BlockWidgetView extends ContentView { + constructor(widget, length, type) { + super(); + this.widget = widget; + this.length = length; + this.type = type; + this.breakAfter = 0; + this.prevWidget = null; + } + merge(from, to, source, _takeDeco, openStart, openEnd) { + if (source && (!(source instanceof BlockWidgetView) || !this.widget.compare(source.widget) || + from > 0 && openStart <= 0 || to < this.length && openEnd <= 0)) + return false; + this.length = from + (source ? source.length : 0) + (this.length - to); + return true; + } + domAtPos(pos) { + return pos == 0 ? DOMPos.before(this.dom) : DOMPos.after(this.dom, pos == this.length); + } + split(at) { + let len = this.length - at; + this.length = at; + let end = new BlockWidgetView(this.widget, len, this.type); + end.breakAfter = this.breakAfter; + return end; + } + get children() { return noChildren; } + sync() { + if (!this.dom || !this.widget.updateDOM(this.dom)) { + if (this.dom && this.prevWidget) + this.prevWidget.destroy(this.dom); + this.prevWidget = null; + this.setDOM(this.widget.toDOM(this.editorView)); + this.dom.contentEditable = "false"; + } + } + get overrideDOMText() { + return this.parent ? this.parent.view.state.doc.slice(this.posAtStart, this.posAtEnd) : Text.empty; + } + domBoundsAround() { return null; } + become(other) { + if (other instanceof BlockWidgetView && other.type == this.type && + other.widget.constructor == this.widget.constructor) { + if (!other.widget.eq(this.widget)) + this.markDirty(true); + if (this.dom && !this.prevWidget) + this.prevWidget = this.widget; + this.widget = other.widget; + this.length = other.length; + this.breakAfter = other.breakAfter; + return true; + } + return false; + } + ignoreMutation() { return true; } + ignoreEvent(event) { return this.widget.ignoreEvent(event); } + destroy() { + super.destroy(); + if (this.dom) + this.widget.destroy(this.dom); + } + } + + class ContentBuilder { + constructor(doc, pos, end, disallowBlockEffectsFor) { + this.doc = doc; + this.pos = pos; + this.end = end; + this.disallowBlockEffectsFor = disallowBlockEffectsFor; + this.content = []; + this.curLine = null; + this.breakAtStart = 0; + this.pendingBuffer = 0 /* Buf.No */; + // Set to false directly after a widget that covers the position after it + this.atCursorPos = true; + this.openStart = -1; + this.openEnd = -1; + this.text = ""; + this.textOff = 0; + this.cursor = doc.iter(); + this.skip = pos; + } + posCovered() { + if (this.content.length == 0) + return !this.breakAtStart && this.doc.lineAt(this.pos).from != this.pos; + let last = this.content[this.content.length - 1]; + return !last.breakAfter && !(last instanceof BlockWidgetView && last.type == BlockType.WidgetBefore); + } + getLine() { + if (!this.curLine) { + this.content.push(this.curLine = new LineView); + this.atCursorPos = true; + } + return this.curLine; + } + flushBuffer(active) { + if (this.pendingBuffer) { + this.curLine.append(wrapMarks(new WidgetBufferView(-1), active), active.length); + this.pendingBuffer = 0 /* Buf.No */; + } + } + addBlockWidget(view) { + this.flushBuffer([]); + this.curLine = null; + this.content.push(view); + } + finish(openEnd) { + if (!openEnd) + this.flushBuffer([]); + else + this.pendingBuffer = 0 /* Buf.No */; + if (!this.posCovered()) + this.getLine(); + } + buildText(length, active, openStart) { + while (length > 0) { + if (this.textOff == this.text.length) { + let { value, lineBreak, done } = this.cursor.next(this.skip); + this.skip = 0; + if (done) + throw new Error("Ran out of text content when drawing inline views"); + if (lineBreak) { + if (!this.posCovered()) + this.getLine(); + if (this.content.length) + this.content[this.content.length - 1].breakAfter = 1; + else + this.breakAtStart = 1; + this.flushBuffer([]); + this.curLine = null; + length--; + continue; + } + else { + this.text = value; + this.textOff = 0; + } + } + let take = Math.min(this.text.length - this.textOff, length, 512 /* T.Chunk */); + this.flushBuffer(active.slice(0, openStart)); + this.getLine().append(wrapMarks(new TextView(this.text.slice(this.textOff, this.textOff + take)), active), openStart); + this.atCursorPos = true; + this.textOff += take; + length -= take; + openStart = 0; + } + } + span(from, to, active, openStart) { + this.buildText(to - from, active, openStart); + this.pos = to; + if (this.openStart < 0) + this.openStart = openStart; + } + point(from, to, deco, active, openStart, index) { + if (this.disallowBlockEffectsFor[index] && deco instanceof PointDecoration) { + if (deco.block) + throw new RangeError("Block decorations may not be specified via plugins"); + if (to > this.doc.lineAt(this.pos).to) + throw new RangeError("Decorations that replace line breaks may not be specified via plugins"); + } + let len = to - from; + if (deco instanceof PointDecoration) { + if (deco.block) { + let { type } = deco; + if (type == BlockType.WidgetAfter && !this.posCovered()) + this.getLine(); + this.addBlockWidget(new BlockWidgetView(deco.widget || new NullWidget("div"), len, type)); + } + else { + let view = WidgetView.create(deco.widget || new NullWidget("span"), len, deco.startSide); + let cursorBefore = this.atCursorPos && !view.isEditable && openStart <= active.length && (from < to || deco.startSide > 0); + let cursorAfter = !view.isEditable && (from < to || deco.startSide <= 0); + let line = this.getLine(); + if (this.pendingBuffer == 2 /* Buf.IfCursor */ && !cursorBefore) + this.pendingBuffer = 0 /* Buf.No */; + this.flushBuffer(active); + if (cursorBefore) { + line.append(wrapMarks(new WidgetBufferView(1), active), openStart); + openStart = active.length + Math.max(0, openStart - active.length); + } + line.append(wrapMarks(view, active), openStart); + this.atCursorPos = cursorAfter; + this.pendingBuffer = !cursorAfter ? 0 /* Buf.No */ : from < to ? 1 /* Buf.Yes */ : 2 /* Buf.IfCursor */; + } + } + else if (this.doc.lineAt(this.pos).from == this.pos) { // Line decoration + this.getLine().addLineDeco(deco); + } + if (len) { + // Advance the iterator past the replaced content + if (this.textOff + len <= this.text.length) { + this.textOff += len; + } + else { + this.skip += len - (this.text.length - this.textOff); + this.text = ""; + this.textOff = 0; + } + this.pos = to; + } + if (this.openStart < 0) + this.openStart = openStart; + } + static build(text, from, to, decorations, dynamicDecorationMap) { + let builder = new ContentBuilder(text, from, to, dynamicDecorationMap); + builder.openEnd = RangeSet.spans(decorations, from, to, builder); + if (builder.openStart < 0) + builder.openStart = builder.openEnd; + builder.finish(builder.openEnd); + return builder; + } + } + function wrapMarks(view, active) { + for (let mark of active) + view = new MarkView(mark, [view], view.length); + return view; + } + class NullWidget extends WidgetType { + constructor(tag) { + super(); + this.tag = tag; + } + eq(other) { return other.tag == this.tag; } + toDOM() { return document.createElement(this.tag); } + updateDOM(elt) { return elt.nodeName.toLowerCase() == this.tag; } + } + + const clickAddsSelectionRange = /*@__PURE__*/Facet.define(); + const dragMovesSelection$1 = /*@__PURE__*/Facet.define(); + const mouseSelectionStyle = /*@__PURE__*/Facet.define(); + const exceptionSink = /*@__PURE__*/Facet.define(); + const updateListener = /*@__PURE__*/Facet.define(); + const inputHandler$1 = /*@__PURE__*/Facet.define(); + const perLineTextDirection = /*@__PURE__*/Facet.define({ + combine: values => values.some(x => x) + }); + class ScrollTarget { + constructor(range, y = "nearest", x = "nearest", yMargin = 5, xMargin = 5) { + this.range = range; + this.y = y; + this.x = x; + this.yMargin = yMargin; + this.xMargin = xMargin; + } + map(changes) { + return changes.empty ? this : new ScrollTarget(this.range.map(changes), this.y, this.x, this.yMargin, this.xMargin); + } + } + const scrollIntoView$1 = /*@__PURE__*/StateEffect.define({ map: (t, ch) => t.map(ch) }); + /** + Log or report an unhandled exception in client code. Should + probably only be used by extension code that allows client code to + provide functions, and calls those functions in a context where an + exception can't be propagated to calling code in a reasonable way + (for example when in an event handler). + + Either calls a handler registered with + [`EditorView.exceptionSink`](https://codemirror.net/6/docs/ref/#view.EditorView^exceptionSink), + `window.onerror`, if defined, or `console.error` (in which case + it'll pass `context`, when given, as first argument). + */ + function logException(state, exception, context) { + let handler = state.facet(exceptionSink); + if (handler.length) + handler[0](exception); + else if (window.onerror) + window.onerror(String(exception), context, undefined, undefined, exception); + else if (context) + console.error(context + ":", exception); + else + console.error(exception); + } + const editable = /*@__PURE__*/Facet.define({ combine: values => values.length ? values[0] : true }); + let nextPluginID = 0; + const viewPlugin = /*@__PURE__*/Facet.define(); + /** + View plugins associate stateful values with a view. They can + influence the way the content is drawn, and are notified of things + that happen in the view. + */ + class ViewPlugin { + constructor( + /** + @internal + */ + id, + /** + @internal + */ + create, + /** + @internal + */ + domEventHandlers, buildExtensions) { + this.id = id; + this.create = create; + this.domEventHandlers = domEventHandlers; + this.extension = buildExtensions(this); + } + /** + Define a plugin from a constructor function that creates the + plugin's value, given an editor view. + */ + static define(create, spec) { + const { eventHandlers, provide, decorations: deco } = spec || {}; + return new ViewPlugin(nextPluginID++, create, eventHandlers, plugin => { + let ext = [viewPlugin.of(plugin)]; + if (deco) + ext.push(decorations.of(view => { + let pluginInst = view.plugin(plugin); + return pluginInst ? deco(pluginInst) : Decoration.none; + })); + if (provide) + ext.push(provide(plugin)); + return ext; + }); + } + /** + Create a plugin for a class whose constructor takes a single + editor view as argument. + */ + static fromClass(cls, spec) { + return ViewPlugin.define(view => new cls(view), spec); + } + } + class PluginInstance { + constructor(spec) { + this.spec = spec; + // When starting an update, all plugins have this field set to the + // update object, indicating they need to be updated. When finished + // updating, it is set to `false`. Retrieving a plugin that needs to + // be updated with `view.plugin` forces an eager update. + this.mustUpdate = null; + // This is null when the plugin is initially created, but + // initialized on the first update. + this.value = null; + } + update(view) { + if (!this.value) { + if (this.spec) { + try { + this.value = this.spec.create(view); + } + catch (e) { + logException(view.state, e, "CodeMirror plugin crashed"); + this.deactivate(); + } + } + } + else if (this.mustUpdate) { + let update = this.mustUpdate; + this.mustUpdate = null; + if (this.value.update) { + try { + this.value.update(update); + } + catch (e) { + logException(update.state, e, "CodeMirror plugin crashed"); + if (this.value.destroy) + try { + this.value.destroy(); + } + catch (_) { } + this.deactivate(); + } + } + } + return this; + } + destroy(view) { + var _a; + if ((_a = this.value) === null || _a === void 0 ? void 0 : _a.destroy) { + try { + this.value.destroy(); + } + catch (e) { + logException(view.state, e, "CodeMirror plugin crashed"); + } + } + } + deactivate() { + this.spec = this.value = null; + } + } + const editorAttributes = /*@__PURE__*/Facet.define(); + const contentAttributes = /*@__PURE__*/Facet.define(); + // Provide decorations + const decorations = /*@__PURE__*/Facet.define(); + const atomicRanges = /*@__PURE__*/Facet.define(); + const scrollMargins = /*@__PURE__*/Facet.define(); + const styleModule = /*@__PURE__*/Facet.define(); + class ChangedRange { + constructor(fromA, toA, fromB, toB) { + this.fromA = fromA; + this.toA = toA; + this.fromB = fromB; + this.toB = toB; + } + join(other) { + return new ChangedRange(Math.min(this.fromA, other.fromA), Math.max(this.toA, other.toA), Math.min(this.fromB, other.fromB), Math.max(this.toB, other.toB)); + } + addToSet(set) { + let i = set.length, me = this; + for (; i > 0; i--) { + let range = set[i - 1]; + if (range.fromA > me.toA) + continue; + if (range.toA < me.fromA) + break; + me = me.join(range); + set.splice(i - 1, 1); + } + set.splice(i, 0, me); + return set; + } + static extendWithRanges(diff, ranges) { + if (ranges.length == 0) + return diff; + let result = []; + for (let dI = 0, rI = 0, posA = 0, posB = 0;; dI++) { + let next = dI == diff.length ? null : diff[dI], off = posA - posB; + let end = next ? next.fromB : 1e9; + while (rI < ranges.length && ranges[rI] < end) { + let from = ranges[rI], to = ranges[rI + 1]; + let fromB = Math.max(posB, from), toB = Math.min(end, to); + if (fromB <= toB) + new ChangedRange(fromB + off, toB + off, fromB, toB).addToSet(result); + if (to > end) + break; + else + rI += 2; + } + if (!next) + return result; + new ChangedRange(next.fromA, next.toA, next.fromB, next.toB).addToSet(result); + posA = next.toA; + posB = next.toB; + } + } + } + /** + View [plugins](https://codemirror.net/6/docs/ref/#view.ViewPlugin) are given instances of this + class, which describe what happened, whenever the view is updated. + */ + class ViewUpdate { + constructor( + /** + The editor view that the update is associated with. + */ + view, + /** + The new editor state. + */ + state, + /** + The transactions involved in the update. May be empty. + */ + transactions) { + this.view = view; + this.state = state; + this.transactions = transactions; + /** + @internal + */ + this.flags = 0; + this.startState = view.state; + this.changes = ChangeSet.empty(this.startState.doc.length); + for (let tr of transactions) + this.changes = this.changes.compose(tr.changes); + let changedRanges = []; + this.changes.iterChangedRanges((fromA, toA, fromB, toB) => changedRanges.push(new ChangedRange(fromA, toA, fromB, toB))); + this.changedRanges = changedRanges; + let focus = view.hasFocus; + if (focus != view.inputState.notifiedFocused) { + view.inputState.notifiedFocused = focus; + this.flags |= 1 /* UpdateFlag.Focus */; + } + } + /** + @internal + */ + static create(view, state, transactions) { + return new ViewUpdate(view, state, transactions); + } + /** + Tells you whether the [viewport](https://codemirror.net/6/docs/ref/#view.EditorView.viewport) or + [visible ranges](https://codemirror.net/6/docs/ref/#view.EditorView.visibleRanges) changed in this + update. + */ + get viewportChanged() { + return (this.flags & 4 /* UpdateFlag.Viewport */) > 0; + } + /** + Indicates whether the height of a block element in the editor + changed in this update. + */ + get heightChanged() { + return (this.flags & 2 /* UpdateFlag.Height */) > 0; + } + /** + Returns true when the document was modified or the size of the + editor, or elements within the editor, changed. + */ + get geometryChanged() { + return this.docChanged || (this.flags & (8 /* UpdateFlag.Geometry */ | 2 /* UpdateFlag.Height */)) > 0; + } + /** + True when this update indicates a focus change. + */ + get focusChanged() { + return (this.flags & 1 /* UpdateFlag.Focus */) > 0; + } + /** + Whether the document changed in this update. + */ + get docChanged() { + return !this.changes.empty; + } + /** + Whether the selection was explicitly set in this update. + */ + get selectionSet() { + return this.transactions.some(tr => tr.selection); + } + /** + @internal + */ + get empty() { return this.flags == 0 && this.transactions.length == 0; } + } + + /** + Used to indicate [text direction](https://codemirror.net/6/docs/ref/#view.EditorView.textDirection). + */ + var Direction = /*@__PURE__*/(function (Direction) { + // (These are chosen to match the base levels, in bidi algorithm + // terms, of spans in that direction.) + /** + Left-to-right. + */ + Direction[Direction["LTR"] = 0] = "LTR"; + /** + Right-to-left. + */ + Direction[Direction["RTL"] = 1] = "RTL"; + return Direction})(Direction || (Direction = {})); + const LTR = Direction.LTR, RTL = Direction.RTL; + // Decode a string with each type encoded as log2(type) + function dec(str) { + let result = []; + for (let i = 0; i < str.length; i++) + result.push(1 << +str[i]); + return result; + } + // Character types for codepoints 0 to 0xf8 + const LowTypes = /*@__PURE__*/dec("88888888888888888888888888888888888666888888787833333333337888888000000000000000000000000008888880000000000000000000000000088888888888888888888888888888888888887866668888088888663380888308888800000000000000000000000800000000000000000000000000000008"); + // Character types for codepoints 0x600 to 0x6f9 + const ArabicTypes = /*@__PURE__*/dec("4444448826627288999999999992222222222222222222222222222222222222222222222229999999999999999999994444444444644222822222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222999999949999999229989999223333333333"); + const Brackets = /*@__PURE__*/Object.create(null), BracketStack = []; + // There's a lot more in + // https://www.unicode.org/Public/UCD/latest/ucd/BidiBrackets.txt, + // which are left out to keep code size down. + for (let p of ["()", "[]", "{}"]) { + let l = /*@__PURE__*/p.charCodeAt(0), r = /*@__PURE__*/p.charCodeAt(1); + Brackets[l] = r; + Brackets[r] = -l; + } + function charType(ch) { + return ch <= 0xf7 ? LowTypes[ch] : + 0x590 <= ch && ch <= 0x5f4 ? 2 /* T.R */ : + 0x600 <= ch && ch <= 0x6f9 ? ArabicTypes[ch - 0x600] : + 0x6ee <= ch && ch <= 0x8ac ? 4 /* T.AL */ : + 0x2000 <= ch && ch <= 0x200b ? 256 /* T.NI */ : + 0xfb50 <= ch && ch <= 0xfdff ? 4 /* T.AL */ : + ch == 0x200c ? 256 /* T.NI */ : 1 /* T.L */; + } + const BidiRE = /[\u0590-\u05f4\u0600-\u06ff\u0700-\u08ac\ufb50-\ufdff]/; + /** + Represents a contiguous range of text that has a single direction + (as in left-to-right or right-to-left). + */ + class BidiSpan { + /** + @internal + */ + constructor( + /** + The start of the span (relative to the start of the line). + */ + from, + /** + The end of the span. + */ + to, + /** + The ["bidi + level"](https://unicode.org/reports/tr9/#Basic_Display_Algorithm) + of the span (in this context, 0 means + left-to-right, 1 means right-to-left, 2 means left-to-right + number inside right-to-left text). + */ + level) { + this.from = from; + this.to = to; + this.level = level; + } + /** + The direction of this span. + */ + get dir() { return this.level % 2 ? RTL : LTR; } + /** + @internal + */ + side(end, dir) { return (this.dir == dir) == end ? this.to : this.from; } + /** + @internal + */ + static find(order, index, level, assoc) { + let maybe = -1; + for (let i = 0; i < order.length; i++) { + let span = order[i]; + if (span.from <= index && span.to >= index) { + if (span.level == level) + return i; + // When multiple spans match, if assoc != 0, take the one that + // covers that side, otherwise take the one with the minimum + // level. + if (maybe < 0 || (assoc != 0 ? (assoc < 0 ? span.from < index : span.to > index) : order[maybe].level > span.level)) + maybe = i; + } + } + if (maybe < 0) + throw new RangeError("Index out of range"); + return maybe; + } + } + // Reused array of character types + const types = []; + function computeOrder(line, direction) { + let len = line.length, outerType = direction == LTR ? 1 /* T.L */ : 2 /* T.R */, oppositeType = direction == LTR ? 2 /* T.R */ : 1 /* T.L */; + if (!line || outerType == 1 /* T.L */ && !BidiRE.test(line)) + return trivialOrder(len); + // 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. + // 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. + // (Left after this: L, R, EN, AN, ET, CS, NI) + for (let i = 0, prev = outerType, prevStrong = outerType; i < len; i++) { + let type = charType(line.charCodeAt(i)); + if (type == 512 /* T.NSM */) + type = prev; + else if (type == 8 /* T.EN */ && prevStrong == 4 /* T.AL */) + type = 16 /* T.AN */; + types[i] = type == 4 /* T.AL */ ? 2 /* T.R */ : type; + if (type & 7 /* T.Strong */) + prevStrong = type; + prev = type; + } + // W5. A sequence of European terminators adjacent to European + // numbers changes to all European numbers. + // W6. Otherwise, separators and terminators change to Other + // Neutral. + // 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. + // (Left after this: L, R, EN+AN, NI) + for (let i = 0, prev = outerType, prevStrong = outerType; i < len; i++) { + let type = types[i]; + if (type == 128 /* T.CS */) { + if (i < len - 1 && prev == types[i + 1] && (prev & 24 /* T.Num */)) + type = types[i] = prev; + else + types[i] = 256 /* T.NI */; + } + else if (type == 64 /* T.ET */) { + let end = i + 1; + while (end < len && types[end] == 64 /* T.ET */) + end++; + let replace = (i && prev == 8 /* T.EN */) || (end < len && types[end] == 8 /* T.EN */) ? (prevStrong == 1 /* T.L */ ? 1 /* T.L */ : 8 /* T.EN */) : 256 /* T.NI */; + for (let j = i; j < end; j++) + types[j] = replace; + i = end - 1; + } + else if (type == 8 /* T.EN */ && prevStrong == 1 /* T.L */) { + types[i] = 1 /* T.L */; + } + prev = type; + if (type & 7 /* T.Strong */) + prevStrong = type; + } + // N0. Process bracket pairs in an isolating run sequence + // sequentially in the logical order of the text positions of the + // opening paired brackets using the logic given below. Within this + // scope, bidirectional types EN and AN are treated as R. + for (let i = 0, sI = 0, context = 0, ch, br, type; i < len; i++) { + // Keeps [startIndex, type, strongSeen] triples for each open + // bracket on BracketStack. + if (br = Brackets[ch = line.charCodeAt(i)]) { + if (br < 0) { // Closing bracket + for (let sJ = sI - 3; sJ >= 0; sJ -= 3) { + if (BracketStack[sJ + 1] == -br) { + let flags = BracketStack[sJ + 2]; + let type = (flags & 2 /* Bracketed.EmbedInside */) ? outerType : + !(flags & 4 /* Bracketed.OppositeInside */) ? 0 : + (flags & 1 /* Bracketed.OppositeBefore */) ? oppositeType : outerType; + if (type) + types[i] = types[BracketStack[sJ]] = type; + sI = sJ; + break; + } + } + } + else if (BracketStack.length == 189 /* Bracketed.MaxDepth */) { + break; + } + else { + BracketStack[sI++] = i; + BracketStack[sI++] = ch; + BracketStack[sI++] = context; + } + } + else if ((type = types[i]) == 2 /* T.R */ || type == 1 /* T.L */) { + let embed = type == outerType; + context = embed ? 0 : 1 /* Bracketed.OppositeBefore */; + for (let sJ = sI - 3; sJ >= 0; sJ -= 3) { + let cur = BracketStack[sJ + 2]; + if (cur & 2 /* Bracketed.EmbedInside */) + break; + if (embed) { + BracketStack[sJ + 2] |= 2 /* Bracketed.EmbedInside */; + } + else { + if (cur & 4 /* Bracketed.OppositeInside */) + break; + BracketStack[sJ + 2] |= 4 /* Bracketed.OppositeInside */; + } + } + } + } + // 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. + // (Left after this: L, R, EN+AN) + for (let i = 0; i < len; i++) { + if (types[i] == 256 /* T.NI */) { + let end = i + 1; + while (end < len && types[end] == 256 /* T.NI */) + end++; + let beforeL = (i ? types[i - 1] : outerType) == 1 /* T.L */; + let afterL = (end < len ? types[end] : outerType) == 1 /* T.L */; + let replace = beforeL == afterL ? (beforeL ? 1 /* T.L */ : 2 /* T.R */) : outerType; + for (let j = i; j < end; j++) + types[j] = replace; + i = end - 1; + } + } + // Here we depart from the documented algorithm, in order to avoid + // building up an actual levels array. Since there are only three + // levels (0, 1, 2) in an implementation that doesn't take + // explicit embedding into account, we can build up the order on + // the fly, without following the level-based algorithm. + let order = []; + if (outerType == 1 /* T.L */) { + for (let i = 0; i < len;) { + let start = i, rtl = types[i++] != 1 /* T.L */; + while (i < len && rtl == (types[i] != 1 /* T.L */)) + i++; + if (rtl) { + for (let j = i; j > start;) { + let end = j, l = types[--j] != 2 /* T.R */; + while (j > start && l == (types[j - 1] != 2 /* T.R */)) + j--; + order.push(new BidiSpan(j, end, l ? 2 : 1)); + } + } + else { + order.push(new BidiSpan(start, i, 0)); + } + } + } + else { + for (let i = 0; i < len;) { + let start = i, rtl = types[i++] == 2 /* T.R */; + while (i < len && rtl == (types[i] == 2 /* T.R */)) + i++; + order.push(new BidiSpan(start, i, rtl ? 1 : 2)); + } + } + return order; + } + function trivialOrder(length) { + return [new BidiSpan(0, length, 0)]; + } + let movedOver = ""; + function moveVisually(line, order, dir, start, forward) { + var _a; + let startIndex = start.head - line.from, spanI = -1; + if (startIndex == 0) { + if (!forward || !line.length) + return null; + if (order[0].level != dir) { + startIndex = order[0].side(false, dir); + spanI = 0; + } + } + else if (startIndex == line.length) { + if (forward) + return null; + let last = order[order.length - 1]; + if (last.level != dir) { + startIndex = last.side(true, dir); + spanI = order.length - 1; + } + } + if (spanI < 0) + spanI = BidiSpan.find(order, startIndex, (_a = start.bidiLevel) !== null && _a !== void 0 ? _a : -1, start.assoc); + let span = order[spanI]; + // End of span. (But not end of line--that was checked for above.) + if (startIndex == span.side(forward, dir)) { + span = order[spanI += forward ? 1 : -1]; + startIndex = span.side(!forward, dir); + } + let indexForward = forward == (span.dir == dir); + let nextIndex = findClusterBreak(line.text, startIndex, indexForward); + movedOver = line.text.slice(Math.min(startIndex, nextIndex), Math.max(startIndex, nextIndex)); + if (nextIndex != span.side(forward, dir)) + return EditorSelection.cursor(nextIndex + line.from, indexForward ? -1 : 1, span.level); + let nextSpan = spanI == (forward ? order.length - 1 : 0) ? null : order[spanI + (forward ? 1 : -1)]; + if (!nextSpan && span.level != dir) + return EditorSelection.cursor(forward ? line.to : line.from, forward ? -1 : 1, dir); + if (nextSpan && nextSpan.level < span.level) + return EditorSelection.cursor(nextSpan.side(!forward, dir) + line.from, forward ? 1 : -1, nextSpan.level); + return EditorSelection.cursor(nextIndex + line.from, forward ? -1 : 1, span.level); + } + + const LineBreakPlaceholder = "\uffff"; + class DOMReader { + constructor(points, state) { + this.points = points; + this.text = ""; + this.lineSeparator = state.facet(EditorState.lineSeparator); + } + append(text) { + this.text += text; + } + lineBreak() { + this.text += LineBreakPlaceholder; + } + readRange(start, end) { + if (!start) + return this; + let parent = start.parentNode; + for (let cur = start;;) { + this.findPointBefore(parent, cur); + this.readNode(cur); + let next = cur.nextSibling; + if (next == end) + break; + let view = ContentView.get(cur), nextView = ContentView.get(next); + if (view && nextView ? view.breakAfter : + (view ? view.breakAfter : isBlockElement(cur)) || + (isBlockElement(next) && (cur.nodeName != "BR" || cur.cmIgnore))) + this.lineBreak(); + cur = next; + } + this.findPointBefore(parent, end); + return this; + } + readTextNode(node) { + let text = node.nodeValue; + for (let point of this.points) + if (point.node == node) + point.pos = this.text.length + Math.min(point.offset, text.length); + for (let off = 0, re = this.lineSeparator ? null : /\r\n?|\n/g;;) { + let nextBreak = -1, breakSize = 1, m; + if (this.lineSeparator) { + nextBreak = text.indexOf(this.lineSeparator, off); + breakSize = this.lineSeparator.length; + } + else if (m = re.exec(text)) { + nextBreak = m.index; + breakSize = m[0].length; + } + this.append(text.slice(off, nextBreak < 0 ? text.length : nextBreak)); + if (nextBreak < 0) + break; + this.lineBreak(); + if (breakSize > 1) + for (let point of this.points) + if (point.node == node && point.pos > this.text.length) + point.pos -= breakSize - 1; + off = nextBreak + breakSize; + } + } + readNode(node) { + if (node.cmIgnore) + return; + let view = ContentView.get(node); + let fromView = view && view.overrideDOMText; + if (fromView != null) { + this.findPointInside(node, fromView.length); + for (let i = fromView.iter(); !i.next().done;) { + if (i.lineBreak) + this.lineBreak(); + else + this.append(i.value); + } + } + else if (node.nodeType == 3) { + this.readTextNode(node); + } + else if (node.nodeName == "BR") { + if (node.nextSibling) + this.lineBreak(); + } + else if (node.nodeType == 1) { + this.readRange(node.firstChild, null); + } + } + findPointBefore(node, next) { + for (let point of this.points) + if (point.node == node && node.childNodes[point.offset] == next) + point.pos = this.text.length; + } + findPointInside(node, maxLen) { + for (let point of this.points) + if (node.nodeType == 3 ? point.node == node : node.contains(point.node)) + point.pos = this.text.length + Math.min(maxLen, point.offset); + } + } + function isBlockElement(node) { + return node.nodeType == 1 && /^(DIV|P|LI|UL|OL|BLOCKQUOTE|DD|DT|H\d|SECTION|PRE)$/.test(node.nodeName); + } + class DOMPoint { + constructor(node, offset) { + this.node = node; + this.offset = offset; + this.pos = -1; + } + } + + class DocView extends ContentView { + constructor(view) { + super(); + this.view = view; + this.compositionDeco = Decoration.none; + this.decorations = []; + this.dynamicDecorationMap = []; + // Track a minimum width for the editor. When measuring sizes in + // measureVisibleLineHeights, this is updated to point at the width + // of a given element and its extent in the document. When a change + // happens in that range, these are reset. That way, once we've seen + // a line/element of a given length, we keep the editor wide enough + // to fit at least that element, until it is changed, at which point + // we forget it again. + this.minWidth = 0; + this.minWidthFrom = 0; + this.minWidthTo = 0; + // Track whether the DOM selection was set in a lossy way, so that + // we don't mess it up when reading it back it + this.impreciseAnchor = null; + this.impreciseHead = null; + this.forceSelection = false; + // Used by the resize observer to ignore resizes that we caused + // ourselves + this.lastUpdate = Date.now(); + this.setDOM(view.contentDOM); + this.children = [new LineView]; + this.children[0].setParent(this); + this.updateDeco(); + this.updateInner([new ChangedRange(0, 0, 0, view.state.doc.length)], 0); + } + get editorView() { return this.view; } + get length() { return this.view.state.doc.length; } + // Update the document view to a given state. scrollIntoView can be + // used as a hint to compute a new viewport that includes that + // position, if we know the editor is going to scroll that position + // into view. + update(update) { + let changedRanges = update.changedRanges; + if (this.minWidth > 0 && changedRanges.length) { + if (!changedRanges.every(({ fromA, toA }) => toA < this.minWidthFrom || fromA > this.minWidthTo)) { + this.minWidth = this.minWidthFrom = this.minWidthTo = 0; + } + else { + this.minWidthFrom = update.changes.mapPos(this.minWidthFrom, 1); + this.minWidthTo = update.changes.mapPos(this.minWidthTo, 1); + } + } + if (this.view.inputState.composing < 0) + this.compositionDeco = Decoration.none; + else if (update.transactions.length || this.dirty) + this.compositionDeco = computeCompositionDeco(this.view, update.changes); + // When the DOM nodes around the selection are moved to another + // parent, Chrome sometimes reports a different selection through + // getSelection than the one that it actually shows to the user. + // This forces a selection update when lines are joined to work + // around that. Issue #54 + if ((browser.ie || browser.chrome) && !this.compositionDeco.size && update && + update.state.doc.lines != update.startState.doc.lines) + this.forceSelection = true; + let prevDeco = this.decorations, deco = this.updateDeco(); + let decoDiff = findChangedDeco(prevDeco, deco, update.changes); + changedRanges = ChangedRange.extendWithRanges(changedRanges, decoDiff); + if (this.dirty == 0 /* Dirty.Not */ && changedRanges.length == 0) { + return false; + } + else { + this.updateInner(changedRanges, update.startState.doc.length); + if (update.transactions.length) + this.lastUpdate = Date.now(); + return true; + } + } + // Used by update and the constructor do perform the actual DOM + // update + updateInner(changes, oldLength) { + this.view.viewState.mustMeasureContent = true; + this.updateChildren(changes, oldLength); + let { observer } = this.view; + observer.ignore(() => { + // Lock the height during redrawing, since Chrome sometimes + // messes with the scroll position during DOM mutation (though + // no relayout is triggered and I cannot imagine how it can + // recompute the scroll position without a layout) + this.dom.style.height = this.view.viewState.contentHeight + "px"; + this.dom.style.flexBasis = this.minWidth ? this.minWidth + "px" : ""; + // Chrome will sometimes, when DOM mutations occur directly + // around the selection, get confused and report a different + // selection from the one it displays (issue #218). This tries + // to detect that situation. + let track = browser.chrome || browser.ios ? { node: observer.selectionRange.focusNode, written: false } : undefined; + this.sync(track); + this.dirty = 0 /* Dirty.Not */; + if (track && (track.written || observer.selectionRange.focusNode != track.node)) + this.forceSelection = true; + this.dom.style.height = ""; + }); + let gaps = []; + if (this.view.viewport.from || this.view.viewport.to < this.view.state.doc.length) + for (let child of this.children) + if (child instanceof BlockWidgetView && child.widget instanceof BlockGapWidget) + gaps.push(child.dom); + observer.updateGaps(gaps); + } + updateChildren(changes, oldLength) { + let cursor = this.childCursor(oldLength); + for (let i = changes.length - 1;; i--) { + let next = i >= 0 ? changes[i] : null; + if (!next) + break; + let { fromA, toA, fromB, toB } = next; + let { content, breakAtStart, openStart, openEnd } = ContentBuilder.build(this.view.state.doc, fromB, toB, this.decorations, this.dynamicDecorationMap); + let { i: toI, off: toOff } = cursor.findPos(toA, 1); + let { i: fromI, off: fromOff } = cursor.findPos(fromA, -1); + replaceRange(this, fromI, fromOff, toI, toOff, content, breakAtStart, openStart, openEnd); + } + } + // Sync the DOM selection to this.state.selection + updateSelection(mustRead = false, fromPointer = false) { + if (mustRead || !this.view.observer.selectionRange.focusNode) + this.view.observer.readSelectionRange(); + if (!(fromPointer || this.mayControlSelection())) + return; + let force = this.forceSelection; + this.forceSelection = false; + let main = this.view.state.selection.main; + // FIXME need to handle the case where the selection falls inside a block range + let anchor = this.domAtPos(main.anchor); + let head = main.empty ? anchor : this.domAtPos(main.head); + // Always reset on Firefox when next to an uneditable node to + // avoid invisible cursor bugs (#111) + if (browser.gecko && main.empty && betweenUneditable(anchor)) { + let dummy = document.createTextNode(""); + this.view.observer.ignore(() => anchor.node.insertBefore(dummy, anchor.node.childNodes[anchor.offset] || null)); + anchor = head = new DOMPos(dummy, 0); + force = true; + } + let domSel = this.view.observer.selectionRange; + // If the selection is already here, or in an equivalent position, don't touch it + if (force || !domSel.focusNode || + !isEquivalentPosition(anchor.node, anchor.offset, domSel.anchorNode, domSel.anchorOffset) || + !isEquivalentPosition(head.node, head.offset, domSel.focusNode, domSel.focusOffset)) { + this.view.observer.ignore(() => { + // Chrome Android will hide the virtual keyboard when tapping + // inside an uneditable node, and not bring it back when we + // move the cursor to its proper position. This tries to + // restore the keyboard by cycling focus. + if (browser.android && browser.chrome && this.dom.contains(domSel.focusNode) && + inUneditable(domSel.focusNode, this.dom)) { + this.dom.blur(); + this.dom.focus({ preventScroll: true }); + } + let rawSel = getSelection(this.view.root); + if (!rawSel) ; + else if (main.empty) { + // Work around https://bugzilla.mozilla.org/show_bug.cgi?id=1612076 + if (browser.gecko) { + let nextTo = nextToUneditable(anchor.node, anchor.offset); + if (nextTo && nextTo != (1 /* NextTo.Before */ | 2 /* NextTo.After */)) { + let text = nearbyTextNode(anchor.node, anchor.offset, nextTo == 1 /* NextTo.Before */ ? 1 : -1); + if (text) + anchor = new DOMPos(text, nextTo == 1 /* NextTo.Before */ ? 0 : text.nodeValue.length); + } + } + rawSel.collapse(anchor.node, anchor.offset); + if (main.bidiLevel != null && domSel.cursorBidiLevel != null) + domSel.cursorBidiLevel = main.bidiLevel; + } + else if (rawSel.extend) { + // Selection.extend can be used to create an 'inverted' selection + // (one where the focus is before the anchor), but not all + // browsers support it yet. + rawSel.collapse(anchor.node, anchor.offset); + // Safari will ignore the call above when the editor is + // hidden, and then raise an error on the call to extend + // (#940). + try { + rawSel.extend(head.node, head.offset); + } + catch (_) { } + } + else { + // Primitive (IE) way + let range = document.createRange(); + if (main.anchor > main.head) + [anchor, head] = [head, anchor]; + range.setEnd(head.node, head.offset); + range.setStart(anchor.node, anchor.offset); + rawSel.removeAllRanges(); + rawSel.addRange(range); + } + }); + this.view.observer.setSelectionRange(anchor, head); + } + this.impreciseAnchor = anchor.precise ? null : new DOMPos(domSel.anchorNode, domSel.anchorOffset); + this.impreciseHead = head.precise ? null : new DOMPos(domSel.focusNode, domSel.focusOffset); + } + enforceCursorAssoc() { + if (this.compositionDeco.size) + return; + let cursor = this.view.state.selection.main; + let sel = getSelection(this.view.root); + if (!sel || !cursor.empty || !cursor.assoc || !sel.modify) + return; + let line = LineView.find(this, cursor.head); + if (!line) + return; + let lineStart = line.posAtStart; + if (cursor.head == lineStart || cursor.head == lineStart + line.length) + return; + let before = this.coordsAt(cursor.head, -1), after = this.coordsAt(cursor.head, 1); + if (!before || !after || before.bottom > after.top) + return; + let dom = this.domAtPos(cursor.head + cursor.assoc); + sel.collapse(dom.node, dom.offset); + sel.modify("move", cursor.assoc < 0 ? "forward" : "backward", "lineboundary"); + } + mayControlSelection() { + let active = this.view.root.activeElement; + return active == this.dom || + hasSelection(this.dom, this.view.observer.selectionRange) && !(active && this.dom.contains(active)); + } + nearest(dom) { + for (let cur = dom; cur;) { + let domView = ContentView.get(cur); + if (domView && domView.rootView == this) + return domView; + cur = cur.parentNode; + } + return null; + } + posFromDOM(node, offset) { + let view = this.nearest(node); + if (!view) + throw new RangeError("Trying to find position for a DOM position outside of the document"); + return view.localPosFromDOM(node, offset) + view.posAtStart; + } + domAtPos(pos) { + let { i, off } = this.childCursor().findPos(pos, -1); + for (; i < this.children.length - 1;) { + let child = this.children[i]; + if (off < child.length || child instanceof LineView) + break; + i++; + off = 0; + } + return this.children[i].domAtPos(off); + } + coordsAt(pos, side) { + for (let off = this.length, i = this.children.length - 1;; i--) { + let child = this.children[i], start = off - child.breakAfter - child.length; + if (pos > start || + (pos == start && child.type != BlockType.WidgetBefore && child.type != BlockType.WidgetAfter && + (!i || side == 2 || this.children[i - 1].breakAfter || + (this.children[i - 1].type == BlockType.WidgetBefore && side > -2)))) + return child.coordsAt(pos - start, side); + off = start; + } + } + measureVisibleLineHeights(viewport) { + let result = [], { from, to } = viewport; + let contentWidth = this.view.contentDOM.clientWidth; + let isWider = contentWidth > Math.max(this.view.scrollDOM.clientWidth, this.minWidth) + 1; + let widest = -1, ltr = this.view.textDirection == Direction.LTR; + for (let pos = 0, i = 0; i < this.children.length; i++) { + let child = this.children[i], end = pos + child.length; + if (end > to) + break; + if (pos >= from) { + let childRect = child.dom.getBoundingClientRect(); + result.push(childRect.height); + if (isWider) { + let last = child.dom.lastChild; + let rects = last ? clientRectsFor(last) : []; + if (rects.length) { + let rect = rects[rects.length - 1]; + let width = ltr ? rect.right - childRect.left : childRect.right - rect.left; + if (width > widest) { + widest = width; + this.minWidth = contentWidth; + this.minWidthFrom = pos; + this.minWidthTo = end; + } + } + } + } + pos = end + child.breakAfter; + } + return result; + } + textDirectionAt(pos) { + let { i } = this.childPos(pos, 1); + return getComputedStyle(this.children[i].dom).direction == "rtl" ? Direction.RTL : Direction.LTR; + } + measureTextSize() { + for (let child of this.children) { + if (child instanceof LineView) { + let measure = child.measureTextSize(); + if (measure) + return measure; + } + } + // If no workable line exists, force a layout of a measurable element + let dummy = document.createElement("div"), lineHeight, charWidth; + dummy.className = "cm-line"; + dummy.style.width = "99999px"; + dummy.textContent = "abc def ghi jkl mno pqr stu"; + this.view.observer.ignore(() => { + this.dom.appendChild(dummy); + let rect = clientRectsFor(dummy.firstChild)[0]; + lineHeight = dummy.getBoundingClientRect().height; + charWidth = rect ? rect.width / 27 : 7; + dummy.remove(); + }); + return { lineHeight, charWidth }; + } + childCursor(pos = this.length) { + // Move back to start of last element when possible, so that + // `ChildCursor.findPos` doesn't have to deal with the edge case + // of being after the last element. + let i = this.children.length; + if (i) + pos -= this.children[--i].length; + return new ChildCursor(this.children, pos, i); + } + computeBlockGapDeco() { + let deco = [], vs = this.view.viewState; + for (let pos = 0, i = 0;; i++) { + let next = i == vs.viewports.length ? null : vs.viewports[i]; + let end = next ? next.from - 1 : this.length; + if (end > pos) { + let height = vs.lineBlockAt(end).bottom - vs.lineBlockAt(pos).top; + deco.push(Decoration.replace({ + widget: new BlockGapWidget(height), + block: true, + inclusive: true, + isBlockGap: true, + }).range(pos, end)); + } + if (!next) + break; + pos = next.to + 1; + } + return Decoration.set(deco); + } + updateDeco() { + let allDeco = this.view.state.facet(decorations).map((d, i) => { + let dynamic = this.dynamicDecorationMap[i] = typeof d == "function"; + return dynamic ? d(this.view) : d; + }); + for (let i = allDeco.length; i < allDeco.length + 3; i++) + this.dynamicDecorationMap[i] = false; + return this.decorations = [ + ...allDeco, + this.compositionDeco, + this.computeBlockGapDeco(), + this.view.viewState.lineGapDeco + ]; + } + scrollIntoView(target) { + let { range } = target; + let rect = this.coordsAt(range.head, range.empty ? range.assoc : range.head > range.anchor ? -1 : 1), other; + if (!rect) + return; + if (!range.empty && (other = this.coordsAt(range.anchor, range.anchor > range.head ? -1 : 1))) + rect = { left: Math.min(rect.left, other.left), top: Math.min(rect.top, other.top), + right: Math.max(rect.right, other.right), bottom: Math.max(rect.bottom, other.bottom) }; + let mLeft = 0, mRight = 0, mTop = 0, mBottom = 0; + for (let margins of this.view.state.facet(scrollMargins).map(f => f(this.view))) + if (margins) { + let { left, right, top, bottom } = margins; + if (left != null) + mLeft = Math.max(mLeft, left); + if (right != null) + mRight = Math.max(mRight, right); + if (top != null) + mTop = Math.max(mTop, top); + if (bottom != null) + mBottom = Math.max(mBottom, bottom); + } + let targetRect = { + left: rect.left - mLeft, top: rect.top - mTop, + right: rect.right + mRight, bottom: rect.bottom + mBottom + }; + scrollRectIntoView(this.view.scrollDOM, targetRect, range.head < range.anchor ? -1 : 1, target.x, target.y, target.xMargin, target.yMargin, this.view.textDirection == Direction.LTR); + } + } + function betweenUneditable(pos) { + return pos.node.nodeType == 1 && pos.node.firstChild && + (pos.offset == 0 || pos.node.childNodes[pos.offset - 1].contentEditable == "false") && + (pos.offset == pos.node.childNodes.length || pos.node.childNodes[pos.offset].contentEditable == "false"); + } + class BlockGapWidget extends WidgetType { + constructor(height) { + super(); + this.height = height; + } + toDOM() { + let elt = document.createElement("div"); + this.updateDOM(elt); + return elt; + } + eq(other) { return other.height == this.height; } + updateDOM(elt) { + elt.style.height = this.height + "px"; + return true; + } + get estimatedHeight() { return this.height; } + } + function compositionSurroundingNode(view) { + let sel = view.observer.selectionRange; + let textNode = sel.focusNode && nearbyTextNode(sel.focusNode, sel.focusOffset, 0); + if (!textNode) + return null; + let cView = view.docView.nearest(textNode); + if (!cView) + return null; + if (cView instanceof LineView) { + let topNode = textNode; + while (topNode.parentNode != cView.dom) + topNode = topNode.parentNode; + let prev = topNode.previousSibling; + while (prev && !ContentView.get(prev)) + prev = prev.previousSibling; + let pos = prev ? ContentView.get(prev).posAtEnd : cView.posAtStart; + return { from: pos, to: pos, node: topNode, text: textNode }; + } + else { + for (;;) { + let { parent } = cView; + if (!parent) + return null; + if (parent instanceof LineView) + break; + cView = parent; + } + let from = cView.posAtStart; + return { from, to: from + cView.length, node: cView.dom, text: textNode }; + } + } + function computeCompositionDeco(view, changes) { + let surrounding = compositionSurroundingNode(view); + if (!surrounding) + return Decoration.none; + let { from, to, node, text: textNode } = surrounding; + let newFrom = changes.mapPos(from, 1), newTo = Math.max(newFrom, changes.mapPos(to, -1)); + let { state } = view, text = node.nodeType == 3 ? node.nodeValue : + new DOMReader([], state).readRange(node.firstChild, null).text; + if (newTo - newFrom < text.length) { + if (state.doc.sliceString(newFrom, Math.min(state.doc.length, newFrom + text.length), LineBreakPlaceholder) == text) + newTo = newFrom + text.length; + else if (state.doc.sliceString(Math.max(0, newTo - text.length), newTo, LineBreakPlaceholder) == text) + newFrom = newTo - text.length; + else + return Decoration.none; + } + else if (state.doc.sliceString(newFrom, newTo, LineBreakPlaceholder) != text) { + return Decoration.none; + } + let topView = ContentView.get(node); + if (topView instanceof CompositionView) + topView = topView.widget.topView; + else if (topView) + topView.parent = null; + return Decoration.set(Decoration.replace({ widget: new CompositionWidget(node, textNode, topView), inclusive: true }) + .range(newFrom, newTo)); + } + class CompositionWidget extends WidgetType { + constructor(top, text, topView) { + super(); + this.top = top; + this.text = text; + this.topView = topView; + } + eq(other) { return this.top == other.top && this.text == other.text; } + toDOM() { return this.top; } + ignoreEvent() { return false; } + get customView() { return CompositionView; } + } + function nearbyTextNode(node, offset, side) { + for (;;) { + if (node.nodeType == 3) + return node; + if (node.nodeType == 1 && offset > 0 && side <= 0) { + node = node.childNodes[offset - 1]; + offset = maxOffset(node); + } + else if (node.nodeType == 1 && offset < node.childNodes.length && side >= 0) { + node = node.childNodes[offset]; + offset = 0; + } + else { + return null; + } + } + } + function nextToUneditable(node, offset) { + if (node.nodeType != 1) + return 0; + return (offset && node.childNodes[offset - 1].contentEditable == "false" ? 1 /* NextTo.Before */ : 0) | + (offset < node.childNodes.length && node.childNodes[offset].contentEditable == "false" ? 2 /* NextTo.After */ : 0); + } + class DecorationComparator$1 { + constructor() { + this.changes = []; + } + compareRange(from, to) { addRange(from, to, this.changes); } + comparePoint(from, to) { addRange(from, to, this.changes); } + } + function findChangedDeco(a, b, diff) { + let comp = new DecorationComparator$1; + RangeSet.compare(a, b, diff, comp); + return comp.changes; + } + function inUneditable(node, inside) { + for (let cur = node; cur && cur != inside; cur = cur.assignedSlot || cur.parentNode) { + if (cur.nodeType == 1 && cur.contentEditable == 'false') { + return true; + } + } + return false; + } + + function groupAt(state, pos, bias = 1) { + let categorize = state.charCategorizer(pos); + let line = state.doc.lineAt(pos), linePos = pos - line.from; + if (line.length == 0) + return EditorSelection.cursor(pos); + if (linePos == 0) + bias = 1; + else if (linePos == line.length) + bias = -1; + let from = linePos, to = linePos; + if (bias < 0) + from = findClusterBreak(line.text, linePos, false); + else + to = findClusterBreak(line.text, linePos); + let cat = categorize(line.text.slice(from, to)); + while (from > 0) { + let prev = findClusterBreak(line.text, from, false); + if (categorize(line.text.slice(prev, from)) != cat) + break; + from = prev; + } + while (to < line.length) { + let next = findClusterBreak(line.text, to); + if (categorize(line.text.slice(to, next)) != cat) + break; + to = next; + } + return EditorSelection.range(from + line.from, to + line.from); + } + // Search the DOM for the {node, offset} position closest to the given + // coordinates. Very inefficient and crude, but can usually be avoided + // by calling caret(Position|Range)FromPoint instead. + function getdx(x, rect) { + return rect.left > x ? rect.left - x : Math.max(0, x - rect.right); + } + function getdy(y, rect) { + return rect.top > y ? rect.top - y : Math.max(0, y - rect.bottom); + } + function yOverlap(a, b) { + return a.top < b.bottom - 1 && a.bottom > b.top + 1; + } + function upTop(rect, top) { + return top < rect.top ? { top, left: rect.left, right: rect.right, bottom: rect.bottom } : rect; + } + function upBot(rect, bottom) { + return bottom > rect.bottom ? { top: rect.top, left: rect.left, right: rect.right, bottom } : rect; + } + function domPosAtCoords(parent, x, y) { + let closest, closestRect, closestX, closestY, closestOverlap = false; + let above, below, aboveRect, belowRect; + for (let child = parent.firstChild; child; child = child.nextSibling) { + let rects = clientRectsFor(child); + for (let i = 0; i < rects.length; i++) { + let rect = rects[i]; + if (closestRect && yOverlap(closestRect, rect)) + rect = upTop(upBot(rect, closestRect.bottom), closestRect.top); + let dx = getdx(x, rect), dy = getdy(y, rect); + if (dx == 0 && dy == 0) + return child.nodeType == 3 ? domPosInText(child, x, y) : domPosAtCoords(child, x, y); + if (!closest || closestY > dy || closestY == dy && closestX > dx) { + closest = child; + closestRect = rect; + closestX = dx; + closestY = dy; + closestOverlap = !dx || (dx > 0 ? i < rects.length - 1 : i > 0); + } + if (dx == 0) { + if (y > rect.bottom && (!aboveRect || aboveRect.bottom < rect.bottom)) { + above = child; + aboveRect = rect; + } + else if (y < rect.top && (!belowRect || belowRect.top > rect.top)) { + below = child; + belowRect = rect; + } + } + else if (aboveRect && yOverlap(aboveRect, rect)) { + aboveRect = upBot(aboveRect, rect.bottom); + } + else if (belowRect && yOverlap(belowRect, rect)) { + belowRect = upTop(belowRect, rect.top); + } + } + } + if (aboveRect && aboveRect.bottom >= y) { + closest = above; + closestRect = aboveRect; + } + else if (belowRect && belowRect.top <= y) { + closest = below; + closestRect = belowRect; + } + if (!closest) + return { node: parent, offset: 0 }; + let clipX = Math.max(closestRect.left, Math.min(closestRect.right, x)); + if (closest.nodeType == 3) + return domPosInText(closest, clipX, y); + if (closestOverlap && closest.contentEditable != "false") + return domPosAtCoords(closest, clipX, y); + let offset = Array.prototype.indexOf.call(parent.childNodes, closest) + + (x >= (closestRect.left + closestRect.right) / 2 ? 1 : 0); + return { node: parent, offset }; + } + function domPosInText(node, x, y) { + let len = node.nodeValue.length; + let closestOffset = -1, closestDY = 1e9, generalSide = 0; + for (let i = 0; i < len; i++) { + let rects = textRange(node, i, i + 1).getClientRects(); + for (let j = 0; j < rects.length; j++) { + let rect = rects[j]; + if (rect.top == rect.bottom) + continue; + if (!generalSide) + generalSide = x - rect.left; + let dy = (rect.top > y ? rect.top - y : y - rect.bottom) - 1; + if (rect.left - 1 <= x && rect.right + 1 >= x && dy < closestDY) { + let right = x >= (rect.left + rect.right) / 2, after = right; + if (browser.chrome || browser.gecko) { + // Check for RTL on browsers that support getting client + // rects for empty ranges. + let rectBefore = textRange(node, i).getBoundingClientRect(); + if (rectBefore.left == rect.right) + after = !right; + } + if (dy <= 0) + return { node, offset: i + (after ? 1 : 0) }; + closestOffset = i + (after ? 1 : 0); + closestDY = dy; + } + } + } + return { node, offset: closestOffset > -1 ? closestOffset : generalSide > 0 ? node.nodeValue.length : 0 }; + } + function posAtCoords(view, { x, y }, precise, bias = -1) { + var _a; + let content = view.contentDOM.getBoundingClientRect(), docTop = content.top + view.viewState.paddingTop; + let block, { docHeight } = view.viewState; + let yOffset = y - docTop; + if (yOffset < 0) + return 0; + if (yOffset > docHeight) + return view.state.doc.length; + // Scan for a text block near the queried y position + for (let halfLine = view.defaultLineHeight / 2, bounced = false;;) { + block = view.elementAtHeight(yOffset); + if (block.type == BlockType.Text) + break; + for (;;) { + // Move the y position out of this block + yOffset = bias > 0 ? block.bottom + halfLine : block.top - halfLine; + if (yOffset >= 0 && yOffset <= docHeight) + break; + // If the document consists entirely of replaced widgets, we + // won't find a text block, so return 0 + if (bounced) + return precise ? null : 0; + bounced = true; + bias = -bias; + } + } + y = docTop + yOffset; + let lineStart = block.from; + // If this is outside of the rendered viewport, we can't determine a position + if (lineStart < view.viewport.from) + return view.viewport.from == 0 ? 0 : precise ? null : posAtCoordsImprecise(view, content, block, x, y); + if (lineStart > view.viewport.to) + return view.viewport.to == view.state.doc.length ? view.state.doc.length : + precise ? null : posAtCoordsImprecise(view, content, block, x, y); + // Prefer ShadowRootOrDocument.elementFromPoint if present, fall back to document if not + let doc = view.dom.ownerDocument; + let root = view.root.elementFromPoint ? view.root : doc; + let element = root.elementFromPoint(x, y); + if (element && !view.contentDOM.contains(element)) + element = null; + // If the element is unexpected, clip x at the sides of the content area and try again + if (!element) { + x = Math.max(content.left + 1, Math.min(content.right - 1, x)); + element = root.elementFromPoint(x, y); + if (element && !view.contentDOM.contains(element)) + element = null; + } + // There's visible editor content under the point, so we can try + // using caret(Position|Range)FromPoint as a shortcut + let node, offset = -1; + if (element && ((_a = view.docView.nearest(element)) === null || _a === void 0 ? void 0 : _a.isEditable) != false) { + if (doc.caretPositionFromPoint) { + let pos = doc.caretPositionFromPoint(x, y); + if (pos) + ({ offsetNode: node, offset } = pos); + } + else if (doc.caretRangeFromPoint) { + let range = doc.caretRangeFromPoint(x, y); + if (range) { + ({ startContainer: node, startOffset: offset } = range); + if (!view.contentDOM.contains(node) || + browser.safari && isSuspiciousSafariCaretResult(node, offset, x) || + browser.chrome && isSuspiciousChromeCaretResult(node, offset, x)) + node = undefined; + } + } + } + // No luck, do our own (potentially expensive) search + if (!node || !view.docView.dom.contains(node)) { + let line = LineView.find(view.docView, lineStart); + if (!line) + return yOffset > block.top + block.height / 2 ? block.to : block.from; + ({ node, offset } = domPosAtCoords(line.dom, x, y)); + } + return view.docView.posFromDOM(node, offset); + } + function posAtCoordsImprecise(view, contentRect, block, x, y) { + let into = Math.round((x - contentRect.left) * view.defaultCharacterWidth); + if (view.lineWrapping && block.height > view.defaultLineHeight * 1.5) { + let line = Math.floor((y - block.top) / view.defaultLineHeight); + into += line * view.viewState.heightOracle.lineLength; + } + let content = view.state.sliceDoc(block.from, block.to); + return block.from + findColumn(content, into, view.state.tabSize); + } + // In case of a high line height, Safari's caretRangeFromPoint treats + // the space between lines as belonging to the last character of the + // line before. This is used to detect such a result so that it can be + // ignored (issue #401). + function isSuspiciousSafariCaretResult(node, offset, x) { + let len; + if (node.nodeType != 3 || offset != (len = node.nodeValue.length)) + return false; + for (let next = node.nextSibling; next; next = next.nextSibling) + if (next.nodeType != 1 || next.nodeName != "BR") + return false; + return textRange(node, len - 1, len).getBoundingClientRect().left > x; + } + // Chrome will move positions between lines to the start of the next line + function isSuspiciousChromeCaretResult(node, offset, x) { + if (offset != 0) + return false; + for (let cur = node;;) { + let parent = cur.parentNode; + if (!parent || parent.nodeType != 1 || parent.firstChild != cur) + return false; + if (parent.classList.contains("cm-line")) + break; + cur = parent; + } + let rect = node.nodeType == 1 ? node.getBoundingClientRect() + : textRange(node, 0, Math.max(node.nodeValue.length, 1)).getBoundingClientRect(); + return x - rect.left > 5; + } + function moveToLineBoundary(view, start, forward, includeWrap) { + let line = view.state.doc.lineAt(start.head); + let coords = !includeWrap || !view.lineWrapping ? null + : view.coordsAtPos(start.assoc < 0 && start.head > line.from ? start.head - 1 : start.head); + if (coords) { + let editorRect = view.dom.getBoundingClientRect(); + let direction = view.textDirectionAt(line.from); + let pos = view.posAtCoords({ x: forward == (direction == Direction.LTR) ? editorRect.right - 1 : editorRect.left + 1, + y: (coords.top + coords.bottom) / 2 }); + if (pos != null) + return EditorSelection.cursor(pos, forward ? -1 : 1); + } + let lineView = LineView.find(view.docView, start.head); + let end = lineView ? (forward ? lineView.posAtEnd : lineView.posAtStart) : (forward ? line.to : line.from); + return EditorSelection.cursor(end, forward ? -1 : 1); + } + function moveByChar(view, start, forward, by) { + let line = view.state.doc.lineAt(start.head), spans = view.bidiSpans(line); + let direction = view.textDirectionAt(line.from); + for (let cur = start, check = null;;) { + let next = moveVisually(line, spans, direction, cur, forward), char = movedOver; + if (!next) { + if (line.number == (forward ? view.state.doc.lines : 1)) + return cur; + char = "\n"; + line = view.state.doc.line(line.number + (forward ? 1 : -1)); + spans = view.bidiSpans(line); + next = EditorSelection.cursor(forward ? line.from : line.to); + } + if (!check) { + if (!by) + return next; + check = by(char); + } + else if (!check(char)) { + return cur; + } + cur = next; + } + } + function byGroup(view, pos, start) { + let categorize = view.state.charCategorizer(pos); + let cat = categorize(start); + return (next) => { + let nextCat = categorize(next); + if (cat == CharCategory.Space) + cat = nextCat; + return cat == nextCat; + }; + } + function moveVertically(view, start, forward, distance) { + let startPos = start.head, dir = forward ? 1 : -1; + if (startPos == (forward ? view.state.doc.length : 0)) + return EditorSelection.cursor(startPos, start.assoc); + let goal = start.goalColumn, startY; + let rect = view.contentDOM.getBoundingClientRect(); + let startCoords = view.coordsAtPos(startPos), docTop = view.documentTop; + if (startCoords) { + if (goal == null) + goal = startCoords.left - rect.left; + startY = dir < 0 ? startCoords.top : startCoords.bottom; + } + else { + let line = view.viewState.lineBlockAt(startPos); + if (goal == null) + goal = Math.min(rect.right - rect.left, view.defaultCharacterWidth * (startPos - line.from)); + startY = (dir < 0 ? line.top : line.bottom) + docTop; + } + let resolvedGoal = rect.left + goal; + let dist = distance !== null && distance !== void 0 ? distance : (view.defaultLineHeight >> 1); + for (let extra = 0;; extra += 10) { + let curY = startY + (dist + extra) * dir; + let pos = posAtCoords(view, { x: resolvedGoal, y: curY }, false, dir); + if (curY < rect.top || curY > rect.bottom || (dir < 0 ? pos < startPos : pos > startPos)) + return EditorSelection.cursor(pos, start.assoc, undefined, goal); + } + } + function skipAtoms(view, oldPos, pos) { + let atoms = view.state.facet(atomicRanges).map(f => f(view)); + for (;;) { + let moved = false; + for (let set of atoms) { + set.between(pos.from - 1, pos.from + 1, (from, to, value) => { + if (pos.from > from && pos.from < to) { + pos = oldPos.head > pos.from ? EditorSelection.cursor(from, 1) : EditorSelection.cursor(to, -1); + moved = true; + } + }); + } + if (!moved) + return pos; + } + } + + // This will also be where dragging info and such goes + class InputState { + constructor(view) { + this.lastKeyCode = 0; + this.lastKeyTime = 0; + this.lastTouchTime = 0; + this.lastFocusTime = 0; + this.lastScrollTop = 0; + this.lastScrollLeft = 0; + this.chromeScrollHack = -1; + // On iOS, some keys need to have their default behavior happen + // (after which we retroactively handle them and reset the DOM) to + // avoid messing up the virtual keyboard state. + this.pendingIOSKey = undefined; + this.lastSelectionOrigin = null; + this.lastSelectionTime = 0; + this.lastEscPress = 0; + this.lastContextMenu = 0; + this.scrollHandlers = []; + this.registeredEvents = []; + this.customHandlers = []; + // -1 means not in a composition. Otherwise, this counts the number + // of changes made during the composition. The count is used to + // avoid treating the start state of the composition, before any + // changes have been made, as part of the composition. + this.composing = -1; + // Tracks whether the next change should be marked as starting the + // composition (null means no composition, true means next is the + // first, false means first has already been marked for this + // composition) + this.compositionFirstChange = null; + this.compositionEndedAt = 0; + this.mouseSelection = null; + for (let type in handlers) { + let handler = handlers[type]; + view.contentDOM.addEventListener(type, (event) => { + if (!eventBelongsToEditor(view, event) || this.ignoreDuringComposition(event)) + return; + if (type == "keydown" && this.keydown(view, event)) + return; + if (this.mustFlushObserver(event)) + view.observer.forceFlush(); + if (this.runCustomHandlers(type, view, event)) + event.preventDefault(); + else + handler(view, event); + }, handlerOptions[type]); + this.registeredEvents.push(type); + } + if (browser.chrome && browser.chrome_version == 102) { // FIXME remove at some point + // On Chrome 102, viewport updates somehow stop wheel-based + // scrolling. Turning off pointer events during the scroll seems + // to avoid the issue. + view.scrollDOM.addEventListener("wheel", () => { + if (this.chromeScrollHack < 0) + view.contentDOM.style.pointerEvents = "none"; + else + window.clearTimeout(this.chromeScrollHack); + this.chromeScrollHack = setTimeout(() => { + this.chromeScrollHack = -1; + view.contentDOM.style.pointerEvents = ""; + }, 100); + }, { passive: true }); + } + this.notifiedFocused = view.hasFocus; + // On Safari adding an input event handler somehow prevents an + // issue where the composition vanishes when you press enter. + if (browser.safari) + view.contentDOM.addEventListener("input", () => null); + } + setSelectionOrigin(origin) { + this.lastSelectionOrigin = origin; + this.lastSelectionTime = Date.now(); + } + ensureHandlers(view, plugins) { + var _a; + let handlers; + this.customHandlers = []; + for (let plugin of plugins) + if (handlers = (_a = plugin.update(view).spec) === null || _a === void 0 ? void 0 : _a.domEventHandlers) { + this.customHandlers.push({ plugin: plugin.value, handlers }); + for (let type in handlers) + if (this.registeredEvents.indexOf(type) < 0 && type != "scroll") { + this.registeredEvents.push(type); + view.contentDOM.addEventListener(type, (event) => { + if (!eventBelongsToEditor(view, event)) + return; + if (this.runCustomHandlers(type, view, event)) + event.preventDefault(); + }); + } + } + } + runCustomHandlers(type, view, event) { + for (let set of this.customHandlers) { + let handler = set.handlers[type]; + if (handler) { + try { + if (handler.call(set.plugin, event, view) || event.defaultPrevented) + return true; + } + catch (e) { + logException(view.state, e); + } + } + } + return false; + } + runScrollHandlers(view, event) { + this.lastScrollTop = view.scrollDOM.scrollTop; + this.lastScrollLeft = view.scrollDOM.scrollLeft; + for (let set of this.customHandlers) { + let handler = set.handlers.scroll; + if (handler) { + try { + handler.call(set.plugin, event, view); + } + catch (e) { + logException(view.state, e); + } + } + } + } + keydown(view, event) { + // Must always run, even if a custom handler handled the event + this.lastKeyCode = event.keyCode; + this.lastKeyTime = Date.now(); + if (event.keyCode == 9 && Date.now() < this.lastEscPress + 2000) + return true; + // Chrome for Android usually doesn't fire proper key events, but + // occasionally does, usually surrounded by a bunch of complicated + // composition changes. When an enter or backspace key event is + // seen, hold off on handling DOM events for a bit, and then + // dispatch it. + if (browser.android && browser.chrome && !event.synthetic && + (event.keyCode == 13 || event.keyCode == 8)) { + view.observer.delayAndroidKey(event.key, event.keyCode); + return true; + } + // Prevent the default behavior of Enter on iOS makes the + // virtual keyboard get stuck in the wrong (lowercase) + // state. So we let it go through, and then, in + // applyDOMChange, notify key handlers of it and reset to + // the state they produce. + let pending; + if (browser.ios && !event.synthetic && !event.altKey && !event.metaKey && + ((pending = PendingKeys.find(key => key.keyCode == event.keyCode)) && !event.ctrlKey || + EmacsyPendingKeys.indexOf(event.key) > -1 && event.ctrlKey && !event.shiftKey)) { + this.pendingIOSKey = pending || event; + setTimeout(() => this.flushIOSKey(view), 250); + return true; + } + return false; + } + flushIOSKey(view) { + let key = this.pendingIOSKey; + if (!key) + return false; + this.pendingIOSKey = undefined; + return dispatchKey(view.contentDOM, key.key, key.keyCode); + } + ignoreDuringComposition(event) { + if (!/^key/.test(event.type)) + return false; + if (this.composing > 0) + return true; + // See https://www.stum.de/2016/06/24/handling-ime-events-in-javascript/. + // On some input method editors (IMEs), the Enter key is used to + // confirm character selection. On Safari, when Enter is pressed, + // compositionend and keydown events are sometimes emitted in the + // wrong order. The key event should still be ignored, even when + // it happens after the compositionend event. + if (browser.safari && !browser.ios && Date.now() - this.compositionEndedAt < 100) { + this.compositionEndedAt = 0; + return true; + } + return false; + } + mustFlushObserver(event) { + return event.type == "keydown" && event.keyCode != 229; + } + startMouseSelection(mouseSelection) { + if (this.mouseSelection) + this.mouseSelection.destroy(); + this.mouseSelection = mouseSelection; + } + update(update) { + if (this.mouseSelection) + this.mouseSelection.update(update); + if (update.transactions.length) + this.lastKeyCode = this.lastSelectionTime = 0; + } + destroy() { + if (this.mouseSelection) + this.mouseSelection.destroy(); + } + } + const PendingKeys = [ + { key: "Backspace", keyCode: 8, inputType: "deleteContentBackward" }, + { key: "Enter", keyCode: 13, inputType: "insertParagraph" }, + { key: "Delete", keyCode: 46, inputType: "deleteContentForward" } + ]; + const EmacsyPendingKeys = "dthko"; + // Key codes for modifier keys + const modifierCodes = [16, 17, 18, 20, 91, 92, 224, 225]; + class MouseSelection { + constructor(view, startEvent, style, mustSelect) { + this.view = view; + this.style = style; + this.mustSelect = mustSelect; + this.lastEvent = startEvent; + let doc = view.contentDOM.ownerDocument; + doc.addEventListener("mousemove", this.move = this.move.bind(this)); + doc.addEventListener("mouseup", this.up = this.up.bind(this)); + this.extend = startEvent.shiftKey; + this.multiple = view.state.facet(EditorState.allowMultipleSelections) && addsSelectionRange(view, startEvent); + this.dragMove = dragMovesSelection(view, startEvent); + this.dragging = isInPrimarySelection(view, startEvent) && getClickType(startEvent) == 1 ? null : false; + // When clicking outside of the selection, immediately apply the + // effect of starting the selection + if (this.dragging === false) { + startEvent.preventDefault(); + this.select(startEvent); + } + } + move(event) { + if (event.buttons == 0) + return this.destroy(); + if (this.dragging !== false) + return; + this.select(this.lastEvent = event); + } + up(event) { + if (this.dragging == null) + this.select(this.lastEvent); + if (!this.dragging) + event.preventDefault(); + this.destroy(); + } + destroy() { + let doc = this.view.contentDOM.ownerDocument; + doc.removeEventListener("mousemove", this.move); + doc.removeEventListener("mouseup", this.up); + this.view.inputState.mouseSelection = null; + } + select(event) { + let selection = this.style.get(event, this.extend, this.multiple); + if (this.mustSelect || !selection.eq(this.view.state.selection) || + selection.main.assoc != this.view.state.selection.main.assoc) + this.view.dispatch({ + selection, + userEvent: "select.pointer", + scrollIntoView: true + }); + this.mustSelect = false; + } + update(update) { + if (update.docChanged && this.dragging) + this.dragging = this.dragging.map(update.changes); + if (this.style.update(update)) + setTimeout(() => this.select(this.lastEvent), 20); + } + } + function addsSelectionRange(view, event) { + let facet = view.state.facet(clickAddsSelectionRange); + return facet.length ? facet[0](event) : browser.mac ? event.metaKey : event.ctrlKey; + } + function dragMovesSelection(view, event) { + let facet = view.state.facet(dragMovesSelection$1); + return facet.length ? facet[0](event) : browser.mac ? !event.altKey : !event.ctrlKey; + } + function isInPrimarySelection(view, event) { + let { main } = view.state.selection; + if (main.empty) + return false; + // On boundary clicks, check whether the coordinates are inside the + // selection's client rectangles + let sel = getSelection(view.root); + if (!sel || sel.rangeCount == 0) + return true; + let rects = sel.getRangeAt(0).getClientRects(); + for (let i = 0; i < rects.length; i++) { + let rect = rects[i]; + if (rect.left <= event.clientX && rect.right >= event.clientX && + rect.top <= event.clientY && rect.bottom >= event.clientY) + return true; + } + return false; + } + function eventBelongsToEditor(view, event) { + if (!event.bubbles) + return true; + if (event.defaultPrevented) + return false; + for (let node = event.target, cView; node != view.contentDOM; node = node.parentNode) + if (!node || node.nodeType == 11 || ((cView = ContentView.get(node)) && cView.ignoreEvent(event))) + return false; + return true; + } + const handlers = /*@__PURE__*/Object.create(null); + const handlerOptions = /*@__PURE__*/Object.create(null); + // This is very crude, but unfortunately both these browsers _pretend_ + // that they have a clipboard API—all the objects and methods are + // there, they just don't work, and they are hard to test. + const brokenClipboardAPI = (browser.ie && browser.ie_version < 15) || + (browser.ios && browser.webkit_version < 604); + function capturePaste(view) { + let parent = view.dom.parentNode; + if (!parent) + return; + let target = parent.appendChild(document.createElement("textarea")); + target.style.cssText = "position: fixed; left: -10000px; top: 10px"; + target.focus(); + setTimeout(() => { + view.focus(); + target.remove(); + doPaste(view, target.value); + }, 50); + } + function doPaste(view, input) { + let { state } = view, changes, i = 1, text = state.toText(input); + let byLine = text.lines == state.selection.ranges.length; + let linewise = lastLinewiseCopy != null && state.selection.ranges.every(r => r.empty) && lastLinewiseCopy == text.toString(); + if (linewise) { + let lastLine = -1; + changes = state.changeByRange(range => { + let line = state.doc.lineAt(range.from); + if (line.from == lastLine) + return { range }; + lastLine = line.from; + let insert = state.toText((byLine ? text.line(i++).text : input) + state.lineBreak); + return { changes: { from: line.from, insert }, + range: EditorSelection.cursor(range.from + insert.length) }; + }); + } + else if (byLine) { + changes = state.changeByRange(range => { + let line = text.line(i++); + return { changes: { from: range.from, to: range.to, insert: line.text }, + range: EditorSelection.cursor(range.from + line.length) }; + }); + } + else { + changes = state.replaceSelection(text); + } + view.dispatch(changes, { + userEvent: "input.paste", + scrollIntoView: true + }); + } + handlers.keydown = (view, event) => { + view.inputState.setSelectionOrigin("select"); + if (event.keyCode == 27) + view.inputState.lastEscPress = Date.now(); + else if (modifierCodes.indexOf(event.keyCode) < 0) + view.inputState.lastEscPress = 0; + }; + handlers.touchstart = (view, e) => { + view.inputState.lastTouchTime = Date.now(); + view.inputState.setSelectionOrigin("select.pointer"); + }; + handlers.touchmove = view => { + view.inputState.setSelectionOrigin("select.pointer"); + }; + handlerOptions.touchstart = handlerOptions.touchmove = { passive: true }; + handlers.mousedown = (view, event) => { + view.observer.flush(); + if (view.inputState.lastTouchTime > Date.now() - 2000) + return; // Ignore touch interaction + let style = null; + for (let makeStyle of view.state.facet(mouseSelectionStyle)) { + style = makeStyle(view, event); + if (style) + break; + } + if (!style && event.button == 0) + style = basicMouseSelection(view, event); + if (style) { + let mustFocus = view.root.activeElement != view.contentDOM; + if (mustFocus) + view.observer.ignore(() => focusPreventScroll(view.contentDOM)); + view.inputState.startMouseSelection(new MouseSelection(view, event, style, mustFocus)); + } + }; + function rangeForClick(view, pos, bias, type) { + if (type == 1) { // Single click + return EditorSelection.cursor(pos, bias); + } + else if (type == 2) { // Double click + return groupAt(view.state, pos, bias); + } + else { // Triple click + let visual = LineView.find(view.docView, pos), line = view.state.doc.lineAt(visual ? visual.posAtEnd : pos); + let from = visual ? visual.posAtStart : line.from, to = visual ? visual.posAtEnd : line.to; + if (to < view.state.doc.length && to == line.to) + to++; + return EditorSelection.range(from, to); + } + } + let insideY = (y, rect) => y >= rect.top && y <= rect.bottom; + let inside = (x, y, rect) => insideY(y, rect) && x >= rect.left && x <= rect.right; + // Try to determine, for the given coordinates, associated with the + // given position, whether they are related to the element before or + // the element after the position. + function findPositionSide(view, pos, x, y) { + let line = LineView.find(view.docView, pos); + if (!line) + return 1; + let off = pos - line.posAtStart; + // Line boundaries point into the line + if (off == 0) + return 1; + if (off == line.length) + return -1; + // Positions on top of an element point at that element + let before = line.coordsAt(off, -1); + if (before && inside(x, y, before)) + return -1; + let after = line.coordsAt(off, 1); + if (after && inside(x, y, after)) + return 1; + // This is probably a line wrap point. Pick before if the point is + // beside it. + return before && insideY(y, before) ? -1 : 1; + } + function queryPos(view, event) { + let pos = view.posAtCoords({ x: event.clientX, y: event.clientY }, false); + return { pos, bias: findPositionSide(view, pos, event.clientX, event.clientY) }; + } + const BadMouseDetail = browser.ie && browser.ie_version <= 11; + let lastMouseDown = null, lastMouseDownCount = 0, lastMouseDownTime = 0; + function getClickType(event) { + if (!BadMouseDetail) + return event.detail; + let last = lastMouseDown, lastTime = lastMouseDownTime; + lastMouseDown = event; + lastMouseDownTime = Date.now(); + return lastMouseDownCount = !last || (lastTime > Date.now() - 400 && Math.abs(last.clientX - event.clientX) < 2 && + Math.abs(last.clientY - event.clientY) < 2) ? (lastMouseDownCount + 1) % 3 : 1; + } + function basicMouseSelection(view, event) { + let start = queryPos(view, event), type = getClickType(event); + let startSel = view.state.selection; + let last = start, lastEvent = event; + return { + update(update) { + if (update.docChanged) { + start.pos = update.changes.mapPos(start.pos); + startSel = startSel.map(update.changes); + lastEvent = null; + } + }, + get(event, extend, multiple) { + let cur; + if (lastEvent && event.clientX == lastEvent.clientX && event.clientY == lastEvent.clientY) + cur = last; + else { + cur = last = queryPos(view, event); + lastEvent = event; + } + let range = rangeForClick(view, cur.pos, cur.bias, type); + if (start.pos != cur.pos && !extend) { + let startRange = rangeForClick(view, start.pos, start.bias, type); + let from = Math.min(startRange.from, range.from), to = Math.max(startRange.to, range.to); + range = from < range.from ? EditorSelection.range(from, to) : EditorSelection.range(to, from); + } + if (extend) + return startSel.replaceRange(startSel.main.extend(range.from, range.to)); + else if (multiple && startSel.ranges.length > 1 && startSel.ranges.some(r => r.eq(range))) + return removeRange(startSel, range); + else if (multiple) + return startSel.addRange(range); + else + return EditorSelection.create([range]); + } + }; + } + function removeRange(sel, range) { + for (let i = 0;; i++) { + if (sel.ranges[i].eq(range)) + return EditorSelection.create(sel.ranges.slice(0, i).concat(sel.ranges.slice(i + 1)), sel.mainIndex == i ? 0 : sel.mainIndex - (sel.mainIndex > i ? 1 : 0)); + } + } + handlers.dragstart = (view, event) => { + let { selection: { main } } = view.state; + let { mouseSelection } = view.inputState; + if (mouseSelection) + mouseSelection.dragging = main; + if (event.dataTransfer) { + event.dataTransfer.setData("Text", view.state.sliceDoc(main.from, main.to)); + event.dataTransfer.effectAllowed = "copyMove"; + } + }; + function dropText(view, event, text, direct) { + if (!text) + return; + let dropPos = view.posAtCoords({ x: event.clientX, y: event.clientY }, false); + event.preventDefault(); + let { mouseSelection } = view.inputState; + let del = direct && mouseSelection && mouseSelection.dragging && mouseSelection.dragMove ? + { from: mouseSelection.dragging.from, to: mouseSelection.dragging.to } : null; + let ins = { from: dropPos, insert: text }; + let changes = view.state.changes(del ? [del, ins] : ins); + view.focus(); + view.dispatch({ + changes, + selection: { anchor: changes.mapPos(dropPos, -1), head: changes.mapPos(dropPos, 1) }, + userEvent: del ? "move.drop" : "input.drop" + }); + } + handlers.drop = (view, event) => { + if (!event.dataTransfer) + return; + if (view.state.readOnly) + return event.preventDefault(); + let files = event.dataTransfer.files; + if (files && files.length) { // For a file drop, read the file's text. + event.preventDefault(); + let text = Array(files.length), read = 0; + let finishFile = () => { + if (++read == files.length) + dropText(view, event, text.filter(s => s != null).join(view.state.lineBreak), false); + }; + for (let i = 0; i < files.length; i++) { + let reader = new FileReader; + reader.onerror = finishFile; + reader.onload = () => { + if (!/[\x00-\x08\x0e-\x1f]{2}/.test(reader.result)) + text[i] = reader.result; + finishFile(); + }; + reader.readAsText(files[i]); + } + } + else { + dropText(view, event, event.dataTransfer.getData("Text"), true); + } + }; + handlers.paste = (view, event) => { + if (view.state.readOnly) + return event.preventDefault(); + view.observer.flush(); + let data = brokenClipboardAPI ? null : event.clipboardData; + if (data) { + doPaste(view, data.getData("text/plain")); + event.preventDefault(); + } + else { + capturePaste(view); + } + }; + function captureCopy(view, text) { + // The extra wrapper is somehow necessary on IE/Edge to prevent the + // content from being mangled when it is put onto the clipboard + let parent = view.dom.parentNode; + if (!parent) + return; + let target = parent.appendChild(document.createElement("textarea")); + target.style.cssText = "position: fixed; left: -10000px; top: 10px"; + target.value = text; + target.focus(); + target.selectionEnd = text.length; + target.selectionStart = 0; + setTimeout(() => { + target.remove(); + view.focus(); + }, 50); + } + function copiedRange(state) { + let content = [], ranges = [], linewise = false; + for (let range of state.selection.ranges) + if (!range.empty) { + content.push(state.sliceDoc(range.from, range.to)); + ranges.push(range); + } + if (!content.length) { + // Nothing selected, do a line-wise copy + let upto = -1; + for (let { from } of state.selection.ranges) { + let line = state.doc.lineAt(from); + if (line.number > upto) { + content.push(line.text); + ranges.push({ from: line.from, to: Math.min(state.doc.length, line.to + 1) }); + } + upto = line.number; + } + linewise = true; + } + return { text: content.join(state.lineBreak), ranges, linewise }; + } + let lastLinewiseCopy = null; + handlers.copy = handlers.cut = (view, event) => { + let { text, ranges, linewise } = copiedRange(view.state); + if (!text && !linewise) + return; + lastLinewiseCopy = linewise ? text : null; + let data = brokenClipboardAPI ? null : event.clipboardData; + if (data) { + event.preventDefault(); + data.clearData(); + data.setData("text/plain", text); + } + else { + captureCopy(view, text); + } + if (event.type == "cut" && !view.state.readOnly) + view.dispatch({ + changes: ranges, + scrollIntoView: true, + userEvent: "delete.cut" + }); + }; + function updateForFocusChange(view) { + setTimeout(() => { + if (view.hasFocus != view.inputState.notifiedFocused) + view.update([]); + }, 10); + } + handlers.focus = view => { + view.inputState.lastFocusTime = Date.now(); + // When focusing reset the scroll position, move it back to where it was + if (!view.scrollDOM.scrollTop && (view.inputState.lastScrollTop || view.inputState.lastScrollLeft)) { + view.scrollDOM.scrollTop = view.inputState.lastScrollTop; + view.scrollDOM.scrollLeft = view.inputState.lastScrollLeft; + } + updateForFocusChange(view); + }; + handlers.blur = view => { + view.observer.clearSelectionRange(); + updateForFocusChange(view); + }; + handlers.compositionstart = handlers.compositionupdate = view => { + if (view.inputState.compositionFirstChange == null) + view.inputState.compositionFirstChange = true; + if (view.inputState.composing < 0) { + // FIXME possibly set a timeout to clear it again on Android + view.inputState.composing = 0; + } + }; + handlers.compositionend = view => { + view.inputState.composing = -1; + view.inputState.compositionEndedAt = Date.now(); + view.inputState.compositionFirstChange = null; + if (browser.chrome && browser.android) + view.observer.flushSoon(); + setTimeout(() => { + // Force the composition state to be cleared if it hasn't already been + if (view.inputState.composing < 0 && view.docView.compositionDeco.size) + view.update([]); + }, 50); + }; + handlers.contextmenu = view => { + view.inputState.lastContextMenu = Date.now(); + }; + handlers.beforeinput = (view, event) => { + var _a; + // Because Chrome Android doesn't fire useful key events, use + // beforeinput to detect backspace (and possibly enter and delete, + // but those usually don't even seem to fire beforeinput events at + // the moment) and fake a key event for it. + // + // (preventDefault on beforeinput, though supported in the spec, + // seems to do nothing at all on Chrome). + let pending; + if (browser.chrome && browser.android && (pending = PendingKeys.find(key => key.inputType == event.inputType))) { + view.observer.delayAndroidKey(pending.key, pending.keyCode); + if (pending.key == "Backspace" || pending.key == "Delete") { + let startViewHeight = ((_a = window.visualViewport) === null || _a === void 0 ? void 0 : _a.height) || 0; + setTimeout(() => { + var _a; + // Backspacing near uneditable nodes on Chrome Android sometimes + // closes the virtual keyboard. This tries to crudely detect + // that and refocus to get it back. + if ((((_a = window.visualViewport) === null || _a === void 0 ? void 0 : _a.height) || 0) > startViewHeight + 10 && view.hasFocus) { + view.contentDOM.blur(); + view.focus(); + } + }, 100); + } + } + }; + + const wrappingWhiteSpace = ["pre-wrap", "normal", "pre-line", "break-spaces"]; + class HeightOracle { + constructor() { + this.doc = Text.empty; + this.lineWrapping = false; + this.heightSamples = {}; + this.lineHeight = 14; + this.charWidth = 7; + this.lineLength = 30; + // Used to track, during updateHeight, if any actual heights changed + this.heightChanged = false; + } + heightForGap(from, to) { + let lines = this.doc.lineAt(to).number - this.doc.lineAt(from).number + 1; + if (this.lineWrapping) + lines += Math.ceil(((to - from) - (lines * this.lineLength * 0.5)) / this.lineLength); + return this.lineHeight * lines; + } + heightForLine(length) { + if (!this.lineWrapping) + return this.lineHeight; + let lines = 1 + Math.max(0, Math.ceil((length - this.lineLength) / (this.lineLength - 5))); + return lines * this.lineHeight; + } + setDoc(doc) { this.doc = doc; return this; } + mustRefreshForWrapping(whiteSpace) { + return (wrappingWhiteSpace.indexOf(whiteSpace) > -1) != this.lineWrapping; + } + mustRefreshForHeights(lineHeights) { + let newHeight = false; + for (let i = 0; i < lineHeights.length; i++) { + let h = lineHeights[i]; + if (h < 0) { + i++; + } + else if (!this.heightSamples[Math.floor(h * 10)]) { // Round to .1 pixels + newHeight = true; + this.heightSamples[Math.floor(h * 10)] = true; + } + } + return newHeight; + } + refresh(whiteSpace, lineHeight, charWidth, lineLength, knownHeights) { + let lineWrapping = wrappingWhiteSpace.indexOf(whiteSpace) > -1; + let changed = Math.round(lineHeight) != Math.round(this.lineHeight) || this.lineWrapping != lineWrapping; + this.lineWrapping = lineWrapping; + this.lineHeight = lineHeight; + this.charWidth = charWidth; + this.lineLength = lineLength; + if (changed) { + this.heightSamples = {}; + for (let i = 0; i < knownHeights.length; i++) { + let h = knownHeights[i]; + if (h < 0) + i++; + else + this.heightSamples[Math.floor(h * 10)] = true; + } + } + return changed; + } + } + // This object is used by `updateHeight` to make DOM measurements + // arrive at the right nides. The `heights` array is a sequence of + // block heights, starting from position `from`. + class MeasuredHeights { + constructor(from, heights) { + this.from = from; + this.heights = heights; + this.index = 0; + } + get more() { return this.index < this.heights.length; } + } + /** + Record used to represent information about a block-level element + in the editor view. + */ + class BlockInfo { + /** + @internal + */ + constructor( + /** + The start of the element in the document. + */ + from, + /** + The length of the element. + */ + length, + /** + The top position of the element (relative to the top of the + document). + */ + top, + /** + Its height. + */ + height, + /** + The type of element this is. When querying lines, this may be + an array of all the blocks that make up the line. + */ + type) { + this.from = from; + this.length = length; + this.top = top; + this.height = height; + this.type = type; + } + /** + The end of the element as a document position. + */ + get to() { return this.from + this.length; } + /** + The bottom position of the element. + */ + get bottom() { return this.top + this.height; } + /** + @internal + */ + join(other) { + let detail = (Array.isArray(this.type) ? this.type : [this]) + .concat(Array.isArray(other.type) ? other.type : [other]); + return new BlockInfo(this.from, this.length + other.length, this.top, this.height + other.height, detail); + } + } + var QueryType$1 = /*@__PURE__*/(function (QueryType) { + QueryType[QueryType["ByPos"] = 0] = "ByPos"; + QueryType[QueryType["ByHeight"] = 1] = "ByHeight"; + QueryType[QueryType["ByPosNoHeight"] = 2] = "ByPosNoHeight"; + return QueryType})(QueryType$1 || (QueryType$1 = {})); + const Epsilon = 1e-3; + class HeightMap { + constructor(length, // The number of characters covered + height, // Height of this part of the document + flags = 2 /* Flag.Outdated */) { + this.length = length; + this.height = height; + this.flags = flags; + } + get outdated() { return (this.flags & 2 /* Flag.Outdated */) > 0; } + set outdated(value) { this.flags = (value ? 2 /* Flag.Outdated */ : 0) | (this.flags & ~2 /* Flag.Outdated */); } + setHeight(oracle, height) { + if (this.height != height) { + if (Math.abs(this.height - height) > Epsilon) + oracle.heightChanged = true; + this.height = height; + } + } + // Base case is to replace a leaf node, which simply builds a tree + // from the new nodes and returns that (HeightMapBranch and + // HeightMapGap override this to actually use from/to) + replace(_from, _to, nodes) { + return HeightMap.of(nodes); + } + // Again, these are base cases, and are overridden for branch and gap nodes. + decomposeLeft(_to, result) { result.push(this); } + decomposeRight(_from, result) { result.push(this); } + applyChanges(decorations, oldDoc, oracle, changes) { + let me = this; + for (let i = changes.length - 1; i >= 0; i--) { + let { fromA, toA, fromB, toB } = changes[i]; + let start = me.lineAt(fromA, QueryType$1.ByPosNoHeight, oldDoc, 0, 0); + let end = start.to >= toA ? start : me.lineAt(toA, QueryType$1.ByPosNoHeight, oldDoc, 0, 0); + toB += end.to - toA; + toA = end.to; + while (i > 0 && start.from <= changes[i - 1].toA) { + fromA = changes[i - 1].fromA; + fromB = changes[i - 1].fromB; + i--; + if (fromA < start.from) + start = me.lineAt(fromA, QueryType$1.ByPosNoHeight, oldDoc, 0, 0); + } + fromB += start.from - fromA; + fromA = start.from; + let nodes = NodeBuilder.build(oracle, decorations, fromB, toB); + me = me.replace(fromA, toA, nodes); + } + return me.updateHeight(oracle, 0); + } + static empty() { return new HeightMapText(0, 0); } + // nodes uses null values to indicate the position of line breaks. + // There are never line breaks at the start or end of the array, or + // two line breaks next to each other, and the array isn't allowed + // to be empty (same restrictions as return value from the builder). + static of(nodes) { + if (nodes.length == 1) + return nodes[0]; + let i = 0, j = nodes.length, before = 0, after = 0; + for (;;) { + if (i == j) { + if (before > after * 2) { + let split = nodes[i - 1]; + if (split.break) + nodes.splice(--i, 1, split.left, null, split.right); + else + nodes.splice(--i, 1, split.left, split.right); + j += 1 + split.break; + before -= split.size; + } + else if (after > before * 2) { + let split = nodes[j]; + if (split.break) + nodes.splice(j, 1, split.left, null, split.right); + else + nodes.splice(j, 1, split.left, split.right); + j += 2 + split.break; + after -= split.size; + } + else { + break; + } + } + else if (before < after) { + let next = nodes[i++]; + if (next) + before += next.size; + } + else { + let next = nodes[--j]; + if (next) + after += next.size; + } + } + let brk = 0; + if (nodes[i - 1] == null) { + brk = 1; + i--; + } + else if (nodes[i] == null) { + brk = 1; + j++; + } + return new HeightMapBranch(HeightMap.of(nodes.slice(0, i)), brk, HeightMap.of(nodes.slice(j))); + } + } + HeightMap.prototype.size = 1; + class HeightMapBlock extends HeightMap { + constructor(length, height, type) { + super(length, height); + this.type = type; + } + blockAt(_height, _doc, top, offset) { + return new BlockInfo(offset, this.length, top, this.height, this.type); + } + lineAt(_value, _type, doc, top, offset) { + return this.blockAt(0, doc, top, offset); + } + forEachLine(from, to, doc, top, offset, f) { + if (from <= offset + this.length && to >= offset) + f(this.blockAt(0, doc, top, offset)); + } + updateHeight(oracle, offset = 0, _force = false, measured) { + if (measured && measured.from <= offset && measured.more) + this.setHeight(oracle, measured.heights[measured.index++]); + this.outdated = false; + return this; + } + toString() { return `block(${this.length})`; } + } + class HeightMapText extends HeightMapBlock { + constructor(length, height) { + super(length, height, BlockType.Text); + this.collapsed = 0; // Amount of collapsed content in the line + this.widgetHeight = 0; // Maximum inline widget height + } + replace(_from, _to, nodes) { + let node = nodes[0]; + if (nodes.length == 1 && (node instanceof HeightMapText || node instanceof HeightMapGap && (node.flags & 4 /* Flag.SingleLine */)) && + Math.abs(this.length - node.length) < 10) { + if (node instanceof HeightMapGap) + node = new HeightMapText(node.length, this.height); + else + node.height = this.height; + if (!this.outdated) + node.outdated = false; + return node; + } + else { + return HeightMap.of(nodes); + } + } + updateHeight(oracle, offset = 0, force = false, measured) { + if (measured && measured.from <= offset && measured.more) + this.setHeight(oracle, measured.heights[measured.index++]); + else if (force || this.outdated) + this.setHeight(oracle, Math.max(this.widgetHeight, oracle.heightForLine(this.length - this.collapsed))); + this.outdated = false; + return this; + } + toString() { + return `line(${this.length}${this.collapsed ? -this.collapsed : ""}${this.widgetHeight ? ":" + this.widgetHeight : ""})`; + } + } + class HeightMapGap extends HeightMap { + constructor(length) { super(length, 0); } + lines(doc, offset) { + let firstLine = doc.lineAt(offset).number, lastLine = doc.lineAt(offset + this.length).number; + return { firstLine, lastLine, lineHeight: this.height / (lastLine - firstLine + 1) }; + } + blockAt(height, doc, top, offset) { + let { firstLine, lastLine, lineHeight } = this.lines(doc, offset); + let line = Math.max(0, Math.min(lastLine - firstLine, Math.floor((height - top) / lineHeight))); + let { from, length } = doc.line(firstLine + line); + return new BlockInfo(from, length, top + lineHeight * line, lineHeight, BlockType.Text); + } + lineAt(value, type, doc, top, offset) { + if (type == QueryType$1.ByHeight) + return this.blockAt(value, doc, top, offset); + if (type == QueryType$1.ByPosNoHeight) { + let { from, to } = doc.lineAt(value); + return new BlockInfo(from, to - from, 0, 0, BlockType.Text); + } + let { firstLine, lineHeight } = this.lines(doc, offset); + let { from, length, number } = doc.lineAt(value); + return new BlockInfo(from, length, top + lineHeight * (number - firstLine), lineHeight, BlockType.Text); + } + forEachLine(from, to, doc, top, offset, f) { + let { firstLine, lineHeight } = this.lines(doc, offset); + for (let pos = Math.max(from, offset), end = Math.min(offset + this.length, to); pos <= end;) { + let line = doc.lineAt(pos); + if (pos == from) + top += lineHeight * (line.number - firstLine); + f(new BlockInfo(line.from, line.length, top, lineHeight, BlockType.Text)); + top += lineHeight; + pos = line.to + 1; + } + } + replace(from, to, nodes) { + let after = this.length - to; + if (after > 0) { + let last = nodes[nodes.length - 1]; + if (last instanceof HeightMapGap) + nodes[nodes.length - 1] = new HeightMapGap(last.length + after); + else + nodes.push(null, new HeightMapGap(after - 1)); + } + if (from > 0) { + let first = nodes[0]; + if (first instanceof HeightMapGap) + nodes[0] = new HeightMapGap(from + first.length); + else + nodes.unshift(new HeightMapGap(from - 1), null); + } + return HeightMap.of(nodes); + } + decomposeLeft(to, result) { + result.push(new HeightMapGap(to - 1), null); + } + decomposeRight(from, result) { + result.push(null, new HeightMapGap(this.length - from - 1)); + } + updateHeight(oracle, offset = 0, force = false, measured) { + let end = offset + this.length; + if (measured && measured.from <= offset + this.length && measured.more) { + // Fill in part of this gap with measured lines. We know there + // can't be widgets or collapsed ranges in those lines, because + // they would already have been added to the heightmap (gaps + // only contain plain text). + let nodes = [], pos = Math.max(offset, measured.from), singleHeight = -1; + let wasChanged = oracle.heightChanged; + if (measured.from > offset) + nodes.push(new HeightMapGap(measured.from - offset - 1).updateHeight(oracle, offset)); + while (pos <= end && measured.more) { + let len = oracle.doc.lineAt(pos).length; + if (nodes.length) + nodes.push(null); + let height = measured.heights[measured.index++]; + if (singleHeight == -1) + singleHeight = height; + else if (Math.abs(height - singleHeight) >= Epsilon) + singleHeight = -2; + let line = new HeightMapText(len, height); + line.outdated = false; + nodes.push(line); + pos += len + 1; + } + if (pos <= end) + nodes.push(null, new HeightMapGap(end - pos).updateHeight(oracle, pos)); + let result = HeightMap.of(nodes); + oracle.heightChanged = wasChanged || singleHeight < 0 || Math.abs(result.height - this.height) >= Epsilon || + Math.abs(singleHeight - this.lines(oracle.doc, offset).lineHeight) >= Epsilon; + return result; + } + else if (force || this.outdated) { + this.setHeight(oracle, oracle.heightForGap(offset, offset + this.length)); + this.outdated = false; + } + return this; + } + toString() { return `gap(${this.length})`; } + } + class HeightMapBranch extends HeightMap { + constructor(left, brk, right) { + super(left.length + brk + right.length, left.height + right.height, brk | (left.outdated || right.outdated ? 2 /* Flag.Outdated */ : 0)); + this.left = left; + this.right = right; + this.size = left.size + right.size; + } + get break() { return this.flags & 1 /* Flag.Break */; } + blockAt(height, doc, top, offset) { + let mid = top + this.left.height; + return height < mid ? this.left.blockAt(height, doc, top, offset) + : this.right.blockAt(height, doc, mid, offset + this.left.length + this.break); + } + lineAt(value, type, doc, top, offset) { + let rightTop = top + this.left.height, rightOffset = offset + this.left.length + this.break; + let left = type == QueryType$1.ByHeight ? value < rightTop : value < rightOffset; + let base = left ? this.left.lineAt(value, type, doc, top, offset) + : this.right.lineAt(value, type, doc, rightTop, rightOffset); + if (this.break || (left ? base.to < rightOffset : base.from > rightOffset)) + return base; + let subQuery = type == QueryType$1.ByPosNoHeight ? QueryType$1.ByPosNoHeight : QueryType$1.ByPos; + if (left) + return base.join(this.right.lineAt(rightOffset, subQuery, doc, rightTop, rightOffset)); + else + return this.left.lineAt(rightOffset, subQuery, doc, top, offset).join(base); + } + forEachLine(from, to, doc, top, offset, f) { + let rightTop = top + this.left.height, rightOffset = offset + this.left.length + this.break; + if (this.break) { + if (from < rightOffset) + this.left.forEachLine(from, to, doc, top, offset, f); + if (to >= rightOffset) + this.right.forEachLine(from, to, doc, rightTop, rightOffset, f); + } + else { + let mid = this.lineAt(rightOffset, QueryType$1.ByPos, doc, top, offset); + if (from < mid.from) + this.left.forEachLine(from, mid.from - 1, doc, top, offset, f); + if (mid.to >= from && mid.from <= to) + f(mid); + if (to > mid.to) + this.right.forEachLine(mid.to + 1, to, doc, rightTop, rightOffset, f); + } + } + replace(from, to, nodes) { + let rightStart = this.left.length + this.break; + if (to < rightStart) + return this.balanced(this.left.replace(from, to, nodes), this.right); + if (from > this.left.length) + return this.balanced(this.left, this.right.replace(from - rightStart, to - rightStart, nodes)); + let result = []; + if (from > 0) + this.decomposeLeft(from, result); + let left = result.length; + for (let node of nodes) + result.push(node); + if (from > 0) + mergeGaps(result, left - 1); + if (to < this.length) { + let right = result.length; + this.decomposeRight(to, result); + mergeGaps(result, right); + } + return HeightMap.of(result); + } + decomposeLeft(to, result) { + let left = this.left.length; + if (to <= left) + return this.left.decomposeLeft(to, result); + result.push(this.left); + if (this.break) { + left++; + if (to >= left) + result.push(null); + } + if (to > left) + this.right.decomposeLeft(to - left, result); + } + decomposeRight(from, result) { + let left = this.left.length, right = left + this.break; + if (from >= right) + return this.right.decomposeRight(from - right, result); + if (from < left) + this.left.decomposeRight(from, result); + if (this.break && from < right) + result.push(null); + result.push(this.right); + } + balanced(left, right) { + if (left.size > 2 * right.size || right.size > 2 * left.size) + return HeightMap.of(this.break ? [left, null, right] : [left, right]); + this.left = left; + this.right = right; + this.height = left.height + right.height; + this.outdated = left.outdated || right.outdated; + this.size = left.size + right.size; + this.length = left.length + this.break + right.length; + return this; + } + updateHeight(oracle, offset = 0, force = false, measured) { + let { left, right } = this, rightStart = offset + left.length + this.break, rebalance = null; + if (measured && measured.from <= offset + left.length && measured.more) + rebalance = left = left.updateHeight(oracle, offset, force, measured); + else + left.updateHeight(oracle, offset, force); + if (measured && measured.from <= rightStart + right.length && measured.more) + rebalance = right = right.updateHeight(oracle, rightStart, force, measured); + else + right.updateHeight(oracle, rightStart, force); + if (rebalance) + return this.balanced(left, right); + this.height = this.left.height + this.right.height; + this.outdated = false; + return this; + } + toString() { return this.left + (this.break ? " " : "-") + this.right; } + } + function mergeGaps(nodes, around) { + let before, after; + if (nodes[around] == null && + (before = nodes[around - 1]) instanceof HeightMapGap && + (after = nodes[around + 1]) instanceof HeightMapGap) + nodes.splice(around - 1, 3, new HeightMapGap(before.length + 1 + after.length)); + } + const relevantWidgetHeight = 5; + class NodeBuilder { + constructor(pos, oracle) { + this.pos = pos; + this.oracle = oracle; + this.nodes = []; + this.lineStart = -1; + this.lineEnd = -1; + this.covering = null; + this.writtenTo = pos; + } + get isCovered() { + return this.covering && this.nodes[this.nodes.length - 1] == this.covering; + } + span(_from, to) { + if (this.lineStart > -1) { + let end = Math.min(to, this.lineEnd), last = this.nodes[this.nodes.length - 1]; + if (last instanceof HeightMapText) + last.length += end - this.pos; + else if (end > this.pos || !this.isCovered) + this.nodes.push(new HeightMapText(end - this.pos, -1)); + this.writtenTo = end; + if (to > end) { + this.nodes.push(null); + this.writtenTo++; + this.lineStart = -1; + } + } + this.pos = to; + } + point(from, to, deco) { + if (from < to || deco.heightRelevant) { + let height = deco.widget ? deco.widget.estimatedHeight : 0; + if (height < 0) + height = this.oracle.lineHeight; + let len = to - from; + if (deco.block) { + this.addBlock(new HeightMapBlock(len, height, deco.type)); + } + else if (len || height >= relevantWidgetHeight) { + this.addLineDeco(height, len); + } + } + else if (to > from) { + this.span(from, to); + } + if (this.lineEnd > -1 && this.lineEnd < this.pos) + this.lineEnd = this.oracle.doc.lineAt(this.pos).to; + } + enterLine() { + if (this.lineStart > -1) + return; + let { from, to } = this.oracle.doc.lineAt(this.pos); + this.lineStart = from; + this.lineEnd = to; + if (this.writtenTo < from) { + if (this.writtenTo < from - 1 || this.nodes[this.nodes.length - 1] == null) + this.nodes.push(this.blankContent(this.writtenTo, from - 1)); + this.nodes.push(null); + } + if (this.pos > from) + this.nodes.push(new HeightMapText(this.pos - from, -1)); + this.writtenTo = this.pos; + } + blankContent(from, to) { + let gap = new HeightMapGap(to - from); + if (this.oracle.doc.lineAt(from).to == to) + gap.flags |= 4 /* Flag.SingleLine */; + return gap; + } + ensureLine() { + this.enterLine(); + let last = this.nodes.length ? this.nodes[this.nodes.length - 1] : null; + if (last instanceof HeightMapText) + return last; + let line = new HeightMapText(0, -1); + this.nodes.push(line); + return line; + } + addBlock(block) { + this.enterLine(); + if (block.type == BlockType.WidgetAfter && !this.isCovered) + this.ensureLine(); + this.nodes.push(block); + this.writtenTo = this.pos = this.pos + block.length; + if (block.type != BlockType.WidgetBefore) + this.covering = block; + } + addLineDeco(height, length) { + let line = this.ensureLine(); + line.length += length; + line.collapsed += length; + line.widgetHeight = Math.max(line.widgetHeight, height); + this.writtenTo = this.pos = this.pos + length; + } + finish(from) { + let last = this.nodes.length == 0 ? null : this.nodes[this.nodes.length - 1]; + if (this.lineStart > -1 && !(last instanceof HeightMapText) && !this.isCovered) + this.nodes.push(new HeightMapText(0, -1)); + else if (this.writtenTo < this.pos || last == null) + this.nodes.push(this.blankContent(this.writtenTo, this.pos)); + let pos = from; + for (let node of this.nodes) { + if (node instanceof HeightMapText) + node.updateHeight(this.oracle, pos); + pos += node ? node.length : 1; + } + return this.nodes; + } + // Always called with a region that on both sides either stretches + // to a line break or the end of the document. + // The returned array uses null to indicate line breaks, but never + // starts or ends in a line break, or has multiple line breaks next + // to each other. + static build(oracle, decorations, from, to) { + let builder = new NodeBuilder(from, oracle); + RangeSet.spans(decorations, from, to, builder, 0); + return builder.finish(from); + } + } + function heightRelevantDecoChanges(a, b, diff) { + let comp = new DecorationComparator; + RangeSet.compare(a, b, diff, comp, 0); + return comp.changes; + } + class DecorationComparator { + constructor() { + this.changes = []; + } + compareRange() { } + comparePoint(from, to, a, b) { + if (from < to || a && a.heightRelevant || b && b.heightRelevant) + addRange(from, to, this.changes, 5); + } + } + + function visiblePixelRange(dom, paddingTop) { + let rect = dom.getBoundingClientRect(); + let doc = dom.ownerDocument, win = doc.defaultView || window; + let left = Math.max(0, rect.left), right = Math.min(win.innerWidth, rect.right); + let top = Math.max(0, rect.top), bottom = Math.min(win.innerHeight, rect.bottom); + for (let parent = dom.parentNode; parent && parent != doc.body;) { + if (parent.nodeType == 1) { + let elt = parent; + let style = window.getComputedStyle(elt); + if ((elt.scrollHeight > elt.clientHeight || elt.scrollWidth > elt.clientWidth) && + style.overflow != "visible") { + let parentRect = elt.getBoundingClientRect(); + left = Math.max(left, parentRect.left); + right = Math.min(right, parentRect.right); + top = Math.max(top, parentRect.top); + bottom = parent == dom.parentNode ? parentRect.bottom : Math.min(bottom, parentRect.bottom); + } + parent = style.position == "absolute" || style.position == "fixed" ? elt.offsetParent : elt.parentNode; + } + else if (parent.nodeType == 11) { // Shadow root + parent = parent.host; + } + else { + break; + } + } + return { left: left - rect.left, right: Math.max(left, right) - rect.left, + top: top - (rect.top + paddingTop), bottom: Math.max(top, bottom) - (rect.top + paddingTop) }; + } + function fullPixelRange(dom, paddingTop) { + let rect = dom.getBoundingClientRect(); + return { left: 0, right: rect.right - rect.left, + top: paddingTop, bottom: rect.bottom - (rect.top + paddingTop) }; + } + // Line gaps are placeholder widgets used to hide pieces of overlong + // lines within the viewport, as a kludge to keep the editor + // responsive when a ridiculously long line is loaded into it. + class LineGap { + constructor(from, to, size) { + this.from = from; + this.to = to; + this.size = size; + } + static same(a, b) { + if (a.length != b.length) + return false; + for (let i = 0; i < a.length; i++) { + let gA = a[i], gB = b[i]; + if (gA.from != gB.from || gA.to != gB.to || gA.size != gB.size) + return false; + } + return true; + } + draw(wrapping) { + return Decoration.replace({ widget: new LineGapWidget(this.size, wrapping) }).range(this.from, this.to); + } + } + class LineGapWidget extends WidgetType { + constructor(size, vertical) { + super(); + this.size = size; + this.vertical = vertical; + } + eq(other) { return other.size == this.size && other.vertical == this.vertical; } + toDOM() { + let elt = document.createElement("div"); + if (this.vertical) { + elt.style.height = this.size + "px"; + } + else { + elt.style.width = this.size + "px"; + elt.style.height = "2px"; + elt.style.display = "inline-block"; + } + return elt; + } + get estimatedHeight() { return this.vertical ? this.size : -1; } + } + class ViewState { + constructor(state) { + this.state = state; + // These are contentDOM-local coordinates + this.pixelViewport = { left: 0, right: window.innerWidth, top: 0, bottom: 0 }; + this.inView = true; + this.paddingTop = 0; + this.paddingBottom = 0; + this.contentDOMWidth = 0; + this.contentDOMHeight = 0; + this.editorHeight = 0; + this.editorWidth = 0; + this.heightOracle = new HeightOracle; + // See VP.MaxDOMHeight + this.scaler = IdScaler; + this.scrollTarget = null; + // Briefly set to true when printing, to disable viewport limiting + this.printing = false; + // Flag set when editor content was redrawn, so that the next + // measure stage knows it must read DOM layout + this.mustMeasureContent = true; + this.defaultTextDirection = Direction.RTL; + this.visibleRanges = []; + // Cursor 'assoc' is only significant when the cursor is on a line + // wrap point, where it must stick to the character that it is + // associated with. Since browsers don't provide a reasonable + // interface to set or query this, when a selection is set that + // might cause this to be significant, this flag is set. The next + // measure phase will check whether the cursor is on a line-wrapping + // boundary and, if so, reset it to make sure it is positioned in + // the right place. + this.mustEnforceCursorAssoc = false; + this.stateDeco = state.facet(decorations).filter(d => typeof d != "function"); + this.heightMap = HeightMap.empty().applyChanges(this.stateDeco, Text.empty, this.heightOracle.setDoc(state.doc), [new ChangedRange(0, 0, 0, state.doc.length)]); + this.viewport = this.getViewport(0, null); + this.updateViewportLines(); + this.updateForViewport(); + this.lineGaps = this.ensureLineGaps([]); + this.lineGapDeco = Decoration.set(this.lineGaps.map(gap => gap.draw(false))); + this.computeVisibleRanges(); + } + updateForViewport() { + let viewports = [this.viewport], { main } = this.state.selection; + for (let i = 0; i <= 1; i++) { + let pos = i ? main.head : main.anchor; + if (!viewports.some(({ from, to }) => pos >= from && pos <= to)) { + let { from, to } = this.lineBlockAt(pos); + viewports.push(new Viewport(from, to)); + } + } + this.viewports = viewports.sort((a, b) => a.from - b.from); + this.scaler = this.heightMap.height <= 7000000 /* VP.MaxDOMHeight */ ? IdScaler : + new BigScaler(this.heightOracle.doc, this.heightMap, this.viewports); + } + updateViewportLines() { + this.viewportLines = []; + this.heightMap.forEachLine(this.viewport.from, this.viewport.to, this.state.doc, 0, 0, block => { + this.viewportLines.push(this.scaler.scale == 1 ? block : scaleBlock(block, this.scaler)); + }); + } + update(update, scrollTarget = null) { + this.state = update.state; + let prevDeco = this.stateDeco; + this.stateDeco = this.state.facet(decorations).filter(d => typeof d != "function"); + let contentChanges = update.changedRanges; + let heightChanges = ChangedRange.extendWithRanges(contentChanges, heightRelevantDecoChanges(prevDeco, this.stateDeco, update ? update.changes : ChangeSet.empty(this.state.doc.length))); + let prevHeight = this.heightMap.height; + this.heightMap = this.heightMap.applyChanges(this.stateDeco, update.startState.doc, this.heightOracle.setDoc(this.state.doc), heightChanges); + if (this.heightMap.height != prevHeight) + update.flags |= 2 /* UpdateFlag.Height */; + let viewport = heightChanges.length ? this.mapViewport(this.viewport, update.changes) : this.viewport; + if (scrollTarget && (scrollTarget.range.head < viewport.from || scrollTarget.range.head > viewport.to) || + !this.viewportIsAppropriate(viewport)) + viewport = this.getViewport(0, scrollTarget); + let updateLines = !update.changes.empty || (update.flags & 2 /* UpdateFlag.Height */) || + viewport.from != this.viewport.from || viewport.to != this.viewport.to; + this.viewport = viewport; + this.updateForViewport(); + if (updateLines) + this.updateViewportLines(); + if (this.lineGaps.length || this.viewport.to - this.viewport.from > (2000 /* LG.Margin */ << 1)) + this.updateLineGaps(this.ensureLineGaps(this.mapLineGaps(this.lineGaps, update.changes))); + update.flags |= this.computeVisibleRanges(); + if (scrollTarget) + this.scrollTarget = scrollTarget; + if (!this.mustEnforceCursorAssoc && update.selectionSet && update.view.lineWrapping && + update.state.selection.main.empty && update.state.selection.main.assoc) + this.mustEnforceCursorAssoc = true; + } + measure(view) { + let dom = view.contentDOM, style = window.getComputedStyle(dom); + let oracle = this.heightOracle; + let whiteSpace = style.whiteSpace; + this.defaultTextDirection = style.direction == "rtl" ? Direction.RTL : Direction.LTR; + let refresh = this.heightOracle.mustRefreshForWrapping(whiteSpace); + let measureContent = refresh || this.mustMeasureContent || this.contentDOMHeight != dom.clientHeight; + this.contentDOMHeight = dom.clientHeight; + this.mustMeasureContent = false; + let result = 0, bias = 0; + // Vertical padding + let paddingTop = parseInt(style.paddingTop) || 0, paddingBottom = parseInt(style.paddingBottom) || 0; + if (this.paddingTop != paddingTop || this.paddingBottom != paddingBottom) { + this.paddingTop = paddingTop; + this.paddingBottom = paddingBottom; + result |= 8 /* UpdateFlag.Geometry */ | 2 /* UpdateFlag.Height */; + } + if (this.editorWidth != view.scrollDOM.clientWidth) { + if (oracle.lineWrapping) + measureContent = true; + this.editorWidth = view.scrollDOM.clientWidth; + result |= 8 /* UpdateFlag.Geometry */; + } + // Pixel viewport + let pixelViewport = (this.printing ? fullPixelRange : visiblePixelRange)(dom, this.paddingTop); + let dTop = pixelViewport.top - this.pixelViewport.top, dBottom = pixelViewport.bottom - this.pixelViewport.bottom; + this.pixelViewport = pixelViewport; + let inView = this.pixelViewport.bottom > this.pixelViewport.top && this.pixelViewport.right > this.pixelViewport.left; + if (inView != this.inView) { + this.inView = inView; + if (inView) + measureContent = true; + } + if (!this.inView && !this.scrollTarget) + return 0; + let contentWidth = dom.clientWidth; + if (this.contentDOMWidth != contentWidth || this.editorHeight != view.scrollDOM.clientHeight) { + this.contentDOMWidth = contentWidth; + this.editorHeight = view.scrollDOM.clientHeight; + result |= 8 /* UpdateFlag.Geometry */; + } + if (measureContent) { + let lineHeights = view.docView.measureVisibleLineHeights(this.viewport); + if (oracle.mustRefreshForHeights(lineHeights)) + refresh = true; + if (refresh || oracle.lineWrapping && Math.abs(contentWidth - this.contentDOMWidth) > oracle.charWidth) { + let { lineHeight, charWidth } = view.docView.measureTextSize(); + refresh = oracle.refresh(whiteSpace, lineHeight, charWidth, contentWidth / charWidth, lineHeights); + if (refresh) { + view.docView.minWidth = 0; + result |= 8 /* UpdateFlag.Geometry */; + } + } + if (dTop > 0 && dBottom > 0) + bias = Math.max(dTop, dBottom); + else if (dTop < 0 && dBottom < 0) + bias = Math.min(dTop, dBottom); + oracle.heightChanged = false; + for (let vp of this.viewports) { + let heights = vp.from == this.viewport.from ? lineHeights : view.docView.measureVisibleLineHeights(vp); + this.heightMap = this.heightMap.updateHeight(oracle, 0, refresh, new MeasuredHeights(vp.from, heights)); + } + if (oracle.heightChanged) + result |= 2 /* UpdateFlag.Height */; + } + let viewportChange = !this.viewportIsAppropriate(this.viewport, bias) || + this.scrollTarget && (this.scrollTarget.range.head < this.viewport.from || this.scrollTarget.range.head > this.viewport.to); + if (viewportChange) + this.viewport = this.getViewport(bias, this.scrollTarget); + this.updateForViewport(); + if ((result & 2 /* UpdateFlag.Height */) || viewportChange) + this.updateViewportLines(); + if (this.lineGaps.length || this.viewport.to - this.viewport.from > (2000 /* LG.Margin */ << 1)) + this.updateLineGaps(this.ensureLineGaps(refresh ? [] : this.lineGaps, view)); + result |= this.computeVisibleRanges(); + if (this.mustEnforceCursorAssoc) { + this.mustEnforceCursorAssoc = false; + // This is done in the read stage, because moving the selection + // to a line end is going to trigger a layout anyway, so it + // can't be a pure write. It should be rare that it does any + // writing. + view.docView.enforceCursorAssoc(); + } + return result; + } + get visibleTop() { return this.scaler.fromDOM(this.pixelViewport.top); } + get visibleBottom() { return this.scaler.fromDOM(this.pixelViewport.bottom); } + getViewport(bias, scrollTarget) { + // This will divide VP.Margin between the top and the + // bottom, depending on the bias (the change in viewport position + // since the last update). It'll hold a number between 0 and 1 + let marginTop = 0.5 - Math.max(-0.5, Math.min(0.5, bias / 1000 /* VP.Margin */ / 2)); + let map = this.heightMap, doc = this.state.doc, { visibleTop, visibleBottom } = this; + let viewport = new Viewport(map.lineAt(visibleTop - marginTop * 1000 /* VP.Margin */, QueryType$1.ByHeight, doc, 0, 0).from, map.lineAt(visibleBottom + (1 - marginTop) * 1000 /* VP.Margin */, QueryType$1.ByHeight, doc, 0, 0).to); + // If scrollTarget is given, make sure the viewport includes that position + if (scrollTarget) { + let { head } = scrollTarget.range; + if (head < viewport.from || head > viewport.to) { + let viewHeight = Math.min(this.editorHeight, this.pixelViewport.bottom - this.pixelViewport.top); + let block = map.lineAt(head, QueryType$1.ByPos, doc, 0, 0), topPos; + if (scrollTarget.y == "center") + topPos = (block.top + block.bottom) / 2 - viewHeight / 2; + else if (scrollTarget.y == "start" || scrollTarget.y == "nearest" && head < viewport.from) + topPos = block.top; + else + topPos = block.bottom - viewHeight; + viewport = new Viewport(map.lineAt(topPos - 1000 /* VP.Margin */ / 2, QueryType$1.ByHeight, doc, 0, 0).from, map.lineAt(topPos + viewHeight + 1000 /* VP.Margin */ / 2, QueryType$1.ByHeight, doc, 0, 0).to); + } + } + return viewport; + } + mapViewport(viewport, changes) { + let from = changes.mapPos(viewport.from, -1), to = changes.mapPos(viewport.to, 1); + return new Viewport(this.heightMap.lineAt(from, QueryType$1.ByPos, this.state.doc, 0, 0).from, this.heightMap.lineAt(to, QueryType$1.ByPos, this.state.doc, 0, 0).to); + } + // Checks if a given viewport covers the visible part of the + // document and not too much beyond that. + viewportIsAppropriate({ from, to }, bias = 0) { + if (!this.inView) + return true; + let { top } = this.heightMap.lineAt(from, QueryType$1.ByPos, this.state.doc, 0, 0); + let { bottom } = this.heightMap.lineAt(to, QueryType$1.ByPos, this.state.doc, 0, 0); + let { visibleTop, visibleBottom } = this; + return (from == 0 || top <= visibleTop - Math.max(10 /* VP.MinCoverMargin */, Math.min(-bias, 250 /* VP.MaxCoverMargin */))) && + (to == this.state.doc.length || + bottom >= visibleBottom + Math.max(10 /* VP.MinCoverMargin */, Math.min(bias, 250 /* VP.MaxCoverMargin */))) && + (top > visibleTop - 2 * 1000 /* VP.Margin */ && bottom < visibleBottom + 2 * 1000 /* VP.Margin */); + } + mapLineGaps(gaps, changes) { + if (!gaps.length || changes.empty) + return gaps; + let mapped = []; + for (let gap of gaps) + if (!changes.touchesRange(gap.from, gap.to)) + mapped.push(new LineGap(changes.mapPos(gap.from), changes.mapPos(gap.to), gap.size)); + return mapped; + } + // Computes positions in the viewport where the start or end of a + // line should be hidden, trying to reuse existing line gaps when + // appropriate to avoid unneccesary redraws. + // Uses crude character-counting for the positioning and sizing, + // since actual DOM coordinates aren't always available and + // predictable. Relies on generous margins (see LG.Margin) to hide + // the artifacts this might produce from the user. + ensureLineGaps(current, mayMeasure) { + let wrapping = this.heightOracle.lineWrapping; + let margin = wrapping ? 10000 /* LG.MarginWrap */ : 2000 /* LG.Margin */, halfMargin = margin >> 1, doubleMargin = margin << 1; + // The non-wrapping logic won't work at all in predominantly right-to-left text. + if (this.defaultTextDirection != Direction.LTR && !wrapping) + return []; + let gaps = []; + let addGap = (from, to, line, structure) => { + if (to - from < halfMargin) + return; + let sel = this.state.selection.main, avoid = [sel.from]; + if (!sel.empty) + avoid.push(sel.to); + for (let pos of avoid) { + if (pos > from && pos < to) { + addGap(from, pos - 10 /* LG.SelectionMargin */, line, structure); + addGap(pos + 10 /* LG.SelectionMargin */, to, line, structure); + return; + } + } + let gap = find(current, gap => gap.from >= line.from && gap.to <= line.to && + Math.abs(gap.from - from) < halfMargin && Math.abs(gap.to - to) < halfMargin && + !avoid.some(pos => gap.from < pos && gap.to > pos)); + if (!gap) { + // When scrolling down, snap gap ends to line starts to avoid shifts in wrapping + if (to < line.to && mayMeasure && wrapping && + mayMeasure.visibleRanges.some(r => r.from <= to && r.to >= to)) { + let lineStart = mayMeasure.moveToLineBoundary(EditorSelection.cursor(to), false, true).head; + if (lineStart > from) + to = lineStart; + } + gap = new LineGap(from, to, this.gapSize(line, from, to, structure)); + } + gaps.push(gap); + }; + for (let line of this.viewportLines) { + if (line.length < doubleMargin) + continue; + let structure = lineStructure(line.from, line.to, this.stateDeco); + if (structure.total < doubleMargin) + continue; + let target = this.scrollTarget ? this.scrollTarget.range.head : null; + let viewFrom, viewTo; + if (wrapping) { + let marginHeight = (margin / this.heightOracle.lineLength) * this.heightOracle.lineHeight; + let top, bot; + if (target != null) { + top = Math.max(line.from, target - margin); + bot = Math.min(line.to, target + margin); + } + else { + top = (this.visibleTop - line.top - marginHeight) / line.height; + bot = (this.visibleBottom - line.top + marginHeight) / line.height; + } + viewFrom = findPosition(structure, top); + viewTo = findPosition(structure, bot); + } + else { + let left, right; + if (target != null) { + left = Math.max(line.from, target - doubleMargin); + right = Math.min(line.to, target + doubleMargin); + } + else { + let totalWidth = structure.total * this.heightOracle.charWidth; + let marginWidth = margin * this.heightOracle.charWidth; + left = (this.pixelViewport.left - marginWidth) / totalWidth; + right = (this.pixelViewport.right + marginWidth) / totalWidth; + } + viewFrom = findPosition(structure, left); + viewTo = findPosition(structure, right); + } + if (viewFrom > line.from) + addGap(line.from, viewFrom, line, structure); + if (viewTo < line.to) + addGap(viewTo, line.to, line, structure); + } + return gaps; + } + gapSize(line, from, to, structure) { + let fraction = findFraction(structure, to) - findFraction(structure, from); + if (this.heightOracle.lineWrapping) { + return line.height * fraction; + } + else { + return structure.total * this.heightOracle.charWidth * fraction; + } + } + updateLineGaps(gaps) { + if (!LineGap.same(gaps, this.lineGaps)) { + this.lineGaps = gaps; + this.lineGapDeco = Decoration.set(gaps.map(gap => gap.draw(this.heightOracle.lineWrapping))); + } + } + computeVisibleRanges() { + let deco = this.stateDeco; + if (this.lineGaps.length) + deco = deco.concat(this.lineGapDeco); + let ranges = []; + RangeSet.spans(deco, this.viewport.from, this.viewport.to, { + span(from, to) { ranges.push({ from, to }); }, + point() { } + }, 20); + let changed = ranges.length != this.visibleRanges.length || + this.visibleRanges.some((r, i) => r.from != ranges[i].from || r.to != ranges[i].to); + this.visibleRanges = ranges; + return changed ? 4 /* UpdateFlag.Viewport */ : 0; + } + lineBlockAt(pos) { + return (pos >= this.viewport.from && pos <= this.viewport.to && this.viewportLines.find(b => b.from <= pos && b.to >= pos)) || + scaleBlock(this.heightMap.lineAt(pos, QueryType$1.ByPos, this.state.doc, 0, 0), this.scaler); + } + lineBlockAtHeight(height) { + return scaleBlock(this.heightMap.lineAt(this.scaler.fromDOM(height), QueryType$1.ByHeight, this.state.doc, 0, 0), this.scaler); + } + elementAtHeight(height) { + return scaleBlock(this.heightMap.blockAt(this.scaler.fromDOM(height), this.state.doc, 0, 0), this.scaler); + } + get docHeight() { + return this.scaler.toDOM(this.heightMap.height); + } + get contentHeight() { + return this.docHeight + this.paddingTop + this.paddingBottom; + } + } + class Viewport { + constructor(from, to) { + this.from = from; + this.to = to; + } + } + function lineStructure(from, to, stateDeco) { + let ranges = [], pos = from, total = 0; + RangeSet.spans(stateDeco, from, to, { + span() { }, + point(from, to) { + if (from > pos) { + ranges.push({ from: pos, to: from }); + total += from - pos; + } + pos = to; + } + }, 20); // We're only interested in collapsed ranges of a significant size + if (pos < to) { + ranges.push({ from: pos, to }); + total += to - pos; + } + return { total, ranges }; + } + function findPosition({ total, ranges }, ratio) { + if (ratio <= 0) + return ranges[0].from; + if (ratio >= 1) + return ranges[ranges.length - 1].to; + let dist = Math.floor(total * ratio); + for (let i = 0;; i++) { + let { from, to } = ranges[i], size = to - from; + if (dist <= size) + return from + dist; + dist -= size; + } + } + function findFraction(structure, pos) { + let counted = 0; + for (let { from, to } of structure.ranges) { + if (pos <= to) { + counted += pos - from; + break; + } + counted += to - from; + } + return counted / structure.total; + } + function find(array, f) { + for (let val of array) + if (f(val)) + return val; + return undefined; + } + // Don't scale when the document height is within the range of what + // the DOM can handle. + const IdScaler = { + toDOM(n) { return n; }, + fromDOM(n) { return n; }, + scale: 1 + }; + // When the height is too big (> VP.MaxDOMHeight), scale down the + // regions outside the viewports so that the total height is + // VP.MaxDOMHeight. + class BigScaler { + constructor(doc, heightMap, viewports) { + let vpHeight = 0, base = 0, domBase = 0; + this.viewports = viewports.map(({ from, to }) => { + let top = heightMap.lineAt(from, QueryType$1.ByPos, doc, 0, 0).top; + let bottom = heightMap.lineAt(to, QueryType$1.ByPos, doc, 0, 0).bottom; + vpHeight += bottom - top; + return { from, to, top, bottom, domTop: 0, domBottom: 0 }; + }); + this.scale = (7000000 /* VP.MaxDOMHeight */ - vpHeight) / (heightMap.height - vpHeight); + for (let obj of this.viewports) { + obj.domTop = domBase + (obj.top - base) * this.scale; + domBase = obj.domBottom = obj.domTop + (obj.bottom - obj.top); + base = obj.bottom; + } + } + toDOM(n) { + for (let i = 0, base = 0, domBase = 0;; i++) { + let vp = i < this.viewports.length ? this.viewports[i] : null; + if (!vp || n < vp.top) + return domBase + (n - base) * this.scale; + if (n <= vp.bottom) + return vp.domTop + (n - vp.top); + base = vp.bottom; + domBase = vp.domBottom; + } + } + fromDOM(n) { + for (let i = 0, base = 0, domBase = 0;; i++) { + let vp = i < this.viewports.length ? this.viewports[i] : null; + if (!vp || n < vp.domTop) + return base + (n - domBase) / this.scale; + if (n <= vp.domBottom) + return vp.top + (n - vp.domTop); + base = vp.bottom; + domBase = vp.domBottom; + } + } + } + function scaleBlock(block, scaler) { + if (scaler.scale == 1) + return block; + let bTop = scaler.toDOM(block.top), bBottom = scaler.toDOM(block.bottom); + return new BlockInfo(block.from, block.length, bTop, bBottom - bTop, Array.isArray(block.type) ? block.type.map(b => scaleBlock(b, scaler)) : block.type); + } + + const theme = /*@__PURE__*/Facet.define({ combine: strs => strs.join(" ") }); + const darkTheme = /*@__PURE__*/Facet.define({ combine: values => values.indexOf(true) > -1 }); + const baseThemeID = /*@__PURE__*/StyleModule.newName(), baseLightID = /*@__PURE__*/StyleModule.newName(), baseDarkID = /*@__PURE__*/StyleModule.newName(); + const lightDarkIDs = { "&light": "." + baseLightID, "&dark": "." + baseDarkID }; + function buildTheme(main, spec, scopes) { + return new StyleModule(spec, { + finish(sel) { + return /&/.test(sel) ? sel.replace(/&\w*/, m => { + if (m == "&") + return main; + if (!scopes || !scopes[m]) + throw new RangeError(`Unsupported selector: ${m}`); + return scopes[m]; + }) : main + " " + sel; + } + }); + } + const baseTheme$1$3 = /*@__PURE__*/buildTheme("." + baseThemeID, { + "&.cm-editor": { + position: "relative !important", + boxSizing: "border-box", + "&.cm-focused": { + // Provide a simple default outline to make sure a focused + // editor is visually distinct. Can't leave the default behavior + // because that will apply to the content element, which is + // inside the scrollable container and doesn't include the + // gutters. We also can't use an 'auto' outline, since those + // are, for some reason, drawn behind the element content, which + // will cause things like the active line background to cover + // the outline (#297). + 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, + minHeight: "100%", + display: "block", + whiteSpace: "pre", + wordWrap: "normal", + boxSizing: "border-box", + 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 4px" + }, + ".cm-selectionLayer": { + zIndex: -1, + contain: "size style" + }, + ".cm-selectionBackground": { + position: "absolute", + }, + "&light .cm-selectionBackground": { + background: "#d9d9d9" + }, + "&dark .cm-selectionBackground": { + background: "#222" + }, + "&light.cm-focused .cm-selectionBackground": { + background: "#d7d4f0" + }, + "&dark.cm-focused .cm-selectionBackground": { + background: "#233" + }, + ".cm-cursorLayer": { + zIndex: 100, + contain: "size style", + pointerEvents: "none" + }, + "&.cm-focused .cm-cursorLayer": { + animation: "steps(1) cm-blink 1.2s infinite" + }, + // Two animations defined so that we can switch between them to + // restart the animation without forcing another style + // recomputation. + "@keyframes cm-blink": { "0%": {}, "50%": { opacity: 0 }, "100%": {} }, + "@keyframes cm-blink2": { "0%": {}, "50%": { opacity: 0 }, "100%": {} }, + ".cm-cursor, .cm-dropCursor": { + position: "absolute", + borderLeft: "1.2px solid black", + marginLeft: "-0.6px", + pointerEvents: "none", + }, + ".cm-cursor": { + display: "none" + }, + "&dark .cm-cursor": { + borderLeftColor: "#444" + }, + "&.cm-focused .cm-cursor": { + display: "block" + }, + "&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", + left: 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-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" + } + }, lightDarkIDs); + + const observeOptions = { + childList: true, + characterData: true, + subtree: true, + attributes: true, + characterDataOldValue: true + }; + // IE11 has very broken mutation observers, so we also listen to + // DOMCharacterDataModified there + const useCharData = browser.ie && browser.ie_version <= 11; + class DOMObserver { + constructor(view, onChange, onScrollChanged) { + this.view = view; + this.onChange = onChange; + this.onScrollChanged = onScrollChanged; + this.active = false; + // The known selection. Kept in our own object, as opposed to just + // directly accessing the selection because: + // - Safari doesn't report the right selection in shadow DOM + // - Reading from the selection forces a DOM layout + // - This way, we can ignore selectionchange events if we have + // already seen the 'new' selection + this.selectionRange = new DOMSelectionState; + // Set when a selection change is detected, cleared on flush + this.selectionChanged = false; + this.delayedFlush = -1; + this.resizeTimeout = -1; + this.queue = []; + this.delayedAndroidKey = null; + this.lastChange = 0; + this.scrollTargets = []; + this.intersection = null; + this.resize = null; + this.intersecting = false; + this.gapIntersection = null; + this.gaps = []; + // Timeout for scheduling check of the parents that need scroll handlers + this.parentCheck = -1; + this.dom = view.contentDOM; + this.observer = new MutationObserver(mutations => { + for (let mut of mutations) + this.queue.push(mut); + // IE11 will sometimes (on typing over a selection or + // backspacing out a single character text node) call the + // observer callback before actually updating the DOM. + // + // Unrelatedly, iOS Safari will, when ending a composition, + // sometimes first clear it, deliver the mutations, and then + // reinsert the finished text. CodeMirror's handling of the + // deletion will prevent the reinsertion from happening, + // breaking composition. + if ((browser.ie && browser.ie_version <= 11 || browser.ios && view.composing) && + mutations.some(m => m.type == "childList" && m.removedNodes.length || + m.type == "characterData" && m.oldValue.length > m.target.nodeValue.length)) + this.flushSoon(); + else + this.flush(); + }); + if (useCharData) + this.onCharData = (event) => { + this.queue.push({ target: event.target, + type: "characterData", + oldValue: event.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); + if (typeof ResizeObserver == "function") { + this.resize = new ResizeObserver(() => { + if (this.view.docView.lastUpdate < Date.now() - 75) + this.onResize(); + }); + this.resize.observe(view.scrollDOM); + } + this.addWindowListeners(this.win = view.win); + this.start(); + if (typeof IntersectionObserver == "function") { + this.intersection = new IntersectionObserver(entries => { + if (this.parentCheck < 0) + this.parentCheck = setTimeout(this.listenForScroll.bind(this), 1000); + if (entries.length > 0 && (entries[entries.length - 1].intersectionRatio > 0) != this.intersecting) { + this.intersecting = !this.intersecting; + if (this.intersecting != this.view.inView) + this.onScrollChanged(document.createEvent("Event")); + } + }, {}); + this.intersection.observe(this.dom); + this.gapIntersection = new IntersectionObserver(entries => { + if (entries.length > 0 && entries[entries.length - 1].intersectionRatio > 0) + this.onScrollChanged(document.createEvent("Event")); + }, {}); + } + this.listenForScroll(); + this.readSelectionRange(); + } + onScroll(e) { + if (this.intersecting) + this.flush(false); + this.onScrollChanged(e); + } + onResize() { + if (this.resizeTimeout < 0) + this.resizeTimeout = setTimeout(() => { + this.resizeTimeout = -1; + this.view.requestMeasure(); + }, 50); + } + onPrint() { + this.view.viewState.printing = true; + this.view.measure(); + setTimeout(() => { + this.view.viewState.printing = false; + this.view.requestMeasure(); + }, 500); + } + updateGaps(gaps) { + if (this.gapIntersection && (gaps.length != this.gaps.length || this.gaps.some((g, i) => g != gaps[i]))) { + this.gapIntersection.disconnect(); + for (let gap of gaps) + this.gapIntersection.observe(gap); + this.gaps = gaps; + } + } + onSelectionChange(event) { + let wasChanged = this.selectionChanged; + if (!this.readSelectionRange() || this.delayedAndroidKey) + return; + let { view } = this, sel = this.selectionRange; + if (view.state.facet(editable) ? view.root.activeElement != this.dom : !hasSelection(view.dom, sel)) + return; + let context = sel.anchorNode && view.docView.nearest(sel.anchorNode); + if (context && context.ignoreEvent(event)) { + if (!wasChanged) + this.selectionChanged = false; + return; + } + // Deletions on IE11 fire their events in the wrong order, giving + // us a selection change event before the DOM changes are + // reported. + // Chrome Android has a similar issue when backspacing out a + // selection (#645). + if ((browser.ie && browser.ie_version <= 11 || browser.android && browser.chrome) && !view.state.selection.main.empty && + // (Selection.isCollapsed isn't reliable on IE) + sel.focusNode && isEquivalentPosition(sel.focusNode, sel.focusOffset, sel.anchorNode, sel.anchorOffset)) + this.flushSoon(); + else + this.flush(false); + } + readSelectionRange() { + let { view } = this; + // The Selection object is broken in shadow roots in Safari. See + // https://github.com/codemirror/dev/issues/414 + let range = browser.safari && view.root.nodeType == 11 && + deepActiveElement(this.dom.ownerDocument) == this.dom && + safariSelectionRangeHack(this.view) || getSelection(view.root); + if (!range || this.selectionRange.eq(range)) + return false; + let local = hasSelection(this.dom, range); + // Detect the situation where the browser has, on focus, moved the + // selection to the start of the content element. Reset it to the + // position from the editor state. + if (local && !this.selectionChanged && + view.inputState.lastFocusTime > Date.now() - 200 && + view.inputState.lastTouchTime < Date.now() - 300 && + atElementStart(this.dom, range)) { + this.view.inputState.lastFocusTime = 0; + view.docView.updateSelection(); + return false; + } + this.selectionRange.setRange(range); + if (local) + this.selectionChanged = true; + return true; + } + setSelectionRange(anchor, head) { + this.selectionRange.set(anchor.node, anchor.offset, head.node, head.offset); + this.selectionChanged = false; + } + clearSelectionRange() { + this.selectionRange.set(null, 0, null, 0); + } + listenForScroll() { + this.parentCheck = -1; + let i = 0, changed = null; + for (let dom = this.dom; dom;) { + if (dom.nodeType == 1) { + if (!changed && i < this.scrollTargets.length && this.scrollTargets[i] == dom) + i++; + else if (!changed) + changed = this.scrollTargets.slice(0, i); + if (changed) + changed.push(dom); + dom = dom.assignedSlot || dom.parentNode; + } + else if (dom.nodeType == 11) { // Shadow root + dom = dom.host; + } + else { + break; + } + } + if (i < this.scrollTargets.length && !changed) + changed = this.scrollTargets.slice(0, i); + if (changed) { + for (let dom of this.scrollTargets) + dom.removeEventListener("scroll", this.onScroll); + for (let dom of this.scrollTargets = changed) + dom.addEventListener("scroll", this.onScroll); + } + } + ignore(f) { + if (!this.active) + return f(); + try { + this.stop(); + return f(); + } + finally { + this.start(); + this.clear(); + } + } + start() { + if (this.active) + return; + this.observer.observe(this.dom, observeOptions); + if (useCharData) + this.dom.addEventListener("DOMCharacterDataModified", this.onCharData); + this.active = true; + } + stop() { + if (!this.active) + return; + this.active = false; + this.observer.disconnect(); + if (useCharData) + this.dom.removeEventListener("DOMCharacterDataModified", this.onCharData); + } + // Throw away any pending changes + clear() { + this.processRecords(); + this.queue.length = 0; + this.selectionChanged = false; + } + // Chrome Android, especially in combination with GBoard, not only + // doesn't reliably fire regular key events, but also often + // surrounds the effect of enter or backspace with a bunch of + // composition events that, when interrupted, cause text duplication + // or other kinds of corruption. This hack makes the editor back off + // from handling DOM changes for a moment when such a key is + // detected (via beforeinput or keydown), and then tries to flush + // them or, if that has no effect, dispatches the given key. + delayAndroidKey(key, keyCode) { + var _a; + if (!this.delayedAndroidKey) + this.view.win.requestAnimationFrame(() => { + let key = this.delayedAndroidKey; + this.delayedAndroidKey = null; + this.delayedFlush = -1; + if (!this.flush() && key.force) + dispatchKey(this.dom, key.key, key.keyCode); + }); + // Since backspace beforeinput is sometimes signalled spuriously, + // Enter always takes precedence. + if (!this.delayedAndroidKey || key == "Enter") + this.delayedAndroidKey = { + key, keyCode, + // Only run the key handler when no changes are detected if + // this isn't coming right after another change, in which case + // it is probably part of a weird chain of updates, and should + // be ignored if it returns the DOM to its previous state. + force: this.lastChange < Date.now() - 50 || !!((_a = this.delayedAndroidKey) === null || _a === void 0 ? void 0 : _a.force) + }; + } + flushSoon() { + if (this.delayedFlush < 0) + this.delayedFlush = this.view.win.requestAnimationFrame(() => { this.delayedFlush = -1; this.flush(); }); + } + forceFlush() { + if (this.delayedFlush >= 0) { + this.view.win.cancelAnimationFrame(this.delayedFlush); + this.delayedFlush = -1; + } + this.flush(); + } + processRecords() { + let records = this.queue; + for (let mut of this.observer.takeRecords()) + records.push(mut); + if (records.length) + this.queue = []; + let from = -1, to = -1, typeOver = false; + for (let record of records) { + let range = this.readMutation(record); + if (!range) + continue; + if (range.typeOver) + typeOver = true; + if (from == -1) { + ({ from, to } = range); + } + else { + from = Math.min(range.from, from); + to = Math.max(range.to, to); + } + } + return { from, to, typeOver }; + } + // Apply pending changes, if any + flush(readSelection = true) { + // Completely hold off flushing when pending keys are set—the code + // managing those will make sure processRecords is called and the + // view is resynchronized after + if (this.delayedFlush >= 0 || this.delayedAndroidKey) + return false; + if (readSelection) + this.readSelectionRange(); + let { from, to, typeOver } = this.processRecords(); + let newSel = this.selectionChanged && hasSelection(this.dom, this.selectionRange); + if (from < 0 && !newSel) + return false; + if (from > -1) + this.lastChange = Date.now(); + this.view.inputState.lastFocusTime = 0; + this.selectionChanged = false; + let startState = this.view.state; + let handled = this.onChange(from, to, typeOver); + // The view wasn't updated + if (this.view.state == startState) + this.view.update([]); + return handled; + } + readMutation(rec) { + let cView = this.view.docView.nearest(rec.target); + if (!cView || cView.ignoreMutation(rec)) + return null; + cView.markDirty(rec.type == "attributes"); + if (rec.type == "attributes") + cView.dirty |= 4 /* Dirty.Attrs */; + if (rec.type == "childList") { + let childBefore = findChild(cView, rec.previousSibling || rec.target.previousSibling, -1); + let childAfter = findChild(cView, rec.nextSibling || rec.target.nextSibling, 1); + return { from: childBefore ? cView.posAfter(childBefore) : cView.posAtStart, + to: childAfter ? cView.posBefore(childAfter) : cView.posAtEnd, typeOver: false }; + } + else if (rec.type == "characterData") { + return { from: cView.posAtStart, to: cView.posAtEnd, typeOver: rec.target.nodeValue == rec.oldValue }; + } + else { + return null; + } + } + setWindow(win) { + if (win != this.win) { + this.removeWindowListeners(this.win); + this.win = win; + this.addWindowListeners(this.win); + } + } + addWindowListeners(win) { + win.addEventListener("resize", this.onResize); + win.addEventListener("beforeprint", this.onPrint); + win.addEventListener("scroll", this.onScroll); + win.document.addEventListener("selectionchange", this.onSelectionChange); + } + removeWindowListeners(win) { + win.removeEventListener("scroll", this.onScroll); + win.removeEventListener("resize", this.onResize); + win.removeEventListener("beforeprint", this.onPrint); + win.document.removeEventListener("selectionchange", this.onSelectionChange); + } + destroy() { + var _a, _b, _c; + this.stop(); + (_a = this.intersection) === null || _a === void 0 ? void 0 : _a.disconnect(); + (_b = this.gapIntersection) === null || _b === void 0 ? void 0 : _b.disconnect(); + (_c = this.resize) === null || _c === void 0 ? void 0 : _c.disconnect(); + for (let dom of this.scrollTargets) + dom.removeEventListener("scroll", this.onScroll); + this.removeWindowListeners(this.win); + clearTimeout(this.parentCheck); + clearTimeout(this.resizeTimeout); + } + } + function findChild(cView, dom, dir) { + while (dom) { + let curView = ContentView.get(dom); + if (curView && curView.parent == cView) + return curView; + let parent = dom.parentNode; + dom = parent != cView.dom ? parent : dir > 0 ? dom.nextSibling : dom.previousSibling; + } + return null; + } + // Used to work around a Safari Selection/shadow DOM bug (#414) + function safariSelectionRangeHack(view) { + let found = null; + // Because Safari (at least in 2018-2021) doesn't provide regular + // access to the selection inside a shadowroot, we have to perform a + // ridiculous hack to get at it—using `execCommand` to trigger a + // `beforeInput` event so that we can read the target range from the + // event. + function read(event) { + event.preventDefault(); + event.stopImmediatePropagation(); + found = event.getTargetRanges()[0]; + } + view.contentDOM.addEventListener("beforeinput", read, true); + view.dom.ownerDocument.execCommand("indent"); + view.contentDOM.removeEventListener("beforeinput", read, true); + if (!found) + return null; + let anchorNode = found.startContainer, anchorOffset = found.startOffset; + let focusNode = found.endContainer, focusOffset = found.endOffset; + let curAnchor = view.docView.domAtPos(view.state.selection.main.anchor); + // Since such a range doesn't distinguish between anchor and head, + // use a heuristic that flips it around if its end matches the + // current anchor. + if (isEquivalentPosition(curAnchor.node, curAnchor.offset, focusNode, focusOffset)) + [anchorNode, anchorOffset, focusNode, focusOffset] = [focusNode, focusOffset, anchorNode, anchorOffset]; + return { anchorNode, anchorOffset, focusNode, focusOffset }; + } + + function applyDOMChange(view, start, end, typeOver) { + let change, newSel; + let sel = view.state.selection.main; + if (start > -1) { + let bounds = view.docView.domBoundsAround(start, end, 0); + if (!bounds || view.state.readOnly) + return false; + let { from, to } = bounds; + let selPoints = view.docView.impreciseHead || view.docView.impreciseAnchor ? [] : selectionPoints(view); + let reader = new DOMReader(selPoints, view.state); + reader.readRange(bounds.startDOM, bounds.endDOM); + let preferredPos = sel.from, preferredSide = null; + // Prefer anchoring to end when Backspace is pressed (or, on + // Android, when something was deleted) + if (view.inputState.lastKeyCode === 8 && view.inputState.lastKeyTime > Date.now() - 100 || + browser.android && reader.text.length < to - from) { + preferredPos = sel.to; + preferredSide = "end"; + } + let diff = findDiff(view.state.doc.sliceString(from, to, LineBreakPlaceholder), reader.text, preferredPos - from, preferredSide); + if (diff) { + // Chrome inserts two newlines when pressing shift-enter at the + // end of a line. This drops one of those. + if (browser.chrome && view.inputState.lastKeyCode == 13 && + diff.toB == diff.from + 2 && reader.text.slice(diff.from, diff.toB) == LineBreakPlaceholder + LineBreakPlaceholder) + diff.toB--; + change = { from: from + diff.from, to: from + diff.toA, + insert: Text.of(reader.text.slice(diff.from, diff.toB).split(LineBreakPlaceholder)) }; + } + newSel = selectionFromPoints(selPoints, from); + } + else if (view.hasFocus || !view.state.facet(editable)) { + let domSel = view.observer.selectionRange; + let { impreciseHead: iHead, impreciseAnchor: iAnchor } = view.docView; + let head = iHead && iHead.node == domSel.focusNode && iHead.offset == domSel.focusOffset || + !contains(view.contentDOM, domSel.focusNode) + ? view.state.selection.main.head + : view.docView.posFromDOM(domSel.focusNode, domSel.focusOffset); + let anchor = iAnchor && iAnchor.node == domSel.anchorNode && iAnchor.offset == domSel.anchorOffset || + !contains(view.contentDOM, domSel.anchorNode) + ? view.state.selection.main.anchor + : view.docView.posFromDOM(domSel.anchorNode, domSel.anchorOffset); + if (head != sel.head || anchor != sel.anchor) + newSel = EditorSelection.single(anchor, head); + } + if (!change && !newSel) + return false; + if (!change && typeOver && !sel.empty && newSel && newSel.main.empty) { + // Heuristic to notice typing over a selected character + change = { from: sel.from, to: sel.to, insert: view.state.doc.slice(sel.from, sel.to) }; + } + else if (change && change.from >= sel.from && change.to <= sel.to && + (change.from != sel.from || change.to != sel.to) && + (sel.to - sel.from) - (change.to - change.from) <= 4) { + // If the change is inside the selection and covers most of it, + // assume it is a selection replace (with identical characters at + // the start/end not included in the diff) + change = { + from: sel.from, to: sel.to, + insert: view.state.doc.slice(sel.from, change.from).append(change.insert).append(view.state.doc.slice(change.to, sel.to)) + }; + } + else if ((browser.mac || browser.android) && change && change.from == change.to && change.from == sel.head - 1 && + /^\. ?$/.test(change.insert.toString())) { + // Detect insert-period-on-double-space Mac and Android behavior, + // and transform it into a regular space insert. + if (newSel && change.insert.length == 2) + newSel = EditorSelection.single(newSel.main.anchor - 1, newSel.main.head - 1); + change = { from: sel.from, to: sel.to, insert: Text.of([" "]) }; + } + if (change) { + let startState = view.state; + if (browser.ios && view.inputState.flushIOSKey(view)) + return true; + // Android browsers don't fire reasonable key events for enter, + // backspace, or delete. So this detects changes that look like + // they're caused by those keys, and reinterprets them as key + // events. (Some of these keys are also handled by beforeinput + // events and the pendingAndroidKey mechanism, but that's not + // reliable in all situations.) + if (browser.android && + ((change.from == sel.from && change.to == sel.to && + change.insert.length == 1 && change.insert.lines == 2 && + dispatchKey(view.contentDOM, "Enter", 13)) || + (change.from == sel.from - 1 && change.to == sel.to && change.insert.length == 0 && + dispatchKey(view.contentDOM, "Backspace", 8)) || + (change.from == sel.from && change.to == sel.to + 1 && change.insert.length == 0 && + dispatchKey(view.contentDOM, "Delete", 46)))) + return true; + let text = change.insert.toString(); + if (view.state.facet(inputHandler$1).some(h => h(view, change.from, change.to, text))) + return true; + if (view.inputState.composing >= 0) + view.inputState.composing++; + let tr; + if (change.from >= sel.from && change.to <= sel.to && change.to - change.from >= (sel.to - sel.from) / 3 && + (!newSel || newSel.main.empty && newSel.main.from == change.from + change.insert.length) && + view.inputState.composing < 0) { + let before = sel.from < change.from ? startState.sliceDoc(sel.from, change.from) : ""; + let after = sel.to > change.to ? startState.sliceDoc(change.to, sel.to) : ""; + tr = startState.replaceSelection(view.state.toText(before + change.insert.sliceString(0, undefined, view.state.lineBreak) + after)); + } + else { + let changes = startState.changes(change); + let mainSel = newSel && !startState.selection.main.eq(newSel.main) && newSel.main.to <= changes.newLength + ? newSel.main : undefined; + // Try to apply a composition change to all cursors + if (startState.selection.ranges.length > 1 && view.inputState.composing >= 0 && + change.to <= sel.to && change.to >= sel.to - 10) { + let replaced = view.state.sliceDoc(change.from, change.to); + let compositionRange = compositionSurroundingNode(view) || view.state.doc.lineAt(sel.head); + let offset = sel.to - change.to, size = sel.to - sel.from; + tr = startState.changeByRange(range => { + if (range.from == sel.from && range.to == sel.to) + return { changes, range: mainSel || range.map(changes) }; + let to = range.to - offset, from = to - replaced.length; + if (range.to - range.from != size || view.state.sliceDoc(from, to) != replaced || + // Unfortunately, there's no way to make multiple + // changes in the same node work without aborting + // composition, so cursors in the composition range are + // ignored. + compositionRange && range.to >= compositionRange.from && range.from <= compositionRange.to) + return { range }; + let rangeChanges = startState.changes({ from, to, insert: change.insert }), selOff = range.to - sel.to; + return { + changes: rangeChanges, + range: !mainSel ? range.map(rangeChanges) : + EditorSelection.range(Math.max(0, mainSel.anchor + selOff), Math.max(0, mainSel.head + selOff)) + }; + }); + } + else { + tr = { + changes, + selection: mainSel && startState.selection.replaceRange(mainSel) + }; + } + } + let userEvent = "input.type"; + if (view.composing) { + userEvent += ".compose"; + if (view.inputState.compositionFirstChange) { + userEvent += ".start"; + view.inputState.compositionFirstChange = false; + } + } + view.dispatch(tr, { scrollIntoView: true, userEvent }); + return true; + } + else if (newSel && !newSel.main.eq(sel)) { + let scrollIntoView = false, userEvent = "select"; + if (view.inputState.lastSelectionTime > Date.now() - 50) { + if (view.inputState.lastSelectionOrigin == "select") + scrollIntoView = true; + userEvent = view.inputState.lastSelectionOrigin; + } + view.dispatch({ selection: newSel, scrollIntoView, userEvent }); + return true; + } + else { + return false; + } + } + function findDiff(a, b, preferredPos, preferredSide) { + let minLen = Math.min(a.length, b.length); + let from = 0; + while (from < minLen && a.charCodeAt(from) == b.charCodeAt(from)) + from++; + if (from == minLen && a.length == b.length) + return null; + let toA = a.length, toB = b.length; + while (toA > 0 && toB > 0 && a.charCodeAt(toA - 1) == b.charCodeAt(toB - 1)) { + toA--; + toB--; + } + if (preferredSide == "end") { + let adjust = Math.max(0, from - Math.min(toA, toB)); + preferredPos -= toA + adjust - from; + } + if (toA < from && a.length < b.length) { + let move = preferredPos <= from && preferredPos >= toA ? from - preferredPos : 0; + from -= move; + toB = from + (toB - toA); + toA = from; + } + else if (toB < from) { + let move = preferredPos <= from && preferredPos >= toB ? from - preferredPos : 0; + from -= move; + toA = from + (toA - toB); + toB = from; + } + return { from, toA, toB }; + } + function selectionPoints(view) { + let result = []; + if (view.root.activeElement != view.contentDOM) + return result; + let { anchorNode, anchorOffset, focusNode, focusOffset } = view.observer.selectionRange; + if (anchorNode) { + result.push(new DOMPoint(anchorNode, anchorOffset)); + if (focusNode != anchorNode || focusOffset != anchorOffset) + result.push(new DOMPoint(focusNode, focusOffset)); + } + return result; + } + function selectionFromPoints(points, base) { + if (points.length == 0) + return null; + let anchor = points[0].pos, head = points.length == 2 ? points[1].pos : anchor; + return anchor > -1 && head > -1 ? EditorSelection.single(anchor + base, head + base) : null; + } + + // The editor's update state machine looks something like this: + // + // Idle → Updating ⇆ Idle (unchecked) → Measuring → Idle + // ↑ ↓ + // Updating (measure) + // + // The difference between 'Idle' and 'Idle (unchecked)' lies in + // whether a layout check has been scheduled. A regular update through + // the `update` method updates the DOM in a write-only fashion, and + // relies on a check (scheduled with `requestAnimationFrame`) to make + // sure everything is where it should be and the viewport covers the + // visible code. That check continues to measure and then optionally + // update until it reaches a coherent state. + /** + An editor view represents the editor's user interface. It holds + the editable DOM surface, and possibly other elements such as the + line number gutter. It handles events and dispatches state + transactions for editing actions. + */ + class EditorView { + /** + Construct a new view. You'll want to either provide a `parent` + option, or put `view.dom` into your document after creating a + view, so that the user can see the editor. + */ + constructor(config = {}) { + this.plugins = []; + this.pluginMap = new Map; + this.editorAttrs = {}; + this.contentAttrs = {}; + this.bidiCache = []; + this.destroyed = false; + /** + @internal + */ + this.updateState = 2 /* UpdateState.Updating */; + /** + @internal + */ + this.measureScheduled = -1; + /** + @internal + */ + 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.style.cssText = "position: absolute; top: -10000px"; + this.announceDOM.setAttribute("aria-live", "polite"); + this.dom = document.createElement("div"); + this.dom.appendChild(this.announceDOM); + this.dom.appendChild(this.scrollDOM); + this._dispatch = config.dispatch || ((tr) => this.update([tr])); + this.dispatch = this.dispatch.bind(this); + this._root = (config.root || getRoot(config.parent) || document); + this.viewState = new ViewState(config.state || EditorState.create(config)); + this.plugins = this.state.facet(viewPlugin).map(spec => new PluginInstance(spec)); + for (let plugin of this.plugins) + plugin.update(this); + this.observer = new DOMObserver(this, (from, to, typeOver) => { + return applyDOMChange(this, from, to, typeOver); + }, event => { + this.inputState.runScrollHandlers(this, event); + if (this.observer.intersecting) + this.measure(); + }); + this.inputState = new InputState(this); + this.inputState.ensureHandlers(this, this.plugins); + this.docView = new DocView(this); + this.mountStyles(); + this.updateAttrs(); + this.updateState = 0 /* UpdateState.Idle */; + this.requestMeasure(); + if (config.parent) + config.parent.appendChild(this.dom); + } + /** + The current editor state. + */ + get state() { return this.viewState.state; } + /** + To be able to display large documents without consuming too much + memory or overloading the browser, CodeMirror only draws the + code that is visible (plus a margin around it) to the DOM. This + property tells you the extent of the current drawn viewport, in + document positions. + */ + get viewport() { return this.viewState.viewport; } + /** + When there are, for example, large collapsed ranges in the + viewport, its size can be a lot bigger than the actual visible + content. Thus, if you are doing something like styling the + content in the viewport, it is preferable to only do so for + these ranges, which are the subset of the viewport that is + actually drawn. + */ + get visibleRanges() { return this.viewState.visibleRanges; } + /** + Returns false when the editor is entirely scrolled out of view + or otherwise hidden. + */ + get inView() { return this.viewState.inView; } + /** + Indicates whether the user is currently composing text via + [IME](https://en.wikipedia.org/wiki/Input_method), and at least + one change has been made in the current composition. + */ + get composing() { return this.inputState.composing > 0; } + /** + Indicates whether the user is currently in composing state. Note + that on some platforms, like Android, this will be the case a + lot, since just putting the cursor on a word starts a + composition there. + */ + get compositionStarted() { return this.inputState.composing >= 0; } + /** + The document or shadow root that the view lives in. + */ + get root() { return this._root; } + /** + @internal + */ + get win() { return this.dom.ownerDocument.defaultView || window; } + dispatch(...input) { + this._dispatch(input.length == 1 && input[0] instanceof Transaction ? input[0] + : this.state.update(...input)); + } + /** + Update the view for the given array of transactions. This will + update the visible document and selection to match the state + produced by the transactions, and notify view plugins of the + change. You should usually call + [`dispatch`](https://codemirror.net/6/docs/ref/#view.EditorView.dispatch) instead, which uses this + as a primitive. + */ + update(transactions) { + if (this.updateState != 0 /* UpdateState.Idle */) + throw new Error("Calls to EditorView.update are not allowed while an update is in progress"); + let redrawn = false, attrsChanged = false, update; + let state = this.state; + for (let tr of transactions) { + if (tr.startState != state) + throw new RangeError("Trying to update state with a transaction that doesn't start from the previous state."); + state = tr.state; + } + if (this.destroyed) { + this.viewState.state = state; + return; + } + this.observer.clear(); + // When the phrases change, redraw the editor + if (state.facet(EditorState.phrases) != this.state.facet(EditorState.phrases)) + return this.setState(state); + update = ViewUpdate.create(this, state, transactions); + let scrollTarget = this.viewState.scrollTarget; + try { + this.updateState = 2 /* UpdateState.Updating */; + for (let tr of transactions) { + if (scrollTarget) + scrollTarget = scrollTarget.map(tr.changes); + if (tr.scrollIntoView) { + let { main } = tr.state.selection; + scrollTarget = new ScrollTarget(main.empty ? main : EditorSelection.cursor(main.head, main.head > main.anchor ? -1 : 1)); + } + for (let e of tr.effects) + if (e.is(scrollIntoView$1)) + scrollTarget = e.value; + } + this.viewState.update(update, scrollTarget); + this.bidiCache = CachedOrder.update(this.bidiCache, update.changes); + if (!update.empty) { + this.updatePlugins(update); + this.inputState.update(update); + } + redrawn = this.docView.update(update); + if (this.state.facet(styleModule) != this.styleModules) + this.mountStyles(); + attrsChanged = this.updateAttrs(); + this.showAnnouncements(transactions); + this.docView.updateSelection(redrawn, transactions.some(tr => tr.isUserEvent("select.pointer"))); + } + finally { + this.updateState = 0 /* UpdateState.Idle */; + } + if (update.startState.facet(theme) != update.state.facet(theme)) + this.viewState.mustMeasureContent = true; + if (redrawn || attrsChanged || scrollTarget || this.viewState.mustEnforceCursorAssoc || this.viewState.mustMeasureContent) + this.requestMeasure(); + if (!update.empty) + for (let listener of this.state.facet(updateListener)) + listener(update); + } + /** + Reset the view to the given state. (This will cause the entire + document to be redrawn and all view plugins to be reinitialized, + so you should probably only use it when the new state isn't + derived from the old state. Otherwise, use + [`dispatch`](https://codemirror.net/6/docs/ref/#view.EditorView.dispatch) instead.) + */ + setState(newState) { + if (this.updateState != 0 /* UpdateState.Idle */) + throw new Error("Calls to EditorView.setState are not allowed while an update is in progress"); + if (this.destroyed) { + this.viewState.state = newState; + return; + } + this.updateState = 2 /* UpdateState.Updating */; + let hadFocus = this.hasFocus; + try { + for (let plugin of this.plugins) + plugin.destroy(this); + this.viewState = new ViewState(newState); + this.plugins = newState.facet(viewPlugin).map(spec => new PluginInstance(spec)); + this.pluginMap.clear(); + for (let plugin of this.plugins) + plugin.update(this); + this.docView = new DocView(this); + this.inputState.ensureHandlers(this, this.plugins); + this.mountStyles(); + this.updateAttrs(); + this.bidiCache = []; + } + finally { + this.updateState = 0 /* UpdateState.Idle */; + } + if (hadFocus) + this.focus(); + this.requestMeasure(); + } + updatePlugins(update) { + let prevSpecs = update.startState.facet(viewPlugin), specs = update.state.facet(viewPlugin); + if (prevSpecs != specs) { + let newPlugins = []; + for (let spec of specs) { + let found = prevSpecs.indexOf(spec); + if (found < 0) { + newPlugins.push(new PluginInstance(spec)); + } + else { + let plugin = this.plugins[found]; + plugin.mustUpdate = update; + newPlugins.push(plugin); + } + } + for (let plugin of this.plugins) + if (plugin.mustUpdate != update) + plugin.destroy(this); + this.plugins = newPlugins; + this.pluginMap.clear(); + this.inputState.ensureHandlers(this, this.plugins); + } + else { + for (let p of this.plugins) + p.mustUpdate = update; + } + for (let i = 0; i < this.plugins.length; i++) + this.plugins[i].update(this); + } + /** + @internal + */ + measure(flush = true) { + if (this.destroyed) + return; + if (this.measureScheduled > -1) + cancelAnimationFrame(this.measureScheduled); + this.measureScheduled = 0; // Prevent requestMeasure calls from scheduling another animation frame + if (flush) + this.observer.forceFlush(); + let updated = null; + let { scrollHeight, scrollTop, clientHeight } = this.scrollDOM; + let refHeight = scrollTop > scrollHeight - clientHeight - 4 ? scrollHeight : scrollTop; + try { + for (let i = 0;; i++) { + this.updateState = 1 /* UpdateState.Measuring */; + let oldViewport = this.viewport; + let refBlock = this.viewState.lineBlockAtHeight(refHeight); + let changed = this.viewState.measure(this); + if (!changed && !this.measureRequests.length && this.viewState.scrollTarget == null) + break; + if (i > 5) { + console.warn(this.measureRequests.length + ? "Measure loop restarted more than 5 times" + : "Viewport failed to stabilize"); + break; + } + let measuring = []; + // Only run measure requests in this cycle when the viewport didn't change + if (!(changed & 4 /* UpdateFlag.Viewport */)) + [this.measureRequests, measuring] = [measuring, this.measureRequests]; + let measured = measuring.map(m => { + try { + return m.read(this); + } + catch (e) { + logException(this.state, e); + return BadMeasure; + } + }); + let update = ViewUpdate.create(this, this.state, []), redrawn = false, scrolled = false; + update.flags |= changed; + if (!updated) + updated = update; + else + updated.flags |= changed; + this.updateState = 2 /* UpdateState.Updating */; + if (!update.empty) { + this.updatePlugins(update); + this.inputState.update(update); + this.updateAttrs(); + redrawn = this.docView.update(update); + } + for (let i = 0; i < measuring.length; i++) + if (measured[i] != BadMeasure) { + try { + let m = measuring[i]; + if (m.write) + m.write(measured[i], this); + } + catch (e) { + logException(this.state, e); + } + } + if (this.viewState.scrollTarget) { + this.docView.scrollIntoView(this.viewState.scrollTarget); + this.viewState.scrollTarget = null; + scrolled = true; + } + else { + let diff = this.viewState.lineBlockAt(refBlock.from).top - refBlock.top; + if (diff > 1 || diff < -1) { + this.scrollDOM.scrollTop += diff; + scrolled = true; + } + } + if (redrawn) + this.docView.updateSelection(true); + if (this.viewport.from == oldViewport.from && this.viewport.to == oldViewport.to && + !scrolled && this.measureRequests.length == 0) + break; + } + } + finally { + this.updateState = 0 /* UpdateState.Idle */; + this.measureScheduled = -1; + } + if (updated && !updated.empty) + for (let listener of this.state.facet(updateListener)) + listener(updated); + } + /** + Get the CSS classes for the currently active editor themes. + */ + get themeClasses() { + return baseThemeID + " " + + (this.state.facet(darkTheme) ? baseDarkID : baseLightID) + " " + + this.state.facet(theme); + } + updateAttrs() { + let editorAttrs = attrsFromFacet(this, editorAttributes, { + class: "cm-editor" + (this.hasFocus ? " cm-focused " : " ") + this.themeClasses + }); + let contentAttrs = { + spellcheck: "false", + autocorrect: "off", + autocapitalize: "off", + translate: "no", + contenteditable: !this.state.facet(editable) ? "false" : "true", + class: "cm-content", + style: `${browser.tabSize}: ${this.state.tabSize}`, + role: "textbox", + "aria-multiline": "true" + }; + if (this.state.readOnly) + contentAttrs["aria-readonly"] = "true"; + attrsFromFacet(this, contentAttributes, contentAttrs); + let changed = this.observer.ignore(() => { + let changedContent = updateAttrs(this.contentDOM, this.contentAttrs, contentAttrs); + let changedEditor = updateAttrs(this.dom, this.editorAttrs, editorAttrs); + return changedContent || changedEditor; + }); + this.editorAttrs = editorAttrs; + this.contentAttrs = contentAttrs; + return changed; + } + showAnnouncements(trs) { + let first = true; + for (let tr of trs) + for (let effect of tr.effects) + if (effect.is(EditorView.announce)) { + if (first) + this.announceDOM.textContent = ""; + first = false; + let div = this.announceDOM.appendChild(document.createElement("div")); + div.textContent = effect.value; + } + } + mountStyles() { + this.styleModules = this.state.facet(styleModule); + StyleModule.mount(this.root, this.styleModules.concat(baseTheme$1$3).reverse()); + } + readMeasured() { + if (this.updateState == 2 /* UpdateState.Updating */) + throw new Error("Reading the editor layout isn't allowed during an update"); + if (this.updateState == 0 /* UpdateState.Idle */ && this.measureScheduled > -1) + this.measure(false); + } + /** + Schedule a layout measurement, optionally providing callbacks to + do custom DOM measuring followed by a DOM write phase. Using + this is preferable reading DOM layout directly from, for + example, an event handler, because it'll make sure measuring and + drawing done by other components is synchronized, avoiding + unnecessary DOM layout computations. + */ + requestMeasure(request) { + if (this.measureScheduled < 0) + this.measureScheduled = this.win.requestAnimationFrame(() => this.measure()); + if (request) { + if (request.key != null) + for (let i = 0; i < this.measureRequests.length; i++) { + if (this.measureRequests[i].key === request.key) { + this.measureRequests[i] = request; + return; + } + } + this.measureRequests.push(request); + } + } + /** + Get the value of a specific plugin, if present. Note that + plugins that crash can be dropped from a view, so even when you + know you registered a given plugin, it is recommended to check + the return value of this method. + */ + plugin(plugin) { + let known = this.pluginMap.get(plugin); + if (known === undefined || known && known.spec != plugin) + this.pluginMap.set(plugin, known = this.plugins.find(p => p.spec == plugin) || null); + return known && known.update(this).value; + } + /** + The top position of the document, in screen coordinates. This + may be negative when the editor is scrolled down. Points + directly to the top of the first line, not above the padding. + */ + get documentTop() { + return this.contentDOM.getBoundingClientRect().top + this.viewState.paddingTop; + } + /** + Reports the padding above and below the document. + */ + get documentPadding() { + return { top: this.viewState.paddingTop, bottom: this.viewState.paddingBottom }; + } + /** + Find the text line or block widget at the given vertical + position (which is interpreted as relative to the [top of the + document](https://codemirror.net/6/docs/ref/#view.EditorView.documentTop)). + */ + elementAtHeight(height) { + this.readMeasured(); + return this.viewState.elementAtHeight(height); + } + /** + Find the line block (see + [`lineBlockAt`](https://codemirror.net/6/docs/ref/#view.EditorView.lineBlockAt) at the given + height, again interpreted relative to the [top of the + document](https://codemirror.net/6/docs/ref/#view.EditorView.documentTop). + */ + lineBlockAtHeight(height) { + this.readMeasured(); + return this.viewState.lineBlockAtHeight(height); + } + /** + Get the extent and vertical position of all [line + blocks](https://codemirror.net/6/docs/ref/#view.EditorView.lineBlockAt) in the viewport. Positions + are relative to the [top of the + document](https://codemirror.net/6/docs/ref/#view.EditorView.documentTop); + */ + get viewportLineBlocks() { + return this.viewState.viewportLines; + } + /** + Find the line block around the given document position. A line + block is a range delimited on both sides by either a + non-[hidden](https://codemirror.net/6/docs/ref/#view.Decoration^replace) line breaks, or the + start/end of the document. It will usually just hold a line of + text, but may be broken into multiple textblocks by block + widgets. + */ + lineBlockAt(pos) { + return this.viewState.lineBlockAt(pos); + } + /** + The editor's total content height. + */ + get contentHeight() { + return this.viewState.contentHeight; + } + /** + Move a cursor position by [grapheme + cluster](https://codemirror.net/6/docs/ref/#state.findClusterBreak). `forward` determines whether + the motion is away from the line start, or towards it. In + bidirectional text, the line is traversed in visual order, using + the editor's [text direction](https://codemirror.net/6/docs/ref/#view.EditorView.textDirection). + When the start position was the last one on the line, the + returned position will be across the line break. If there is no + further line, the original position is returned. + + By default, this method moves over a single cluster. The + optional `by` argument can be used to move across more. It will + be called with the first cluster as argument, and should return + a predicate that determines, for each subsequent cluster, + whether it should also be moved over. + */ + moveByChar(start, forward, by) { + return skipAtoms(this, start, moveByChar(this, start, forward, by)); + } + /** + Move a cursor position across the next group of either + [letters](https://codemirror.net/6/docs/ref/#state.EditorState.charCategorizer) or non-letter + non-whitespace characters. + */ + moveByGroup(start, forward) { + return skipAtoms(this, start, moveByChar(this, start, forward, initial => byGroup(this, start.head, initial))); + } + /** + Move to the next line boundary in the given direction. If + `includeWrap` is true, line wrapping is on, and there is a + further wrap point on the current line, the wrap point will be + returned. Otherwise this function will return the start or end + of the line. + */ + moveToLineBoundary(start, forward, includeWrap = true) { + return moveToLineBoundary(this, start, forward, includeWrap); + } + /** + Move a cursor position vertically. When `distance` isn't given, + it defaults to moving to the next line (including wrapped + lines). Otherwise, `distance` should provide a positive distance + in pixels. + + When `start` has a + [`goalColumn`](https://codemirror.net/6/docs/ref/#state.SelectionRange.goalColumn), the vertical + motion will use that as a target horizontal position. Otherwise, + the cursor's own horizontal position is used. The returned + cursor will have its goal column set to whichever column was + used. + */ + moveVertically(start, forward, distance) { + return skipAtoms(this, start, moveVertically(this, start, forward, distance)); + } + /** + Find the DOM parent node and offset (child offset if `node` is + an element, character offset when it is a text node) at the + given document position. + + Note that for positions that aren't currently in + `visibleRanges`, the resulting DOM position isn't necessarily + meaningful (it may just point before or after a placeholder + element). + */ + domAtPos(pos) { + return this.docView.domAtPos(pos); + } + /** + Find the document position at the given DOM node. Can be useful + for associating positions with DOM events. Will raise an error + when `node` isn't part of the editor content. + */ + posAtDOM(node, offset = 0) { + return this.docView.posFromDOM(node, offset); + } + posAtCoords(coords, precise = true) { + this.readMeasured(); + return posAtCoords(this, coords, precise); + } + /** + Get the screen coordinates at the given document position. + `side` determines whether the coordinates are based on the + element before (-1) or after (1) the position (if no element is + available on the given side, the method will transparently use + another strategy to get reasonable coordinates). + */ + coordsAtPos(pos, side = 1) { + this.readMeasured(); + let rect = this.docView.coordsAt(pos, side); + if (!rect || rect.left == rect.right) + return rect; + let line = this.state.doc.lineAt(pos), order = this.bidiSpans(line); + let span = order[BidiSpan.find(order, pos - line.from, -1, side)]; + return flattenRect(rect, (span.dir == Direction.LTR) == (side > 0)); + } + /** + The default width of a character in the editor. May not + accurately reflect the width of all characters (given variable + width fonts or styling of invididual ranges). + */ + get defaultCharacterWidth() { return this.viewState.heightOracle.charWidth; } + /** + The default height of a line in the editor. May not be accurate + for all lines. + */ + get defaultLineHeight() { return this.viewState.heightOracle.lineHeight; } + /** + The text direction + ([`direction`](https://developer.mozilla.org/en-US/docs/Web/CSS/direction) + CSS property) of the editor's content element. + */ + get textDirection() { return this.viewState.defaultTextDirection; } + /** + Find the text direction of the block at the given position, as + assigned by CSS. If + [`perLineTextDirection`](https://codemirror.net/6/docs/ref/#view.EditorView^perLineTextDirection) + isn't enabled, or the given position is outside of the viewport, + this will always return the same as + [`textDirection`](https://codemirror.net/6/docs/ref/#view.EditorView.textDirection). Note that + this may trigger a DOM layout. + */ + textDirectionAt(pos) { + let perLine = this.state.facet(perLineTextDirection); + if (!perLine || pos < this.viewport.from || pos > this.viewport.to) + return this.textDirection; + this.readMeasured(); + return this.docView.textDirectionAt(pos); + } + /** + Whether this editor [wraps lines](https://codemirror.net/6/docs/ref/#view.EditorView.lineWrapping) + (as determined by the + [`white-space`](https://developer.mozilla.org/en-US/docs/Web/CSS/white-space) + CSS property of its content element). + */ + get lineWrapping() { return this.viewState.heightOracle.lineWrapping; } + /** + Returns the bidirectional text structure of the given line + (which should be in the current document) as an array of span + objects. The order of these spans matches the [text + direction](https://codemirror.net/6/docs/ref/#view.EditorView.textDirection)—if that is + left-to-right, the leftmost spans come first, otherwise the + rightmost spans come first. + */ + bidiSpans(line) { + if (line.length > MaxBidiLine) + return trivialOrder(line.length); + let dir = this.textDirectionAt(line.from); + for (let entry of this.bidiCache) + if (entry.from == line.from && entry.dir == dir) + return entry.order; + let order = computeOrder(line.text, dir); + this.bidiCache.push(new CachedOrder(line.from, line.to, dir, order)); + return order; + } + /** + Check whether the editor has focus. + */ + get hasFocus() { + var _a; + // Safari return false for hasFocus when the context menu is open + // or closing, which leads us to ignore selection changes from the + // context menu because it looks like the editor isn't focused. + // This kludges around that. + return (this.dom.ownerDocument.hasFocus() || browser.safari && ((_a = this.inputState) === null || _a === void 0 ? void 0 : _a.lastContextMenu) > Date.now() - 3e4) && + this.root.activeElement == this.contentDOM; + } + /** + Put focus on the editor. + */ + focus() { + this.observer.ignore(() => { + focusPreventScroll(this.contentDOM); + this.docView.updateSelection(); + }); + } + /** + Update the [root](https://codemirror.net/6/docs/ref/##view.EditorViewConfig.root) in which the editor lives. This is only + necessary when moving the editor's existing DOM to a new window or shadow root. + */ + setRoot(root) { + if (this._root != root) { + this._root = root; + this.observer.setWindow((root.nodeType == 9 ? root : root.ownerDocument).defaultView || window); + this.mountStyles(); + } + } + /** + Clean up this editor view, removing its element from the + document, unregistering event handlers, and notifying + plugins. The view instance can no longer be used after + calling this. + */ + destroy() { + for (let plugin of this.plugins) + plugin.destroy(this); + this.plugins = []; + this.inputState.destroy(); + this.dom.remove(); + this.observer.destroy(); + if (this.measureScheduled > -1) + cancelAnimationFrame(this.measureScheduled); + this.destroyed = true; + } + /** + Returns an effect that can be + [added](https://codemirror.net/6/docs/ref/#state.TransactionSpec.effects) to a transaction to + cause it to scroll the given position or range into view. + */ + static scrollIntoView(pos, options = {}) { + return scrollIntoView$1.of(new ScrollTarget(typeof pos == "number" ? EditorSelection.cursor(pos) : pos, options.y, options.x, options.yMargin, options.xMargin)); + } + /** + Returns an extension that can be used to add DOM event handlers. + The value should be an object mapping event names to handler + functions. For any given event, such functions are ordered by + extension precedence, and the first handler to return true will + be assumed to have handled that event, and no other handlers or + built-in behavior will be activated for it. These are registered + on the [content element](https://codemirror.net/6/docs/ref/#view.EditorView.contentDOM), except + for `scroll` handlers, which will be called any time the + editor's [scroll element](https://codemirror.net/6/docs/ref/#view.EditorView.scrollDOM) or one of + its parent nodes is scrolled. + */ + static domEventHandlers(handlers) { + return ViewPlugin.define(() => ({}), { eventHandlers: handlers }); + } + /** + Create a theme extension. The first argument can be a + [`style-mod`](https://github.com/marijnh/style-mod#documentation) + style spec providing the styles for the theme. These will be + prefixed with a generated class for the style. + + Because the selectors will be prefixed with a scope class, rule + that directly match the editor's [wrapper + element](https://codemirror.net/6/docs/ref/#view.EditorView.dom)—to which the scope class will be + added—need to be explicitly differentiated by adding an `&` to + the selector for that element—for example + `&.cm-focused`. + + When `dark` is set to true, the theme will be marked as dark, + which will cause the `&dark` rules from [base + themes](https://codemirror.net/6/docs/ref/#view.EditorView^baseTheme) to be used (as opposed to + `&light` when a light theme is active). + */ + static theme(spec, options) { + let prefix = StyleModule.newName(); + let result = [theme.of(prefix), styleModule.of(buildTheme(`.${prefix}`, spec))]; + if (options && options.dark) + result.push(darkTheme.of(true)); + return result; + } + /** + Create an extension that adds styles to the base theme. Like + with [`theme`](https://codemirror.net/6/docs/ref/#view.EditorView^theme), use `&` to indicate the + place of the editor wrapper element when directly targeting + that. You can also use `&dark` or `&light` instead to only + target editors with a dark or light theme. + */ + static baseTheme(spec) { + return Prec.lowest(styleModule.of(buildTheme("." + baseThemeID, spec, lightDarkIDs))); + } + /** + Retrieve an editor view instance from the view's DOM + representation. + */ + static findFromDOM(dom) { + var _a; + let content = dom.querySelector(".cm-content"); + let cView = content && ContentView.get(content) || ContentView.get(dom); + return ((_a = cView === null || cView === void 0 ? void 0 : cView.rootView) === null || _a === void 0 ? void 0 : _a.view) || null; + } + } + /** + Facet to add a [style + module](https://github.com/marijnh/style-mod#documentation) to + an editor view. The view will ensure that the module is + mounted in its [document + root](https://codemirror.net/6/docs/ref/#view.EditorView.constructor^config.root). + */ + EditorView.styleModule = styleModule; + /** + An input handler can override the way changes to the editable + DOM content are handled. Handlers are passed the document + positions between which the change was found, and the new + content. When one returns true, no further input handlers are + called and the default behavior is prevented. + */ + EditorView.inputHandler = inputHandler$1; + /** + By default, the editor assumes all its content has the same + [text direction](https://codemirror.net/6/docs/ref/#view.Direction). Configure this with a `true` + value to make it read the text direction of every (rendered) + line separately. + */ + EditorView.perLineTextDirection = perLineTextDirection; + /** + Allows you to provide a function that should be called when the + library catches an exception from an extension (mostly from view + plugins, but may be used by other extensions to route exceptions + from user-code-provided callbacks). This is mostly useful for + debugging and logging. See [`logException`](https://codemirror.net/6/docs/ref/#view.logException). + */ + EditorView.exceptionSink = exceptionSink; + /** + A facet that can be used to register a function to be called + every time the view updates. + */ + EditorView.updateListener = updateListener; + /** + Facet that controls whether the editor content DOM is editable. + When its highest-precedence value is `false`, the element will + not have its `contenteditable` attribute set. (Note that this + doesn't affect API calls that change the editor content, even + when those are bound to keys or buttons. See the + [`readOnly`](https://codemirror.net/6/docs/ref/#state.EditorState.readOnly) facet for that.) + */ + EditorView.editable = editable; + /** + Allows you to influence the way mouse selection happens. The + functions in this facet will be called for a `mousedown` event + on the editor, and can return an object that overrides the way a + selection is computed from that mouse click or drag. + */ + EditorView.mouseSelectionStyle = mouseSelectionStyle; + /** + Facet used to configure whether a given selection drag event + should move or copy the selection. The given predicate will be + called with the `mousedown` event, and can return `true` when + the drag should move the content. + */ + EditorView.dragMovesSelection = dragMovesSelection$1; + /** + Facet used to configure whether a given selecting click adds a + new range to the existing selection or replaces it entirely. The + default behavior is to check `event.metaKey` on macOS, and + `event.ctrlKey` elsewhere. + */ + EditorView.clickAddsSelectionRange = clickAddsSelectionRange; + /** + A facet that determines which [decorations](https://codemirror.net/6/docs/ref/#view.Decoration) + are shown in the view. Decorations can be provided in two + ways—directly, or via a function that takes an editor view. + + Only decoration sets provided directly are allowed to influence + the editor's vertical layout structure. The ones provided as + functions are called _after_ the new viewport has been computed, + and thus **must not** introduce block widgets or replacing + decorations that cover line breaks. + + If you want decorated ranges to behave like atomic units for + cursor motion and deletion purposes, also provide the range set + containing the decorations to + [`EditorView.atomicRanges`](https://codemirror.net/6/docs/ref/#view.EditorView^atomicRanges). + */ + EditorView.decorations = decorations; + /** + Used to provide ranges that should be treated as atoms as far as + cursor motion is concerned. This causes methods like + [`moveByChar`](https://codemirror.net/6/docs/ref/#view.EditorView.moveByChar) and + [`moveVertically`](https://codemirror.net/6/docs/ref/#view.EditorView.moveVertically) (and the + commands built on top of them) to skip across such regions when + a selection endpoint would enter them. This does _not_ prevent + direct programmatic [selection + updates](https://codemirror.net/6/docs/ref/#state.TransactionSpec.selection) from moving into such + regions. + */ + EditorView.atomicRanges = atomicRanges; + /** + Facet that allows extensions to provide additional scroll + margins (space around the sides of the scrolling element that + should be considered invisible). This can be useful when the + plugin introduces elements that cover part of that element (for + example a horizontally fixed gutter). + */ + EditorView.scrollMargins = scrollMargins; + /** + This facet records whether a dark theme is active. The extension + returned by [`theme`](https://codemirror.net/6/docs/ref/#view.EditorView^theme) automatically + includes an instance of this when the `dark` option is set to + true. + */ + EditorView.darkTheme = darkTheme; + /** + Facet that provides additional DOM attributes for the editor's + editable DOM element. + */ + EditorView.contentAttributes = contentAttributes; + /** + Facet that provides DOM attributes for the editor's outer + element. + */ + EditorView.editorAttributes = editorAttributes; + /** + An extension that enables line wrapping in the editor (by + setting CSS `white-space` to `pre-wrap` in the content). + */ + EditorView.lineWrapping = /*@__PURE__*/EditorView.contentAttributes.of({ "class": "cm-lineWrapping" }); + /** + State effect used to include screen reader announcements in a + transaction. These will be added to the DOM in a visually hidden + element with `aria-live="polite"` set, and should be used to + describe effects that are visually obvious but may not be + noticed by screen reader users (such as moving to the next + search match). + */ + EditorView.announce = /*@__PURE__*/StateEffect.define(); + // Maximum line length for which we compute accurate bidi info + const MaxBidiLine = 4096; + const BadMeasure = {}; + class CachedOrder { + constructor(from, to, dir, order) { + this.from = from; + this.to = to; + this.dir = dir; + this.order = order; + } + static update(cache, changes) { + if (changes.empty) + return cache; + let result = [], lastDir = cache.length ? cache[cache.length - 1].dir : Direction.LTR; + for (let i = Math.max(0, cache.length - 10); i < cache.length; i++) { + let entry = cache[i]; + if (entry.dir == lastDir && !changes.touchesRange(entry.from, entry.to)) + result.push(new CachedOrder(changes.mapPos(entry.from, 1), changes.mapPos(entry.to, -1), entry.dir, entry.order)); + } + return result; + } + } + function attrsFromFacet(view, facet, base) { + for (let sources = view.state.facet(facet), i = sources.length - 1; i >= 0; i--) { + let source = sources[i], value = typeof source == "function" ? source(view) : source; + if (value) + combineAttrs(value, base); + } + return base; + } + + const currentPlatform = browser.mac ? "mac" : browser.windows ? "win" : browser.linux ? "linux" : "key"; + function normalizeKeyName(name, platform) { + const parts = name.split(/-(?!$)/); + let result = parts[parts.length - 1]; + if (result == "Space") + result = " "; + let alt, ctrl, shift, meta; + for (let i = 0; i < parts.length - 1; ++i) { + const mod = parts[i]; + if (/^(cmd|meta|m)$/i.test(mod)) + meta = 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 if (/^mod$/i.test(mod)) { + if (platform == "mac") + meta = true; + else + ctrl = true; + } + else + throw new Error("Unrecognized modifier name: " + mod); + } + if (alt) + result = "Alt-" + result; + if (ctrl) + result = "Ctrl-" + result; + if (meta) + result = "Meta-" + result; + if (shift) + result = "Shift-" + result; + return result; + } + function modifiers(name, event, shift) { + if (event.altKey) + name = "Alt-" + name; + if (event.ctrlKey) + name = "Ctrl-" + name; + if (event.metaKey) + name = "Meta-" + name; + if (shift !== false && event.shiftKey) + name = "Shift-" + name; + return name; + } + const handleKeyEvents = /*@__PURE__*/Prec.default(/*@__PURE__*/EditorView.domEventHandlers({ + keydown(event, view) { + return runHandlers(getKeymap(view.state), event, view, "editor"); + } + })); + /** + Facet used for registering keymaps. + + You can add multiple keymaps to an editor. Their priorities + determine their precedence (the ones specified early or with high + priority get checked first). When a handler has returned `true` + for a given key, no further handlers are called. + */ + const keymap = /*@__PURE__*/Facet.define({ enables: handleKeyEvents }); + const Keymaps = /*@__PURE__*/new WeakMap(); + // This is hidden behind an indirection, rather than directly computed + // by the facet, to keep internal types out of the facet's type. + function getKeymap(state) { + let bindings = state.facet(keymap); + let map = Keymaps.get(bindings); + if (!map) + Keymaps.set(bindings, map = buildKeymap(bindings.reduce((a, b) => a.concat(b), []))); + return map; + } + /** + Run the key handlers registered for a given scope. The event + object should be a `"keydown"` event. Returns true if any of the + handlers handled it. + */ + function runScopeHandlers(view, event, scope) { + return runHandlers(getKeymap(view.state), event, view, scope); + } + let storedPrefix = null; + const PrefixTimeout = 4000; + function buildKeymap(bindings, platform = currentPlatform) { + let bound = Object.create(null); + let isPrefix = Object.create(null); + let checkPrefix = (name, is) => { + let current = isPrefix[name]; + if (current == null) + isPrefix[name] = is; + else if (current != is) + throw new Error("Key binding " + name + " is used both as a regular binding and as a multi-stroke prefix"); + }; + let add = (scope, key, command, preventDefault) => { + var _a, _b; + let scopeObj = bound[scope] || (bound[scope] = Object.create(null)); + let parts = key.split(/ (?!$)/).map(k => normalizeKeyName(k, platform)); + for (let i = 1; i < parts.length; i++) { + let prefix = parts.slice(0, i).join(" "); + checkPrefix(prefix, true); + if (!scopeObj[prefix]) + scopeObj[prefix] = { + preventDefault: true, + run: [(view) => { + let ourObj = storedPrefix = { view, prefix, scope }; + setTimeout(() => { if (storedPrefix == ourObj) + storedPrefix = null; }, PrefixTimeout); + return true; + }] + }; + } + let full = parts.join(" "); + checkPrefix(full, false); + let binding = scopeObj[full] || (scopeObj[full] = { preventDefault: false, run: ((_b = (_a = scopeObj._any) === null || _a === void 0 ? void 0 : _a.run) === null || _b === void 0 ? void 0 : _b.slice()) || [] }); + if (command) + binding.run.push(command); + if (preventDefault) + binding.preventDefault = true; + }; + for (let b of bindings) { + let scopes = b.scope ? b.scope.split(" ") : ["editor"]; + if (b.any) + for (let scope of scopes) { + let scopeObj = bound[scope] || (bound[scope] = Object.create(null)); + if (!scopeObj._any) + scopeObj._any = { preventDefault: false, run: [] }; + for (let key in scopeObj) + scopeObj[key].run.push(b.any); + } + let name = b[platform] || b.key; + if (!name) + continue; + for (let scope of scopes) { + add(scope, name, b.run, b.preventDefault); + if (b.shift) + add(scope, "Shift-" + name, b.shift, b.preventDefault); + } + } + return bound; + } + function runHandlers(map, event, view, scope) { + let name = keyName(event); + let charCode = codePointAt(name, 0), isChar = codePointSize(charCode) == name.length && name != " "; + let prefix = "", fallthrough = false; + if (storedPrefix && storedPrefix.view == view && storedPrefix.scope == scope) { + prefix = storedPrefix.prefix + " "; + if (fallthrough = modifierCodes.indexOf(event.keyCode) < 0) + storedPrefix = null; + } + let ran = new Set; + let runFor = (binding) => { + if (binding) { + for (let cmd of binding.run) + if (!ran.has(cmd)) { + ran.add(cmd); + if (cmd(view, event)) + return true; + } + if (binding.preventDefault) + fallthrough = true; + } + return false; + }; + let scopeObj = map[scope], baseName, shiftName; + if (scopeObj) { + if (runFor(scopeObj[prefix + modifiers(name, event, !isChar)])) + return true; + if (isChar && (event.shiftKey || event.altKey || event.metaKey || charCode > 127) && + (baseName = base[event.keyCode]) && baseName != name) { + if (runFor(scopeObj[prefix + modifiers(baseName, event, true)])) + return true; + else if (event.shiftKey && (shiftName = shift[event.keyCode]) != name && shiftName != baseName && + runFor(scopeObj[prefix + modifiers(shiftName, event, false)])) + return true; + } + else if (isChar && event.shiftKey) { + if (runFor(scopeObj[prefix + modifiers(name, event, true)])) + return true; + } + if (runFor(scopeObj._any)) + return true; + } + return fallthrough; + } + + const CanHidePrimary = !browser.ios; // FIXME test IE + const selectionConfig = /*@__PURE__*/Facet.define({ + combine(configs) { + return combineConfig(configs, { + cursorBlinkRate: 1200, + drawRangeCursor: true + }, { + cursorBlinkRate: (a, b) => Math.min(a, b), + drawRangeCursor: (a, b) => a || b + }); + } + }); + /** + Returns an extension that hides the browser's native selection and + cursor, replacing the selection with a background behind the text + (with the `cm-selectionBackground` class), and the + cursors with elements overlaid over the code (using + `cm-cursor-primary` and `cm-cursor-secondary`). + + This allows the editor to display secondary selection ranges, and + tends to produce a type of selection more in line with that users + expect in a text editor (the native selection styling will often + leave gaps between lines and won't fill the horizontal space after + a line when the selection continues past it). + + It does have a performance cost, in that it requires an extra DOM + layout cycle for many updates (the selection is drawn based on DOM + layout information that's only available after laying out the + content). + */ + function drawSelection(config = {}) { + return [ + selectionConfig.of(config), + drawSelectionPlugin, + hideNativeSelection + ]; + } + class Piece { + constructor(left, top, width, height, className) { + this.left = left; + this.top = top; + this.width = width; + this.height = height; + this.className = className; + } + draw() { + let elt = document.createElement("div"); + elt.className = this.className; + this.adjust(elt); + return elt; + } + adjust(elt) { + elt.style.left = this.left + "px"; + elt.style.top = this.top + "px"; + if (this.width >= 0) + elt.style.width = this.width + "px"; + elt.style.height = this.height + "px"; + } + eq(p) { + return this.left == p.left && this.top == p.top && this.width == p.width && this.height == p.height && + this.className == p.className; + } + } + const drawSelectionPlugin = /*@__PURE__*/ViewPlugin.fromClass(class { + constructor(view) { + this.view = view; + this.rangePieces = []; + this.cursors = []; + this.measureReq = { read: this.readPos.bind(this), write: this.drawSel.bind(this) }; + this.selectionLayer = view.scrollDOM.appendChild(document.createElement("div")); + this.selectionLayer.className = "cm-selectionLayer"; + this.selectionLayer.setAttribute("aria-hidden", "true"); + this.cursorLayer = view.scrollDOM.appendChild(document.createElement("div")); + this.cursorLayer.className = "cm-cursorLayer"; + this.cursorLayer.setAttribute("aria-hidden", "true"); + view.requestMeasure(this.measureReq); + this.setBlinkRate(); + } + setBlinkRate() { + this.cursorLayer.style.animationDuration = this.view.state.facet(selectionConfig).cursorBlinkRate + "ms"; + } + update(update) { + let confChanged = update.startState.facet(selectionConfig) != update.state.facet(selectionConfig); + if (confChanged || update.selectionSet || update.geometryChanged || update.viewportChanged) + this.view.requestMeasure(this.measureReq); + if (update.transactions.some(tr => tr.scrollIntoView)) + this.cursorLayer.style.animationName = this.cursorLayer.style.animationName == "cm-blink" ? "cm-blink2" : "cm-blink"; + if (confChanged) + this.setBlinkRate(); + } + readPos() { + let { state } = this.view, conf = state.facet(selectionConfig); + let rangePieces = state.selection.ranges.map(r => r.empty ? [] : measureRange(this.view, r)).reduce((a, b) => a.concat(b)); + let cursors = []; + for (let r of state.selection.ranges) { + let prim = r == state.selection.main; + if (r.empty ? !prim || CanHidePrimary : conf.drawRangeCursor) { + let piece = measureCursor(this.view, r, prim); + if (piece) + cursors.push(piece); + } + } + return { rangePieces, cursors }; + } + drawSel({ rangePieces, cursors }) { + if (rangePieces.length != this.rangePieces.length || rangePieces.some((p, i) => !p.eq(this.rangePieces[i]))) { + this.selectionLayer.textContent = ""; + for (let p of rangePieces) + this.selectionLayer.appendChild(p.draw()); + this.rangePieces = rangePieces; + } + if (cursors.length != this.cursors.length || cursors.some((c, i) => !c.eq(this.cursors[i]))) { + let oldCursors = this.cursorLayer.children; + if (oldCursors.length !== cursors.length) { + this.cursorLayer.textContent = ""; + for (const c of cursors) + this.cursorLayer.appendChild(c.draw()); + } + else { + cursors.forEach((c, idx) => c.adjust(oldCursors[idx])); + } + this.cursors = cursors; + } + } + destroy() { + this.selectionLayer.remove(); + this.cursorLayer.remove(); + } + }); + const themeSpec = { + ".cm-line": { + "& ::selection": { backgroundColor: "transparent !important" }, + "&::selection": { backgroundColor: "transparent !important" } + } + }; + if (CanHidePrimary) + themeSpec[".cm-line"].caretColor = "transparent !important"; + const hideNativeSelection = /*@__PURE__*/Prec.highest(/*@__PURE__*/EditorView.theme(themeSpec)); + function getBase(view) { + let rect = view.scrollDOM.getBoundingClientRect(); + let left = view.textDirection == Direction.LTR ? rect.left : rect.right - view.scrollDOM.clientWidth; + return { left: left - view.scrollDOM.scrollLeft, top: rect.top - view.scrollDOM.scrollTop }; + } + function wrappedLine(view, pos, inside) { + let range = EditorSelection.cursor(pos); + return { from: Math.max(inside.from, view.moveToLineBoundary(range, false, true).from), + to: Math.min(inside.to, view.moveToLineBoundary(range, true, true).from), + type: BlockType.Text }; + } + function blockAt(view, pos) { + let line = view.lineBlockAt(pos); + if (Array.isArray(line.type)) + for (let l of line.type) { + if (l.to > pos || l.to == pos && (l.to == line.to || l.type == BlockType.Text)) + return l; + } + return line; + } + function measureRange(view, range) { + if (range.to <= view.viewport.from || range.from >= view.viewport.to) + return []; + let from = Math.max(range.from, view.viewport.from), to = Math.min(range.to, view.viewport.to); + let ltr = view.textDirection == Direction.LTR; + let content = view.contentDOM, contentRect = content.getBoundingClientRect(), base = getBase(view); + let lineStyle = window.getComputedStyle(content.firstChild); + let leftSide = contentRect.left + parseInt(lineStyle.paddingLeft) + Math.min(0, parseInt(lineStyle.textIndent)); + let rightSide = contentRect.right - parseInt(lineStyle.paddingRight); + let startBlock = blockAt(view, from), endBlock = blockAt(view, to); + let visualStart = startBlock.type == BlockType.Text ? startBlock : null; + let visualEnd = endBlock.type == BlockType.Text ? endBlock : null; + if (view.lineWrapping) { + if (visualStart) + visualStart = wrappedLine(view, from, visualStart); + if (visualEnd) + visualEnd = wrappedLine(view, to, visualEnd); + } + if (visualStart && visualEnd && visualStart.from == visualEnd.from) { + return pieces(drawForLine(range.from, range.to, visualStart)); + } + else { + let top = visualStart ? drawForLine(range.from, null, visualStart) : drawForWidget(startBlock, false); + let bottom = visualEnd ? drawForLine(null, range.to, visualEnd) : drawForWidget(endBlock, true); + let between = []; + if ((visualStart || startBlock).to < (visualEnd || endBlock).from - 1) + between.push(piece(leftSide, top.bottom, rightSide, bottom.top)); + else if (top.bottom < bottom.top && view.elementAtHeight((top.bottom + bottom.top) / 2).type == BlockType.Text) + top.bottom = bottom.top = (top.bottom + bottom.top) / 2; + return pieces(top).concat(between).concat(pieces(bottom)); + } + function piece(left, top, right, bottom) { + return new Piece(left - base.left, top - base.top - 0.01 /* C.Epsilon */, right - left, bottom - top + 0.01 /* C.Epsilon */, "cm-selectionBackground"); + } + function pieces({ top, bottom, horizontal }) { + let pieces = []; + for (let i = 0; i < horizontal.length; i += 2) + pieces.push(piece(horizontal[i], top, horizontal[i + 1], bottom)); + return pieces; + } + // Gets passed from/to in line-local positions + function drawForLine(from, to, line) { + let top = 1e9, bottom = -1e9, horizontal = []; + function addSpan(from, fromOpen, to, toOpen, dir) { + // Passing 2/-2 is a kludge to force the view to return + // coordinates on the proper side of block widgets, since + // normalizing the side there, though appropriate for most + // coordsAtPos queries, would break selection drawing. + let fromCoords = view.coordsAtPos(from, (from == line.to ? -2 : 2)); + let toCoords = view.coordsAtPos(to, (to == line.from ? 2 : -2)); + top = Math.min(fromCoords.top, toCoords.top, top); + bottom = Math.max(fromCoords.bottom, toCoords.bottom, bottom); + if (dir == Direction.LTR) + horizontal.push(ltr && fromOpen ? leftSide : fromCoords.left, ltr && toOpen ? rightSide : toCoords.right); + else + horizontal.push(!ltr && toOpen ? leftSide : toCoords.left, !ltr && fromOpen ? rightSide : fromCoords.right); + } + let start = from !== null && from !== void 0 ? from : line.from, end = to !== null && to !== void 0 ? to : line.to; + // Split the range by visible range and document line + for (let r of view.visibleRanges) + if (r.to > start && r.from < end) { + for (let pos = Math.max(r.from, start), endPos = Math.min(r.to, end);;) { + let docLine = view.state.doc.lineAt(pos); + for (let span of view.bidiSpans(docLine)) { + let spanFrom = span.from + docLine.from, spanTo = span.to + docLine.from; + if (spanFrom >= endPos) + break; + if (spanTo > pos) + addSpan(Math.max(spanFrom, pos), from == null && spanFrom <= start, Math.min(spanTo, endPos), to == null && spanTo >= end, span.dir); + } + pos = docLine.to + 1; + if (pos >= endPos) + break; + } + } + if (horizontal.length == 0) + addSpan(start, from == null, end, to == null, view.textDirection); + return { top, bottom, horizontal }; + } + function drawForWidget(block, top) { + let y = contentRect.top + (top ? block.top : block.bottom); + return { top: y, bottom: y, horizontal: [] }; + } + } + function measureCursor(view, cursor, primary) { + let pos = view.coordsAtPos(cursor.head, cursor.assoc || 1); + if (!pos) + return null; + let base = getBase(view); + return new Piece(pos.left - base.left, pos.top - base.top, -1, pos.bottom - pos.top, primary ? "cm-cursor cm-cursor-primary" : "cm-cursor cm-cursor-secondary"); + } + + const setDropCursorPos = /*@__PURE__*/StateEffect.define({ + map(pos, mapping) { return pos == null ? null : mapping.mapPos(pos); } + }); + const dropCursorPos = /*@__PURE__*/StateField.define({ + create() { return null; }, + update(pos, tr) { + if (pos != null) + pos = tr.changes.mapPos(pos); + return tr.effects.reduce((pos, e) => e.is(setDropCursorPos) ? e.value : pos, pos); + } + }); + const drawDropCursor = /*@__PURE__*/ViewPlugin.fromClass(class { + constructor(view) { + this.view = view; + this.cursor = null; + this.measureReq = { read: this.readPos.bind(this), write: this.drawCursor.bind(this) }; + } + update(update) { + var _a; + let cursorPos = update.state.field(dropCursorPos); + if (cursorPos == null) { + if (this.cursor != null) { + (_a = this.cursor) === null || _a === void 0 ? void 0 : _a.remove(); + this.cursor = null; + } + } + else { + if (!this.cursor) { + this.cursor = this.view.scrollDOM.appendChild(document.createElement("div")); + this.cursor.className = "cm-dropCursor"; + } + if (update.startState.field(dropCursorPos) != cursorPos || update.docChanged || update.geometryChanged) + this.view.requestMeasure(this.measureReq); + } + } + readPos() { + let pos = this.view.state.field(dropCursorPos); + let rect = pos != null && this.view.coordsAtPos(pos); + if (!rect) + return null; + let outer = this.view.scrollDOM.getBoundingClientRect(); + return { + left: rect.left - outer.left + this.view.scrollDOM.scrollLeft, + top: rect.top - outer.top + this.view.scrollDOM.scrollTop, + height: rect.bottom - rect.top + }; + } + drawCursor(pos) { + if (this.cursor) { + if (pos) { + this.cursor.style.left = pos.left + "px"; + this.cursor.style.top = pos.top + "px"; + this.cursor.style.height = pos.height + "px"; + } + else { + this.cursor.style.left = "-100000px"; + } + } + } + destroy() { + if (this.cursor) + this.cursor.remove(); + } + setDropPos(pos) { + if (this.view.state.field(dropCursorPos) != pos) + this.view.dispatch({ effects: setDropCursorPos.of(pos) }); + } + }, { + eventHandlers: { + dragover(event) { + this.setDropPos(this.view.posAtCoords({ x: event.clientX, y: event.clientY })); + }, + dragleave(event) { + if (event.target == this.view.contentDOM || !this.view.contentDOM.contains(event.relatedTarget)) + this.setDropPos(null); + }, + dragend() { + this.setDropPos(null); + }, + drop() { + this.setDropPos(null); + } + } + }); + /** + Draws a cursor at the current drop position when something is + dragged over the editor. + */ + function dropCursor() { + return [dropCursorPos, drawDropCursor]; + } + + function iterMatches(doc, re, from, to, f) { + re.lastIndex = 0; + for (let cursor = doc.iterRange(from, to), pos = from, m; !cursor.next().done; pos += cursor.value.length) { + if (!cursor.lineBreak) + while (m = re.exec(cursor.value)) + f(pos + m.index, m); + } + } + function matchRanges(view, maxLength) { + let visible = view.visibleRanges; + if (visible.length == 1 && visible[0].from == view.viewport.from && + visible[0].to == view.viewport.to) + return visible; + let result = []; + for (let { from, to } of visible) { + from = Math.max(view.state.doc.lineAt(from).from, from - maxLength); + to = Math.min(view.state.doc.lineAt(to).to, to + maxLength); + if (result.length && result[result.length - 1].to >= from) + result[result.length - 1].to = to; + else + result.push({ from, to }); + } + return result; + } + /** + Helper class used to make it easier to maintain decorations on + visible code that matches a given regular expression. To be used + in a [view plugin](https://codemirror.net/6/docs/ref/#view.ViewPlugin). Instances of this object + represent a matching configuration. + */ + class MatchDecorator { + /** + Create a decorator. + */ + constructor(config) { + const { regexp, decoration, decorate, boundary, maxLength = 1000 } = config; + if (!regexp.global) + throw new RangeError("The regular expression given to MatchDecorator should have its 'g' flag set"); + this.regexp = regexp; + if (decorate) { + this.addMatch = (match, view, from, add) => decorate(add, from, from + match[0].length, match, view); + } + else if (typeof decoration == "function") { + this.addMatch = (match, view, from, add) => { + let deco = decoration(match, view, from); + if (deco) + add(from, from + match[0].length, deco); + }; + } + else if (decoration) { + this.addMatch = (match, _view, from, add) => add(from, from + match[0].length, decoration); + } + else { + throw new RangeError("Either 'decorate' or 'decoration' should be provided to MatchDecorator"); + } + this.boundary = boundary; + this.maxLength = maxLength; + } + /** + Compute the full set of decorations for matches in the given + view's viewport. You'll want to call this when initializing your + plugin. + */ + createDeco(view) { + let build = new RangeSetBuilder(), add = build.add.bind(build); + for (let { from, to } of matchRanges(view, this.maxLength)) + iterMatches(view.state.doc, this.regexp, from, to, (from, m) => this.addMatch(m, view, from, add)); + return build.finish(); + } + /** + Update a set of decorations for a view update. `deco` _must_ be + the set of decorations produced by _this_ `MatchDecorator` for + the view state before the update. + */ + updateDeco(update, deco) { + let changeFrom = 1e9, changeTo = -1; + if (update.docChanged) + update.changes.iterChanges((_f, _t, from, to) => { + if (to > update.view.viewport.from && from < update.view.viewport.to) { + changeFrom = Math.min(from, changeFrom); + changeTo = Math.max(to, changeTo); + } + }); + if (update.viewportChanged || changeTo - changeFrom > 1000) + return this.createDeco(update.view); + if (changeTo > -1) + return this.updateRange(update.view, deco.map(update.changes), changeFrom, changeTo); + return deco; + } + updateRange(view, deco, updateFrom, updateTo) { + for (let r of view.visibleRanges) { + let from = Math.max(r.from, updateFrom), to = Math.min(r.to, updateTo); + if (to > from) { + let fromLine = view.state.doc.lineAt(from), toLine = fromLine.to < to ? view.state.doc.lineAt(to) : fromLine; + let start = Math.max(r.from, fromLine.from), end = Math.min(r.to, toLine.to); + if (this.boundary) { + for (; from > fromLine.from; from--) + if (this.boundary.test(fromLine.text[from - 1 - fromLine.from])) { + start = from; + break; + } + for (; to < toLine.to; to++) + if (this.boundary.test(toLine.text[to - toLine.from])) { + end = to; + break; + } + } + let ranges = [], m; + let add = (from, to, deco) => ranges.push(deco.range(from, to)); + if (fromLine == toLine) { + this.regexp.lastIndex = start - fromLine.from; + while ((m = this.regexp.exec(fromLine.text)) && m.index < end - fromLine.from) + this.addMatch(m, view, m.index + fromLine.from, add); + } + else { + iterMatches(view.state.doc, this.regexp, start, end, (from, m) => this.addMatch(m, view, from, add)); + } + deco = deco.update({ filterFrom: start, filterTo: end, filter: (from, to) => from < start || to > end, add: ranges }); + } + } + return deco; + } + } + + const UnicodeRegexpSupport = /x/.unicode != null ? "gu" : "g"; + const Specials = /*@__PURE__*/new RegExp("[\u0000-\u0008\u000a-\u001f\u007f-\u009f\u00ad\u061c\u200b\u200e\u200f\u2028\u2029\u202d\u202e\u2066\u2067\u2069\ufeff\ufff9-\ufffc]", UnicodeRegexpSupport); + const Names = { + 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 _supportsTabSize = null; + function supportsTabSize() { + var _a; + if (_supportsTabSize == null && typeof document != "undefined" && document.body) { + let styles = document.body.style; + _supportsTabSize = ((_a = styles.tabSize) !== null && _a !== void 0 ? _a : styles.MozTabSize) != null; + } + return _supportsTabSize || false; + } + const specialCharConfig = /*@__PURE__*/Facet.define({ + combine(configs) { + let config = combineConfig(configs, { + render: null, + specialChars: Specials, + addSpecialChars: null + }); + if (config.replaceTabs = !supportsTabSize()) + config.specialChars = new RegExp("\t|" + config.specialChars.source, UnicodeRegexpSupport); + if (config.addSpecialChars) + config.specialChars = new RegExp(config.specialChars.source + "|" + config.addSpecialChars.source, UnicodeRegexpSupport); + return config; + } + }); + /** + Returns an extension that installs highlighting of special + characters. + */ + function highlightSpecialChars( + /** + Configuration options. + */ + config = {}) { + return [specialCharConfig.of(config), specialCharPlugin()]; + } + let _plugin = null; + function specialCharPlugin() { + return _plugin || (_plugin = ViewPlugin.fromClass(class { + constructor(view) { + this.view = view; + this.decorations = Decoration.none; + this.decorationCache = Object.create(null); + this.decorator = this.makeDecorator(view.state.facet(specialCharConfig)); + this.decorations = this.decorator.createDeco(view); + } + makeDecorator(conf) { + return new MatchDecorator({ + regexp: conf.specialChars, + decoration: (m, view, pos) => { + let { doc } = view.state; + let code = codePointAt(m[0], 0); + if (code == 9) { + let line = doc.lineAt(pos); + let size = view.state.tabSize, col = countColumn(line.text, size, pos - line.from); + return Decoration.replace({ widget: new TabWidget((size - (col % size)) * this.view.defaultCharacterWidth) }); + } + return this.decorationCache[code] || + (this.decorationCache[code] = Decoration.replace({ widget: new SpecialCharWidget(conf, code) })); + }, + boundary: conf.replaceTabs ? undefined : /[^]/ + }); + } + update(update) { + let conf = update.state.facet(specialCharConfig); + if (update.startState.facet(specialCharConfig) != conf) { + this.decorator = this.makeDecorator(conf); + this.decorations = this.decorator.createDeco(update.view); + } + else { + this.decorations = this.decorator.updateDeco(update, this.decorations); + } + } + }, { + decorations: v => v.decorations + })); + } + const DefaultPlaceholder = "\u2022"; + // Assigns placeholder characters from the Control Pictures block to + // ASCII control characters + function placeholder$1(code) { + if (code >= 32) + return DefaultPlaceholder; + if (code == 10) + return "\u2424"; + return String.fromCharCode(9216 + code); + } + class SpecialCharWidget extends WidgetType { + constructor(options, code) { + super(); + this.options = options; + this.code = code; + } + eq(other) { return other.code == this.code; } + toDOM(view) { + let ph = placeholder$1(this.code); + let desc = view.state.phrase("Control character") + " " + (Names[this.code] || "0x" + this.code.toString(16)); + let custom = this.options.render && this.options.render(this.code, desc, ph); + if (custom) + return custom; + let span = document.createElement("span"); + span.textContent = ph; + span.title = desc; + span.setAttribute("aria-label", desc); + span.className = "cm-specialChar"; + return span; + } + ignoreEvent() { return false; } + } + class TabWidget extends WidgetType { + constructor(width) { + super(); + this.width = width; + } + eq(other) { return other.width == this.width; } + toDOM() { + let span = document.createElement("span"); + span.textContent = "\t"; + span.className = "cm-tab"; + span.style.width = this.width + "px"; + return span; + } + ignoreEvent() { return false; } + } + + /** + Mark lines that have a cursor on them with the `"cm-activeLine"` + DOM class. + */ + function highlightActiveLine() { + return activeLineHighlighter; + } + const lineDeco = /*@__PURE__*/Decoration.line({ class: "cm-activeLine" }); + const activeLineHighlighter = /*@__PURE__*/ViewPlugin.fromClass(class { + constructor(view) { + this.decorations = this.getDeco(view); + } + update(update) { + if (update.docChanged || update.selectionSet) + this.decorations = this.getDeco(update.view); + } + getDeco(view) { + let lastLineStart = -1, deco = []; + for (let r of view.state.selection.ranges) { + let line = view.lineBlockAt(r.head); + if (line.from > lastLineStart) { + deco.push(lineDeco.range(line.from)); + lastLineStart = line.from; + } + } + return Decoration.set(deco); + } + }, { + decorations: v => v.decorations + }); + + // Don't compute precise column positions for line offsets above this + // (since it could get expensive). Assume offset==column for them. + const MaxOff = 2000; + function rectangleFor(state, a, b) { + let startLine = Math.min(a.line, b.line), endLine = Math.max(a.line, b.line); + let ranges = []; + if (a.off > MaxOff || b.off > MaxOff || a.col < 0 || b.col < 0) { + let startOff = Math.min(a.off, b.off), endOff = Math.max(a.off, b.off); + for (let i = startLine; i <= endLine; i++) { + let line = state.doc.line(i); + if (line.length <= endOff) + ranges.push(EditorSelection.range(line.from + startOff, line.to + endOff)); + } + } + else { + let startCol = Math.min(a.col, b.col), endCol = Math.max(a.col, b.col); + for (let i = startLine; i <= endLine; i++) { + let line = state.doc.line(i); + let start = findColumn(line.text, startCol, state.tabSize, true); + if (start > -1) { + let end = findColumn(line.text, endCol, state.tabSize); + ranges.push(EditorSelection.range(line.from + start, line.from + end)); + } + } + } + return ranges; + } + function absoluteColumn(view, x) { + let ref = view.coordsAtPos(view.viewport.from); + return ref ? Math.round(Math.abs((ref.left - x) / view.defaultCharacterWidth)) : -1; + } + function getPos(view, event) { + let offset = view.posAtCoords({ x: event.clientX, y: event.clientY }, false); + let line = view.state.doc.lineAt(offset), off = offset - line.from; + let col = off > MaxOff ? -1 + : off == line.length ? absoluteColumn(view, event.clientX) + : countColumn(line.text, view.state.tabSize, offset - line.from); + return { line: line.number, col, off }; + } + function rectangleSelectionStyle(view, event) { + let start = getPos(view, event), startSel = view.state.selection; + if (!start) + return null; + return { + update(update) { + if (update.docChanged) { + let newStart = update.changes.mapPos(update.startState.doc.line(start.line).from); + let newLine = update.state.doc.lineAt(newStart); + start = { line: newLine.number, col: start.col, off: Math.min(start.off, newLine.length) }; + startSel = startSel.map(update.changes); + } + }, + get(event, _extend, multiple) { + let cur = getPos(view, event); + if (!cur) + return startSel; + let ranges = rectangleFor(view.state, start, cur); + if (!ranges.length) + return startSel; + if (multiple) + return EditorSelection.create(ranges.concat(startSel.ranges)); + else + return EditorSelection.create(ranges); + } + }; + } + /** + Create an extension that enables rectangular selections. By + default, it will react to left mouse drag with the Alt key held + down. When such a selection occurs, the text within the rectangle + that was dragged over will be selected, as one selection + [range](https://codemirror.net/6/docs/ref/#state.SelectionRange) per line. + */ + function rectangularSelection(options) { + let filter = (options === null || options === void 0 ? void 0 : options.eventFilter) || (e => e.altKey && e.button == 0); + return EditorView.mouseSelectionStyle.of((view, event) => filter(event) ? rectangleSelectionStyle(view, event) : null); + } + const keys = { + Alt: [18, e => e.altKey], + Control: [17, e => e.ctrlKey], + Shift: [16, e => e.shiftKey], + Meta: [91, e => e.metaKey] + }; + const showCrosshair = { style: "cursor: crosshair" }; + /** + Returns an extension that turns the pointer cursor into a + crosshair when a given modifier key, defaulting to Alt, is held + down. Can serve as a visual hint that rectangular selection is + going to happen when paired with + [`rectangularSelection`](https://codemirror.net/6/docs/ref/#view.rectangularSelection). + */ + function crosshairCursor(options = {}) { + let [code, getter] = keys[options.key || "Alt"]; + let plugin = ViewPlugin.fromClass(class { + constructor(view) { + this.view = view; + this.isDown = false; + } + set(isDown) { + if (this.isDown != isDown) { + this.isDown = isDown; + this.view.update([]); + } + } + }, { + eventHandlers: { + keydown(e) { + this.set(e.keyCode == code || getter(e)); + }, + keyup(e) { + if (e.keyCode == code || !getter(e)) + this.set(false); + } + } + }); + return [ + plugin, + EditorView.contentAttributes.of(view => { var _a; return ((_a = view.plugin(plugin)) === null || _a === void 0 ? void 0 : _a.isDown) ? showCrosshair : null; }) + ]; + } + + const Outside = "-10000px"; + class TooltipViewManager { + constructor(view, facet, createTooltipView) { + this.facet = facet; + this.createTooltipView = createTooltipView; + this.input = view.state.facet(facet); + this.tooltips = this.input.filter(t => t); + this.tooltipViews = this.tooltips.map(createTooltipView); + } + update(update) { + let input = update.state.facet(this.facet); + let tooltips = input.filter(x => x); + if (input === this.input) { + for (let t of this.tooltipViews) + if (t.update) + t.update(update); + return false; + } + let tooltipViews = []; + for (let i = 0; i < tooltips.length; i++) { + let tip = tooltips[i], known = -1; + if (!tip) + continue; + for (let i = 0; i < this.tooltips.length; i++) { + let other = this.tooltips[i]; + if (other && other.create == tip.create) + known = i; + } + if (known < 0) { + tooltipViews[i] = this.createTooltipView(tip); + } + else { + let tooltipView = tooltipViews[i] = this.tooltipViews[known]; + if (tooltipView.update) + tooltipView.update(update); + } + } + for (let t of this.tooltipViews) + if (tooltipViews.indexOf(t) < 0) + t.dom.remove(); + this.input = input; + this.tooltips = tooltips; + this.tooltipViews = tooltipViews; + return true; + } + } + function windowSpace(view) { + let { win } = view; + return { top: 0, left: 0, bottom: win.innerHeight, right: win.innerWidth }; + } + const tooltipConfig = /*@__PURE__*/Facet.define({ + combine: values => { + var _a, _b, _c; + return ({ + position: browser.ios ? "absolute" : ((_a = values.find(conf => conf.position)) === null || _a === void 0 ? void 0 : _a.position) || "fixed", + parent: ((_b = values.find(conf => conf.parent)) === null || _b === void 0 ? void 0 : _b.parent) || null, + tooltipSpace: ((_c = values.find(conf => conf.tooltipSpace)) === null || _c === void 0 ? void 0 : _c.tooltipSpace) || windowSpace, + }); + } + }); + const tooltipPlugin = /*@__PURE__*/ViewPlugin.fromClass(class { + constructor(view) { + this.view = view; + this.inView = true; + this.lastTransaction = 0; + this.measureTimeout = -1; + let config = view.state.facet(tooltipConfig); + this.position = config.position; + this.parent = config.parent; + this.classes = view.themeClasses; + this.createContainer(); + this.measureReq = { read: this.readMeasure.bind(this), write: this.writeMeasure.bind(this), key: this }; + this.manager = new TooltipViewManager(view, showTooltip, t => this.createTooltip(t)); + this.intersectionObserver = typeof IntersectionObserver == "function" ? new IntersectionObserver(entries => { + if (Date.now() > this.lastTransaction - 50 && + entries.length > 0 && entries[entries.length - 1].intersectionRatio < 1) + this.measureSoon(); + }, { threshold: [1] }) : null; + this.observeIntersection(); + view.win.addEventListener("resize", this.measureSoon = this.measureSoon.bind(this)); + this.maybeMeasure(); + } + createContainer() { + if (this.parent) { + this.container = document.createElement("div"); + this.container.style.position = "relative"; + this.container.className = this.view.themeClasses; + this.parent.appendChild(this.container); + } + else { + this.container = this.view.dom; + } + } + observeIntersection() { + if (this.intersectionObserver) { + this.intersectionObserver.disconnect(); + for (let tooltip of this.manager.tooltipViews) + this.intersectionObserver.observe(tooltip.dom); + } + } + measureSoon() { + if (this.measureTimeout < 0) + this.measureTimeout = setTimeout(() => { + this.measureTimeout = -1; + this.maybeMeasure(); + }, 50); + } + update(update) { + if (update.transactions.length) + this.lastTransaction = Date.now(); + let updated = this.manager.update(update); + if (updated) + this.observeIntersection(); + let shouldMeasure = updated || update.geometryChanged; + let newConfig = update.state.facet(tooltipConfig); + if (newConfig.position != this.position) { + this.position = newConfig.position; + for (let t of this.manager.tooltipViews) + t.dom.style.position = this.position; + shouldMeasure = true; + } + if (newConfig.parent != this.parent) { + if (this.parent) + this.container.remove(); + this.parent = newConfig.parent; + this.createContainer(); + for (let t of this.manager.tooltipViews) + this.container.appendChild(t.dom); + shouldMeasure = true; + } + else if (this.parent && this.view.themeClasses != this.classes) { + this.classes = this.container.className = this.view.themeClasses; + } + if (shouldMeasure) + this.maybeMeasure(); + } + createTooltip(tooltip) { + let tooltipView = tooltip.create(this.view); + tooltipView.dom.classList.add("cm-tooltip"); + if (tooltip.arrow && !tooltipView.dom.querySelector(".cm-tooltip > .cm-tooltip-arrow")) { + let arrow = document.createElement("div"); + arrow.className = "cm-tooltip-arrow"; + tooltipView.dom.appendChild(arrow); + } + tooltipView.dom.style.position = this.position; + tooltipView.dom.style.top = Outside; + this.container.appendChild(tooltipView.dom); + if (tooltipView.mount) + tooltipView.mount(this.view); + return tooltipView; + } + destroy() { + var _a; + this.view.win.removeEventListener("resize", this.measureSoon); + for (let { dom } of this.manager.tooltipViews) + dom.remove(); + (_a = this.intersectionObserver) === null || _a === void 0 ? void 0 : _a.disconnect(); + clearTimeout(this.measureTimeout); + } + readMeasure() { + let editor = this.view.dom.getBoundingClientRect(); + return { + editor, + parent: this.parent ? this.container.getBoundingClientRect() : editor, + pos: this.manager.tooltips.map((t, i) => { + let tv = this.manager.tooltipViews[i]; + return tv.getCoords ? tv.getCoords(t.pos) : this.view.coordsAtPos(t.pos); + }), + size: this.manager.tooltipViews.map(({ dom }) => dom.getBoundingClientRect()), + space: this.view.state.facet(tooltipConfig).tooltipSpace(this.view), + }; + } + writeMeasure(measured) { + let { editor, space } = measured; + let others = []; + for (let i = 0; i < this.manager.tooltips.length; i++) { + let tooltip = this.manager.tooltips[i], tView = this.manager.tooltipViews[i], { dom } = tView; + let pos = measured.pos[i], size = measured.size[i]; + // Hide tooltips that are outside of the editor. + if (!pos || pos.bottom <= Math.max(editor.top, space.top) || + pos.top >= Math.min(editor.bottom, space.bottom) || + pos.right < Math.max(editor.left, space.left) - .1 || + pos.left > Math.min(editor.right, space.right) + .1) { + dom.style.top = Outside; + continue; + } + let arrow = tooltip.arrow ? tView.dom.querySelector(".cm-tooltip-arrow") : null; + let arrowHeight = arrow ? 7 /* Arrow.Size */ : 0; + let width = size.right - size.left, height = size.bottom - size.top; + let offset = tView.offset || noOffset, ltr = this.view.textDirection == Direction.LTR; + let left = size.width > space.right - space.left ? (ltr ? space.left : space.right - size.width) + : ltr ? Math.min(pos.left - (arrow ? 14 /* Arrow.Offset */ : 0) + offset.x, space.right - width) + : Math.max(space.left, pos.left - width + (arrow ? 14 /* Arrow.Offset */ : 0) - offset.x); + let above = !!tooltip.above; + if (!tooltip.strictSide && (above + ? pos.top - (size.bottom - size.top) - offset.y < space.top + : pos.bottom + (size.bottom - size.top) + offset.y > space.bottom) && + above == (space.bottom - pos.bottom > pos.top - space.top)) + above = !above; + let top = above ? pos.top - height - arrowHeight - offset.y : pos.bottom + arrowHeight + offset.y; + let right = left + width; + if (tView.overlap !== true) + for (let r of others) + if (r.left < right && r.right > left && r.top < top + height && r.bottom > top) + top = above ? r.top - height - 2 - arrowHeight : r.bottom + arrowHeight + 2; + if (this.position == "absolute") { + dom.style.top = (top - measured.parent.top) + "px"; + dom.style.left = (left - measured.parent.left) + "px"; + } + else { + dom.style.top = top + "px"; + dom.style.left = left + "px"; + } + if (arrow) + arrow.style.left = `${pos.left + (ltr ? offset.x : -offset.x) - (left + 14 /* Arrow.Offset */ - 7 /* Arrow.Size */)}px`; + if (tView.overlap !== true) + others.push({ left, top, right, bottom: top + height }); + dom.classList.toggle("cm-tooltip-above", above); + dom.classList.toggle("cm-tooltip-below", !above); + if (tView.positioned) + tView.positioned(); + } + } + maybeMeasure() { + if (this.manager.tooltips.length) { + if (this.view.inView) + this.view.requestMeasure(this.measureReq); + if (this.inView != this.view.inView) { + this.inView = this.view.inView; + if (!this.inView) + for (let tv of this.manager.tooltipViews) + tv.dom.style.top = Outside; + } + } + } + }, { + eventHandlers: { + scroll() { this.maybeMeasure(); } + } + }); + const baseTheme$4 = /*@__PURE__*/EditorView.baseTheme({ + ".cm-tooltip": { + zIndex: 100 + }, + "&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: `${7 /* Arrow.Size */}px`, + width: `${7 /* Arrow.Size */ * 2}px`, + position: "absolute", + zIndex: -1, + overflow: "hidden", + "&:before, &:after": { + content: "''", + position: "absolute", + width: 0, + height: 0, + borderLeft: `${7 /* Arrow.Size */}px solid transparent`, + borderRight: `${7 /* Arrow.Size */}px solid transparent`, + }, + ".cm-tooltip-above &": { + bottom: `-${7 /* Arrow.Size */}px`, + "&:before": { + borderTop: `${7 /* Arrow.Size */}px solid #bbb`, + }, + "&:after": { + borderTop: `${7 /* Arrow.Size */}px solid #f5f5f5`, + bottom: "1px" + } + }, + ".cm-tooltip-below &": { + top: `-${7 /* Arrow.Size */}px`, + "&:before": { + borderBottom: `${7 /* Arrow.Size */}px solid #bbb`, + }, + "&:after": { + borderBottom: `${7 /* Arrow.Size */}px solid #f5f5f5`, + top: "1px" + } + }, + }, + "&dark .cm-tooltip .cm-tooltip-arrow": { + "&:before": { + borderTopColor: "#333338", + borderBottomColor: "#333338" + }, + "&:after": { + borderTopColor: "transparent", + borderBottomColor: "transparent" + } + } + }); + const noOffset = { x: 0, y: 0 }; + /** + Facet to which an extension can add a value to show a tooltip. + */ + const showTooltip = /*@__PURE__*/Facet.define({ + enables: [tooltipPlugin, baseTheme$4] + }); + const showHoverTooltip = /*@__PURE__*/Facet.define(); + class HoverTooltipHost { + constructor(view) { + this.view = view; + this.mounted = false; + this.dom = document.createElement("div"); + this.dom.classList.add("cm-tooltip-hover"); + this.manager = new TooltipViewManager(view, showHoverTooltip, t => this.createHostedView(t)); + } + // Needs to be static so that host tooltip instances always match + static create(view) { + return new HoverTooltipHost(view); + } + createHostedView(tooltip) { + let hostedView = tooltip.create(this.view); + hostedView.dom.classList.add("cm-tooltip-section"); + this.dom.appendChild(hostedView.dom); + if (this.mounted && hostedView.mount) + hostedView.mount(this.view); + return hostedView; + } + mount(view) { + for (let hostedView of this.manager.tooltipViews) { + if (hostedView.mount) + hostedView.mount(view); + } + this.mounted = true; + } + positioned() { + for (let hostedView of this.manager.tooltipViews) { + if (hostedView.positioned) + hostedView.positioned(); + } + } + update(update) { + this.manager.update(update); + } + } + const showHoverTooltipHost = /*@__PURE__*/showTooltip.compute([showHoverTooltip], state => { + let tooltips = state.facet(showHoverTooltip).filter(t => t); + if (tooltips.length === 0) + return null; + return { + pos: Math.min(...tooltips.map(t => t.pos)), + end: Math.max(...tooltips.filter(t => t.end != null).map(t => t.end)), + create: HoverTooltipHost.create, + above: tooltips[0].above, + arrow: tooltips.some(t => t.arrow), + }; + }); + class HoverPlugin { + constructor(view, source, field, setHover, hoverTime) { + this.view = view; + this.source = source; + this.field = field; + this.setHover = setHover; + this.hoverTime = hoverTime; + this.hoverTimeout = -1; + this.restartTimeout = -1; + this.pending = null; + this.lastMove = { x: 0, y: 0, target: view.dom, time: 0 }; + this.checkHover = this.checkHover.bind(this); + view.dom.addEventListener("mouseleave", this.mouseleave = this.mouseleave.bind(this)); + view.dom.addEventListener("mousemove", this.mousemove = this.mousemove.bind(this)); + } + update() { + if (this.pending) { + this.pending = null; + clearTimeout(this.restartTimeout); + this.restartTimeout = setTimeout(() => this.startHover(), 20); + } + } + get active() { + return this.view.state.field(this.field); + } + checkHover() { + this.hoverTimeout = -1; + if (this.active) + return; + let hovered = Date.now() - this.lastMove.time; + if (hovered < this.hoverTime) + this.hoverTimeout = setTimeout(this.checkHover, this.hoverTime - hovered); + else + this.startHover(); + } + startHover() { + clearTimeout(this.restartTimeout); + let { lastMove } = this; + let pos = this.view.contentDOM.contains(lastMove.target) ? this.view.posAtCoords(lastMove) : null; + if (pos == null) + return; + let posCoords = this.view.coordsAtPos(pos); + if (posCoords == null || lastMove.y < posCoords.top || lastMove.y > posCoords.bottom || + lastMove.x < posCoords.left - this.view.defaultCharacterWidth || + lastMove.x > posCoords.right + this.view.defaultCharacterWidth) + return; + let bidi = this.view.bidiSpans(this.view.state.doc.lineAt(pos)).find(s => s.from <= pos && s.to >= pos); + let rtl = bidi && bidi.dir == Direction.RTL ? -1 : 1; + let open = this.source(this.view, pos, (lastMove.x < posCoords.left ? -rtl : rtl)); + if (open === null || open === void 0 ? void 0 : open.then) { + let pending = this.pending = { pos }; + open.then(result => { + if (this.pending == pending) { + this.pending = null; + if (result) + this.view.dispatch({ effects: this.setHover.of(result) }); + } + }, e => logException(this.view.state, e, "hover tooltip")); + } + else if (open) { + this.view.dispatch({ effects: this.setHover.of(open) }); + } + } + mousemove(event) { + var _a; + this.lastMove = { x: event.clientX, y: event.clientY, target: event.target, time: Date.now() }; + if (this.hoverTimeout < 0) + this.hoverTimeout = setTimeout(this.checkHover, this.hoverTime); + let tooltip = this.active; + if (tooltip && !isInTooltip(this.lastMove.target) || this.pending) { + let { pos } = tooltip || this.pending, end = (_a = tooltip === null || tooltip === void 0 ? void 0 : tooltip.end) !== null && _a !== void 0 ? _a : pos; + if ((pos == end ? this.view.posAtCoords(this.lastMove) != pos + : !isOverRange(this.view, pos, end, event.clientX, event.clientY, 6 /* Hover.MaxDist */))) { + this.view.dispatch({ effects: this.setHover.of(null) }); + this.pending = null; + } + } + } + mouseleave() { + clearTimeout(this.hoverTimeout); + this.hoverTimeout = -1; + if (this.active) + this.view.dispatch({ effects: this.setHover.of(null) }); + } + destroy() { + clearTimeout(this.hoverTimeout); + this.view.dom.removeEventListener("mouseleave", this.mouseleave); + this.view.dom.removeEventListener("mousemove", this.mousemove); + } + } + function isInTooltip(elt) { + for (let cur = elt; cur; cur = cur.parentNode) + if (cur.nodeType == 1 && cur.classList.contains("cm-tooltip")) + return true; + return false; + } + function isOverRange(view, from, to, x, y, margin) { + let range = document.createRange(); + let fromDOM = view.domAtPos(from), toDOM = view.domAtPos(to); + range.setEnd(toDOM.node, toDOM.offset); + range.setStart(fromDOM.node, fromDOM.offset); + let rects = range.getClientRects(); + range.detach(); + for (let i = 0; i < rects.length; i++) { + let rect = rects[i]; + let dist = Math.max(rect.top - y, y - rect.bottom, rect.left - x, x - rect.right); + if (dist <= margin) + return true; + } + return false; + } + /** + Set up a hover tooltip, which shows up when the pointer hovers + over ranges of text. The callback is called when the mouse hovers + over the document text. It should, if there is a tooltip + associated with position `pos`, return the tooltip description + (either directly or in a promise). The `side` argument indicates + on which side of the position the pointer is—it will be -1 if the + pointer is before the position, 1 if after the position. + + Note that all hover tooltips are hosted within a single tooltip + container element. This allows multiple tooltips over the same + range to be "merged" together without overlapping. + */ + function hoverTooltip(source, options = {}) { + let setHover = StateEffect.define(); + let hoverState = StateField.define({ + create() { return null; }, + update(value, tr) { + if (value && (options.hideOnChange && (tr.docChanged || tr.selection) || + options.hideOn && options.hideOn(tr, value))) + return null; + if (value && tr.docChanged) { + let newPos = tr.changes.mapPos(value.pos, -1, MapMode.TrackDel); + if (newPos == null) + return null; + let copy = Object.assign(Object.create(null), value); + copy.pos = newPos; + if (value.end != null) + copy.end = tr.changes.mapPos(value.end); + value = copy; + } + for (let effect of tr.effects) { + if (effect.is(setHover)) + value = effect.value; + if (effect.is(closeHoverTooltipEffect)) + value = null; + } + return value; + }, + provide: f => showHoverTooltip.from(f) + }); + return [ + hoverState, + ViewPlugin.define(view => new HoverPlugin(view, source, hoverState, setHover, options.hoverTime || 300 /* Hover.Time */)), + showHoverTooltipHost + ]; + } + /** + Get the active tooltip view for a given tooltip, if available. + */ + function getTooltip(view, tooltip) { + let plugin = view.plugin(tooltipPlugin); + if (!plugin) + return null; + let found = plugin.manager.tooltips.indexOf(tooltip); + return found < 0 ? null : plugin.manager.tooltipViews[found]; + } + const closeHoverTooltipEffect = /*@__PURE__*/StateEffect.define(); + + const panelConfig = /*@__PURE__*/Facet.define({ + combine(configs) { + let topContainer, bottomContainer; + for (let c of configs) { + topContainer = topContainer || c.topContainer; + bottomContainer = bottomContainer || c.bottomContainer; + } + return { topContainer, bottomContainer }; + } + }); + /** + Get the active panel created by the given constructor, if any. + This can be useful when you need access to your panels' DOM + structure. + */ + function getPanel(view, panel) { + let plugin = view.plugin(panelPlugin); + let index = plugin ? plugin.specs.indexOf(panel) : -1; + return index > -1 ? plugin.panels[index] : null; + } + const panelPlugin = /*@__PURE__*/ViewPlugin.fromClass(class { + constructor(view) { + this.input = view.state.facet(showPanel); + this.specs = this.input.filter(s => s); + this.panels = this.specs.map(spec => spec(view)); + let conf = view.state.facet(panelConfig); + this.top = new PanelGroup(view, true, conf.topContainer); + this.bottom = new PanelGroup(view, false, conf.bottomContainer); + this.top.sync(this.panels.filter(p => p.top)); + this.bottom.sync(this.panels.filter(p => !p.top)); + for (let p of this.panels) { + p.dom.classList.add("cm-panel"); + if (p.mount) + p.mount(); + } + } + update(update) { + let conf = update.state.facet(panelConfig); + if (this.top.container != conf.topContainer) { + this.top.sync([]); + this.top = new PanelGroup(update.view, true, conf.topContainer); + } + if (this.bottom.container != conf.bottomContainer) { + this.bottom.sync([]); + this.bottom = new PanelGroup(update.view, false, conf.bottomContainer); + } + this.top.syncClasses(); + this.bottom.syncClasses(); + let input = update.state.facet(showPanel); + if (input != this.input) { + let specs = input.filter(x => x); + let panels = [], top = [], bottom = [], mount = []; + for (let spec of specs) { + let known = this.specs.indexOf(spec), panel; + if (known < 0) { + panel = spec(update.view); + mount.push(panel); + } + else { + panel = this.panels[known]; + if (panel.update) + panel.update(update); + } + panels.push(panel); + (panel.top ? top : bottom).push(panel); + } + this.specs = specs; + this.panels = panels; + this.top.sync(top); + this.bottom.sync(bottom); + for (let p of mount) { + p.dom.classList.add("cm-panel"); + if (p.mount) + p.mount(); + } + } + else { + for (let p of this.panels) + if (p.update) + p.update(update); + } + } + destroy() { + this.top.sync([]); + this.bottom.sync([]); + } + }, { + provide: plugin => EditorView.scrollMargins.of(view => { + let value = view.plugin(plugin); + return value && { top: value.top.scrollMargin(), bottom: value.bottom.scrollMargin() }; + }) + }); + class PanelGroup { + constructor(view, top, container) { + this.view = view; + this.top = top; + this.container = container; + this.dom = undefined; + this.classes = ""; + this.panels = []; + this.syncClasses(); + } + sync(panels) { + for (let p of this.panels) + if (p.destroy && panels.indexOf(p) < 0) + p.destroy(); + this.panels = panels; + this.syncDOM(); + } + syncDOM() { + if (this.panels.length == 0) { + if (this.dom) { + this.dom.remove(); + this.dom = undefined; + } + return; + } + 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 parent = this.container || this.view.dom; + parent.insertBefore(this.dom, this.top ? parent.firstChild : null); + } + let curDOM = this.dom.firstChild; + for (let panel of this.panels) { + if (panel.dom.parentNode == this.dom) { + while (curDOM != panel.dom) + curDOM = rm(curDOM); + curDOM = curDOM.nextSibling; + } + else { + this.dom.insertBefore(panel.dom, curDOM); + } + } + while (curDOM) + curDOM = rm(curDOM); + } + 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) + return; + for (let cls of this.classes.split(" ")) + if (cls) + this.container.classList.remove(cls); + for (let cls of (this.classes = this.view.themeClasses).split(" ")) + if (cls) + this.container.classList.add(cls); + } + } + function rm(node) { + let next = node.nextSibling; + node.remove(); + return next; + } + /** + Opening a panel is done by providing a constructor function for + the panel through this facet. (The panel is closed again when its + constructor is no longer provided.) Values of `null` are ignored. + */ + const showPanel = /*@__PURE__*/Facet.define({ + enables: panelPlugin + }); + + /** + A gutter marker represents a bit of information attached to a line + in a specific gutter. Your own custom markers have to extend this + class. + */ + class GutterMarker extends RangeValue { + /** + @internal + */ + compare(other) { + return this == other || this.constructor == other.constructor && this.eq(other); + } + /** + Compare this marker to another marker of the same type. + */ + eq(other) { return false; } + /** + Called if the marker has a `toDOM` method and its representation + was removed from a gutter. + */ + destroy(dom) { } + } + GutterMarker.prototype.elementClass = ""; + GutterMarker.prototype.toDOM = undefined; + GutterMarker.prototype.mapMode = MapMode.TrackBefore; + GutterMarker.prototype.startSide = GutterMarker.prototype.endSide = -1; + GutterMarker.prototype.point = true; + /** + Facet used to add a class to all gutter elements for a given line. + Markers given to this facet should _only_ define an + [`elementclass`](https://codemirror.net/6/docs/ref/#view.GutterMarker.elementClass), not a + [`toDOM`](https://codemirror.net/6/docs/ref/#view.GutterMarker.toDOM) (or the marker will appear + in all gutters for the line). + */ + const gutterLineClass = /*@__PURE__*/Facet.define(); + const defaults$1 = { + class: "", + renderEmptyElements: false, + elementStyle: "", + markers: () => RangeSet.empty, + lineMarker: () => null, + lineMarkerChange: null, + initialSpacer: null, + updateSpacer: null, + domEventHandlers: {} + }; + const activeGutters = /*@__PURE__*/Facet.define(); + /** + Define an editor gutter. The order in which the gutters appear is + determined by their extension priority. + */ + function gutter(config) { + return [gutters(), activeGutters.of(Object.assign(Object.assign({}, defaults$1), config))]; + } + const unfixGutters = /*@__PURE__*/Facet.define({ + combine: values => values.some(x => x) + }); + /** + The gutter-drawing plugin is automatically enabled when you add a + gutter, but you can use this function to explicitly configure it. + + Unless `fixed` is explicitly set to `false`, the gutters are + fixed, meaning they don't scroll along with the content + horizontally (except on Internet Explorer, which doesn't support + CSS [`position: + sticky`](https://developer.mozilla.org/en-US/docs/Web/CSS/position#sticky)). + */ + function gutters(config) { + let result = [ + gutterView, + ]; + if (config && config.fixed === false) + result.push(unfixGutters.of(true)); + return result; + } + const gutterView = /*@__PURE__*/ViewPlugin.fromClass(class { + constructor(view) { + this.view = view; + this.prevViewport = view.viewport; + this.dom = document.createElement("div"); + this.dom.className = "cm-gutters"; + this.dom.setAttribute("aria-hidden", "true"); + this.dom.style.minHeight = this.view.contentHeight + "px"; + this.gutters = view.state.facet(activeGutters).map(conf => new SingleGutterView(view, conf)); + for (let gutter of this.gutters) + this.dom.appendChild(gutter.dom); + this.fixed = !view.state.facet(unfixGutters); + if (this.fixed) { + // FIXME IE11 fallback, which doesn't support position: sticky, + // by using position: relative + event handlers that realign the + // gutter (or just force fixed=false on IE11?) + this.dom.style.position = "sticky"; + } + this.syncGutters(false); + view.scrollDOM.insertBefore(this.dom, view.contentDOM); + } + update(update) { + if (this.updateGutters(update)) { + // Detach during sync when the viewport changed significantly + // (such as during scrolling), since for large updates that is + // faster. + let vpA = this.prevViewport, vpB = update.view.viewport; + let vpOverlap = Math.min(vpA.to, vpB.to) - Math.max(vpA.from, vpB.from); + this.syncGutters(vpOverlap < (vpB.to - vpB.from) * 0.8); + } + if (update.geometryChanged) + this.dom.style.minHeight = this.view.contentHeight + "px"; + if (this.view.state.facet(unfixGutters) != !this.fixed) { + this.fixed = !this.fixed; + this.dom.style.position = this.fixed ? "sticky" : ""; + } + this.prevViewport = update.view.viewport; + } + syncGutters(detach) { + let after = this.dom.nextSibling; + if (detach) + this.dom.remove(); + let lineClasses = RangeSet.iter(this.view.state.facet(gutterLineClass), this.view.viewport.from); + let classSet = []; + let contexts = this.gutters.map(gutter => new UpdateContext(gutter, this.view.viewport, -this.view.documentPadding.top)); + for (let line of this.view.viewportLineBlocks) { + let text; + if (Array.isArray(line.type)) { + for (let b of line.type) + if (b.type == BlockType.Text) { + text = b; + break; + } + } + else { + text = line.type == BlockType.Text ? line : undefined; + } + if (!text) + continue; + if (classSet.length) + classSet = []; + advanceCursor(lineClasses, classSet, line.from); + for (let cx of contexts) + cx.line(this.view, text, classSet); + } + for (let cx of contexts) + cx.finish(); + if (detach) + this.view.scrollDOM.insertBefore(this.dom, after); + } + updateGutters(update) { + let prev = update.startState.facet(activeGutters), cur = update.state.facet(activeGutters); + let change = update.docChanged || update.heightChanged || update.viewportChanged || + !RangeSet.eq(update.startState.facet(gutterLineClass), update.state.facet(gutterLineClass), update.view.viewport.from, update.view.viewport.to); + if (prev == cur) { + for (let gutter of this.gutters) + if (gutter.update(update)) + change = true; + } + else { + change = true; + let gutters = []; + for (let conf of cur) { + let known = prev.indexOf(conf); + if (known < 0) { + gutters.push(new SingleGutterView(this.view, conf)); + } + else { + this.gutters[known].update(update); + gutters.push(this.gutters[known]); + } + } + for (let g of this.gutters) { + g.dom.remove(); + if (gutters.indexOf(g) < 0) + g.destroy(); + } + for (let g of gutters) + this.dom.appendChild(g.dom); + this.gutters = gutters; + } + return change; + } + destroy() { + for (let view of this.gutters) + view.destroy(); + this.dom.remove(); + } + }, { + provide: plugin => EditorView.scrollMargins.of(view => { + let value = view.plugin(plugin); + if (!value || value.gutters.length == 0 || !value.fixed) + return null; + return view.textDirection == Direction.LTR ? { left: value.dom.offsetWidth } : { right: value.dom.offsetWidth }; + }) + }); + function asArray(val) { return (Array.isArray(val) ? val : [val]); } + function advanceCursor(cursor, collect, pos) { + while (cursor.value && cursor.from <= pos) { + if (cursor.from == pos) + collect.push(cursor.value); + cursor.next(); + } + } + class UpdateContext { + constructor(gutter, viewport, height) { + this.gutter = gutter; + this.height = height; + this.localMarkers = []; + this.i = 0; + this.cursor = RangeSet.iter(gutter.markers, viewport.from); + } + line(view, line, extraMarkers) { + if (this.localMarkers.length) + this.localMarkers = []; + advanceCursor(this.cursor, this.localMarkers, line.from); + let localMarkers = extraMarkers.length ? this.localMarkers.concat(extraMarkers) : this.localMarkers; + let forLine = this.gutter.config.lineMarker(view, line, localMarkers); + if (forLine) + localMarkers.unshift(forLine); + let gutter = this.gutter; + if (localMarkers.length == 0 && !gutter.config.renderEmptyElements) + return; + let above = line.top - this.height; + if (this.i == gutter.elements.length) { + let newElt = new GutterElement(view, line.height, above, localMarkers); + gutter.elements.push(newElt); + gutter.dom.appendChild(newElt.dom); + } + else { + gutter.elements[this.i].update(view, line.height, above, localMarkers); + } + this.height = line.bottom; + this.i++; + } + finish() { + let gutter = this.gutter; + while (gutter.elements.length > this.i) { + let last = gutter.elements.pop(); + gutter.dom.removeChild(last.dom); + last.destroy(); + } + } + } + class SingleGutterView { + constructor(view, config) { + this.view = view; + this.config = config; + this.elements = []; + this.spacer = null; + this.dom = document.createElement("div"); + this.dom.className = "cm-gutter" + (this.config.class ? " " + this.config.class : ""); + for (let prop in config.domEventHandlers) { + this.dom.addEventListener(prop, (event) => { + let line = view.lineBlockAtHeight(event.clientY - view.documentTop); + if (config.domEventHandlers[prop](view, line, event)) + event.preventDefault(); + }); + } + this.markers = asArray(config.markers(view)); + if (config.initialSpacer) { + this.spacer = new GutterElement(view, 0, 0, [config.initialSpacer(view)]); + this.dom.appendChild(this.spacer.dom); + this.spacer.dom.style.cssText += "visibility: hidden; pointer-events: none"; + } + } + update(update) { + let prevMarkers = this.markers; + this.markers = asArray(this.config.markers(update.view)); + if (this.spacer && this.config.updateSpacer) { + let updated = this.config.updateSpacer(this.spacer.markers[0], update); + if (updated != this.spacer.markers[0]) + this.spacer.update(update.view, 0, 0, [updated]); + } + let vp = update.view.viewport; + return !RangeSet.eq(this.markers, prevMarkers, vp.from, vp.to) || + (this.config.lineMarkerChange ? this.config.lineMarkerChange(update) : false); + } + destroy() { + for (let elt of this.elements) + elt.destroy(); + } + } + class GutterElement { + constructor(view, height, above, markers) { + this.height = -1; + this.above = 0; + this.markers = []; + this.dom = document.createElement("div"); + this.dom.className = "cm-gutterElement"; + this.update(view, height, above, markers); + } + update(view, height, above, markers) { + if (this.height != height) + this.dom.style.height = (this.height = height) + "px"; + if (this.above != above) + this.dom.style.marginTop = (this.above = above) ? above + "px" : ""; + if (!sameMarkers(this.markers, markers)) + this.setMarkers(view, markers); + } + setMarkers(view, markers) { + let cls = "cm-gutterElement", domPos = this.dom.firstChild; + for (let iNew = 0, iOld = 0;;) { + let skipTo = iOld, marker = iNew < markers.length ? markers[iNew++] : null, matched = false; + if (marker) { + let c = marker.elementClass; + if (c) + cls += " " + c; + for (let i = iOld; i < this.markers.length; i++) + if (this.markers[i].compare(marker)) { + skipTo = i; + matched = true; + break; + } + } + else { + skipTo = this.markers.length; + } + while (iOld < skipTo) { + let next = this.markers[iOld++]; + if (next.toDOM) { + next.destroy(domPos); + let after = domPos.nextSibling; + domPos.remove(); + domPos = after; + } + } + if (!marker) + break; + if (marker.toDOM) { + if (matched) + domPos = domPos.nextSibling; + else + this.dom.insertBefore(marker.toDOM(view), domPos); + } + if (matched) + iOld++; + } + this.dom.className = cls; + this.markers = markers; + } + destroy() { + this.setMarkers(null, []); // First argument not used unless creating markers + } + } + function sameMarkers(a, b) { + if (a.length != b.length) + return false; + for (let i = 0; i < a.length; i++) + if (!a[i].compare(b[i])) + return false; + return true; + } + /** + Facet used to provide markers to the line number gutter. + */ + const lineNumberMarkers = /*@__PURE__*/Facet.define(); + const lineNumberConfig = /*@__PURE__*/Facet.define({ + combine(values) { + return combineConfig(values, { formatNumber: String, domEventHandlers: {} }, { + domEventHandlers(a, b) { + let result = Object.assign({}, a); + for (let event in b) { + let exists = result[event], add = b[event]; + result[event] = exists ? (view, line, event) => exists(view, line, event) || add(view, line, event) : add; + } + return result; + } + }); + } + }); + class NumberMarker extends GutterMarker { + constructor(number) { + super(); + this.number = number; + } + eq(other) { return this.number == other.number; } + toDOM() { return document.createTextNode(this.number); } + } + function formatNumber(view, number) { + return view.state.facet(lineNumberConfig).formatNumber(number, view.state); + } + const lineNumberGutter = /*@__PURE__*/activeGutters.compute([lineNumberConfig], state => ({ + class: "cm-lineNumbers", + renderEmptyElements: false, + markers(view) { return view.state.facet(lineNumberMarkers); }, + lineMarker(view, line, others) { + if (others.some(m => m.toDOM)) + return null; + return new NumberMarker(formatNumber(view, view.state.doc.lineAt(line.from).number)); + }, + lineMarkerChange: update => update.startState.facet(lineNumberConfig) != update.state.facet(lineNumberConfig), + initialSpacer(view) { + return new NumberMarker(formatNumber(view, maxLineNumber(view.state.doc.lines))); + }, + updateSpacer(spacer, update) { + let max = formatNumber(update.view, maxLineNumber(update.view.state.doc.lines)); + return max == spacer.number ? spacer : new NumberMarker(max); + }, + domEventHandlers: state.facet(lineNumberConfig).domEventHandlers + })); + /** + Create a line number gutter extension. + */ + function lineNumbers(config = {}) { + return [ + lineNumberConfig.of(config), + gutters(), + lineNumberGutter + ]; + } + function maxLineNumber(lines) { + let last = 9; + while (last < lines) + last = last * 10 + 9; + return last; + } + const activeLineGutterMarker = /*@__PURE__*/new class extends GutterMarker { + constructor() { + super(...arguments); + this.elementClass = "cm-activeLineGutter"; + } + }; + const activeLineGutterHighlighter = /*@__PURE__*/gutterLineClass.compute(["selection"], state => { + let marks = [], last = -1; + for (let range of state.selection.ranges) { + let linePos = state.doc.lineAt(range.head).from; + if (linePos > last) { + last = linePos; + marks.push(activeLineGutterMarker.range(linePos)); + } + } + return RangeSet.of(marks); + }); + /** + Returns an extension that adds a `cm-activeLineGutter` class to + all gutter elements on the [active + line](https://codemirror.net/6/docs/ref/#view.highlightActiveLine). + */ + function highlightActiveLineGutter() { + return activeLineGutterHighlighter; + } + + // FIXME profile adding a per-Tree TreeNode cache, validating it by + // parent pointer + /// The default maximum length of a `TreeBuffer` node. + const DefaultBufferLength = 1024; + let nextPropID = 0; + class Range { + constructor(from, to) { + this.from = from; + this.to = to; + } + } + /// Each [node type](#common.NodeType) or [individual tree](#common.Tree) + /// can have metadata associated with it in props. Instances of this + /// class represent prop names. + class NodeProp { + /// Create a new node prop type. + constructor(config = {}) { + this.id = nextPropID++; + this.perNode = !!config.perNode; + this.deserialize = config.deserialize || (() => { + throw new Error("This node type doesn't define a deserialize function"); + }); + } + /// This is meant to be used with + /// [`NodeSet.extend`](#common.NodeSet.extend) or + /// [`LRParser.configure`](#lr.ParserConfig.props) to compute + /// prop values for each node type in the set. Takes a [match + /// object](#common.NodeType^match) or function that returns undefined + /// if the node type doesn't get this prop, and the prop's value if + /// it does. + add(match) { + if (this.perNode) + throw new RangeError("Can't add per-node props to node types"); + if (typeof match != "function") + match = NodeType.match(match); + return (type) => { + let result = match(type); + return result === undefined ? null : [this, result]; + }; + } + } + /// Prop that is used to describe matching delimiters. For opening + /// delimiters, this holds an array of node names (written as a + /// space-separated string when declaring this prop in a grammar) + /// for the node types of closing delimiters that match it. + NodeProp.closedBy = new NodeProp({ deserialize: str => str.split(" ") }); + /// The inverse of [`closedBy`](#common.NodeProp^closedBy). This is + /// attached to closing delimiters, holding an array of node names + /// of types of matching opening delimiters. + NodeProp.openedBy = new NodeProp({ deserialize: str => str.split(" ") }); + /// Used to assign node types to groups (for example, all node + /// types that represent an expression could be tagged with an + /// `"Expression"` group). + NodeProp.group = new NodeProp({ deserialize: str => str.split(" ") }); + /// The hash of the [context](#lr.ContextTracker.constructor) + /// that the node was parsed in, if any. Used to limit reuse of + /// contextual nodes. + NodeProp.contextHash = new NodeProp({ perNode: true }); + /// The distance beyond the end of the node that the tokenizer + /// looked ahead for any of the tokens inside the node. (The LR + /// parser only stores this when it is larger than 25, for + /// efficiency reasons.) + NodeProp.lookAhead = new NodeProp({ perNode: true }); + /// This per-node prop is used to replace a given node, or part of a + /// node, with another tree. This is useful to include trees from + /// different languages in mixed-language parsers. + NodeProp.mounted = new NodeProp({ perNode: true }); + const noProps = Object.create(null); + /// Each node in a syntax tree has a node type associated with it. + class NodeType { + /// @internal + constructor( + /// The name of the node type. Not necessarily unique, but if the + /// grammar was written properly, different node types with the + /// same name within a node set should play the same semantic + /// role. + name, + /// @internal + props, + /// The id of this node in its set. Corresponds to the term ids + /// used in the parser. + id, + /// @internal + flags = 0) { + this.name = name; + this.props = props; + this.id = id; + this.flags = flags; + } + /// Define a node type. + static define(spec) { + let props = spec.props && spec.props.length ? Object.create(null) : noProps; + let flags = (spec.top ? 1 /* Top */ : 0) | (spec.skipped ? 2 /* Skipped */ : 0) | + (spec.error ? 4 /* Error */ : 0) | (spec.name == null ? 8 /* Anonymous */ : 0); + let type = new NodeType(spec.name || "", props, spec.id, flags); + if (spec.props) + for (let src of spec.props) { + if (!Array.isArray(src)) + src = src(type); + if (src) { + if (src[0].perNode) + throw new RangeError("Can't store a per-node prop on a node type"); + props[src[0].id] = src[1]; + } + } + return type; + } + /// Retrieves a node prop for this type. Will return `undefined` if + /// the prop isn't present on this node. + prop(prop) { return this.props[prop.id]; } + /// True when this is the top node of a grammar. + get isTop() { return (this.flags & 1 /* Top */) > 0; } + /// True when this node is produced by a skip rule. + get isSkipped() { return (this.flags & 2 /* Skipped */) > 0; } + /// Indicates whether this is an error node. + get isError() { return (this.flags & 4 /* Error */) > 0; } + /// When true, this node type doesn't correspond to a user-declared + /// named node, for example because it is used to cache repetition. + get isAnonymous() { return (this.flags & 8 /* Anonymous */) > 0; } + /// Returns true when this node's name or one of its + /// [groups](#common.NodeProp^group) matches the given string. + is(name) { + if (typeof name == 'string') { + if (this.name == name) + return true; + let group = this.prop(NodeProp.group); + return group ? group.indexOf(name) > -1 : false; + } + return this.id == name; + } + /// Create a function from node types to arbitrary values by + /// specifying an object whose property names are node or + /// [group](#common.NodeProp^group) names. Often useful with + /// [`NodeProp.add`](#common.NodeProp.add). You can put multiple + /// names, separated by spaces, in a single property name to map + /// multiple node names to a single value. + static match(map) { + let direct = Object.create(null); + for (let prop in map) + for (let name of prop.split(" ")) + direct[name] = map[prop]; + return (node) => { + for (let groups = node.prop(NodeProp.group), i = -1; i < (groups ? groups.length : 0); i++) { + let found = direct[i < 0 ? node.name : groups[i]]; + if (found) + return found; + } + }; + } + } + /// An empty dummy node type to use when no actual type is available. + NodeType.none = new NodeType("", Object.create(null), 0, 8 /* Anonymous */); + /// A node set holds a collection of node types. It is used to + /// compactly represent trees by storing their type ids, rather than a + /// full pointer to the type object, in a numeric array. Each parser + /// [has](#lr.LRParser.nodeSet) a node set, and [tree + /// buffers](#common.TreeBuffer) can only store collections of nodes + /// from the same set. A set can have a maximum of 2**16 (65536) node + /// types in it, so that the ids fit into 16-bit typed array slots. + class NodeSet { + /// Create a set with the given types. The `id` property of each + /// type should correspond to its position within the array. + constructor( + /// The node types in this set, by id. + types) { + this.types = types; + for (let i = 0; i < types.length; i++) + if (types[i].id != i) + throw new RangeError("Node type ids should correspond to array positions when creating a node set"); + } + /// Create a copy of this set with some node properties added. The + /// arguments to this method can be created with + /// [`NodeProp.add`](#common.NodeProp.add). + extend(...props) { + let newTypes = []; + for (let type of this.types) { + let newProps = null; + for (let source of props) { + let add = source(type); + if (add) { + if (!newProps) + newProps = Object.assign({}, type.props); + newProps[add[0].id] = add[1]; + } + } + newTypes.push(newProps ? new NodeType(type.name, newProps, type.id, type.flags) : type); + } + return new NodeSet(newTypes); + } + } + const CachedNode = new WeakMap(), CachedInnerNode = new WeakMap(); + /// Options that control iteration. Can be combined with the `|` + /// operator to enable multiple ones. + var IterMode; + (function (IterMode) { + /// When enabled, iteration will only visit [`Tree`](#common.Tree) + /// objects, not nodes packed into + /// [`TreeBuffer`](#common.TreeBuffer)s. + IterMode[IterMode["ExcludeBuffers"] = 1] = "ExcludeBuffers"; + /// Enable this to make iteration include anonymous nodes (such as + /// the nodes that wrap repeated grammar constructs into a balanced + /// tree). + IterMode[IterMode["IncludeAnonymous"] = 2] = "IncludeAnonymous"; + /// By default, regular [mounted](#common.NodeProp^mounted) nodes + /// replace their base node in iteration. Enable this to ignore them + /// instead. + IterMode[IterMode["IgnoreMounts"] = 4] = "IgnoreMounts"; + /// This option only applies in + /// [`enter`](#common.SyntaxNode.enter)-style methods. It tells the + /// library to not enter mounted overlays if one covers the given + /// position. + IterMode[IterMode["IgnoreOverlays"] = 8] = "IgnoreOverlays"; + })(IterMode || (IterMode = {})); + /// A piece of syntax tree. There are two ways to approach these + /// trees: the way they are actually stored in memory, and the + /// convenient way. + /// + /// Syntax trees are stored as a tree of `Tree` and `TreeBuffer` + /// objects. By packing detail information into `TreeBuffer` leaf + /// nodes, the representation is made a lot more memory-efficient. + /// + /// However, when you want to actually work with tree nodes, this + /// representation is very awkward, so most client code will want to + /// use the [`TreeCursor`](#common.TreeCursor) or + /// [`SyntaxNode`](#common.SyntaxNode) interface instead, which provides + /// a view on some part of this data structure, and can be used to + /// move around to adjacent nodes. + class Tree { + /// Construct a new tree. See also [`Tree.build`](#common.Tree^build). + constructor( + /// The type of the top node. + type, + /// This node's child nodes. + children, + /// The positions (offsets relative to the start of this tree) of + /// the children. + positions, + /// The total length of this tree + length, + /// Per-node [node props](#common.NodeProp) to associate with this node. + props) { + this.type = type; + this.children = children; + this.positions = positions; + this.length = length; + /// @internal + this.props = null; + if (props && props.length) { + this.props = Object.create(null); + for (let [prop, value] of props) + this.props[typeof prop == "number" ? prop : prop.id] = value; + } + } + /// @internal + toString() { + let mounted = this.prop(NodeProp.mounted); + if (mounted && !mounted.overlay) + return mounted.tree.toString(); + let children = ""; + for (let ch of this.children) { + let str = ch.toString(); + if (str) { + if (children) + children += ","; + children += str; + } + } + return !this.type.name ? children : + (/\W/.test(this.type.name) && !this.type.isError ? JSON.stringify(this.type.name) : this.type.name) + + (children.length ? "(" + children + ")" : ""); + } + /// Get a [tree cursor](#common.TreeCursor) positioned at the top of + /// the tree. Mode can be used to [control](#common.IterMode) which + /// nodes the cursor visits. + cursor(mode = 0) { + return new TreeCursor(this.topNode, mode); + } + /// Get a [tree cursor](#common.TreeCursor) pointing into this tree + /// at the given position and side (see + /// [`moveTo`](#common.TreeCursor.moveTo). + cursorAt(pos, side = 0, mode = 0) { + let scope = CachedNode.get(this) || this.topNode; + let cursor = new TreeCursor(scope); + cursor.moveTo(pos, side); + CachedNode.set(this, cursor._tree); + return cursor; + } + /// Get a [syntax node](#common.SyntaxNode) object for the top of the + /// tree. + get topNode() { + return new TreeNode(this, 0, 0, null); + } + /// Get the [syntax node](#common.SyntaxNode) at the given position. + /// If `side` is -1, this will move into nodes that end at the + /// position. If 1, it'll move into nodes that start at the + /// position. With 0, it'll only enter nodes that cover the position + /// from both sides. + /// + /// Note that this will not enter + /// [overlays](#common.MountedTree.overlay), and you often want + /// [`resolveInner`](#common.Tree.resolveInner) instead. + resolve(pos, side = 0) { + let node = resolveNode(CachedNode.get(this) || this.topNode, pos, side, false); + CachedNode.set(this, node); + return node; + } + /// Like [`resolve`](#common.Tree.resolve), but will enter + /// [overlaid](#common.MountedTree.overlay) nodes, producing a syntax node + /// pointing into the innermost overlaid tree at the given position + /// (with parent links going through all parent structure, including + /// the host trees). + resolveInner(pos, side = 0) { + let node = resolveNode(CachedInnerNode.get(this) || this.topNode, pos, side, true); + CachedInnerNode.set(this, node); + return node; + } + /// Iterate over the tree and its children, calling `enter` for any + /// node that touches the `from`/`to` region (if given) before + /// running over such a node's children, and `leave` (if given) when + /// leaving the node. When `enter` returns `false`, that node will + /// not have its children iterated over (or `leave` called). + iterate(spec) { + let { enter, leave, from = 0, to = this.length } = spec; + for (let c = this.cursor((spec.mode || 0) | IterMode.IncludeAnonymous);;) { + let entered = false; + if (c.from <= to && c.to >= from && (c.type.isAnonymous || enter(c) !== false)) { + if (c.firstChild()) + continue; + entered = true; + } + for (;;) { + if (entered && leave && !c.type.isAnonymous) + leave(c); + if (c.nextSibling()) + break; + if (!c.parent()) + return; + entered = true; + } + } + } + /// Get the value of the given [node prop](#common.NodeProp) for this + /// node. Works with both per-node and per-type props. + prop(prop) { + return !prop.perNode ? this.type.prop(prop) : this.props ? this.props[prop.id] : undefined; + } + /// Returns the node's [per-node props](#common.NodeProp.perNode) in a + /// format that can be passed to the [`Tree`](#common.Tree) + /// constructor. + get propValues() { + let result = []; + if (this.props) + for (let id in this.props) + result.push([+id, this.props[id]]); + return result; + } + /// Balance the direct children of this tree, producing a copy of + /// which may have children grouped into subtrees with type + /// [`NodeType.none`](#common.NodeType^none). + balance(config = {}) { + return this.children.length <= 8 /* BranchFactor */ ? this : + balanceRange(NodeType.none, this.children, this.positions, 0, this.children.length, 0, this.length, (children, positions, length) => new Tree(this.type, children, positions, length, this.propValues), config.makeTree || ((children, positions, length) => new Tree(NodeType.none, children, positions, length))); + } + /// Build a tree from a postfix-ordered buffer of node information, + /// or a cursor over such a buffer. + static build(data) { return buildTree(data); } + } + /// The empty tree + Tree.empty = new Tree(NodeType.none, [], [], 0); + class FlatBufferCursor { + constructor(buffer, index) { + this.buffer = buffer; + this.index = index; + } + 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 FlatBufferCursor(this.buffer, this.index); } + } + /// Tree buffers contain (type, start, end, endIndex) quads for each + /// node. In such a buffer, nodes are stored in prefix order (parents + /// before children, with the endIndex of the parent indicating which + /// children belong to it). + class TreeBuffer { + /// Create a tree buffer. + constructor( + /// The buffer's content. + buffer, + /// The total length of the group of nodes in the buffer. + length, + /// The node set used in this buffer. + set) { + this.buffer = buffer; + this.length = length; + this.set = set; + } + /// @internal + get type() { return NodeType.none; } + /// @internal + toString() { + let result = []; + for (let index = 0; index < this.buffer.length;) { + result.push(this.childString(index)); + index = this.buffer[index + 3]; + } + return result.join(","); + } + /// @internal + childString(index) { + let id = this.buffer[index], endIndex = this.buffer[index + 3]; + let type = this.set.types[id], result = type.name; + if (/\W/.test(result) && !type.isError) + result = JSON.stringify(result); + index += 4; + if (endIndex == index) + return result; + let children = []; + while (index < endIndex) { + children.push(this.childString(index)); + index = this.buffer[index + 3]; + } + return result + "(" + children.join(",") + ")"; + } + /// @internal + findChild(startIndex, endIndex, dir, pos, side) { + let { buffer } = this, pick = -1; + for (let i = startIndex; i != endIndex; i = buffer[i + 3]) { + if (checkSide(side, pos, buffer[i + 1], buffer[i + 2])) { + pick = i; + if (dir > 0) + break; + } + } + return pick; + } + /// @internal + slice(startI, endI, from, to) { + let b = this.buffer; + let copy = new Uint16Array(endI - startI); + for (let i = startI, j = 0; i < endI;) { + copy[j++] = b[i++]; + copy[j++] = b[i++] - from; + copy[j++] = b[i++] - from; + copy[j++] = b[i++] - startI; + } + return new TreeBuffer(copy, to - from, this.set); + } + } + function checkSide(side, pos, from, to) { + switch (side) { + case -2 /* Before */: return from < pos; + case -1 /* AtOrBefore */: return to >= pos && from < pos; + case 0 /* Around */: return from < pos && to > pos; + case 1 /* AtOrAfter */: return from <= pos && to > pos; + case 2 /* After */: return to > pos; + case 4 /* DontCare */: return true; + } + } + function enterUnfinishedNodesBefore(node, pos) { + let scan = node.childBefore(pos); + while (scan) { + let last = scan.lastChild; + if (!last || last.to != scan.to) + break; + if (last.type.isError && last.from == last.to) { + node = scan; + scan = last.prevSibling; + } + else { + scan = last; + } + } + return node; + } + function resolveNode(node, pos, side, overlays) { + var _a; + // Move up to a node that actually holds the position, if possible + while (node.from == node.to || + (side < 1 ? node.from >= pos : node.from > pos) || + (side > -1 ? node.to <= pos : node.to < pos)) { + let parent = !overlays && node instanceof TreeNode && node.index < 0 ? null : node.parent; + if (!parent) + return node; + node = parent; + } + let mode = overlays ? 0 : IterMode.IgnoreOverlays; + // Must go up out of overlays when those do not overlap with pos + if (overlays) + for (let scan = node, parent = scan.parent; parent; scan = parent, parent = scan.parent) { + if (scan instanceof TreeNode && scan.index < 0 && ((_a = parent.enter(pos, side, mode)) === null || _a === void 0 ? void 0 : _a.from) != scan.from) + node = parent; + } + for (;;) { + let inner = node.enter(pos, side, mode); + if (!inner) + return node; + node = inner; + } + } + class TreeNode { + constructor(_tree, from, + // Index in parent node, set to -1 if the node is not a direct child of _parent.node (overlay) + index, _parent) { + this._tree = _tree; + this.from = from; + this.index = index; + this._parent = _parent; + } + get type() { return this._tree.type; } + get name() { return this._tree.type.name; } + get to() { return this.from + this._tree.length; } + nextChild(i, dir, pos, side, mode = 0) { + for (let parent = this;;) { + for (let { children, positions } = parent._tree, e = dir > 0 ? children.length : -1; i != e; i += dir) { + let next = children[i], start = positions[i] + parent.from; + if (!checkSide(side, pos, start, start + next.length)) + continue; + if (next instanceof TreeBuffer) { + if (mode & IterMode.ExcludeBuffers) + continue; + let index = next.findChild(0, next.buffer.length, dir, pos - start, side); + if (index > -1) + return new BufferNode(new BufferContext(parent, next, i, start), null, index); + } + else if ((mode & IterMode.IncludeAnonymous) || (!next.type.isAnonymous || hasChild(next))) { + let mounted; + if (!(mode & IterMode.IgnoreMounts) && + next.props && (mounted = next.prop(NodeProp.mounted)) && !mounted.overlay) + return new TreeNode(mounted.tree, start, i, parent); + let inner = new TreeNode(next, start, i, parent); + return (mode & IterMode.IncludeAnonymous) || !inner.type.isAnonymous ? inner + : inner.nextChild(dir < 0 ? next.children.length - 1 : 0, dir, pos, side); + } + } + if ((mode & IterMode.IncludeAnonymous) || !parent.type.isAnonymous) + return null; + if (parent.index >= 0) + i = parent.index + dir; + else + i = dir < 0 ? -1 : parent._parent._tree.children.length; + parent = parent._parent; + if (!parent) + return null; + } + } + get firstChild() { return this.nextChild(0, 1, 0, 4 /* DontCare */); } + get lastChild() { return this.nextChild(this._tree.children.length - 1, -1, 0, 4 /* DontCare */); } + childAfter(pos) { return this.nextChild(0, 1, pos, 2 /* After */); } + childBefore(pos) { return this.nextChild(this._tree.children.length - 1, -1, pos, -2 /* Before */); } + enter(pos, side, mode = 0) { + let mounted; + if (!(mode & IterMode.IgnoreOverlays) && (mounted = this._tree.prop(NodeProp.mounted)) && mounted.overlay) { + let rPos = pos - this.from; + for (let { from, to } of mounted.overlay) { + if ((side > 0 ? from <= rPos : from < rPos) && + (side < 0 ? to >= rPos : to > rPos)) + return new TreeNode(mounted.tree, mounted.overlay[0].from + this.from, -1, this); + } + } + return this.nextChild(0, 1, pos, side, mode); + } + nextSignificantParent() { + let val = this; + while (val.type.isAnonymous && val._parent) + val = val._parent; + return val; + } + 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 /* DontCare */) : null; + } + get prevSibling() { + return this._parent && this.index >= 0 ? this._parent.nextChild(this.index - 1, -1, 0, 4 /* DontCare */) : null; + } + cursor(mode = 0) { return new TreeCursor(this, mode); } + get tree() { return this._tree; } + toTree() { return this._tree; } + resolve(pos, side = 0) { + return resolveNode(this, pos, side, false); + } + resolveInner(pos, side = 0) { + return resolveNode(this, pos, side, true); + } + enterUnfinishedNodesBefore(pos) { return enterUnfinishedNodesBefore(this, pos); } + getChild(type, before = null, after = null) { + let r = getChildren(this, type, before, after); + return r.length ? r[0] : null; + } + getChildren(type, before = null, after = null) { + return getChildren(this, type, before, after); + } + /// @internal + toString() { return this._tree.toString(); } + get node() { return this; } + matchContext(context) { return matchNodeContext(this, context); } + } + function getChildren(node, type, before, after) { + let cur = node.cursor(), result = []; + if (!cur.firstChild()) + return result; + if (before != null) + while (!cur.type.is(before)) + if (!cur.nextSibling()) + return result; + for (;;) { + if (after != null && cur.type.is(after)) + return result; + if (cur.type.is(type)) + result.push(cur.node); + if (!cur.nextSibling()) + return after == null ? result : []; + } + } + function matchNodeContext(node, context, i = context.length - 1) { + for (let p = node.parent; i >= 0; p = p.parent) { + if (!p) + return false; + if (!p.type.isAnonymous) { + if (context[i] && context[i] != p.name) + return false; + i--; + } + } + return true; + } + class BufferContext { + constructor(parent, buffer, index, start) { + this.parent = parent; + this.buffer = buffer; + this.index = index; + this.start = start; + } + } + class BufferNode { + constructor(context, _parent, index) { + this.context = context; + this._parent = _parent; + this.index = index; + this.type = context.buffer.set.types[context.buffer.buffer[index]]; + } + 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]; } + child(dir, pos, side) { + let { buffer } = this.context; + let index = buffer.findChild(this.index + 4, buffer.buffer[this.index + 3], dir, pos - this.context.start, side); + return index < 0 ? null : new BufferNode(this.context, this, index); + } + get firstChild() { return this.child(1, 0, 4 /* DontCare */); } + get lastChild() { return this.child(-1, 0, 4 /* DontCare */); } + childAfter(pos) { return this.child(1, pos, 2 /* After */); } + childBefore(pos) { return this.child(-1, pos, -2 /* Before */); } + enter(pos, side, mode = 0) { + if (mode & IterMode.ExcludeBuffers) + return null; + let { buffer } = this.context; + let index = buffer.findChild(this.index + 4, buffer.buffer[this.index + 3], side > 0 ? 1 : -1, pos - this.context.start, side); + return index < 0 ? null : new BufferNode(this.context, this, index); + } + get parent() { + return this._parent || this.context.parent.nextSignificantParent(); + } + externalSibling(dir) { + return this._parent ? null : this.context.parent.nextChild(this.context.index + dir, dir, 0, 4 /* DontCare */); + } + get nextSibling() { + let { buffer } = this.context; + let after = buffer.buffer[this.index + 3]; + if (after < (this._parent ? buffer.buffer[this._parent.index + 3] : buffer.buffer.length)) + return new BufferNode(this.context, this._parent, after); + return this.externalSibling(1); + } + get prevSibling() { + let { buffer } = this.context; + let parentStart = this._parent ? this._parent.index + 4 : 0; + if (this.index == parentStart) + return this.externalSibling(-1); + return new BufferNode(this.context, this._parent, buffer.findChild(parentStart, this.index, -1, 0, 4 /* DontCare */)); + } + cursor(mode = 0) { return new TreeCursor(this, mode); } + get tree() { return null; } + toTree() { + let children = [], positions = []; + let { buffer } = this.context; + let startI = this.index + 4, endI = buffer.buffer[this.index + 3]; + if (endI > startI) { + let from = buffer.buffer[this.index + 1], to = buffer.buffer[this.index + 2]; + children.push(buffer.slice(startI, endI, from, to)); + positions.push(0); + } + return new Tree(this.type, children, positions, this.to - this.from); + } + resolve(pos, side = 0) { + return resolveNode(this, pos, side, false); + } + resolveInner(pos, side = 0) { + return resolveNode(this, pos, side, true); + } + enterUnfinishedNodesBefore(pos) { return enterUnfinishedNodesBefore(this, pos); } + /// @internal + toString() { return this.context.buffer.childString(this.index); } + getChild(type, before = null, after = null) { + let r = getChildren(this, type, before, after); + return r.length ? r[0] : null; + } + getChildren(type, before = null, after = null) { + return getChildren(this, type, before, after); + } + get node() { return this; } + matchContext(context) { return matchNodeContext(this, context); } + } + /// A tree cursor object focuses on a given node in a syntax tree, and + /// allows you to move to adjacent nodes. + class TreeCursor { + /// @internal + constructor(node, + /// @internal + mode = 0) { + this.mode = mode; + /// @internal + this.buffer = null; + this.stack = []; + /// @internal + this.index = 0; + this.bufferNode = null; + if (node instanceof TreeNode) { + this.yieldNode(node); + } + else { + this._tree = node.context.parent; + this.buffer = node.context; + for (let n = node._parent; n; n = n._parent) + this.stack.unshift(n.index); + this.bufferNode = node; + this.yieldBuf(node.index); + } + } + /// Shorthand for `.type.name`. + get name() { return this.type.name; } + yieldNode(node) { + if (!node) + return false; + this._tree = node; + this.type = node.type; + this.from = node.from; + this.to = node.to; + return true; + } + yieldBuf(index, type) { + this.index = index; + let { start, buffer } = this.buffer; + this.type = type || buffer.set.types[buffer.buffer[index]]; + this.from = start + buffer.buffer[index + 1]; + this.to = start + buffer.buffer[index + 2]; + return true; + } + yield(node) { + if (!node) + return false; + if (node instanceof TreeNode) { + this.buffer = null; + return this.yieldNode(node); + } + this.buffer = node.context; + return this.yieldBuf(node.index, node.type); + } + /// @internal + toString() { + return this.buffer ? this.buffer.buffer.childString(this.index) : this._tree.toString(); + } + /// @internal + enterChild(dir, pos, side) { + if (!this.buffer) + return this.yield(this._tree.nextChild(dir < 0 ? this._tree._tree.children.length - 1 : 0, dir, pos, side, this.mode)); + let { buffer } = this.buffer; + let index = buffer.findChild(this.index + 4, buffer.buffer[this.index + 3], dir, pos - this.buffer.start, side); + if (index < 0) + return false; + this.stack.push(this.index); + return this.yieldBuf(index); + } + /// Move the cursor to this node's first child. When this returns + /// false, the node has no child, and the cursor has not been moved. + firstChild() { return this.enterChild(1, 0, 4 /* DontCare */); } + /// Move the cursor to this node's last child. + lastChild() { return this.enterChild(-1, 0, 4 /* DontCare */); } + /// Move the cursor to the first child that ends after `pos`. + childAfter(pos) { return this.enterChild(1, pos, 2 /* After */); } + /// Move to the last child that starts before `pos`. + childBefore(pos) { return this.enterChild(-1, pos, -2 /* Before */); } + /// Move the cursor to the child around `pos`. If side is -1 the + /// child may end at that position, when 1 it may start there. This + /// will also enter [overlaid](#common.MountedTree.overlay) + /// [mounted](#common.NodeProp^mounted) trees unless `overlays` is + /// set to false. + enter(pos, side, mode = this.mode) { + if (!this.buffer) + return this.yield(this._tree.enter(pos, side, mode)); + return mode & IterMode.ExcludeBuffers ? false : this.enterChild(1, pos, side); + } + /// Move to the node's parent node, if this isn't the top node. + parent() { + if (!this.buffer) + return this.yieldNode((this.mode & IterMode.IncludeAnonymous) ? this._tree._parent : this._tree.parent); + if (this.stack.length) + return this.yieldBuf(this.stack.pop()); + let parent = (this.mode & IterMode.IncludeAnonymous) ? this.buffer.parent : this.buffer.parent.nextSignificantParent(); + this.buffer = null; + return this.yieldNode(parent); + } + /// @internal + sibling(dir) { + if (!this.buffer) + return !this._tree._parent ? false + : this.yield(this._tree.index < 0 ? null + : this._tree._parent.nextChild(this._tree.index + dir, dir, 0, 4 /* DontCare */, this.mode)); + let { buffer } = this.buffer, d = this.stack.length - 1; + if (dir < 0) { + let parentStart = d < 0 ? 0 : this.stack[d] + 4; + if (this.index != parentStart) + return this.yieldBuf(buffer.findChild(parentStart, this.index, -1, 0, 4 /* DontCare */)); + } + else { + let after = buffer.buffer[this.index + 3]; + if (after < (d < 0 ? buffer.buffer.length : buffer.buffer[this.stack[d] + 3])) + return this.yieldBuf(after); + } + return d < 0 ? this.yield(this.buffer.parent.nextChild(this.buffer.index + dir, dir, 0, 4 /* DontCare */, this.mode)) : false; + } + /// Move to this node's next sibling, if any. + nextSibling() { return this.sibling(1); } + /// Move to this node's previous sibling, if any. + prevSibling() { return this.sibling(-1); } + atLastNode(dir) { + let index, parent, { buffer } = this; + if (buffer) { + if (dir > 0) { + if (this.index < buffer.buffer.buffer.length) + return false; + } + else { + for (let i = 0; i < this.index; i++) + if (buffer.buffer.buffer[i + 3] < this.index) + return false; + } + ({ index, parent } = buffer); + } + else { + ({ index, _parent: parent } = this._tree); + } + for (; parent; { index, _parent: parent } = parent) { + if (index > -1) + for (let i = index + dir, e = dir < 0 ? -1 : parent._tree.children.length; i != e; i += dir) { + let child = parent._tree.children[i]; + if ((this.mode & IterMode.IncludeAnonymous) || + child instanceof TreeBuffer || + !child.type.isAnonymous || + hasChild(child)) + return false; + } + } + return true; + } + move(dir, enter) { + if (enter && this.enterChild(dir, 0, 4 /* DontCare */)) + return true; + for (;;) { + if (this.sibling(dir)) + return true; + if (this.atLastNode(dir) || !this.parent()) + return false; + } + } + /// Move to the next node in a + /// [pre-order](https://en.wikipedia.org/wiki/Tree_traversal#Pre-order_(NLR)) + /// traversal, going from a node to its first child or, if the + /// current node is empty or `enter` is false, its next sibling or + /// the next sibling of the first parent node that has one. + next(enter = true) { return this.move(1, enter); } + /// Move to the next node in a last-to-first pre-order traveral. A + /// node is followed by its last child or, if it has none, its + /// previous sibling or the previous sibling of the first parent + /// node that has one. + prev(enter = true) { return this.move(-1, enter); } + /// Move the cursor to the innermost node that covers `pos`. If + /// `side` is -1, it will enter nodes that end at `pos`. If it is 1, + /// it will enter nodes that start at `pos`. + moveTo(pos, side = 0) { + // Move up to a node that actually holds the position, if possible + while (this.from == this.to || + (side < 1 ? this.from >= pos : this.from > pos) || + (side > -1 ? this.to <= pos : this.to < pos)) + if (!this.parent()) + break; + // Then scan down into child nodes as far as possible + while (this.enterChild(1, pos, side)) { } + return this; + } + /// Get a [syntax node](#common.SyntaxNode) at the cursor's current + /// position. + get node() { + if (!this.buffer) + return this._tree; + let cache = this.bufferNode, result = null, depth = 0; + if (cache && cache.context == this.buffer) { + scan: for (let index = this.index, d = this.stack.length; d >= 0;) { + for (let c = cache; c; c = c._parent) + if (c.index == index) { + if (index == this.index) + return c; + result = c; + depth = d + 1; + break scan; + } + index = this.stack[--d]; + } + } + for (let i = depth; i < this.stack.length; i++) + result = new BufferNode(this.buffer, result, this.stack[i]); + return this.bufferNode = new BufferNode(this.buffer, result, this.index); + } + /// Get the [tree](#common.Tree) that represents the current node, if + /// any. Will return null when the node is in a [tree + /// buffer](#common.TreeBuffer). + get tree() { + return this.buffer ? null : this._tree._tree; + } + /// Iterate over the current node and all its descendants, calling + /// `enter` when entering a node and `leave`, if given, when leaving + /// one. When `enter` returns `false`, any children of that node are + /// skipped, and `leave` isn't called for it. + iterate(enter, leave) { + for (let depth = 0;;) { + let mustLeave = false; + if (this.type.isAnonymous || enter(this) !== false) { + if (this.firstChild()) { + depth++; + continue; + } + if (!this.type.isAnonymous) + mustLeave = true; + } + for (;;) { + if (mustLeave && leave) + leave(this); + mustLeave = this.type.isAnonymous; + if (this.nextSibling()) + break; + if (!depth) + return; + this.parent(); + depth--; + mustLeave = true; + } + } + } + /// Test whether the current node matches a given context—a sequence + /// of direct parent node names. Empty strings in the context array + /// are treated as wildcards. + matchContext(context) { + if (!this.buffer) + return matchNodeContext(this.node, context); + let { buffer } = this.buffer, { types } = buffer.set; + for (let i = context.length - 1, d = this.stack.length - 1; i >= 0; d--) { + if (d < 0) + return matchNodeContext(this.node, context, i); + let type = types[buffer.buffer[this.stack[d]]]; + if (!type.isAnonymous) { + if (context[i] && context[i] != type.name) + return false; + i--; + } + } + return true; + } + } + function hasChild(tree) { + return tree.children.some(ch => ch instanceof TreeBuffer || !ch.type.isAnonymous || hasChild(ch)); + } + function buildTree(data) { + var _a; + let { buffer, nodeSet, maxBufferLength = DefaultBufferLength, reused = [], minRepeatType = nodeSet.types.length } = data; + let cursor = Array.isArray(buffer) ? new FlatBufferCursor(buffer, buffer.length) : buffer; + let types = nodeSet.types; + let contextHash = 0, lookAhead = 0; + function takeNode(parentStart, minPos, children, positions, inRepeat) { + let { id, start, end, size } = cursor; + let lookAheadAtStart = lookAhead; + while (size < 0) { + cursor.next(); + if (size == -1 /* Reuse */) { + let node = reused[id]; + children.push(node); + positions.push(start - parentStart); + return; + } + else if (size == -3 /* ContextChange */) { // Context change + contextHash = id; + return; + } + else if (size == -4 /* LookAhead */) { + lookAhead = id; + return; + } + else { + throw new RangeError(`Unrecognized record size: ${size}`); + } + } + let type = types[id], node, buffer; + let startPos = start - parentStart; + if (end - start <= maxBufferLength && (buffer = findBufferSize(cursor.pos - minPos, inRepeat))) { + // Small enough for a buffer, and no reused nodes inside + let data = new Uint16Array(buffer.size - buffer.skip); + let endPos = cursor.pos - buffer.size, index = data.length; + while (cursor.pos > endPos) + index = copyToBuffer(buffer.start, data, index); + node = new TreeBuffer(data, end - buffer.start, nodeSet); + startPos = buffer.start - parentStart; + } + else { // Make it a node + let endPos = cursor.pos - size; + cursor.next(); + let localChildren = [], localPositions = []; + let localInRepeat = id >= minRepeatType ? id : -1; + let lastGroup = 0, lastEnd = end; + while (cursor.pos > endPos) { + if (localInRepeat >= 0 && cursor.id == localInRepeat && cursor.size >= 0) { + if (cursor.end <= lastEnd - maxBufferLength) { + makeRepeatLeaf(localChildren, localPositions, start, lastGroup, cursor.end, lastEnd, localInRepeat, lookAheadAtStart); + lastGroup = localChildren.length; + lastEnd = cursor.end; + } + cursor.next(); + } + else { + takeNode(start, endPos, localChildren, localPositions, localInRepeat); + } + } + if (localInRepeat >= 0 && lastGroup > 0 && lastGroup < localChildren.length) + makeRepeatLeaf(localChildren, localPositions, start, lastGroup, start, lastEnd, localInRepeat, lookAheadAtStart); + localChildren.reverse(); + localPositions.reverse(); + if (localInRepeat > -1 && lastGroup > 0) { + let make = makeBalanced(type); + node = balanceRange(type, localChildren, localPositions, 0, localChildren.length, 0, end - start, make, make); + } + else { + node = makeTree(type, localChildren, localPositions, end - start, lookAheadAtStart - end); + } + } + children.push(node); + positions.push(startPos); + } + function makeBalanced(type) { + return (children, positions, length) => { + let lookAhead = 0, lastI = children.length - 1, last, lookAheadProp; + if (lastI >= 0 && (last = children[lastI]) instanceof Tree) { + if (!lastI && last.type == type && last.length == length) + return last; + if (lookAheadProp = last.prop(NodeProp.lookAhead)) + lookAhead = positions[lastI] + last.length + lookAheadProp; + } + return makeTree(type, children, positions, length, lookAhead); + }; + } + function makeRepeatLeaf(children, positions, base, i, from, to, type, lookAhead) { + let localChildren = [], localPositions = []; + while (children.length > i) { + localChildren.push(children.pop()); + localPositions.push(positions.pop() + base - from); + } + children.push(makeTree(nodeSet.types[type], localChildren, localPositions, to - from, lookAhead - to)); + positions.push(from - base); + } + function makeTree(type, children, positions, length, lookAhead = 0, props) { + if (contextHash) { + let pair = [NodeProp.contextHash, contextHash]; + props = props ? [pair].concat(props) : [pair]; + } + if (lookAhead > 25) { + let pair = [NodeProp.lookAhead, lookAhead]; + props = props ? [pair].concat(props) : [pair]; + } + return new Tree(type, children, positions, length, props); + } + function findBufferSize(maxSize, inRepeat) { + // Scan through the buffer to find previous siblings that fit + // together in a TreeBuffer, and don't contain any reused nodes + // (which can't be stored in a buffer). + // If `inRepeat` is > -1, ignore node boundaries of that type for + // nesting, but make sure the end falls either at the start + // (`maxSize`) or before such a node. + let fork = cursor.fork(); + let size = 0, start = 0, skip = 0, minStart = fork.end - maxBufferLength; + let result = { size: 0, start: 0, skip: 0 }; + scan: for (let minPos = fork.pos - maxSize; fork.pos > minPos;) { + let nodeSize = fork.size; + // Pretend nested repeat nodes of the same type don't exist + if (fork.id == inRepeat && nodeSize >= 0) { + // Except that we store the current state as a valid return + // value. + result.size = size; + result.start = start; + result.skip = skip; + skip += 4; + size += 4; + fork.next(); + continue; + } + let startPos = fork.pos - nodeSize; + if (nodeSize < 0 || startPos < minPos || fork.start < minStart) + break; + let localSkipped = fork.id >= minRepeatType ? 4 : 0; + let nodeStart = fork.start; + fork.next(); + while (fork.pos > startPos) { + if (fork.size < 0) { + if (fork.size == -3 /* ContextChange */) + localSkipped += 4; + else + break scan; + } + else if (fork.id >= minRepeatType) { + localSkipped += 4; + } + fork.next(); + } + start = nodeStart; + size += nodeSize; + skip += localSkipped; + } + if (inRepeat < 0 || size == maxSize) { + result.size = size; + result.start = start; + result.skip = skip; + } + return result.size > 4 ? result : undefined; + } + function copyToBuffer(bufferStart, buffer, index) { + let { id, start, end, size } = cursor; + cursor.next(); + if (size >= 0 && id < minRepeatType) { + let startIndex = index; + if (size > 4) { + let endPos = cursor.pos - (size - 4); + while (cursor.pos > endPos) + index = copyToBuffer(bufferStart, buffer, index); + } + buffer[--index] = startIndex; + buffer[--index] = end - bufferStart; + buffer[--index] = start - bufferStart; + buffer[--index] = id; + } + else if (size == -3 /* ContextChange */) { + contextHash = id; + } + else if (size == -4 /* LookAhead */) { + lookAhead = id; + } + return index; + } + let children = [], positions = []; + while (cursor.pos > 0) + takeNode(data.start || 0, data.bufferStart || 0, children, positions, -1); + let length = (_a = data.length) !== null && _a !== void 0 ? _a : (children.length ? positions[0] + children[0].length : 0); + return new Tree(types[data.topID], children.reverse(), positions.reverse(), length); + } + const nodeSizeCache = new WeakMap; + function nodeSize(balanceType, node) { + if (!balanceType.isAnonymous || node instanceof TreeBuffer || node.type != balanceType) + return 1; + let size = nodeSizeCache.get(node); + if (size == null) { + size = 1; + for (let child of node.children) { + if (child.type != balanceType || !(child instanceof Tree)) { + size = 1; + break; + } + size += nodeSize(balanceType, child); + } + nodeSizeCache.set(node, size); + } + return size; + } + function balanceRange( + // The type the balanced tree's inner nodes. + balanceType, + // The direct children and their positions + children, positions, + // The index range in children/positions to use + from, to, + // The start position of the nodes, relative to their parent. + start, + // Length of the outer node + length, + // Function to build the top node of the balanced tree + mkTop, + // Function to build internal nodes for the balanced tree + mkTree) { + let total = 0; + for (let i = from; i < to; i++) + total += nodeSize(balanceType, children[i]); + let maxChild = Math.ceil((total * 1.5) / 8 /* BranchFactor */); + let localChildren = [], localPositions = []; + function divide(children, positions, from, to, offset) { + for (let i = from; i < to;) { + let groupFrom = i, groupStart = positions[i], groupSize = nodeSize(balanceType, children[i]); + i++; + for (; i < to; i++) { + let nextSize = nodeSize(balanceType, children[i]); + if (groupSize + nextSize >= maxChild) + break; + groupSize += nextSize; + } + if (i == groupFrom + 1) { + if (groupSize > maxChild) { + let only = children[groupFrom]; // Only trees can have a size > 1 + divide(only.children, only.positions, 0, only.children.length, positions[groupFrom] + offset); + continue; + } + localChildren.push(children[groupFrom]); + } + else { + let length = positions[i - 1] + children[i - 1].length - groupStart; + localChildren.push(balanceRange(balanceType, children, positions, groupFrom, i, groupStart, length, null, mkTree)); + } + localPositions.push(groupStart + offset - start); + } + } + divide(children, positions, from, to, 0); + return (mkTop || mkTree)(localChildren, localPositions, length); + } + + /// Tree fragments are used during [incremental + /// parsing](#common.Parser.startParse) to track parts of old trees + /// that can be reused in a new parse. An array of fragments is used + /// to track regions of an old tree whose nodes might be reused in new + /// parses. Use the static + /// [`applyChanges`](#common.TreeFragment^applyChanges) method to + /// update fragments for document changes. + class TreeFragment { + /// Construct a tree fragment. You'll usually want to use + /// [`addTree`](#common.TreeFragment^addTree) and + /// [`applyChanges`](#common.TreeFragment^applyChanges) instead of + /// calling this directly. + constructor( + /// The start of the unchanged range pointed to by this fragment. + /// This refers to an offset in the _updated_ document (as opposed + /// to the original tree). + from, + /// The end of the unchanged range. + to, + /// The tree that this fragment is based on. + tree, + /// The offset between the fragment's tree and the document that + /// this fragment can be used against. Add this when going from + /// document to tree positions, subtract it to go from tree to + /// document positions. + offset, openStart = false, openEnd = false) { + this.from = from; + this.to = to; + this.tree = tree; + this.offset = offset; + this.open = (openStart ? 1 /* Start */ : 0) | (openEnd ? 2 /* End */ : 0); + } + /// Whether the start of the fragment represents the start of a + /// parse, or the end of a change. (In the second case, it may not + /// be safe to reuse some nodes at the start, depending on the + /// parsing algorithm.) + get openStart() { return (this.open & 1 /* Start */) > 0; } + /// Whether the end of the fragment represents the end of a + /// full-document parse, or the start of a change. + get openEnd() { return (this.open & 2 /* End */) > 0; } + /// Create a set of fragments from a freshly parsed tree, or update + /// an existing set of fragments by replacing the ones that overlap + /// with a tree with content from the new tree. When `partial` is + /// true, the parse is treated as incomplete, and the resulting + /// fragment has [`openEnd`](#common.TreeFragment.openEnd) set to + /// true. + static addTree(tree, fragments = [], partial = false) { + let result = [new TreeFragment(0, tree.length, tree, 0, false, partial)]; + for (let f of fragments) + if (f.to > tree.length) + result.push(f); + return result; + } + /// Apply a set of edits to an array of fragments, removing or + /// splitting fragments as necessary to remove edited ranges, and + /// adjusting offsets for fragments that moved. + static applyChanges(fragments, changes, minGap = 128) { + if (!changes.length) + return fragments; + let result = []; + let fI = 1, nextF = fragments.length ? fragments[0] : null; + for (let cI = 0, pos = 0, off = 0;; cI++) { + let nextC = cI < changes.length ? changes[cI] : null; + let nextPos = nextC ? nextC.fromA : 1e9; + if (nextPos - pos >= minGap) + while (nextF && nextF.from < nextPos) { + let cut = nextF; + if (pos >= cut.from || nextPos <= cut.to || off) { + let fFrom = Math.max(cut.from, pos) - off, fTo = Math.min(cut.to, nextPos) - off; + cut = fFrom >= fTo ? null : new TreeFragment(fFrom, fTo, cut.tree, cut.offset + off, cI > 0, !!nextC); + } + if (cut) + result.push(cut); + if (nextF.to > nextPos) + break; + nextF = fI < fragments.length ? fragments[fI++] : null; + } + if (!nextC) + break; + pos = nextC.toA; + off = nextC.toA - nextC.toB; + } + return result; + } + } + /// A superclass that parsers should extend. + class Parser { + /// Start a parse, returning a [partial parse](#common.PartialParse) + /// object. [`fragments`](#common.TreeFragment) can be passed in to + /// make the parse incremental. + /// + /// By default, the entire input is parsed. You can pass `ranges`, + /// which should be a sorted array of non-empty, non-overlapping + /// ranges, to parse only those ranges. The tree returned in that + /// case will start at `ranges[0].from`. + startParse(input, fragments, ranges) { + if (typeof input == "string") + input = new StringInput(input); + ranges = !ranges ? [new Range(0, input.length)] : ranges.length ? ranges.map(r => new Range(r.from, r.to)) : [new Range(0, 0)]; + return this.createParse(input, fragments || [], ranges); + } + /// Run a full parse, returning the resulting tree. + parse(input, fragments, ranges) { + let parse = this.startParse(input, fragments, ranges); + for (;;) { + let done = parse.advance(); + if (done) + return done; + } + } + } + class StringInput { + constructor(string) { + this.string = string; + } + get length() { return this.string.length; } + chunk(from) { return this.string.slice(from); } + get lineChunks() { return false; } + read(from, to) { return this.string.slice(from, to); } + } + new NodeProp({ perNode: true }); + + let nextTagID = 0; + /// Highlighting tags are markers that denote a highlighting category. + /// They are [associated](#highlight.styleTags) with parts of a syntax + /// tree by a language mode, and then mapped to an actual CSS style by + /// a [highlighter](#highlight.Highlighter). + /// + /// Because syntax tree node types and highlight styles have to be + /// able to talk the same language, CodeMirror uses a mostly _closed_ + /// [vocabulary](#highlight.tags) of syntax tags (as opposed to + /// traditional open string-based systems, which make it hard for + /// highlighting themes to cover all the tokens produced by the + /// various languages). + /// + /// It _is_ possible to [define](#highlight.Tag^define) your own + /// highlighting tags for system-internal use (where you control both + /// the language package and the highlighter), but such tags will not + /// be picked up by regular highlighters (though you can derive them + /// from standard tags to allow highlighters to fall back to those). + class Tag { + /// @internal + constructor( + /// The set of this tag and all its parent tags, starting with + /// this one itself and sorted in order of decreasing specificity. + set, + /// The base unmodified tag that this one is based on, if it's + /// modified @internal + base, + /// The modifiers applied to this.base @internal + modified) { + this.set = set; + this.base = base; + this.modified = modified; + /// @internal + this.id = nextTagID++; + } + /// Define a new tag. If `parent` is given, the tag is treated as a + /// sub-tag of that parent, and + /// [highlighters](#highlight.tagHighlighter) that don't mention + /// this tag will try to fall back to the parent tag (or grandparent + /// tag, etc). + static define(parent) { + if (parent === null || parent === void 0 ? void 0 : parent.base) + throw new Error("Can not derive from a modified tag"); + let tag = new Tag([], null, []); + tag.set.push(tag); + if (parent) + for (let t of parent.set) + tag.set.push(t); + return tag; + } + /// Define a tag _modifier_, which is a function that, given a tag, + /// will return a tag that is a subtag of the original. Applying the + /// same modifier to a twice tag will return the same value (`m1(t1) + /// == m1(t1)`) and applying multiple modifiers will, regardless or + /// order, produce the same tag (`m1(m2(t1)) == m2(m1(t1))`). + /// + /// When multiple modifiers are applied to a given base tag, each + /// smaller set of modifiers is registered as a parent, so that for + /// example `m1(m2(m3(t1)))` is a subtype of `m1(m2(t1))`, + /// `m1(m3(t1)`, and so on. + static defineModifier() { + let mod = new Modifier; + return (tag) => { + if (tag.modified.indexOf(mod) > -1) + return tag; + return Modifier.get(tag.base || tag, tag.modified.concat(mod).sort((a, b) => a.id - b.id)); + }; + } + } + let nextModifierID = 0; + class Modifier { + constructor() { + this.instances = []; + this.id = nextModifierID++; + } + static get(base, mods) { + if (!mods.length) + return base; + let exists = mods[0].instances.find(t => t.base == base && sameArray(mods, t.modified)); + if (exists) + return exists; + let set = [], tag = new Tag(set, base, mods); + for (let m of mods) + m.instances.push(tag); + let configs = permute(mods); + for (let parent of base.set) + for (let config of configs) + set.push(Modifier.get(parent, config)); + return tag; + } + } + function sameArray(a, b) { + return a.length == b.length && a.every((x, i) => x == b[i]); + } + function permute(array) { + let result = [array]; + for (let i = 0; i < array.length; i++) { + for (let a of permute(array.slice(0, i).concat(array.slice(i + 1)))) + result.push(a); + } + return result; + } + /// This function is used to add a set of tags to a language syntax + /// via [`NodeSet.extend`](#common.NodeSet.extend) or + /// [`LRParser.configure`](#lr.LRParser.configure). + /// + /// The argument object maps node selectors to [highlighting + /// tags](#highlight.Tag) or arrays of tags. + /// + /// Node selectors may hold one or more (space-separated) node paths. + /// Such a path can be a [node name](#common.NodeType.name), or + /// multiple node names (or `*` wildcards) separated by slash + /// characters, as in `"Block/Declaration/VariableName"`. Such a path + /// matches the final node but only if its direct parent nodes are the + /// other nodes mentioned. A `*` in such a path matches any parent, + /// but only a single level—wildcards that match multiple parents + /// aren't supported, both for efficiency reasons and because Lezer + /// trees make it rather hard to reason about what they would match.) + /// + /// A path can be ended with `/...` to indicate that the tag assigned + /// to the node should also apply to all child nodes, even if they + /// match their own style (by default, only the innermost style is + /// used). + /// + /// When a path ends in `!`, as in `Attribute!`, no further matching + /// happens for the node's child nodes, and the entire node gets the + /// given style. + /// + /// In this notation, node names that contain `/`, `!`, `*`, or `...` + /// must be quoted as JSON strings. + /// + /// For example: + /// + /// ```javascript + /// parser.withProps( + /// styleTags({ + /// // Style Number and BigNumber nodes + /// "Number BigNumber": tags.number, + /// // Style Escape nodes whose parent is String + /// "String/Escape": tags.escape, + /// // Style anything inside Attributes nodes + /// "Attributes!": tags.meta, + /// // Add a style to all content inside Italic nodes + /// "Italic/...": tags.emphasis, + /// // Style InvalidString nodes as both `string` and `invalid` + /// "InvalidString": [tags.string, tags.invalid], + /// // Style the node named "/" as punctuation + /// '"/"': tags.punctuation + /// }) + /// ) + /// ``` + function styleTags(spec) { + let byName = Object.create(null); + for (let prop in spec) { + let tags = spec[prop]; + if (!Array.isArray(tags)) + tags = [tags]; + for (let part of prop.split(" ")) + if (part) { + let pieces = [], mode = 2 /* Normal */, rest = part; + for (let pos = 0;;) { + if (rest == "..." && pos > 0 && pos + 3 == part.length) { + mode = 1 /* Inherit */; + break; + } + let m = /^"(?:[^"\\]|\\.)*?"|[^\/!]+/.exec(rest); + if (!m) + throw new RangeError("Invalid path: " + part); + pieces.push(m[0] == "*" ? "" : m[0][0] == '"' ? JSON.parse(m[0]) : m[0]); + pos += m[0].length; + if (pos == part.length) + break; + let next = part[pos++]; + if (pos == part.length && next == "!") { + mode = 0 /* Opaque */; + break; + } + if (next != "/") + throw new RangeError("Invalid path: " + part); + rest = part.slice(pos); + } + let last = pieces.length - 1, inner = pieces[last]; + if (!inner) + throw new RangeError("Invalid path: " + part); + let rule = new Rule(tags, mode, last > 0 ? pieces.slice(0, last) : null); + byName[inner] = rule.sort(byName[inner]); + } + } + return ruleNodeProp.add(byName); + } + const ruleNodeProp = new NodeProp(); + class Rule { + constructor(tags, mode, context, next) { + this.tags = tags; + this.mode = mode; + this.context = context; + this.next = next; + } + get opaque() { return this.mode == 0 /* Opaque */; } + get inherit() { return this.mode == 1 /* Inherit */; } + sort(other) { + if (!other || other.depth < this.depth) { + this.next = other; + return this; + } + other.next = this.sort(other.next); + return other; + } + get depth() { return this.context ? this.context.length : 0; } + } + Rule.empty = new Rule([], 2 /* Normal */, null); + /// Define a [highlighter](#highlight.Highlighter) from an array of + /// tag/class pairs. Classes associated with more specific tags will + /// take precedence. + function tagHighlighter(tags, options) { + let map = Object.create(null); + for (let style of tags) { + if (!Array.isArray(style.tag)) + map[style.tag.id] = style.class; + else + for (let tag of style.tag) + map[tag.id] = style.class; + } + let { scope, all = null } = options || {}; + return { + style: (tags) => { + let cls = all; + for (let tag of tags) { + for (let sub of tag.set) { + let tagClass = map[sub.id]; + if (tagClass) { + cls = cls ? cls + " " + tagClass : tagClass; + break; + } + } + } + return cls; + }, + scope + }; + } + function highlightTags(highlighters, tags) { + let result = null; + for (let highlighter of highlighters) { + let value = highlighter.style(tags); + if (value) + result = result ? result + " " + value : value; + } + return result; + } + /// Highlight the given [tree](#common.Tree) with the given + /// [highlighter](#highlight.Highlighter). + function highlightTree(tree, highlighter, + /// Assign styling to a region of the text. Will be called, in order + /// of position, for any ranges where more than zero classes apply. + /// `classes` is a space separated string of CSS classes. + putStyle, + /// The start of the range to highlight. + from = 0, + /// The end of the range. + to = tree.length) { + let builder = new HighlightBuilder(from, Array.isArray(highlighter) ? highlighter : [highlighter], putStyle); + builder.highlightRange(tree.cursor(), from, to, "", builder.highlighters); + builder.flush(to); + } + class HighlightBuilder { + constructor(at, highlighters, span) { + this.at = at; + this.highlighters = highlighters; + this.span = span; + this.class = ""; + } + startSpan(at, cls) { + if (cls != this.class) { + this.flush(at); + if (at > this.at) + this.at = at; + this.class = cls; + } + } + flush(to) { + if (to > this.at && this.class) + this.span(this.at, to, this.class); + } + highlightRange(cursor, from, to, inheritedClass, highlighters) { + let { type, from: start, to: end } = cursor; + if (start >= to || end <= from) + return; + if (type.isTop) + highlighters = this.highlighters.filter(h => !h.scope || h.scope(type)); + let cls = inheritedClass; + let rule = getStyleTags(cursor) || Rule.empty; + let tagCls = highlightTags(highlighters, rule.tags); + if (tagCls) { + if (cls) + cls += " "; + cls += tagCls; + if (rule.mode == 1 /* Inherit */) + inheritedClass += (inheritedClass ? " " : "") + tagCls; + } + this.startSpan(cursor.from, cls); + if (rule.opaque) + return; + let mounted = cursor.tree && cursor.tree.prop(NodeProp.mounted); + if (mounted && mounted.overlay) { + let inner = cursor.node.enter(mounted.overlay[0].from + start, 1); + let innerHighlighters = this.highlighters.filter(h => !h.scope || h.scope(mounted.tree.type)); + let hasChild = cursor.firstChild(); + for (let i = 0, pos = start;; i++) { + let next = i < mounted.overlay.length ? mounted.overlay[i] : null; + let nextPos = next ? next.from + start : end; + let rangeFrom = Math.max(from, pos), rangeTo = Math.min(to, nextPos); + if (rangeFrom < rangeTo && hasChild) { + while (cursor.from < rangeTo) { + this.highlightRange(cursor, rangeFrom, rangeTo, inheritedClass, highlighters); + this.startSpan(Math.min(to, cursor.to), cls); + if (cursor.to >= nextPos || !cursor.nextSibling()) + break; + } + } + if (!next || nextPos > to) + break; + pos = next.to + start; + if (pos > from) { + this.highlightRange(inner.cursor(), Math.max(from, next.from + start), Math.min(to, pos), inheritedClass, innerHighlighters); + this.startSpan(pos, cls); + } + } + if (hasChild) + cursor.parent(); + } + else if (cursor.firstChild()) { + do { + if (cursor.to <= from) + continue; + if (cursor.from >= to) + break; + this.highlightRange(cursor, from, to, inheritedClass, highlighters); + this.startSpan(Math.min(to, cursor.to), cls); + } while (cursor.nextSibling()); + cursor.parent(); + } + } + } + /// Match a syntax node's [highlight rules](#highlight.styleTags). If + /// there's a match, return its set of tags, and whether it is + /// opaque (uses a `!`) or applies to all child nodes (`/...`). + function getStyleTags(node) { + let rule = node.type.prop(ruleNodeProp); + while (rule && rule.context && !node.matchContext(rule.context)) + rule = rule.next; + return rule || null; + } + const t = Tag.define; + const comment = t(), name = t(), typeName = t(name), propertyName = t(name), literal = t(), string = t(literal), number = t(literal), content = t(), heading = t(content), keyword = t(), operator = t(), punctuation = t(), bracket = t(punctuation), meta = t(); + /// The default set of highlighting [tags](#highlight.Tag). + /// + /// This collection is heavily biased towards programming languages, + /// and necessarily incomplete. A full ontology of syntactic + /// constructs would fill a stack of books, and be impractical to + /// write themes for. So try to make do with this set. If all else + /// fails, [open an + /// issue](https://github.com/codemirror/codemirror.next) to propose a + /// new tag, or [define](#highlight.Tag^define) a local custom tag for + /// your use case. + /// + /// Note that it is not obligatory to always attach the most specific + /// tag possible to an element—if your grammar can't easily + /// distinguish a certain type of element (such as a local variable), + /// it is okay to style it as its more general variant (a variable). + /// + /// For tags that extend some parent tag, the documentation links to + /// the parent. + const tags = { + /// A comment. + comment, + /// A line [comment](#highlight.tags.comment). + lineComment: t(comment), + /// A block [comment](#highlight.tags.comment). + blockComment: t(comment), + /// A documentation [comment](#highlight.tags.comment). + docComment: t(comment), + /// Any kind of identifier. + name, + /// The [name](#highlight.tags.name) of a variable. + variableName: t(name), + /// A type [name](#highlight.tags.name). + typeName: typeName, + /// A tag name (subtag of [`typeName`](#highlight.tags.typeName)). + tagName: t(typeName), + /// A property or field [name](#highlight.tags.name). + propertyName: propertyName, + /// An attribute name (subtag of [`propertyName`](#highlight.tags.propertyName)). + attributeName: t(propertyName), + /// The [name](#highlight.tags.name) of a class. + className: t(name), + /// A label [name](#highlight.tags.name). + labelName: t(name), + /// A namespace [name](#highlight.tags.name). + namespace: t(name), + /// The [name](#highlight.tags.name) of a macro. + macroName: t(name), + /// A literal value. + literal, + /// A string [literal](#highlight.tags.literal). + string, + /// A documentation [string](#highlight.tags.string). + docString: t(string), + /// A character literal (subtag of [string](#highlight.tags.string)). + character: t(string), + /// An attribute value (subtag of [string](#highlight.tags.string)). + attributeValue: t(string), + /// A number [literal](#highlight.tags.literal). + number, + /// An integer [number](#highlight.tags.number) literal. + integer: t(number), + /// A floating-point [number](#highlight.tags.number) literal. + float: t(number), + /// A boolean [literal](#highlight.tags.literal). + bool: t(literal), + /// Regular expression [literal](#highlight.tags.literal). + regexp: t(literal), + /// An escape [literal](#highlight.tags.literal), for example a + /// backslash escape in a string. + escape: t(literal), + /// A color [literal](#highlight.tags.literal). + color: t(literal), + /// A URL [literal](#highlight.tags.literal). + url: t(literal), + /// A language keyword. + keyword, + /// The [keyword](#highlight.tags.keyword) for the self or this + /// object. + self: t(keyword), + /// The [keyword](#highlight.tags.keyword) for null. + null: t(keyword), + /// A [keyword](#highlight.tags.keyword) denoting some atomic value. + atom: t(keyword), + /// A [keyword](#highlight.tags.keyword) that represents a unit. + unit: t(keyword), + /// A modifier [keyword](#highlight.tags.keyword). + modifier: t(keyword), + /// A [keyword](#highlight.tags.keyword) that acts as an operator. + operatorKeyword: t(keyword), + /// A control-flow related [keyword](#highlight.tags.keyword). + controlKeyword: t(keyword), + /// A [keyword](#highlight.tags.keyword) that defines something. + definitionKeyword: t(keyword), + /// A [keyword](#highlight.tags.keyword) related to defining or + /// interfacing with modules. + moduleKeyword: t(keyword), + /// An operator. + operator, + /// An [operator](#highlight.tags.operator) that dereferences something. + derefOperator: t(operator), + /// Arithmetic-related [operator](#highlight.tags.operator). + arithmeticOperator: t(operator), + /// Logical [operator](#highlight.tags.operator). + logicOperator: t(operator), + /// Bit [operator](#highlight.tags.operator). + bitwiseOperator: t(operator), + /// Comparison [operator](#highlight.tags.operator). + compareOperator: t(operator), + /// [Operator](#highlight.tags.operator) that updates its operand. + updateOperator: t(operator), + /// [Operator](#highlight.tags.operator) that defines something. + definitionOperator: t(operator), + /// Type-related [operator](#highlight.tags.operator). + typeOperator: t(operator), + /// Control-flow [operator](#highlight.tags.operator). + controlOperator: t(operator), + /// Program or markup punctuation. + punctuation, + /// [Punctuation](#highlight.tags.punctuation) that separates + /// things. + separator: t(punctuation), + /// Bracket-style [punctuation](#highlight.tags.punctuation). + bracket, + /// Angle [brackets](#highlight.tags.bracket) (usually `<` and `>` + /// tokens). + angleBracket: t(bracket), + /// Square [brackets](#highlight.tags.bracket) (usually `[` and `]` + /// tokens). + squareBracket: t(bracket), + /// Parentheses (usually `(` and `)` tokens). Subtag of + /// [bracket](#highlight.tags.bracket). + paren: t(bracket), + /// Braces (usually `{` and `}` tokens). Subtag of + /// [bracket](#highlight.tags.bracket). + brace: t(bracket), + /// Content, for example plain text in XML or markup documents. + content, + /// [Content](#highlight.tags.content) that represents a heading. + heading, + /// A level 1 [heading](#highlight.tags.heading). + heading1: t(heading), + /// A level 2 [heading](#highlight.tags.heading). + heading2: t(heading), + /// A level 3 [heading](#highlight.tags.heading). + heading3: t(heading), + /// A level 4 [heading](#highlight.tags.heading). + heading4: t(heading), + /// A level 5 [heading](#highlight.tags.heading). + heading5: t(heading), + /// A level 6 [heading](#highlight.tags.heading). + heading6: t(heading), + /// A prose separator (such as a horizontal rule). + contentSeparator: t(content), + /// [Content](#highlight.tags.content) that represents a list. + list: t(content), + /// [Content](#highlight.tags.content) that represents a quote. + quote: t(content), + /// [Content](#highlight.tags.content) that is emphasized. + emphasis: t(content), + /// [Content](#highlight.tags.content) that is styled strong. + strong: t(content), + /// [Content](#highlight.tags.content) that is part of a link. + link: t(content), + /// [Content](#highlight.tags.content) that is styled as code or + /// monospace. + monospace: t(content), + /// [Content](#highlight.tags.content) that has a strike-through + /// style. + strikethrough: t(content), + /// Inserted text in a change-tracking format. + inserted: t(), + /// Deleted text. + deleted: t(), + /// Changed text. + changed: t(), + /// An invalid or unsyntactic element. + invalid: t(), + /// Metadata or meta-instruction. + meta, + /// [Metadata](#highlight.tags.meta) that applies to the entire + /// document. + documentMeta: t(meta), + /// [Metadata](#highlight.tags.meta) that annotates or adds + /// attributes to a given syntactic element. + annotation: t(meta), + /// Processing instruction or preprocessor directive. Subtag of + /// [meta](#highlight.tags.meta). + processingInstruction: t(meta), + /// [Modifier](#highlight.Tag^defineModifier) that indicates that a + /// given element is being defined. Expected to be used with the + /// various [name](#highlight.tags.name) tags. + definition: Tag.defineModifier(), + /// [Modifier](#highlight.Tag^defineModifier) that indicates that + /// something is constant. Mostly expected to be used with + /// [variable names](#highlight.tags.variableName). + constant: Tag.defineModifier(), + /// [Modifier](#highlight.Tag^defineModifier) used to indicate that + /// a [variable](#highlight.tags.variableName) or [property + /// name](#highlight.tags.propertyName) is being called or defined + /// as a function. + function: Tag.defineModifier(), + /// [Modifier](#highlight.Tag^defineModifier) that can be applied to + /// [names](#highlight.tags.name) to indicate that they belong to + /// the language's standard environment. + standard: Tag.defineModifier(), + /// [Modifier](#highlight.Tag^defineModifier) that indicates a given + /// [names](#highlight.tags.name) is local to some scope. + local: Tag.defineModifier(), + /// A generic variant [modifier](#highlight.Tag^defineModifier) that + /// can be used to tag language-specific alternative variants of + /// some common tag. It is recommended for themes to define special + /// forms of at least the [string](#highlight.tags.string) and + /// [variable name](#highlight.tags.variableName) tags, since those + /// come up a lot. + special: Tag.defineModifier() + }; + /// This is a highlighter that adds stable, predictable classes to + /// tokens, for styling with external CSS. + /// + /// The following tags are mapped to their name prefixed with `"tok-"` + /// (for example `"tok-comment"`): + /// + /// * [`link`](#highlight.tags.link) + /// * [`heading`](#highlight.tags.heading) + /// * [`emphasis`](#highlight.tags.emphasis) + /// * [`strong`](#highlight.tags.strong) + /// * [`keyword`](#highlight.tags.keyword) + /// * [`atom`](#highlight.tags.atom) + /// * [`bool`](#highlight.tags.bool) + /// * [`url`](#highlight.tags.url) + /// * [`labelName`](#highlight.tags.labelName) + /// * [`inserted`](#highlight.tags.inserted) + /// * [`deleted`](#highlight.tags.deleted) + /// * [`literal`](#highlight.tags.literal) + /// * [`string`](#highlight.tags.string) + /// * [`number`](#highlight.tags.number) + /// * [`variableName`](#highlight.tags.variableName) + /// * [`typeName`](#highlight.tags.typeName) + /// * [`namespace`](#highlight.tags.namespace) + /// * [`className`](#highlight.tags.className) + /// * [`macroName`](#highlight.tags.macroName) + /// * [`propertyName`](#highlight.tags.propertyName) + /// * [`operator`](#highlight.tags.operator) + /// * [`comment`](#highlight.tags.comment) + /// * [`meta`](#highlight.tags.meta) + /// * [`punctuation`](#highlight.tags.punctuation) + /// * [`invalid`](#highlight.tags.invalid) + /// + /// In addition, these mappings are provided: + /// + /// * [`regexp`](#highlight.tags.regexp), + /// [`escape`](#highlight.tags.escape), and + /// [`special`](#highlight.tags.special)[`(string)`](#highlight.tags.string) + /// are mapped to `"tok-string2"` + /// * [`special`](#highlight.tags.special)[`(variableName)`](#highlight.tags.variableName) + /// to `"tok-variableName2"` + /// * [`local`](#highlight.tags.local)[`(variableName)`](#highlight.tags.variableName) + /// to `"tok-variableName tok-local"` + /// * [`definition`](#highlight.tags.definition)[`(variableName)`](#highlight.tags.variableName) + /// to `"tok-variableName tok-definition"` + /// * [`definition`](#highlight.tags.definition)[`(propertyName)`](#highlight.tags.propertyName) + /// to `"tok-propertyName tok-definition"` + tagHighlighter([ + { tag: tags.link, class: "tok-link" }, + { tag: tags.heading, class: "tok-heading" }, + { tag: tags.emphasis, class: "tok-emphasis" }, + { tag: tags.strong, class: "tok-strong" }, + { tag: tags.keyword, class: "tok-keyword" }, + { tag: tags.atom, class: "tok-atom" }, + { tag: tags.bool, class: "tok-bool" }, + { tag: tags.url, class: "tok-url" }, + { tag: tags.labelName, class: "tok-labelName" }, + { tag: tags.inserted, class: "tok-inserted" }, + { tag: tags.deleted, class: "tok-deleted" }, + { tag: tags.literal, class: "tok-literal" }, + { tag: tags.string, class: "tok-string" }, + { tag: tags.number, class: "tok-number" }, + { tag: [tags.regexp, tags.escape, tags.special(tags.string)], class: "tok-string2" }, + { tag: tags.variableName, class: "tok-variableName" }, + { tag: tags.local(tags.variableName), class: "tok-variableName tok-local" }, + { tag: tags.definition(tags.variableName), class: "tok-variableName tok-definition" }, + { tag: tags.special(tags.variableName), class: "tok-variableName2" }, + { tag: tags.definition(tags.propertyName), class: "tok-propertyName tok-definition" }, + { tag: tags.typeName, class: "tok-typeName" }, + { tag: tags.namespace, class: "tok-namespace" }, + { tag: tags.className, class: "tok-className" }, + { tag: tags.macroName, class: "tok-macroName" }, + { tag: tags.propertyName, class: "tok-propertyName" }, + { tag: tags.operator, class: "tok-operator" }, + { tag: tags.comment, class: "tok-comment" }, + { tag: tags.meta, class: "tok-meta" }, + { tag: tags.invalid, class: "tok-invalid" }, + { tag: tags.punctuation, class: "tok-punctuation" } + ]); + + var _a; + /** + Node prop stored in a parser's top syntax node to provide the + facet that stores language-specific data for that language. + */ + const languageDataProp = /*@__PURE__*/new NodeProp(); + /** + Helper function to define a facet (to be added to the top syntax + node(s) for a language via + [`languageDataProp`](https://codemirror.net/6/docs/ref/#language.languageDataProp)), that will be + used to associate language data with the language. You + probably only need this when subclassing + [`Language`](https://codemirror.net/6/docs/ref/#language.Language). + */ + function defineLanguageFacet(baseData) { + return Facet.define({ + combine: baseData ? values => values.concat(baseData) : undefined + }); + } + /** + A language object manages parsing and per-language + [metadata](https://codemirror.net/6/docs/ref/#state.EditorState.languageDataAt). Parse data is + managed as a [Lezer](https://lezer.codemirror.net) tree. The class + can be used directly, via the [`LRLanguage`](https://codemirror.net/6/docs/ref/#language.LRLanguage) + subclass for [Lezer](https://lezer.codemirror.net/) LR parsers, or + via the [`StreamLanguage`](https://codemirror.net/6/docs/ref/#language.StreamLanguage) subclass + for stream parsers. + */ + class Language { + /** + Construct a language object. If you need to invoke this + directly, first define a data facet with + [`defineLanguageFacet`](https://codemirror.net/6/docs/ref/#language.defineLanguageFacet), and then + configure your parser to [attach](https://codemirror.net/6/docs/ref/#language.languageDataProp) it + to the language's outer syntax node. + */ + constructor( + /** + The [language data](https://codemirror.net/6/docs/ref/#state.EditorState.languageDataAt) facet + used for this language. + */ + data, parser, extraExtensions = []) { + this.data = data; + // Kludge to define EditorState.tree as a debugging helper, + // without the EditorState package actually knowing about + // languages and lezer trees. + if (!EditorState.prototype.hasOwnProperty("tree")) + Object.defineProperty(EditorState.prototype, "tree", { get() { return syntaxTree(this); } }); + this.parser = parser; + this.extension = [ + language.of(this), + EditorState.languageData.of((state, pos, side) => state.facet(languageDataFacetAt(state, pos, side))) + ].concat(extraExtensions); + } + /** + Query whether this language is active at the given position. + */ + isActiveAt(state, pos, side = -1) { + return languageDataFacetAt(state, pos, side) == this.data; + } + /** + Find the document regions that were parsed using this language. + The returned regions will _include_ any nested languages rooted + in this language, when those exist. + */ + findRegions(state) { + let lang = state.facet(language); + if ((lang === null || lang === void 0 ? void 0 : lang.data) == this.data) + return [{ from: 0, to: state.doc.length }]; + if (!lang || !lang.allowsNesting) + return []; + let result = []; + let explore = (tree, from) => { + if (tree.prop(languageDataProp) == this.data) { + result.push({ from, to: from + tree.length }); + return; + } + let mount = tree.prop(NodeProp.mounted); + if (mount) { + if (mount.tree.prop(languageDataProp) == this.data) { + if (mount.overlay) + for (let r of mount.overlay) + result.push({ from: r.from + from, to: r.to + from }); + else + result.push({ from: from, to: from + tree.length }); + return; + } + else if (mount.overlay) { + let size = result.length; + explore(mount.tree, mount.overlay[0].from + from); + if (result.length > size) + return; + } + } + for (let i = 0; i < tree.children.length; i++) { + let ch = tree.children[i]; + if (ch instanceof Tree) + explore(ch, tree.positions[i] + from); + } + }; + explore(syntaxTree(state), 0); + return result; + } + /** + Indicates whether this language allows nested languages. The + default implementation returns true. + */ + get allowsNesting() { return true; } + } + /** + @internal + */ + Language.setState = /*@__PURE__*/StateEffect.define(); + function languageDataFacetAt(state, pos, side) { + let topLang = state.facet(language); + if (!topLang) + return null; + let facet = topLang.data; + if (topLang.allowsNesting) { + for (let node = syntaxTree(state).topNode; node; node = node.enter(pos, side, IterMode.ExcludeBuffers)) + facet = node.type.prop(languageDataProp) || facet; + } + return facet; + } + /** + A subclass of [`Language`](https://codemirror.net/6/docs/ref/#language.Language) for use with Lezer + [LR parsers](https://lezer.codemirror.net/docs/ref#lr.LRParser) + parsers. + */ + class LRLanguage extends Language { + constructor(data, parser) { + super(data, parser); + this.parser = parser; + } + /** + Define a language from a parser. + */ + static define(spec) { + let data = defineLanguageFacet(spec.languageData); + return new LRLanguage(data, spec.parser.configure({ + props: [languageDataProp.add(type => type.isTop ? data : undefined)] + })); + } + /** + Create a new instance of this language with a reconfigured + version of its parser. + */ + configure(options) { + return new LRLanguage(this.data, this.parser.configure(options)); + } + get allowsNesting() { return this.parser.hasWrappers(); } + } + /** + Get the syntax tree for a state, which is the current (possibly + incomplete) parse tree of the active + [language](https://codemirror.net/6/docs/ref/#language.Language), or the empty tree if there is no + language available. + */ + function syntaxTree(state) { + let field = state.field(Language.state, false); + return field ? field.tree : Tree.empty; + } + // Lezer-style Input object for a Text document. + class DocInput { + constructor(doc, length = doc.length) { + this.doc = doc; + this.length = length; + this.cursorPos = 0; + this.string = ""; + this.cursor = doc.iter(); + } + syncTo(pos) { + this.string = this.cursor.next(pos - this.cursorPos).value; + this.cursorPos = pos + this.string.length; + return this.cursorPos - this.string.length; + } + chunk(pos) { + this.syncTo(pos); + return this.string; + } + get lineChunks() { return true; } + read(from, to) { + let stringStart = this.cursorPos - this.string.length; + if (from < stringStart || to >= this.cursorPos) + return this.doc.sliceString(from, to); + else + return this.string.slice(from - stringStart, to - stringStart); + } + } + let currentContext = null; + /** + A parse context provided to parsers working on the editor content. + */ + class ParseContext { + constructor(parser, + /** + The current editor state. + */ + state, + /** + Tree fragments that can be reused by incremental re-parses. + */ + fragments = [], + /** + @internal + */ + tree, + /** + @internal + */ + treeLen, + /** + The current editor viewport (or some overapproximation + thereof). Intended to be used for opportunistically avoiding + work (in which case + [`skipUntilInView`](https://codemirror.net/6/docs/ref/#language.ParseContext.skipUntilInView) + should be called to make sure the parser is restarted when the + skipped region becomes visible). + */ + viewport, + /** + @internal + */ + skipped, + /** + This is where skipping parsers can register a promise that, + when resolved, will schedule a new parse. It is cleared when + the parse worker picks up the promise. @internal + */ + scheduleOn) { + this.parser = parser; + this.state = state; + this.fragments = fragments; + this.tree = tree; + this.treeLen = treeLen; + this.viewport = viewport; + this.skipped = skipped; + this.scheduleOn = scheduleOn; + this.parse = null; + /** + @internal + */ + this.tempSkipped = []; + } + /** + @internal + */ + static create(parser, state, viewport) { + return new ParseContext(parser, state, [], Tree.empty, 0, viewport, [], null); + } + startParse() { + return this.parser.startParse(new DocInput(this.state.doc), this.fragments); + } + /** + @internal + */ + work(until, upto) { + if (upto != null && upto >= this.state.doc.length) + upto = undefined; + if (this.tree != Tree.empty && this.isDone(upto !== null && upto !== void 0 ? upto : this.state.doc.length)) { + this.takeTree(); + return true; + } + return this.withContext(() => { + var _a; + if (typeof until == "number") { + let endTime = Date.now() + until; + until = () => Date.now() > endTime; + } + if (!this.parse) + this.parse = this.startParse(); + if (upto != null && (this.parse.stoppedAt == null || this.parse.stoppedAt > upto) && + upto < this.state.doc.length) + this.parse.stopAt(upto); + for (;;) { + let done = this.parse.advance(); + if (done) { + this.fragments = this.withoutTempSkipped(TreeFragment.addTree(done, this.fragments, this.parse.stoppedAt != null)); + this.treeLen = (_a = this.parse.stoppedAt) !== null && _a !== void 0 ? _a : this.state.doc.length; + this.tree = done; + this.parse = null; + if (this.treeLen < (upto !== null && upto !== void 0 ? upto : this.state.doc.length)) + this.parse = this.startParse(); + else + return true; + } + if (until()) + return false; + } + }); + } + /** + @internal + */ + takeTree() { + let pos, tree; + if (this.parse && (pos = this.parse.parsedPos) >= this.treeLen) { + if (this.parse.stoppedAt == null || this.parse.stoppedAt > pos) + this.parse.stopAt(pos); + this.withContext(() => { while (!(tree = this.parse.advance())) { } }); + this.treeLen = pos; + this.tree = tree; + this.fragments = this.withoutTempSkipped(TreeFragment.addTree(this.tree, this.fragments, true)); + this.parse = null; + } + } + withContext(f) { + let prev = currentContext; + currentContext = this; + try { + return f(); + } + finally { + currentContext = prev; + } + } + withoutTempSkipped(fragments) { + for (let r; r = this.tempSkipped.pop();) + fragments = cutFragments(fragments, r.from, r.to); + return fragments; + } + /** + @internal + */ + changes(changes, newState) { + let { fragments, tree, treeLen, viewport, skipped } = this; + this.takeTree(); + if (!changes.empty) { + let ranges = []; + changes.iterChangedRanges((fromA, toA, fromB, toB) => ranges.push({ fromA, toA, fromB, toB })); + fragments = TreeFragment.applyChanges(fragments, ranges); + tree = Tree.empty; + treeLen = 0; + viewport = { from: changes.mapPos(viewport.from, -1), to: changes.mapPos(viewport.to, 1) }; + if (this.skipped.length) { + skipped = []; + for (let r of this.skipped) { + let from = changes.mapPos(r.from, 1), to = changes.mapPos(r.to, -1); + if (from < to) + skipped.push({ from, to }); + } + } + } + return new ParseContext(this.parser, newState, fragments, tree, treeLen, viewport, skipped, this.scheduleOn); + } + /** + @internal + */ + updateViewport(viewport) { + if (this.viewport.from == viewport.from && this.viewport.to == viewport.to) + return false; + this.viewport = viewport; + let startLen = this.skipped.length; + for (let i = 0; i < this.skipped.length; i++) { + let { from, to } = this.skipped[i]; + if (from < viewport.to && to > viewport.from) { + this.fragments = cutFragments(this.fragments, from, to); + this.skipped.splice(i--, 1); + } + } + if (this.skipped.length >= startLen) + return false; + this.reset(); + return true; + } + /** + @internal + */ + reset() { + if (this.parse) { + this.takeTree(); + this.parse = null; + } + } + /** + Notify the parse scheduler that the given region was skipped + because it wasn't in view, and the parse should be restarted + when it comes into view. + */ + skipUntilInView(from, to) { + this.skipped.push({ from, to }); + } + /** + Returns a parser intended to be used as placeholder when + asynchronously loading a nested parser. It'll skip its input and + mark it as not-really-parsed, so that the next update will parse + it again. + + When `until` is given, a reparse will be scheduled when that + promise resolves. + */ + static getSkippingParser(until) { + return new class extends Parser { + createParse(input, fragments, ranges) { + let from = ranges[0].from, to = ranges[ranges.length - 1].to; + let parser = { + parsedPos: from, + advance() { + let cx = currentContext; + if (cx) { + for (let r of ranges) + cx.tempSkipped.push(r); + if (until) + cx.scheduleOn = cx.scheduleOn ? Promise.all([cx.scheduleOn, until]) : until; + } + this.parsedPos = to; + return new Tree(NodeType.none, [], [], to - from); + }, + stoppedAt: null, + stopAt() { } + }; + return parser; + } + }; + } + /** + @internal + */ + isDone(upto) { + upto = Math.min(upto, this.state.doc.length); + let frags = this.fragments; + return this.treeLen >= upto && frags.length && frags[0].from == 0 && frags[0].to >= upto; + } + /** + Get the context for the current parse, or `null` if no editor + parse is in progress. + */ + static get() { return currentContext; } + } + function cutFragments(fragments, from, to) { + return TreeFragment.applyChanges(fragments, [{ fromA: from, toA: to, fromB: from, toB: to }]); + } + class LanguageState { + constructor( + // A mutable parse state that is used to preserve work done during + // the lifetime of a state when moving to the next state. + context) { + this.context = context; + this.tree = context.tree; + } + apply(tr) { + if (!tr.docChanged && this.tree == this.context.tree) + return this; + let newCx = this.context.changes(tr.changes, tr.state); + // If the previous parse wasn't done, go forward only up to its + // end position or the end of the viewport, to avoid slowing down + // state updates with parse work beyond the viewport. + let upto = this.context.treeLen == tr.startState.doc.length ? undefined + : Math.max(tr.changes.mapPos(this.context.treeLen), newCx.viewport.to); + if (!newCx.work(20 /* Apply */, upto)) + newCx.takeTree(); + return new LanguageState(newCx); + } + static init(state) { + let vpTo = Math.min(3000 /* InitViewport */, state.doc.length); + let parseState = ParseContext.create(state.facet(language).parser, state, { from: 0, to: vpTo }); + if (!parseState.work(20 /* Apply */, vpTo)) + parseState.takeTree(); + return new LanguageState(parseState); + } + } + Language.state = /*@__PURE__*/StateField.define({ + create: LanguageState.init, + update(value, tr) { + for (let e of tr.effects) + if (e.is(Language.setState)) + return e.value; + if (tr.startState.facet(language) != tr.state.facet(language)) + return LanguageState.init(tr.state); + return value.apply(tr); + } + }); + let requestIdle = (callback) => { + let timeout = setTimeout(() => callback(), 500 /* MaxPause */); + return () => clearTimeout(timeout); + }; + if (typeof requestIdleCallback != "undefined") + requestIdle = (callback) => { + let idle = -1, timeout = setTimeout(() => { + idle = requestIdleCallback(callback, { timeout: 500 /* MaxPause */ - 100 /* MinPause */ }); + }, 100 /* MinPause */); + return () => idle < 0 ? clearTimeout(timeout) : cancelIdleCallback(idle); + }; + const isInputPending = typeof navigator != "undefined" && ((_a = navigator.scheduling) === null || _a === void 0 ? void 0 : _a.isInputPending) + ? () => navigator.scheduling.isInputPending() : null; + const parseWorker = /*@__PURE__*/ViewPlugin.fromClass(class ParseWorker { + constructor(view) { + this.view = view; + this.working = null; + this.workScheduled = 0; + // End of the current time chunk + this.chunkEnd = -1; + // Milliseconds of budget left for this chunk + this.chunkBudget = -1; + this.work = this.work.bind(this); + this.scheduleWork(); + } + update(update) { + let cx = this.view.state.field(Language.state).context; + if (cx.updateViewport(update.view.viewport) || this.view.viewport.to > cx.treeLen) + this.scheduleWork(); + if (update.docChanged) { + if (this.view.hasFocus) + this.chunkBudget += 50 /* ChangeBonus */; + this.scheduleWork(); + } + this.checkAsyncSchedule(cx); + } + scheduleWork() { + if (this.working) + return; + let { state } = this.view, field = state.field(Language.state); + if (field.tree != field.context.tree || !field.context.isDone(state.doc.length)) + this.working = requestIdle(this.work); + } + work(deadline) { + this.working = null; + let now = Date.now(); + if (this.chunkEnd < now && (this.chunkEnd < 0 || this.view.hasFocus)) { // Start a new chunk + this.chunkEnd = now + 30000 /* ChunkTime */; + this.chunkBudget = 3000 /* ChunkBudget */; + } + if (this.chunkBudget <= 0) + return; // No more budget + let { state, viewport: { to: vpTo } } = this.view, field = state.field(Language.state); + if (field.tree == field.context.tree && field.context.isDone(vpTo + 100000 /* MaxParseAhead */)) + return; + let endTime = Date.now() + Math.min(this.chunkBudget, 100 /* Slice */, deadline && !isInputPending ? Math.max(25 /* MinSlice */, deadline.timeRemaining() - 5) : 1e9); + let viewportFirst = field.context.treeLen < vpTo && state.doc.length > vpTo + 1000; + let done = field.context.work(() => { + return isInputPending && isInputPending() || Date.now() > endTime; + }, vpTo + (viewportFirst ? 0 : 100000 /* MaxParseAhead */)); + this.chunkBudget -= Date.now() - now; + if (done || this.chunkBudget <= 0) { + field.context.takeTree(); + this.view.dispatch({ effects: Language.setState.of(new LanguageState(field.context)) }); + } + if (this.chunkBudget > 0 && !(done && !viewportFirst)) + this.scheduleWork(); + this.checkAsyncSchedule(field.context); + } + checkAsyncSchedule(cx) { + if (cx.scheduleOn) { + this.workScheduled++; + cx.scheduleOn + .then(() => this.scheduleWork()) + .catch(err => logException(this.view.state, err)) + .then(() => this.workScheduled--); + cx.scheduleOn = null; + } + } + destroy() { + if (this.working) + this.working(); + } + isWorking() { + return !!(this.working || this.workScheduled > 0); + } + }, { + eventHandlers: { focus() { this.scheduleWork(); } } + }); + /** + The facet used to associate a language with an editor state. Used + by `Language` object's `extension` property (so you don't need to + manually wrap your languages in this). Can be used to access the + current language on a state. + */ + const language = /*@__PURE__*/Facet.define({ + combine(languages) { return languages.length ? languages[0] : null; }, + enables: [Language.state, parseWorker] + }); + /** + This class bundles a [language](https://codemirror.net/6/docs/ref/#language.Language) with an + optional set of supporting extensions. Language packages are + encouraged to export a function that optionally takes a + configuration object and returns a `LanguageSupport` instance, as + the main way for client code to use the package. + */ + class LanguageSupport { + /** + Create a language support object. + */ + constructor( + /** + The language object. + */ + language, + /** + An optional set of supporting extensions. When nesting a + language in another language, the outer language is encouraged + to include the supporting extensions for its inner languages + in its own set of support extensions. + */ + support = []) { + this.language = language; + this.support = support; + this.extension = [language, support]; + } + } + + /** + Facet that defines a way to provide a function that computes the + appropriate indentation depth at the start of a given line, or + `null` to indicate no appropriate indentation could be determined. + */ + const indentService = /*@__PURE__*/Facet.define(); + /** + Facet for overriding the unit by which indentation happens. + Should be a string consisting either entirely of spaces or + entirely of tabs. When not set, this defaults to 2 spaces. + */ + const indentUnit = /*@__PURE__*/Facet.define({ + combine: values => { + if (!values.length) + return " "; + if (!/^(?: +|\t+)$/.test(values[0])) + throw new Error("Invalid indent unit: " + JSON.stringify(values[0])); + return values[0]; + } + }); + /** + Return the _column width_ of an indent unit in the state. + Determined by the [`indentUnit`](https://codemirror.net/6/docs/ref/#language.indentUnit) + facet, and [`tabSize`](https://codemirror.net/6/docs/ref/#state.EditorState^tabSize) when that + contains tabs. + */ + function getIndentUnit(state) { + let unit = state.facet(indentUnit); + return unit.charCodeAt(0) == 9 ? state.tabSize * unit.length : unit.length; + } + /** + Create an indentation string that covers columns 0 to `cols`. + Will use tabs for as much of the columns as possible when the + [`indentUnit`](https://codemirror.net/6/docs/ref/#language.indentUnit) facet contains + tabs. + */ + function indentString(state, cols) { + let result = "", ts = state.tabSize; + if (state.facet(indentUnit).charCodeAt(0) == 9) + while (cols >= ts) { + result += "\t"; + cols -= ts; + } + for (let i = 0; i < cols; i++) + result += " "; + return result; + } + /** + Get the indentation at the given position. Will first consult any + [indent services](https://codemirror.net/6/docs/ref/#language.indentService) that are registered, + and if none of those return an indentation, this will check the + syntax tree for the [indent node prop](https://codemirror.net/6/docs/ref/#language.indentNodeProp) + and use that if found. Returns a number when an indentation could + be determined, and null otherwise. + */ + function getIndentation(context, pos) { + if (context instanceof EditorState) + context = new IndentContext(context); + for (let service of context.state.facet(indentService)) { + let result = service(context, pos); + if (result != null) + return result; + } + let tree = syntaxTree(context.state); + return tree ? syntaxIndentation(context, tree, pos) : null; + } + /** + Indentation contexts are used when calling [indentation + services](https://codemirror.net/6/docs/ref/#language.indentService). They provide helper utilities + useful in indentation logic, and can selectively override the + indentation reported for some lines. + */ + class IndentContext { + /** + Create an indent context. + */ + constructor( + /** + The editor state. + */ + state, + /** + @internal + */ + options = {}) { + this.state = state; + this.options = options; + this.unit = getIndentUnit(state); + } + /** + Get a description of the line at the given position, taking + [simulated line + breaks](https://codemirror.net/6/docs/ref/#language.IndentContext.constructor^options.simulateBreak) + into account. If there is such a break at `pos`, the `bias` + argument determines whether the part of the line line before or + after the break is used. + */ + lineAt(pos, bias = 1) { + let line = this.state.doc.lineAt(pos); + let { simulateBreak, simulateDoubleBreak } = this.options; + if (simulateBreak != null && simulateBreak >= line.from && simulateBreak <= line.to) { + if (simulateDoubleBreak && simulateBreak == pos) + return { text: "", from: pos }; + else if (bias < 0 ? simulateBreak < pos : simulateBreak <= pos) + return { text: line.text.slice(simulateBreak - line.from), from: simulateBreak }; + else + return { text: line.text.slice(0, simulateBreak - line.from), from: line.from }; + } + return line; + } + /** + Get the text directly after `pos`, either the entire line + or the next 100 characters, whichever is shorter. + */ + textAfterPos(pos, bias = 1) { + if (this.options.simulateDoubleBreak && pos == this.options.simulateBreak) + return ""; + let { text, from } = this.lineAt(pos, bias); + return text.slice(pos - from, Math.min(text.length, pos + 100 - from)); + } + /** + Find the column for the given position. + */ + column(pos, bias = 1) { + let { text, from } = this.lineAt(pos, bias); + let result = this.countColumn(text, pos - from); + let override = this.options.overrideIndentation ? this.options.overrideIndentation(from) : -1; + if (override > -1) + result += override - this.countColumn(text, text.search(/\S|$/)); + return result; + } + /** + Find the column position (taking tabs into account) of the given + position in the given string. + */ + countColumn(line, pos = line.length) { + return countColumn(line, this.state.tabSize, pos); + } + /** + Find the indentation column of the line at the given point. + */ + lineIndent(pos, bias = 1) { + let { text, from } = this.lineAt(pos, bias); + let override = this.options.overrideIndentation; + if (override) { + let overriden = override(from); + if (overriden > -1) + return overriden; + } + return this.countColumn(text, text.search(/\S|$/)); + } + /** + Returns the [simulated line + break](https://codemirror.net/6/docs/ref/#language.IndentContext.constructor^options.simulateBreak) + for this context, if any. + */ + get simulatedBreak() { + return this.options.simulateBreak || null; + } + } + /** + A syntax tree node prop used to associate indentation strategies + with node types. Such a strategy is a function from an indentation + context to a column number or null, where null indicates that no + definitive indentation can be determined. + */ + const indentNodeProp = /*@__PURE__*/new NodeProp(); + // Compute the indentation for a given position from the syntax tree. + function syntaxIndentation(cx, ast, pos) { + return indentFrom(ast.resolveInner(pos).enterUnfinishedNodesBefore(pos), pos, cx); + } + function ignoreClosed(cx) { + return cx.pos == cx.options.simulateBreak && cx.options.simulateDoubleBreak; + } + function indentStrategy(tree) { + let strategy = tree.type.prop(indentNodeProp); + if (strategy) + return strategy; + let first = tree.firstChild, close; + if (first && (close = first.type.prop(NodeProp.closedBy))) { + let last = tree.lastChild, closed = last && close.indexOf(last.name) > -1; + return cx => delimitedStrategy(cx, true, 1, undefined, closed && !ignoreClosed(cx) ? last.from : undefined); + } + return tree.parent == null ? topIndent$1 : null; + } + function indentFrom(node, pos, base) { + for (; node; node = node.parent) { + let strategy = indentStrategy(node); + if (strategy) + return strategy(TreeIndentContext.create(base, pos, node)); + } + return null; + } + function topIndent$1() { return 0; } + /** + Objects of this type provide context information and helper + methods to indentation functions registered on syntax nodes. + */ + class TreeIndentContext extends IndentContext { + constructor(base, + /** + The position at which indentation is being computed. + */ + pos, + /** + The syntax tree node to which the indentation strategy + applies. + */ + node) { + super(base.state, base.options); + this.base = base; + this.pos = pos; + this.node = node; + } + /** + @internal + */ + static create(base, pos, node) { + return new TreeIndentContext(base, pos, node); + } + /** + Get the text directly after `this.pos`, either the entire line + or the next 100 characters, whichever is shorter. + */ + get textAfter() { + return this.textAfterPos(this.pos); + } + /** + Get the indentation at the reference line for `this.node`, which + is the line on which it starts, unless there is a node that is + _not_ a parent of this node covering the start of that line. If + so, the line at the start of that node is tried, again skipping + on if it is covered by another such node. + */ + get baseIndent() { + let line = this.state.doc.lineAt(this.node.from); + // Skip line starts that are covered by a sibling (or cousin, etc) + for (;;) { + let atBreak = this.node.resolve(line.from); + while (atBreak.parent && atBreak.parent.from == atBreak.from) + atBreak = atBreak.parent; + if (isParent(atBreak, this.node)) + break; + line = this.state.doc.lineAt(atBreak.from); + } + return this.lineIndent(line.from); + } + /** + Continue looking for indentations in the node's parent nodes, + and return the result of that. + */ + continue() { + let parent = this.node.parent; + return parent ? indentFrom(parent, this.pos, this.base) : 0; + } + } + function isParent(parent, of) { + for (let cur = of; cur; cur = cur.parent) + if (parent == cur) + return true; + return false; + } + // Check whether a delimited node is aligned (meaning there are + // non-skipped nodes on the same line as the opening delimiter). And + // if so, return the opening token. + function bracketedAligned(context) { + let tree = context.node; + let openToken = tree.childAfter(tree.from), last = tree.lastChild; + if (!openToken) + return null; + let sim = context.options.simulateBreak; + let openLine = context.state.doc.lineAt(openToken.from); + let lineEnd = sim == null || sim <= openLine.from ? openLine.to : Math.min(openLine.to, sim); + for (let pos = openToken.to;;) { + let next = tree.childAfter(pos); + if (!next || next == last) + return null; + if (!next.type.isSkipped) + return next.from < lineEnd ? openToken : null; + pos = next.to; + } + } + /** + An indentation strategy for delimited (usually bracketed) nodes. + Will, by default, indent one unit more than the parent's base + indent unless the line starts with a closing token. When `align` + is true and there are non-skipped nodes on the node's opening + line, the content of the node will be aligned with the end of the + opening node, like this: + + foo(bar, + baz) + */ + function delimitedIndent({ closing, align = true, units = 1 }) { + return (context) => delimitedStrategy(context, align, units, closing); + } + function delimitedStrategy(context, align, units, closing, closedAt) { + let after = context.textAfter, space = after.match(/^\s*/)[0].length; + let closed = closing && after.slice(space, space + closing.length) == closing || closedAt == context.pos + space; + let aligned = align ? bracketedAligned(context) : null; + if (aligned) + return closed ? context.column(aligned.from) : context.column(aligned.to); + return context.baseIndent + (closed ? 0 : context.unit * units); + } + const DontIndentBeyond = 200; + /** + Enables reindentation on input. When a language defines an + `indentOnInput` field in its [language + data](https://codemirror.net/6/docs/ref/#state.EditorState.languageDataAt), which must hold a regular + expression, the line at the cursor will be reindented whenever new + text is typed and the input from the start of the line up to the + cursor matches that regexp. + + To avoid unneccesary reindents, it is recommended to start the + regexp with `^` (usually followed by `\s*`), and end it with `$`. + For example, `/^\s*\}$/` will reindent when a closing brace is + added at the start of a line. + */ + function indentOnInput() { + return EditorState.transactionFilter.of(tr => { + if (!tr.docChanged || !tr.isUserEvent("input.type") && !tr.isUserEvent("input.complete")) + return tr; + let rules = tr.startState.languageDataAt("indentOnInput", tr.startState.selection.main.head); + if (!rules.length) + return tr; + let doc = tr.newDoc, { head } = tr.newSelection.main, line = doc.lineAt(head); + if (head > line.from + DontIndentBeyond) + return tr; + let lineStart = doc.sliceString(line.from, head); + if (!rules.some(r => r.test(lineStart))) + return tr; + let { state } = tr, last = -1, changes = []; + for (let { head } of state.selection.ranges) { + let line = state.doc.lineAt(head); + if (line.from == last) + continue; + last = line.from; + let indent = getIndentation(state, line.from); + if (indent == null) + continue; + let cur = /^\s*/.exec(line.text)[0]; + let norm = indentString(state, indent); + if (cur != norm) + changes.push({ from: line.from, to: line.from + cur.length, insert: norm }); + } + return changes.length ? [tr, { changes, sequential: true }] : tr; + }); + } + + /** + A facet that registers a code folding service. When called with + the extent of a line, such a function should return a foldable + range that starts on that line (but continues beyond it), if one + can be found. + */ + const foldService = /*@__PURE__*/Facet.define(); + /** + This node prop is used to associate folding information with + syntax node types. Given a syntax node, it should check whether + that tree is foldable and return the range that can be collapsed + when it is. + */ + const foldNodeProp = /*@__PURE__*/new NodeProp(); + /** + [Fold](https://codemirror.net/6/docs/ref/#language.foldNodeProp) function that folds everything but + the first and the last child of a syntax node. Useful for nodes + that start and end with delimiters. + */ + function foldInside(node) { + let first = node.firstChild, last = node.lastChild; + return first && first.to < last.from ? { from: first.to, to: last.type.isError ? node.to : last.from } : null; + } + function syntaxFolding(state, start, end) { + let tree = syntaxTree(state); + if (tree.length < end) + return null; + let inner = tree.resolveInner(end); + let found = null; + for (let cur = inner; cur; cur = cur.parent) { + if (cur.to <= end || cur.from > end) + continue; + if (found && cur.from < start) + break; + let prop = cur.type.prop(foldNodeProp); + if (prop && (cur.to < tree.length - 50 || tree.length == state.doc.length || !isUnfinished(cur))) { + let value = prop(cur, state); + if (value && value.from <= end && value.from >= start && value.to > end) + found = value; + } + } + return found; + } + function isUnfinished(node) { + let ch = node.lastChild; + return ch && ch.to == node.to && ch.type.isError; + } + /** + Check whether the given line is foldable. First asks any fold + services registered through + [`foldService`](https://codemirror.net/6/docs/ref/#language.foldService), and if none of them return + a result, tries to query the [fold node + prop](https://codemirror.net/6/docs/ref/#language.foldNodeProp) of syntax nodes that cover the end + of the line. + */ + function foldable(state, lineStart, lineEnd) { + for (let service of state.facet(foldService)) { + let result = service(state, lineStart, lineEnd); + if (result) + return result; + } + return syntaxFolding(state, lineStart, lineEnd); + } + function mapRange(range, mapping) { + let from = mapping.mapPos(range.from, 1), to = mapping.mapPos(range.to, -1); + return from >= to ? undefined : { from, to }; + } + /** + State effect that can be attached to a transaction to fold the + given range. (You probably only need this in exceptional + circumstances—usually you'll just want to let + [`foldCode`](https://codemirror.net/6/docs/ref/#language.foldCode) and the [fold + gutter](https://codemirror.net/6/docs/ref/#language.foldGutter) create the transactions.) + */ + const foldEffect = /*@__PURE__*/StateEffect.define({ map: mapRange }); + /** + State effect that unfolds the given range (if it was folded). + */ + const unfoldEffect = /*@__PURE__*/StateEffect.define({ map: mapRange }); + function selectedLines(view) { + let lines = []; + for (let { head } of view.state.selection.ranges) { + if (lines.some(l => l.from <= head && l.to >= head)) + continue; + lines.push(view.lineBlockAt(head)); + } + return lines; + } + /** + The state field that stores the folded ranges (as a [decoration + set](https://codemirror.net/6/docs/ref/#view.DecorationSet)). Can be passed to + [`EditorState.toJSON`](https://codemirror.net/6/docs/ref/#state.EditorState.toJSON) and + [`fromJSON`](https://codemirror.net/6/docs/ref/#state.EditorState^fromJSON) to serialize the fold + state. + */ + const foldState = /*@__PURE__*/StateField.define({ + create() { + return Decoration.none; + }, + update(folded, tr) { + folded = folded.map(tr.changes); + for (let e of tr.effects) { + if (e.is(foldEffect) && !foldExists(folded, e.value.from, e.value.to)) + folded = folded.update({ add: [foldWidget.range(e.value.from, e.value.to)] }); + else if (e.is(unfoldEffect)) + folded = folded.update({ filter: (from, to) => e.value.from != from || e.value.to != to, + filterFrom: e.value.from, filterTo: e.value.to }); + } + // Clear folded ranges that cover the selection head + if (tr.selection) { + let onSelection = false, { head } = tr.selection.main; + folded.between(head, head, (a, b) => { if (a < head && b > head) + onSelection = true; }); + if (onSelection) + folded = folded.update({ + filterFrom: head, + filterTo: head, + filter: (a, b) => b <= head || a >= head + }); + } + return folded; + }, + provide: f => EditorView.decorations.from(f), + toJSON(folded, state) { + let ranges = []; + folded.between(0, state.doc.length, (from, to) => { ranges.push(from, to); }); + return ranges; + }, + fromJSON(value) { + if (!Array.isArray(value) || value.length % 2) + throw new RangeError("Invalid JSON for fold state"); + let ranges = []; + for (let i = 0; i < value.length;) { + let from = value[i++], to = value[i++]; + if (typeof from != "number" || typeof to != "number") + throw new RangeError("Invalid JSON for fold state"); + ranges.push(foldWidget.range(from, to)); + } + return Decoration.set(ranges, true); + } + }); + function findFold(state, from, to) { + var _a; + let found = null; + (_a = state.field(foldState, false)) === null || _a === void 0 ? void 0 : _a.between(from, to, (from, to) => { + if (!found || found.from > from) + found = { from, to }; + }); + return found; + } + function foldExists(folded, from, to) { + let found = false; + folded.between(from, from, (a, b) => { if (a == from && b == to) + found = true; }); + return found; + } + function maybeEnable(state, other) { + return state.field(foldState, false) ? other : other.concat(StateEffect.appendConfig.of(codeFolding())); + } + /** + Fold the lines that are selected, if possible. + */ + const foldCode = view => { + for (let line of selectedLines(view)) { + let range = foldable(view.state, line.from, line.to); + if (range) { + view.dispatch({ effects: maybeEnable(view.state, [foldEffect.of(range), announceFold(view, range)]) }); + return true; + } + } + return false; + }; + /** + Unfold folded ranges on selected lines. + */ + const unfoldCode = view => { + if (!view.state.field(foldState, false)) + return false; + let effects = []; + for (let line of selectedLines(view)) { + let folded = findFold(view.state, line.from, line.to); + if (folded) + effects.push(unfoldEffect.of(folded), announceFold(view, folded, false)); + } + if (effects.length) + view.dispatch({ effects }); + return effects.length > 0; + }; + function announceFold(view, range, fold = true) { + let lineFrom = view.state.doc.lineAt(range.from).number, lineTo = view.state.doc.lineAt(range.to).number; + return EditorView.announce.of(`${view.state.phrase(fold ? "Folded lines" : "Unfolded lines")} ${lineFrom} ${view.state.phrase("to")} ${lineTo}.`); + } + /** + Fold all top-level foldable ranges. Note that, in most cases, + folding information will depend on the [syntax + tree](https://codemirror.net/6/docs/ref/#language.syntaxTree), and folding everything may not work + reliably when the document hasn't been fully parsed (either + because the editor state was only just initialized, or because the + document is so big that the parser decided not to parse it + entirely). + */ + const foldAll = view => { + let { state } = view, effects = []; + for (let pos = 0; pos < state.doc.length;) { + let line = view.lineBlockAt(pos), range = foldable(state, line.from, line.to); + if (range) + effects.push(foldEffect.of(range)); + pos = (range ? view.lineBlockAt(range.to) : line).to + 1; + } + if (effects.length) + view.dispatch({ effects: maybeEnable(view.state, effects) }); + return !!effects.length; + }; + /** + Unfold all folded code. + */ + const unfoldAll = view => { + let field = view.state.field(foldState, false); + if (!field || !field.size) + return false; + let effects = []; + field.between(0, view.state.doc.length, (from, to) => { effects.push(unfoldEffect.of({ from, to })); }); + view.dispatch({ effects }); + return true; + }; + /** + Default fold-related key bindings. + + - Ctrl-Shift-[ (Cmd-Alt-[ on macOS): [`foldCode`](https://codemirror.net/6/docs/ref/#language.foldCode). + - Ctrl-Shift-] (Cmd-Alt-] on macOS): [`unfoldCode`](https://codemirror.net/6/docs/ref/#language.unfoldCode). + - Ctrl-Alt-[: [`foldAll`](https://codemirror.net/6/docs/ref/#language.foldAll). + - Ctrl-Alt-]: [`unfoldAll`](https://codemirror.net/6/docs/ref/#language.unfoldAll). + */ + const foldKeymap = [ + { key: "Ctrl-Shift-[", mac: "Cmd-Alt-[", run: foldCode }, + { key: "Ctrl-Shift-]", mac: "Cmd-Alt-]", run: unfoldCode }, + { key: "Ctrl-Alt-[", run: foldAll }, + { key: "Ctrl-Alt-]", run: unfoldAll } + ]; + const defaultConfig = { + placeholderDOM: null, + placeholderText: "…" + }; + const foldConfig = /*@__PURE__*/Facet.define({ + combine(values) { return combineConfig(values, defaultConfig); } + }); + /** + Create an extension that configures code folding. + */ + function codeFolding(config) { + let result = [foldState, baseTheme$1$2]; + if (config) + result.push(foldConfig.of(config)); + return result; + } + const foldWidget = /*@__PURE__*/Decoration.replace({ widget: /*@__PURE__*/new class extends WidgetType { + toDOM(view) { + let { state } = view, conf = state.facet(foldConfig); + let onclick = (event) => { + let line = view.lineBlockAt(view.posAtDOM(event.target)); + let folded = findFold(view.state, line.from, line.to); + if (folded) + view.dispatch({ effects: unfoldEffect.of(folded) }); + event.preventDefault(); + }; + if (conf.placeholderDOM) + return conf.placeholderDOM(view, onclick); + let element = document.createElement("span"); + element.textContent = conf.placeholderText; + element.setAttribute("aria-label", state.phrase("folded code")); + element.title = state.phrase("unfold"); + element.className = "cm-foldPlaceholder"; + element.onclick = onclick; + return element; + } + } }); + const foldGutterDefaults = { + openText: "⌄", + closedText: "›", + markerDOM: null, + domEventHandlers: {}, + foldingChanged: () => false + }; + class FoldMarker extends GutterMarker { + constructor(config, open) { + super(); + this.config = config; + this.open = open; + } + eq(other) { return this.config == other.config && this.open == other.open; } + toDOM(view) { + if (this.config.markerDOM) + return this.config.markerDOM(this.open); + let span = document.createElement("span"); + span.textContent = this.open ? this.config.openText : this.config.closedText; + span.title = view.state.phrase(this.open ? "Fold line" : "Unfold line"); + return span; + } + } + /** + Create an extension that registers a fold gutter, which shows a + fold status indicator before foldable lines (which can be clicked + to fold or unfold the line). + */ + function foldGutter(config = {}) { + let fullConfig = Object.assign(Object.assign({}, foldGutterDefaults), config); + let canFold = new FoldMarker(fullConfig, true), canUnfold = new FoldMarker(fullConfig, false); + let markers = ViewPlugin.fromClass(class { + constructor(view) { + this.from = view.viewport.from; + this.markers = this.buildMarkers(view); + } + update(update) { + if (update.docChanged || update.viewportChanged || + update.startState.facet(language) != update.state.facet(language) || + update.startState.field(foldState, false) != update.state.field(foldState, false) || + syntaxTree(update.startState) != syntaxTree(update.state) || + fullConfig.foldingChanged(update)) + this.markers = this.buildMarkers(update.view); + } + buildMarkers(view) { + let builder = new RangeSetBuilder(); + for (let line of view.viewportLineBlocks) { + let mark = findFold(view.state, line.from, line.to) ? canUnfold + : foldable(view.state, line.from, line.to) ? canFold : null; + if (mark) + builder.add(line.from, line.from, mark); + } + return builder.finish(); + } + }); + let { domEventHandlers } = fullConfig; + return [ + markers, + gutter({ + class: "cm-foldGutter", + markers(view) { var _a; return ((_a = view.plugin(markers)) === null || _a === void 0 ? void 0 : _a.markers) || RangeSet.empty; }, + initialSpacer() { + return new FoldMarker(fullConfig, false); + }, + domEventHandlers: Object.assign(Object.assign({}, domEventHandlers), { click: (view, line, event) => { + if (domEventHandlers.click && domEventHandlers.click(view, line, event)) + return true; + let folded = findFold(view.state, line.from, line.to); + if (folded) { + view.dispatch({ effects: unfoldEffect.of(folded) }); + return true; + } + let range = foldable(view.state, line.from, line.to); + if (range) { + view.dispatch({ effects: foldEffect.of(range) }); + return true; + } + return false; + } }) + }), + codeFolding() + ]; + } + const baseTheme$1$2 = /*@__PURE__*/EditorView.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" + } + }); + + /** + A highlight style associates CSS styles with higlighting + [tags](https://lezer.codemirror.net/docs/ref#highlight.Tag). + */ + class HighlightStyle { + constructor(spec, options) { + let modSpec; + function def(spec) { + let cls = StyleModule.newName(); + (modSpec || (modSpec = Object.create(null)))["." + cls] = spec; + return cls; + } + const all = typeof options.all == "string" ? options.all : options.all ? def(options.all) : undefined; + const scopeOpt = options.scope; + this.scope = scopeOpt instanceof Language ? (type) => type.prop(languageDataProp) == scopeOpt.data + : scopeOpt ? (type) => type == scopeOpt : undefined; + this.style = tagHighlighter(spec.map(style => ({ + tag: style.tag, + class: style.class || def(Object.assign({}, style, { tag: null })) + })), { + all, + }).style; + this.module = modSpec ? new StyleModule(modSpec) : null; + this.themeType = options.themeType; + } + /** + Create a highlighter style that associates the given styles to + the given tags. The specs must be objects that hold a style tag + or array of tags in their `tag` property, and either a single + `class` property providing a static CSS class (for highlighter + that rely on external styling), or a + [`style-mod`](https://github.com/marijnh/style-mod#documentation)-style + set of CSS properties (which define the styling for those tags). + + The CSS rules created for a highlighter will be emitted in the + order of the spec's properties. That means that for elements that + have multiple tags associated with them, styles defined further + down in the list will have a higher CSS precedence than styles + defined earlier. + */ + static define(specs, options) { + return new HighlightStyle(specs, options || {}); + } + } + const highlighterFacet = /*@__PURE__*/Facet.define(); + const fallbackHighlighter = /*@__PURE__*/Facet.define({ + combine(values) { return values.length ? [values[0]] : null; } + }); + function getHighlighters(state) { + let main = state.facet(highlighterFacet); + return main.length ? main : state.facet(fallbackHighlighter); + } + /** + Wrap a highlighter in an editor extension that uses it to apply + syntax highlighting to the editor content. + + When multiple (non-fallback) styles are provided, the styling + applied is the union of the classes they emit. + */ + function syntaxHighlighting(highlighter, options) { + let ext = [treeHighlighter], themeType; + if (highlighter instanceof HighlightStyle) { + if (highlighter.module) + ext.push(EditorView.styleModule.of(highlighter.module)); + themeType = highlighter.themeType; + } + if (options === null || options === void 0 ? void 0 : options.fallback) + ext.push(fallbackHighlighter.of(highlighter)); + else if (themeType) + ext.push(highlighterFacet.computeN([EditorView.darkTheme], state => { + return state.facet(EditorView.darkTheme) == (themeType == "dark") ? [highlighter] : []; + })); + else + ext.push(highlighterFacet.of(highlighter)); + return ext; + } + class TreeHighlighter { + constructor(view) { + this.markCache = Object.create(null); + this.tree = syntaxTree(view.state); + this.decorations = this.buildDeco(view, getHighlighters(view.state)); + } + update(update) { + let tree = syntaxTree(update.state), highlighters = getHighlighters(update.state); + let styleChange = highlighters != getHighlighters(update.startState); + if (tree.length < update.view.viewport.to && !styleChange && tree.type == this.tree.type) { + this.decorations = this.decorations.map(update.changes); + } + else if (tree != this.tree || update.viewportChanged || styleChange) { + this.tree = tree; + this.decorations = this.buildDeco(update.view, highlighters); + } + } + buildDeco(view, highlighters) { + if (!highlighters || !this.tree.length) + return Decoration.none; + let builder = new RangeSetBuilder(); + for (let { from, to } of view.visibleRanges) { + highlightTree(this.tree, highlighters, (from, to, style) => { + builder.add(from, to, this.markCache[style] || (this.markCache[style] = Decoration.mark({ class: style }))); + }, from, to); + } + return builder.finish(); + } + } + const treeHighlighter = /*@__PURE__*/Prec.high(/*@__PURE__*/ViewPlugin.fromClass(TreeHighlighter, { + decorations: v => v.decorations + })); + /** + A default highlight style (works well with light themes). + */ + const defaultHighlightStyle = /*@__PURE__*/HighlightStyle.define([ + { tag: tags.meta, + color: "#7a757a" }, + { tag: tags.link, + textDecoration: "underline" }, + { tag: tags.heading, + textDecoration: "underline", + fontWeight: "bold" }, + { tag: tags.emphasis, + fontStyle: "italic" }, + { tag: tags.strong, + fontWeight: "bold" }, + { tag: tags.strikethrough, + textDecoration: "line-through" }, + { tag: tags.keyword, + color: "#708" }, + { tag: [tags.atom, tags.bool, tags.url, tags.contentSeparator, tags.labelName], + color: "#219" }, + { tag: [tags.literal, tags.inserted], + color: "#164" }, + { tag: [tags.string, tags.deleted], + color: "#a11" }, + { tag: [tags.regexp, tags.escape, /*@__PURE__*/tags.special(tags.string)], + color: "#e40" }, + { tag: /*@__PURE__*/tags.definition(tags.variableName), + color: "#00f" }, + { tag: /*@__PURE__*/tags.local(tags.variableName), + color: "#30a" }, + { tag: [tags.typeName, tags.namespace], + color: "#085" }, + { tag: tags.className, + color: "#167" }, + { tag: [/*@__PURE__*/tags.special(tags.variableName), tags.macroName], + color: "#256" }, + { tag: /*@__PURE__*/tags.definition(tags.propertyName), + color: "#00c" }, + { tag: tags.comment, + color: "#940" }, + { tag: tags.invalid, + color: "#f00" } + ]); + + const baseTheme$3 = /*@__PURE__*/EditorView.baseTheme({ + "&.cm-focused .cm-matchingBracket": { backgroundColor: "#328c8252" }, + "&.cm-focused .cm-nonmatchingBracket": { backgroundColor: "#bb555544" } + }); + const DefaultScanDist = 10000, DefaultBrackets = "()[]{}"; + const bracketMatchingConfig = /*@__PURE__*/Facet.define({ + combine(configs) { + return combineConfig(configs, { + afterCursor: true, + brackets: DefaultBrackets, + maxScanDistance: DefaultScanDist, + renderMatch: defaultRenderMatch + }); + } + }); + const matchingMark = /*@__PURE__*/Decoration.mark({ class: "cm-matchingBracket" }), nonmatchingMark = /*@__PURE__*/Decoration.mark({ class: "cm-nonmatchingBracket" }); + function defaultRenderMatch(match) { + let decorations = []; + let mark = match.matched ? matchingMark : nonmatchingMark; + decorations.push(mark.range(match.start.from, match.start.to)); + if (match.end) + decorations.push(mark.range(match.end.from, match.end.to)); + return decorations; + } + const bracketMatchingState = /*@__PURE__*/StateField.define({ + create() { return Decoration.none; }, + update(deco, tr) { + if (!tr.docChanged && !tr.selection) + return deco; + let decorations = []; + let config = tr.state.facet(bracketMatchingConfig); + for (let range of tr.state.selection.ranges) { + if (!range.empty) + continue; + let match = matchBrackets(tr.state, range.head, -1, config) + || (range.head > 0 && matchBrackets(tr.state, range.head - 1, 1, config)) + || (config.afterCursor && + (matchBrackets(tr.state, range.head, 1, config) || + (range.head < tr.state.doc.length && matchBrackets(tr.state, range.head + 1, -1, config)))); + if (match) + decorations = decorations.concat(config.renderMatch(match, tr.state)); + } + return Decoration.set(decorations, true); + }, + provide: f => EditorView.decorations.from(f) + }); + const bracketMatchingUnique = [ + bracketMatchingState, + baseTheme$3 + ]; + /** + Create an extension that enables bracket matching. Whenever the + cursor is next to a bracket, that bracket and the one it matches + are highlighted. Or, when no matching bracket is found, another + highlighting style is used to indicate this. + */ + function bracketMatching(config = {}) { + return [bracketMatchingConfig.of(config), bracketMatchingUnique]; + } + function matchingNodes(node, dir, brackets) { + let byProp = node.prop(dir < 0 ? NodeProp.openedBy : NodeProp.closedBy); + if (byProp) + return byProp; + if (node.name.length == 1) { + let index = brackets.indexOf(node.name); + if (index > -1 && index % 2 == (dir < 0 ? 1 : 0)) + return [brackets[index + dir]]; + } + return null; + } + /** + Find the matching bracket for the token at `pos`, scanning + direction `dir`. Only the `brackets` and `maxScanDistance` + properties are used from `config`, if given. Returns null if no + bracket was found at `pos`, or a match result otherwise. + */ + function matchBrackets(state, pos, dir, config = {}) { + let maxScanDistance = config.maxScanDistance || DefaultScanDist, brackets = config.brackets || DefaultBrackets; + let tree = syntaxTree(state), node = tree.resolveInner(pos, dir); + for (let cur = node; cur; cur = cur.parent) { + let matches = matchingNodes(cur.type, dir, brackets); + if (matches && cur.from < cur.to) + return matchMarkedBrackets(state, pos, dir, cur, matches, brackets); + } + return matchPlainBrackets(state, pos, dir, tree, node.type, maxScanDistance, brackets); + } + function matchMarkedBrackets(_state, _pos, dir, token, matching, brackets) { + let parent = token.parent, firstToken = { from: token.from, to: token.to }; + let depth = 0, cursor = parent === null || parent === void 0 ? void 0 : parent.cursor(); + if (cursor && (dir < 0 ? cursor.childBefore(token.from) : cursor.childAfter(token.to))) + do { + if (dir < 0 ? cursor.to <= token.from : cursor.from >= token.to) { + if (depth == 0 && matching.indexOf(cursor.type.name) > -1 && cursor.from < cursor.to) { + return { start: firstToken, end: { from: cursor.from, to: cursor.to }, matched: true }; + } + else if (matchingNodes(cursor.type, dir, brackets)) { + depth++; + } + else if (matchingNodes(cursor.type, -dir, brackets)) { + if (depth == 0) + return { + start: firstToken, + end: cursor.from == cursor.to ? undefined : { from: cursor.from, to: cursor.to }, + matched: false + }; + depth--; + } + } + } while (dir < 0 ? cursor.prevSibling() : cursor.nextSibling()); + return { start: firstToken, matched: false }; + } + function matchPlainBrackets(state, pos, dir, tree, tokenType, maxScanDistance, brackets) { + let startCh = dir < 0 ? state.sliceDoc(pos - 1, pos) : state.sliceDoc(pos, pos + 1); + let bracket = brackets.indexOf(startCh); + if (bracket < 0 || (bracket % 2 == 0) != (dir > 0)) + return null; + let startToken = { from: dir < 0 ? pos - 1 : pos, to: dir > 0 ? pos + 1 : pos }; + let iter = state.doc.iterRange(pos, dir > 0 ? state.doc.length : 0), depth = 0; + for (let distance = 0; !(iter.next()).done && distance <= maxScanDistance;) { + let text = iter.value; + if (dir < 0) + distance += text.length; + let basePos = pos + distance * dir; + for (let pos = dir > 0 ? 0 : text.length - 1, end = dir > 0 ? text.length : -1; pos != end; pos += dir) { + let found = brackets.indexOf(text[pos]); + if (found < 0 || tree.resolveInner(basePos + pos, 1).type != tokenType) + continue; + if ((found % 2 == 0) == (dir > 0)) { + depth++; + } + else if (depth == 1) { // Closing + return { start: startToken, end: { from: basePos + pos, to: basePos + pos + 1 }, matched: (found >> 1) == (bracket >> 1) }; + } + else { + depth--; + } + } + if (dir > 0) + distance += text.length; + } + return iter.done ? { start: startToken, matched: false } : null; + } + const noTokens = /*@__PURE__*/Object.create(null); + const typeArray = [NodeType.none]; + const warned = []; + const defaultTable = /*@__PURE__*/Object.create(null); + for (let [legacyName, name] 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"] + ]) + defaultTable[legacyName] = /*@__PURE__*/createTokenType(noTokens, name); + function warnForPart(part, msg) { + if (warned.indexOf(part) > -1) + return; + warned.push(part); + console.warn(msg); + } + function createTokenType(extra, tagStr) { + let tag = null; + for (let part of tagStr.split(".")) { + let value = (extra[part] || tags[part]); + if (!value) { + warnForPart(part, `Unknown highlighting tag ${part}`); + } + else if (typeof value == "function") { + if (!tag) + warnForPart(part, `Modifier ${part} used at start of tag`); + else + tag = value(tag); + } + else { + if (tag) + warnForPart(part, `Tag ${part} used as modifier`); + else + tag = value; + } + } + if (!tag) + return 0; + let name = tagStr.replace(/ /g, "_"), type = NodeType.define({ + id: typeArray.length, + name, + props: [styleTags({ [name]: tag })] + }); + typeArray.push(type); + return type.id; + } + + /** + Comment or uncomment the current selection. Will use line comments + if available, otherwise falling back to block comments. + */ + const toggleComment = target => { + let config = getConfig(target.state); + return config.line ? toggleLineComment(target) : config.block ? toggleBlockCommentByLine(target) : false; + }; + function command(f, option) { + return ({ state, dispatch }) => { + if (state.readOnly) + return false; + let tr = f(option, state); + if (!tr) + return false; + dispatch(state.update(tr)); + return true; + }; + } + /** + Comment or uncomment the current selection using line comments. + The line comment syntax is taken from the + [`commentTokens`](https://codemirror.net/6/docs/ref/#commands.CommentTokens) [language + data](https://codemirror.net/6/docs/ref/#state.EditorState.languageDataAt). + */ + const toggleLineComment = /*@__PURE__*/command(changeLineComment, 0 /* CommentOption.Toggle */); + /** + Comment or uncomment the current selection using block comments. + The block comment syntax is taken from the + [`commentTokens`](https://codemirror.net/6/docs/ref/#commands.CommentTokens) [language + data](https://codemirror.net/6/docs/ref/#state.EditorState.languageDataAt). + */ + const toggleBlockComment = /*@__PURE__*/command(changeBlockComment, 0 /* CommentOption.Toggle */); + /** + Comment or uncomment the lines around the current selection using + block comments. + */ + const toggleBlockCommentByLine = /*@__PURE__*/command((o, s) => changeBlockComment(o, s, selectedLineRanges(s)), 0 /* CommentOption.Toggle */); + function getConfig(state, pos = state.selection.main.head) { + let data = state.languageDataAt("commentTokens", pos); + return data.length ? data[0] : {}; + } + const SearchMargin = 50; + /** + Determines if the given range is block-commented in the given + state. + */ + function findBlockComment(state, { open, close }, from, to) { + let textBefore = state.sliceDoc(from - SearchMargin, from); + let textAfter = state.sliceDoc(to, to + SearchMargin); + let spaceBefore = /\s*$/.exec(textBefore)[0].length, spaceAfter = /^\s*/.exec(textAfter)[0].length; + let beforeOff = textBefore.length - spaceBefore; + if (textBefore.slice(beforeOff - open.length, beforeOff) == open && + textAfter.slice(spaceAfter, spaceAfter + close.length) == close) { + return { open: { pos: from - spaceBefore, margin: spaceBefore && 1 }, + close: { pos: to + spaceAfter, margin: spaceAfter && 1 } }; + } + let startText, endText; + if (to - from <= 2 * SearchMargin) { + startText = endText = state.sliceDoc(from, to); + } + else { + startText = state.sliceDoc(from, from + SearchMargin); + endText = state.sliceDoc(to - SearchMargin, to); + } + let startSpace = /^\s*/.exec(startText)[0].length, endSpace = /\s*$/.exec(endText)[0].length; + let endOff = endText.length - endSpace - close.length; + if (startText.slice(startSpace, startSpace + open.length) == open && + endText.slice(endOff, endOff + close.length) == close) { + return { open: { pos: from + startSpace + open.length, + margin: /\s/.test(startText.charAt(startSpace + open.length)) ? 1 : 0 }, + close: { pos: to - endSpace - close.length, + margin: /\s/.test(endText.charAt(endOff - 1)) ? 1 : 0 } }; + } + return null; + } + function selectedLineRanges(state) { + let ranges = []; + for (let r of state.selection.ranges) { + let fromLine = state.doc.lineAt(r.from); + let toLine = r.to <= fromLine.to ? fromLine : state.doc.lineAt(r.to); + let last = ranges.length - 1; + if (last >= 0 && ranges[last].to > fromLine.from) + ranges[last].to = toLine.to; + else + ranges.push({ from: fromLine.from, to: toLine.to }); + } + return ranges; + } + // Performs toggle, comment and uncomment of block comments in + // languages that support them. + function changeBlockComment(option, state, ranges = state.selection.ranges) { + let tokens = ranges.map(r => getConfig(state, r.from).block); + if (!tokens.every(c => c)) + return null; + let comments = ranges.map((r, i) => findBlockComment(state, tokens[i], r.from, r.to)); + if (option != 2 /* CommentOption.Uncomment */ && !comments.every(c => c)) { + return { changes: state.changes(ranges.map((range, i) => { + if (comments[i]) + return []; + return [{ from: range.from, insert: tokens[i].open + " " }, { from: range.to, insert: " " + tokens[i].close }]; + })) }; + } + else if (option != 1 /* CommentOption.Comment */ && comments.some(c => c)) { + let changes = []; + for (let i = 0, comment; i < comments.length; i++) + if (comment = comments[i]) { + let token = tokens[i], { open, close } = comment; + changes.push({ from: open.pos - token.open.length, to: open.pos + open.margin }, { from: close.pos - close.margin, to: close.pos + token.close.length }); + } + return { changes }; + } + return null; + } + // Performs toggle, comment and uncomment of line comments. + function changeLineComment(option, state, ranges = state.selection.ranges) { + let lines = []; + let prevLine = -1; + for (let { from, to } of ranges) { + let startI = lines.length, minIndent = 1e9; + for (let pos = from; pos <= to;) { + let line = state.doc.lineAt(pos); + if (line.from > prevLine && (from == to || to > line.from)) { + prevLine = line.from; + let token = getConfig(state, pos).line; + if (!token) + continue; + let indent = /^\s*/.exec(line.text)[0].length; + let empty = indent == line.length; + let comment = line.text.slice(indent, indent + token.length) == token ? indent : -1; + if (indent < line.text.length && indent < minIndent) + minIndent = indent; + lines.push({ line, comment, token, indent, empty, single: false }); + } + pos = line.to + 1; + } + if (minIndent < 1e9) + for (let i = startI; i < lines.length; i++) + if (lines[i].indent < lines[i].line.text.length) + lines[i].indent = minIndent; + if (lines.length == startI + 1) + lines[startI].single = true; + } + if (option != 2 /* CommentOption.Uncomment */ && lines.some(l => l.comment < 0 && (!l.empty || l.single))) { + let changes = []; + for (let { line, token, indent, empty, single } of lines) + if (single || !empty) + changes.push({ from: line.from + indent, insert: token + " " }); + let changeSet = state.changes(changes); + return { changes: changeSet, selection: state.selection.map(changeSet, 1) }; + } + else if (option != 1 /* CommentOption.Comment */ && lines.some(l => l.comment >= 0)) { + let changes = []; + for (let { line, comment, token } of lines) + if (comment >= 0) { + let from = line.from + comment, to = from + token.length; + if (line.text[to - line.from] == " ") + to++; + changes.push({ from, to }); + } + return { changes }; + } + return null; + } + + const fromHistory = /*@__PURE__*/Annotation.define(); + /** + Transaction annotation that will prevent that transaction from + being combined with other transactions in the undo history. Given + `"before"`, it'll prevent merging with previous transactions. With + `"after"`, subsequent transactions won't be combined with this + one. With `"full"`, the transaction is isolated on both sides. + */ + const isolateHistory = /*@__PURE__*/Annotation.define(); + /** + This facet provides a way to register functions that, given a + transaction, provide a set of effects that the history should + store when inverting the transaction. This can be used to + integrate some kinds of effects in the history, so that they can + be undone (and redone again). + */ + const invertedEffects = /*@__PURE__*/Facet.define(); + const historyConfig = /*@__PURE__*/Facet.define({ + combine(configs) { + return combineConfig(configs, { + minDepth: 100, + newGroupDelay: 500 + }, { minDepth: Math.max, newGroupDelay: Math.min }); + } + }); + function changeEnd(changes) { + let end = 0; + changes.iterChangedRanges((_, to) => end = to); + return end; + } + const historyField_ = /*@__PURE__*/StateField.define({ + create() { + return HistoryState.empty; + }, + update(state, tr) { + let config = tr.state.facet(historyConfig); + let fromHist = tr.annotation(fromHistory); + if (fromHist) { + let selection = tr.docChanged ? EditorSelection.single(changeEnd(tr.changes)) : undefined; + let item = HistEvent.fromTransaction(tr, selection), from = fromHist.side; + let other = from == 0 /* BranchName.Done */ ? state.undone : state.done; + if (item) + other = updateBranch(other, other.length, config.minDepth, item); + else + other = addSelection(other, tr.startState.selection); + return new HistoryState(from == 0 /* BranchName.Done */ ? fromHist.rest : other, from == 0 /* BranchName.Done */ ? other : fromHist.rest); + } + let isolate = tr.annotation(isolateHistory); + if (isolate == "full" || isolate == "before") + state = state.isolate(); + if (tr.annotation(Transaction.addToHistory) === false) + return !tr.changes.empty ? state.addMapping(tr.changes.desc) : state; + let event = HistEvent.fromTransaction(tr); + let time = tr.annotation(Transaction.time), userEvent = tr.annotation(Transaction.userEvent); + if (event) + state = state.addChanges(event, time, userEvent, config.newGroupDelay, config.minDepth); + else if (tr.selection) + state = state.addSelection(tr.startState.selection, time, userEvent, config.newGroupDelay); + if (isolate == "full" || isolate == "after") + state = state.isolate(); + return state; + }, + toJSON(value) { + return { done: value.done.map(e => e.toJSON()), undone: value.undone.map(e => e.toJSON()) }; + }, + fromJSON(json) { + return new HistoryState(json.done.map(HistEvent.fromJSON), json.undone.map(HistEvent.fromJSON)); + } + }); + /** + Create a history extension with the given configuration. + */ + function history(config = {}) { + return [ + historyField_, + historyConfig.of(config), + EditorView.domEventHandlers({ + beforeinput(e, view) { + let command = e.inputType == "historyUndo" ? undo : e.inputType == "historyRedo" ? redo : null; + if (!command) + return false; + e.preventDefault(); + return command(view); + } + }) + ]; + } + function cmd(side, selection) { + return function ({ state, dispatch }) { + if (!selection && state.readOnly) + return false; + let historyState = state.field(historyField_, false); + if (!historyState) + return false; + let tr = historyState.pop(side, state, selection); + if (!tr) + return false; + dispatch(tr); + return true; + }; + } + /** + Undo a single group of history events. Returns false if no group + was available. + */ + const undo = /*@__PURE__*/cmd(0 /* BranchName.Done */, false); + /** + Redo a group of history events. Returns false if no group was + available. + */ + const redo = /*@__PURE__*/cmd(1 /* BranchName.Undone */, false); + /** + Undo a change or selection change. + */ + const undoSelection = /*@__PURE__*/cmd(0 /* BranchName.Done */, true); + /** + Redo a change or selection change. + */ + const redoSelection = /*@__PURE__*/cmd(1 /* BranchName.Undone */, true); + // History events store groups of changes or effects that need to be + // undone/redone together. + class HistEvent { + constructor( + // The changes in this event. Normal events hold at least one + // change or effect. But it may be necessary to store selection + // events before the first change, in which case a special type of + // instance is created which doesn't hold any changes, with + // changes == startSelection == undefined + changes, + // The effects associated with this event + effects, + // Accumulated mapping (from addToHistory==false) that should be + // applied to events below this one. + mapped, + // The selection before this event + startSelection, + // Stores selection changes after this event, to be used for + // selection undo/redo. + selectionsAfter) { + this.changes = changes; + this.effects = effects; + this.mapped = mapped; + this.startSelection = startSelection; + this.selectionsAfter = selectionsAfter; + } + setSelAfter(after) { + return new HistEvent(this.changes, this.effects, this.mapped, this.startSelection, after); + } + toJSON() { + var _a, _b, _c; + return { + changes: (_a = this.changes) === null || _a === void 0 ? void 0 : _a.toJSON(), + mapped: (_b = this.mapped) === null || _b === void 0 ? void 0 : _b.toJSON(), + startSelection: (_c = this.startSelection) === null || _c === void 0 ? void 0 : _c.toJSON(), + selectionsAfter: this.selectionsAfter.map(s => s.toJSON()) + }; + } + static fromJSON(json) { + return new HistEvent(json.changes && ChangeSet.fromJSON(json.changes), [], json.mapped && ChangeDesc.fromJSON(json.mapped), json.startSelection && EditorSelection.fromJSON(json.startSelection), json.selectionsAfter.map(EditorSelection.fromJSON)); + } + // This does not check `addToHistory` and such, it assumes the + // transaction needs to be converted to an item. Returns null when + // there are no changes or effects in the transaction. + static fromTransaction(tr, selection) { + let effects = none$1; + for (let invert of tr.startState.facet(invertedEffects)) { + let result = invert(tr); + if (result.length) + effects = effects.concat(result); + } + if (!effects.length && tr.changes.empty) + return null; + return new HistEvent(tr.changes.invert(tr.startState.doc), effects, undefined, selection || tr.startState.selection, none$1); + } + static selection(selections) { + return new HistEvent(undefined, none$1, undefined, undefined, selections); + } + } + function updateBranch(branch, to, maxLen, newEvent) { + let start = to + 1 > maxLen + 20 ? to - maxLen - 1 : 0; + let newBranch = branch.slice(start, to); + newBranch.push(newEvent); + return newBranch; + } + function isAdjacent(a, b) { + let ranges = [], isAdjacent = false; + a.iterChangedRanges((f, t) => ranges.push(f, t)); + b.iterChangedRanges((_f, _t, f, t) => { + for (let i = 0; i < ranges.length;) { + let from = ranges[i++], to = ranges[i++]; + if (t >= from && f <= to) + isAdjacent = true; + } + }); + return isAdjacent; + } + function eqSelectionShape(a, b) { + return a.ranges.length == b.ranges.length && + a.ranges.filter((r, i) => r.empty != b.ranges[i].empty).length === 0; + } + function conc(a, b) { + return !a.length ? b : !b.length ? a : a.concat(b); + } + const none$1 = []; + const MaxSelectionsPerEvent = 200; + function addSelection(branch, selection) { + if (!branch.length) { + return [HistEvent.selection([selection])]; + } + else { + let lastEvent = branch[branch.length - 1]; + let sels = lastEvent.selectionsAfter.slice(Math.max(0, lastEvent.selectionsAfter.length - MaxSelectionsPerEvent)); + if (sels.length && sels[sels.length - 1].eq(selection)) + return branch; + sels.push(selection); + return updateBranch(branch, branch.length - 1, 1e9, lastEvent.setSelAfter(sels)); + } + } + // Assumes the top item has one or more selectionAfter values + function popSelection(branch) { + let last = branch[branch.length - 1]; + let newBranch = branch.slice(); + newBranch[branch.length - 1] = last.setSelAfter(last.selectionsAfter.slice(0, last.selectionsAfter.length - 1)); + return newBranch; + } + // Add a mapping to the top event in the given branch. If this maps + // away all the changes and effects in that item, drop it and + // propagate the mapping to the next item. + function addMappingToBranch(branch, mapping) { + if (!branch.length) + return branch; + let length = branch.length, selections = none$1; + while (length) { + let event = mapEvent(branch[length - 1], mapping, selections); + if (event.changes && !event.changes.empty || event.effects.length) { // Event survived mapping + let result = branch.slice(0, length); + result[length - 1] = event; + return result; + } + else { // Drop this event, since there's no changes or effects left + mapping = event.mapped; + length--; + selections = event.selectionsAfter; + } + } + return selections.length ? [HistEvent.selection(selections)] : none$1; + } + function mapEvent(event, mapping, extraSelections) { + let selections = conc(event.selectionsAfter.length ? event.selectionsAfter.map(s => s.map(mapping)) : none$1, extraSelections); + // Change-less events don't store mappings (they are always the last event in a branch) + if (!event.changes) + return HistEvent.selection(selections); + let mappedChanges = event.changes.map(mapping), before = mapping.mapDesc(event.changes, true); + let fullMapping = event.mapped ? event.mapped.composeDesc(before) : before; + return new HistEvent(mappedChanges, StateEffect.mapEffects(event.effects, mapping), fullMapping, event.startSelection.map(before), selections); + } + const joinableUserEvent = /^(input\.type|delete)($|\.)/; + class HistoryState { + constructor(done, undone, prevTime = 0, prevUserEvent = undefined) { + this.done = done; + this.undone = undone; + this.prevTime = prevTime; + this.prevUserEvent = prevUserEvent; + } + isolate() { + return this.prevTime ? new HistoryState(this.done, this.undone) : this; + } + addChanges(event, time, userEvent, newGroupDelay, maxLen) { + let done = this.done, lastEvent = done[done.length - 1]; + if (lastEvent && lastEvent.changes && !lastEvent.changes.empty && event.changes && + (!userEvent || joinableUserEvent.test(userEvent)) && + ((!lastEvent.selectionsAfter.length && + time - this.prevTime < newGroupDelay && + isAdjacent(lastEvent.changes, event.changes)) || + // For compose (but not compose.start) events, always join with previous event + userEvent == "input.type.compose")) { + done = updateBranch(done, done.length - 1, maxLen, new HistEvent(event.changes.compose(lastEvent.changes), conc(event.effects, lastEvent.effects), lastEvent.mapped, lastEvent.startSelection, none$1)); + } + else { + done = updateBranch(done, done.length, maxLen, event); + } + return new HistoryState(done, none$1, time, userEvent); + } + addSelection(selection, time, userEvent, newGroupDelay) { + let last = this.done.length ? this.done[this.done.length - 1].selectionsAfter : none$1; + if (last.length > 0 && + time - this.prevTime < newGroupDelay && + userEvent == this.prevUserEvent && userEvent && /^select($|\.)/.test(userEvent) && + eqSelectionShape(last[last.length - 1], selection)) + return this; + return new HistoryState(addSelection(this.done, selection), this.undone, time, userEvent); + } + addMapping(mapping) { + return new HistoryState(addMappingToBranch(this.done, mapping), addMappingToBranch(this.undone, mapping), this.prevTime, this.prevUserEvent); + } + pop(side, state, selection) { + let branch = side == 0 /* BranchName.Done */ ? this.done : this.undone; + if (branch.length == 0) + return null; + let event = branch[branch.length - 1]; + if (selection && event.selectionsAfter.length) { + return state.update({ + selection: event.selectionsAfter[event.selectionsAfter.length - 1], + annotations: fromHistory.of({ side, rest: popSelection(branch) }), + userEvent: side == 0 /* BranchName.Done */ ? "select.undo" : "select.redo", + scrollIntoView: true + }); + } + else if (!event.changes) { + return null; + } + else { + let rest = branch.length == 1 ? none$1 : branch.slice(0, branch.length - 1); + if (event.mapped) + rest = addMappingToBranch(rest, event.mapped); + return state.update({ + changes: event.changes, + selection: event.startSelection, + effects: event.effects, + annotations: fromHistory.of({ side, rest }), + filter: false, + userEvent: side == 0 /* BranchName.Done */ ? "undo" : "redo", + scrollIntoView: true + }); + } + } + } + HistoryState.empty = /*@__PURE__*/new HistoryState(none$1, none$1); + /** + Default key bindings for the undo history. + + - Mod-z: [`undo`](https://codemirror.net/6/docs/ref/#commands.undo). + - Mod-y (Mod-Shift-z on macOS) + Ctrl-Shift-z on Linux: [`redo`](https://codemirror.net/6/docs/ref/#commands.redo). + - Mod-u: [`undoSelection`](https://codemirror.net/6/docs/ref/#commands.undoSelection). + - Alt-u (Mod-Shift-u on macOS): [`redoSelection`](https://codemirror.net/6/docs/ref/#commands.redoSelection). + */ + const historyKeymap = [ + { key: "Mod-z", run: undo, preventDefault: true }, + { key: "Mod-y", mac: "Mod-Shift-z", run: redo, preventDefault: true }, + { linux: "Ctrl-Shift-z", run: redo, preventDefault: true }, + { key: "Mod-u", run: undoSelection, preventDefault: true }, + { key: "Alt-u", mac: "Mod-Shift-u", run: redoSelection, preventDefault: true } + ]; + + function updateSel(sel, by) { + return EditorSelection.create(sel.ranges.map(by), sel.mainIndex); + } + function setSel(state, selection) { + return state.update({ selection, scrollIntoView: true, userEvent: "select" }); + } + function moveSel({ state, dispatch }, how) { + let selection = updateSel(state.selection, how); + if (selection.eq(state.selection)) + return false; + dispatch(setSel(state, selection)); + return true; + } + function rangeEnd(range, forward) { + return EditorSelection.cursor(forward ? range.to : range.from); + } + function cursorByChar(view, forward) { + return moveSel(view, range => range.empty ? view.moveByChar(range, forward) : rangeEnd(range, forward)); + } + function ltrAtCursor(view) { + return view.textDirectionAt(view.state.selection.main.head) == Direction.LTR; + } + /** + Move the selection one character to the left (which is backward in + left-to-right text, forward in right-to-left text). + */ + const cursorCharLeft = view => cursorByChar(view, !ltrAtCursor(view)); + /** + Move the selection one character to the right. + */ + const cursorCharRight = view => cursorByChar(view, ltrAtCursor(view)); + function cursorByGroup(view, forward) { + return moveSel(view, range => range.empty ? view.moveByGroup(range, forward) : rangeEnd(range, forward)); + } + /** + Move the selection to the left across one group of word or + non-word (but also non-space) characters. + */ + const cursorGroupLeft = view => cursorByGroup(view, !ltrAtCursor(view)); + /** + Move the selection one group to the right. + */ + const cursorGroupRight = view => cursorByGroup(view, ltrAtCursor(view)); + function interestingNode(state, node, bracketProp) { + if (node.type.prop(bracketProp)) + return true; + let len = node.to - node.from; + return len && (len > 2 || /[^\s,.;:]/.test(state.sliceDoc(node.from, node.to))) || node.firstChild; + } + function moveBySyntax(state, start, forward) { + let pos = syntaxTree(state).resolveInner(start.head); + let bracketProp = forward ? NodeProp.closedBy : NodeProp.openedBy; + // Scan forward through child nodes to see if there's an interesting + // node ahead. + for (let at = start.head;;) { + let next = forward ? pos.childAfter(at) : pos.childBefore(at); + if (!next) + break; + if (interestingNode(state, next, bracketProp)) + pos = next; + else + at = forward ? next.to : next.from; + } + let bracket = pos.type.prop(bracketProp), match, newPos; + if (bracket && (match = forward ? matchBrackets(state, pos.from, 1) : matchBrackets(state, pos.to, -1)) && match.matched) + newPos = forward ? match.end.to : match.end.from; + else + newPos = forward ? pos.to : pos.from; + return EditorSelection.cursor(newPos, forward ? -1 : 1); + } + /** + Move the cursor over the next syntactic element to the left. + */ + const cursorSyntaxLeft = view => moveSel(view, range => moveBySyntax(view.state, range, !ltrAtCursor(view))); + /** + Move the cursor over the next syntactic element to the right. + */ + const cursorSyntaxRight = view => moveSel(view, range => moveBySyntax(view.state, range, ltrAtCursor(view))); + function cursorByLine(view, forward) { + return moveSel(view, range => { + if (!range.empty) + return rangeEnd(range, forward); + let moved = view.moveVertically(range, forward); + return moved.head != range.head ? moved : view.moveToLineBoundary(range, forward); + }); + } + /** + Move the selection one line up. + */ + const cursorLineUp = view => cursorByLine(view, false); + /** + Move the selection one line down. + */ + const cursorLineDown = view => cursorByLine(view, true); + function pageHeight(view) { + return Math.max(view.defaultLineHeight, Math.min(view.dom.clientHeight, innerHeight) - 5); + } + function cursorByPage(view, forward) { + let { state } = view, selection = updateSel(state.selection, range => { + return range.empty ? view.moveVertically(range, forward, pageHeight(view)) : rangeEnd(range, forward); + }); + if (selection.eq(state.selection)) + return false; + let startPos = view.coordsAtPos(state.selection.main.head); + let scrollRect = view.scrollDOM.getBoundingClientRect(); + let effect; + if (startPos && startPos.top > scrollRect.top && startPos.bottom < scrollRect.bottom && + startPos.top - scrollRect.top <= view.scrollDOM.scrollHeight - view.scrollDOM.scrollTop - view.scrollDOM.clientHeight) + effect = EditorView.scrollIntoView(selection.main.head, { y: "start", yMargin: startPos.top - scrollRect.top }); + view.dispatch(setSel(state, selection), { effects: effect }); + return true; + } + /** + Move the selection one page up. + */ + const cursorPageUp = view => cursorByPage(view, false); + /** + Move the selection one page down. + */ + const cursorPageDown = view => cursorByPage(view, true); + function moveByLineBoundary(view, start, forward) { + let line = view.lineBlockAt(start.head), moved = view.moveToLineBoundary(start, forward); + if (moved.head == start.head && moved.head != (forward ? line.to : line.from)) + moved = view.moveToLineBoundary(start, forward, false); + if (!forward && moved.head == line.from && line.length) { + let space = /^\s*/.exec(view.state.sliceDoc(line.from, Math.min(line.from + 100, line.to)))[0].length; + if (space && start.head != line.from + space) + moved = EditorSelection.cursor(line.from + space); + } + return moved; + } + /** + Move the selection to the next line wrap point, or to the end of + the line if there isn't one left on this line. + */ + const cursorLineBoundaryForward = view => moveSel(view, range => moveByLineBoundary(view, range, true)); + /** + Move the selection to previous line wrap point, or failing that to + the start of the line. If the line is indented, and the cursor + isn't already at the end of the indentation, this will move to the + end of the indentation instead of the start of the line. + */ + const cursorLineBoundaryBackward = view => moveSel(view, range => moveByLineBoundary(view, range, false)); + /** + Move the selection one line wrap point to the left. + */ + const cursorLineBoundaryLeft = view => moveSel(view, range => moveByLineBoundary(view, range, !ltrAtCursor(view))); + /** + Move the selection one line wrap point to the right. + */ + const cursorLineBoundaryRight = view => moveSel(view, range => moveByLineBoundary(view, range, ltrAtCursor(view))); + /** + Move the selection to the start of the line. + */ + const cursorLineStart = view => moveSel(view, range => EditorSelection.cursor(view.lineBlockAt(range.head).from, 1)); + /** + Move the selection to the end of the line. + */ + const cursorLineEnd = view => moveSel(view, range => EditorSelection.cursor(view.lineBlockAt(range.head).to, -1)); + function toMatchingBracket(state, dispatch, extend) { + let found = false, selection = updateSel(state.selection, range => { + let matching = matchBrackets(state, range.head, -1) + || matchBrackets(state, range.head, 1) + || (range.head > 0 && matchBrackets(state, range.head - 1, 1)) + || (range.head < state.doc.length && matchBrackets(state, range.head + 1, -1)); + if (!matching || !matching.end) + return range; + found = true; + let head = matching.start.from == range.head ? matching.end.to : matching.end.from; + return extend ? EditorSelection.range(range.anchor, head) : EditorSelection.cursor(head); + }); + if (!found) + return false; + dispatch(setSel(state, selection)); + return true; + } + /** + Move the selection to the bracket matching the one it is currently + on, if any. + */ + const cursorMatchingBracket = ({ state, dispatch }) => toMatchingBracket(state, dispatch, false); + function extendSel(view, how) { + let selection = updateSel(view.state.selection, range => { + let head = how(range); + return EditorSelection.range(range.anchor, head.head, head.goalColumn); + }); + if (selection.eq(view.state.selection)) + return false; + view.dispatch(setSel(view.state, selection)); + return true; + } + function selectByChar(view, forward) { + return extendSel(view, range => view.moveByChar(range, forward)); + } + /** + Move the selection head one character to the left, while leaving + the anchor in place. + */ + const selectCharLeft = view => selectByChar(view, !ltrAtCursor(view)); + /** + Move the selection head one character to the right. + */ + const selectCharRight = view => selectByChar(view, ltrAtCursor(view)); + function selectByGroup(view, forward) { + return extendSel(view, range => view.moveByGroup(range, forward)); + } + /** + Move the selection head one [group](https://codemirror.net/6/docs/ref/#commands.cursorGroupLeft) to + the left. + */ + const selectGroupLeft = view => selectByGroup(view, !ltrAtCursor(view)); + /** + Move the selection head one group to the right. + */ + const selectGroupRight = view => selectByGroup(view, ltrAtCursor(view)); + /** + Move the selection head over the next syntactic element to the left. + */ + const selectSyntaxLeft = view => extendSel(view, range => moveBySyntax(view.state, range, !ltrAtCursor(view))); + /** + Move the selection head over the next syntactic element to the right. + */ + const selectSyntaxRight = view => extendSel(view, range => moveBySyntax(view.state, range, ltrAtCursor(view))); + function selectByLine(view, forward) { + return extendSel(view, range => view.moveVertically(range, forward)); + } + /** + Move the selection head one line up. + */ + const selectLineUp = view => selectByLine(view, false); + /** + Move the selection head one line down. + */ + const selectLineDown = view => selectByLine(view, true); + function selectByPage(view, forward) { + return extendSel(view, range => view.moveVertically(range, forward, pageHeight(view))); + } + /** + Move the selection head one page up. + */ + const selectPageUp = view => selectByPage(view, false); + /** + Move the selection head one page down. + */ + const selectPageDown = view => selectByPage(view, true); + /** + Move the selection head to the next line boundary. + */ + const selectLineBoundaryForward = view => extendSel(view, range => moveByLineBoundary(view, range, true)); + /** + Move the selection head to the previous line boundary. + */ + const selectLineBoundaryBackward = view => extendSel(view, range => moveByLineBoundary(view, range, false)); + /** + Move the selection head one line boundary to the left. + */ + const selectLineBoundaryLeft = view => extendSel(view, range => moveByLineBoundary(view, range, !ltrAtCursor(view))); + /** + Move the selection head one line boundary to the right. + */ + const selectLineBoundaryRight = view => extendSel(view, range => moveByLineBoundary(view, range, ltrAtCursor(view))); + /** + Move the selection head to the start of the line. + */ + const selectLineStart = view => extendSel(view, range => EditorSelection.cursor(view.lineBlockAt(range.head).from)); + /** + Move the selection head to the end of the line. + */ + const selectLineEnd = view => extendSel(view, range => EditorSelection.cursor(view.lineBlockAt(range.head).to)); + /** + Move the selection to the start of the document. + */ + const cursorDocStart = ({ state, dispatch }) => { + dispatch(setSel(state, { anchor: 0 })); + return true; + }; + /** + Move the selection to the end of the document. + */ + const cursorDocEnd = ({ state, dispatch }) => { + dispatch(setSel(state, { anchor: state.doc.length })); + return true; + }; + /** + Move the selection head to the start of the document. + */ + const selectDocStart = ({ state, dispatch }) => { + dispatch(setSel(state, { anchor: state.selection.main.anchor, head: 0 })); + return true; + }; + /** + Move the selection head to the end of the document. + */ + const selectDocEnd = ({ state, dispatch }) => { + dispatch(setSel(state, { anchor: state.selection.main.anchor, head: state.doc.length })); + return true; + }; + /** + Select the entire document. + */ + const selectAll = ({ state, dispatch }) => { + dispatch(state.update({ selection: { anchor: 0, head: state.doc.length }, userEvent: "select" })); + return true; + }; + /** + Expand the selection to cover entire lines. + */ + const selectLine = ({ state, dispatch }) => { + let ranges = selectedLineBlocks(state).map(({ from, to }) => EditorSelection.range(from, Math.min(to + 1, state.doc.length))); + dispatch(state.update({ selection: EditorSelection.create(ranges), userEvent: "select" })); + return true; + }; + /** + Select the next syntactic construct that is larger than the + selection. Note that this will only work insofar as the language + [provider](https://codemirror.net/6/docs/ref/#language.language) you use builds up a full + syntax tree. + */ + const selectParentSyntax = ({ state, dispatch }) => { + let selection = updateSel(state.selection, range => { + var _a; + let context = syntaxTree(state).resolveInner(range.head, 1); + while (!((context.from < range.from && context.to >= range.to) || + (context.to > range.to && context.from <= range.from) || + !((_a = context.parent) === null || _a === void 0 ? void 0 : _a.parent))) + context = context.parent; + return EditorSelection.range(context.to, context.from); + }); + dispatch(setSel(state, selection)); + return true; + }; + /** + Simplify the current selection. When multiple ranges are selected, + reduce it to its main range. Otherwise, if the selection is + non-empty, convert it to a cursor selection. + */ + const simplifySelection = ({ state, dispatch }) => { + let cur = state.selection, selection = null; + if (cur.ranges.length > 1) + selection = EditorSelection.create([cur.main]); + else if (!cur.main.empty) + selection = EditorSelection.create([EditorSelection.cursor(cur.main.head)]); + if (!selection) + return false; + dispatch(setSel(state, selection)); + return true; + }; + function deleteBy(target, by) { + if (target.state.readOnly) + return false; + let event = "delete.selection", { state } = target; + let changes = state.changeByRange(range => { + let { from, to } = range; + if (from == to) { + let towards = by(from); + if (towards < from) { + event = "delete.backward"; + towards = skipAtomic(target, towards, false); + } + else if (towards > from) { + event = "delete.forward"; + towards = skipAtomic(target, towards, true); + } + from = Math.min(from, towards); + to = Math.max(to, towards); + } + else { + from = skipAtomic(target, from, false); + to = skipAtomic(target, from, true); + } + return from == to ? { range } : { changes: { from, to }, range: EditorSelection.cursor(from) }; + }); + if (changes.changes.empty) + return false; + target.dispatch(state.update(changes, { + scrollIntoView: true, + userEvent: event, + effects: event == "delete.selection" ? EditorView.announce.of(state.phrase("Selection deleted")) : undefined + })); + return true; + } + function skipAtomic(target, pos, forward) { + if (target instanceof EditorView) + for (let ranges of target.state.facet(EditorView.atomicRanges).map(f => f(target))) + ranges.between(pos, pos, (from, to) => { + if (from < pos && to > pos) + pos = forward ? to : from; + }); + return pos; + } + const deleteByChar = (target, forward) => deleteBy(target, pos => { + let { state } = target, line = state.doc.lineAt(pos), before, targetPos; + if (!forward && pos > line.from && pos < line.from + 200 && + !/[^ \t]/.test(before = line.text.slice(0, pos - line.from))) { + if (before[before.length - 1] == "\t") + return pos - 1; + let col = countColumn(before, state.tabSize), drop = col % getIndentUnit(state) || getIndentUnit(state); + for (let i = 0; i < drop && before[before.length - 1 - i] == " "; i++) + pos--; + targetPos = pos; + } + else { + targetPos = findClusterBreak(line.text, pos - line.from, forward, forward) + line.from; + if (targetPos == pos && line.number != (forward ? state.doc.lines : 1)) + targetPos += forward ? 1 : -1; + } + return targetPos; + }); + /** + Delete the selection, or, for cursor selections, the character + before the cursor. + */ + const deleteCharBackward = view => deleteByChar(view, false); + /** + Delete the selection or the character after the cursor. + */ + const deleteCharForward = view => deleteByChar(view, true); + const deleteByGroup = (target, forward) => deleteBy(target, start => { + let pos = start, { state } = target, line = state.doc.lineAt(pos); + let categorize = state.charCategorizer(pos); + for (let cat = null;;) { + if (pos == (forward ? line.to : line.from)) { + if (pos == start && line.number != (forward ? state.doc.lines : 1)) + pos += forward ? 1 : -1; + break; + } + let next = findClusterBreak(line.text, pos - line.from, forward) + line.from; + let nextChar = line.text.slice(Math.min(pos, next) - line.from, Math.max(pos, next) - line.from); + let nextCat = categorize(nextChar); + if (cat != null && nextCat != cat) + break; + if (nextChar != " " || pos != start) + cat = nextCat; + pos = next; + } + return pos; + }); + /** + Delete the selection or backward until the end of the next + [group](https://codemirror.net/6/docs/ref/#view.EditorView.moveByGroup), only skipping groups of + whitespace when they consist of a single space. + */ + const deleteGroupBackward = target => deleteByGroup(target, false); + /** + Delete the selection or forward until the end of the next group. + */ + const deleteGroupForward = target => deleteByGroup(target, true); + /** + Delete the selection, or, if it is a cursor selection, delete to + the end of the line. If the cursor is directly at the end of the + line, delete the line break after it. + */ + const deleteToLineEnd = view => deleteBy(view, pos => { + let lineEnd = view.lineBlockAt(pos).to; + return pos < lineEnd ? lineEnd : Math.min(view.state.doc.length, pos + 1); + }); + /** + Delete the selection, or, if it is a cursor selection, delete to + the start of the line. If the cursor is directly at the start of the + line, delete the line break before it. + */ + const deleteToLineStart = view => deleteBy(view, pos => { + let lineStart = view.lineBlockAt(pos).from; + return pos > lineStart ? lineStart : Math.max(0, pos - 1); + }); + /** + Replace each selection range with a line break, leaving the cursor + on the line before the break. + */ + const splitLine = ({ state, dispatch }) => { + if (state.readOnly) + return false; + let changes = state.changeByRange(range => { + return { changes: { from: range.from, to: range.to, insert: Text.of(["", ""]) }, + range: EditorSelection.cursor(range.from) }; + }); + dispatch(state.update(changes, { scrollIntoView: true, userEvent: "input" })); + return true; + }; + /** + Flip the characters before and after the cursor(s). + */ + const transposeChars = ({ state, dispatch }) => { + if (state.readOnly) + return false; + let changes = state.changeByRange(range => { + if (!range.empty || range.from == 0 || range.from == state.doc.length) + return { range }; + let pos = range.from, line = state.doc.lineAt(pos); + let from = pos == line.from ? pos - 1 : findClusterBreak(line.text, pos - line.from, false) + line.from; + let to = pos == line.to ? pos + 1 : findClusterBreak(line.text, pos - line.from, true) + line.from; + return { changes: { from, to, insert: state.doc.slice(pos, to).append(state.doc.slice(from, pos)) }, + range: EditorSelection.cursor(to) }; + }); + if (changes.changes.empty) + return false; + dispatch(state.update(changes, { scrollIntoView: true, userEvent: "move.character" })); + return true; + }; + function selectedLineBlocks(state) { + let blocks = [], upto = -1; + for (let range of state.selection.ranges) { + let startLine = state.doc.lineAt(range.from), endLine = state.doc.lineAt(range.to); + if (!range.empty && range.to == endLine.from) + endLine = state.doc.lineAt(range.to - 1); + if (upto >= startLine.number) { + let prev = blocks[blocks.length - 1]; + prev.to = endLine.to; + prev.ranges.push(range); + } + else { + blocks.push({ from: startLine.from, to: endLine.to, ranges: [range] }); + } + upto = endLine.number + 1; + } + return blocks; + } + function moveLine(state, dispatch, forward) { + if (state.readOnly) + return false; + let changes = [], ranges = []; + for (let block of selectedLineBlocks(state)) { + if (forward ? block.to == state.doc.length : block.from == 0) + continue; + let nextLine = state.doc.lineAt(forward ? block.to + 1 : block.from - 1); + let size = nextLine.length + 1; + if (forward) { + changes.push({ from: block.to, to: nextLine.to }, { from: block.from, insert: nextLine.text + state.lineBreak }); + for (let r of block.ranges) + ranges.push(EditorSelection.range(Math.min(state.doc.length, r.anchor + size), Math.min(state.doc.length, r.head + size))); + } + else { + changes.push({ from: nextLine.from, to: block.from }, { from: block.to, insert: state.lineBreak + nextLine.text }); + for (let r of block.ranges) + ranges.push(EditorSelection.range(r.anchor - size, r.head - size)); + } + } + if (!changes.length) + return false; + dispatch(state.update({ + changes, + scrollIntoView: true, + selection: EditorSelection.create(ranges, state.selection.mainIndex), + userEvent: "move.line" + })); + return true; + } + /** + Move the selected lines up one line. + */ + const moveLineUp = ({ state, dispatch }) => moveLine(state, dispatch, false); + /** + Move the selected lines down one line. + */ + const moveLineDown = ({ state, dispatch }) => moveLine(state, dispatch, true); + function copyLine(state, dispatch, forward) { + if (state.readOnly) + return false; + let changes = []; + for (let block of selectedLineBlocks(state)) { + if (forward) + changes.push({ from: block.from, insert: state.doc.slice(block.from, block.to) + state.lineBreak }); + else + changes.push({ from: block.to, insert: state.lineBreak + state.doc.slice(block.from, block.to) }); + } + dispatch(state.update({ changes, scrollIntoView: true, userEvent: "input.copyline" })); + return true; + } + /** + Create a copy of the selected lines. Keep the selection in the top copy. + */ + const copyLineUp = ({ state, dispatch }) => copyLine(state, dispatch, false); + /** + Create a copy of the selected lines. Keep the selection in the bottom copy. + */ + const copyLineDown = ({ state, dispatch }) => copyLine(state, dispatch, true); + /** + Delete selected lines. + */ + const deleteLine = view => { + if (view.state.readOnly) + return false; + let { state } = view, changes = state.changes(selectedLineBlocks(state).map(({ from, to }) => { + if (from > 0) + from--; + else if (to < state.doc.length) + to++; + return { from, to }; + })); + let selection = updateSel(state.selection, range => view.moveVertically(range, true)).map(changes); + view.dispatch({ changes, selection, scrollIntoView: true, userEvent: "delete.line" }); + return true; + }; + function isBetweenBrackets(state, pos) { + if (/\(\)|\[\]|\{\}/.test(state.sliceDoc(pos - 1, pos + 1))) + return { from: pos, to: pos }; + let context = syntaxTree(state).resolveInner(pos); + let before = context.childBefore(pos), after = context.childAfter(pos), closedBy; + if (before && after && before.to <= pos && after.from >= pos && + (closedBy = before.type.prop(NodeProp.closedBy)) && closedBy.indexOf(after.name) > -1 && + state.doc.lineAt(before.to).from == state.doc.lineAt(after.from).from) + return { from: before.to, to: after.from }; + return null; + } + /** + Replace the selection with a newline and indent the newly created + line(s). If the current line consists only of whitespace, this + will also delete that whitespace. When the cursor is between + matching brackets, an additional newline will be inserted after + the cursor. + */ + const insertNewlineAndIndent = /*@__PURE__*/newlineAndIndent(false); + /** + Create a blank, indented line below the current line. + */ + const insertBlankLine = /*@__PURE__*/newlineAndIndent(true); + function newlineAndIndent(atEof) { + return ({ state, dispatch }) => { + if (state.readOnly) + return false; + let changes = state.changeByRange(range => { + let { from, to } = range, line = state.doc.lineAt(from); + let explode = !atEof && from == to && isBetweenBrackets(state, from); + if (atEof) + from = to = (to <= line.to ? line : state.doc.lineAt(to)).to; + let cx = new IndentContext(state, { simulateBreak: from, simulateDoubleBreak: !!explode }); + let indent = getIndentation(cx, from); + if (indent == null) + indent = /^\s*/.exec(state.doc.lineAt(from).text)[0].length; + while (to < line.to && /\s/.test(line.text[to - line.from])) + to++; + if (explode) + ({ from, to } = explode); + else if (from > line.from && from < line.from + 100 && !/\S/.test(line.text.slice(0, from))) + from = line.from; + let insert = ["", indentString(state, indent)]; + if (explode) + insert.push(indentString(state, cx.lineIndent(line.from, -1))); + return { changes: { from, to, insert: Text.of(insert) }, + range: EditorSelection.cursor(from + 1 + insert[1].length) }; + }); + dispatch(state.update(changes, { scrollIntoView: true, userEvent: "input" })); + return true; + }; + } + function changeBySelectedLine(state, f) { + let atLine = -1; + return state.changeByRange(range => { + let changes = []; + for (let pos = range.from; pos <= range.to;) { + let line = state.doc.lineAt(pos); + if (line.number > atLine && (range.empty || range.to > line.from)) { + f(line, changes, range); + atLine = line.number; + } + pos = line.to + 1; + } + let changeSet = state.changes(changes); + return { changes, + range: EditorSelection.range(changeSet.mapPos(range.anchor, 1), changeSet.mapPos(range.head, 1)) }; + }); + } + /** + Auto-indent the selected lines. This uses the [indentation service + facet](https://codemirror.net/6/docs/ref/#language.indentService) as source for auto-indent + information. + */ + const indentSelection = ({ state, dispatch }) => { + if (state.readOnly) + return false; + let updated = Object.create(null); + let context = new IndentContext(state, { overrideIndentation: start => { + let found = updated[start]; + return found == null ? -1 : found; + } }); + let changes = changeBySelectedLine(state, (line, changes, range) => { + let indent = getIndentation(context, line.from); + if (indent == null) + return; + if (!/\S/.test(line.text)) + indent = 0; + let cur = /^\s*/.exec(line.text)[0]; + let norm = indentString(state, indent); + if (cur != norm || range.from < line.from + cur.length) { + updated[line.from] = indent; + changes.push({ from: line.from, to: line.from + cur.length, insert: norm }); + } + }); + if (!changes.changes.empty) + dispatch(state.update(changes, { userEvent: "indent" })); + return true; + }; + /** + Add a [unit](https://codemirror.net/6/docs/ref/#language.indentUnit) of indentation to all selected + lines. + */ + const indentMore = ({ state, dispatch }) => { + if (state.readOnly) + return false; + dispatch(state.update(changeBySelectedLine(state, (line, changes) => { + changes.push({ from: line.from, insert: state.facet(indentUnit) }); + }), { userEvent: "input.indent" })); + return true; + }; + /** + Remove a [unit](https://codemirror.net/6/docs/ref/#language.indentUnit) of indentation from all + selected lines. + */ + const indentLess = ({ state, dispatch }) => { + if (state.readOnly) + return false; + dispatch(state.update(changeBySelectedLine(state, (line, changes) => { + let space = /^\s*/.exec(line.text)[0]; + if (!space) + return; + let col = countColumn(space, state.tabSize), keep = 0; + let insert = indentString(state, Math.max(0, col - getIndentUnit(state))); + while (keep < space.length && keep < insert.length && space.charCodeAt(keep) == insert.charCodeAt(keep)) + keep++; + changes.push({ from: line.from + keep, to: line.from + space.length, insert: insert.slice(keep) }); + }), { userEvent: "delete.dedent" })); + return true; + }; + /** + Array of key bindings containing the Emacs-style bindings that are + available on macOS by default. + + - Ctrl-b: [`cursorCharLeft`](https://codemirror.net/6/docs/ref/#commands.cursorCharLeft) ([`selectCharLeft`](https://codemirror.net/6/docs/ref/#commands.selectCharLeft) with Shift) + - Ctrl-f: [`cursorCharRight`](https://codemirror.net/6/docs/ref/#commands.cursorCharRight) ([`selectCharRight`](https://codemirror.net/6/docs/ref/#commands.selectCharRight) with Shift) + - Ctrl-p: [`cursorLineUp`](https://codemirror.net/6/docs/ref/#commands.cursorLineUp) ([`selectLineUp`](https://codemirror.net/6/docs/ref/#commands.selectLineUp) with Shift) + - Ctrl-n: [`cursorLineDown`](https://codemirror.net/6/docs/ref/#commands.cursorLineDown) ([`selectLineDown`](https://codemirror.net/6/docs/ref/#commands.selectLineDown) with Shift) + - Ctrl-a: [`cursorLineStart`](https://codemirror.net/6/docs/ref/#commands.cursorLineStart) ([`selectLineStart`](https://codemirror.net/6/docs/ref/#commands.selectLineStart) with Shift) + - Ctrl-e: [`cursorLineEnd`](https://codemirror.net/6/docs/ref/#commands.cursorLineEnd) ([`selectLineEnd`](https://codemirror.net/6/docs/ref/#commands.selectLineEnd) with Shift) + - Ctrl-d: [`deleteCharForward`](https://codemirror.net/6/docs/ref/#commands.deleteCharForward) + - Ctrl-h: [`deleteCharBackward`](https://codemirror.net/6/docs/ref/#commands.deleteCharBackward) + - Ctrl-k: [`deleteToLineEnd`](https://codemirror.net/6/docs/ref/#commands.deleteToLineEnd) + - Ctrl-Alt-h: [`deleteGroupBackward`](https://codemirror.net/6/docs/ref/#commands.deleteGroupBackward) + - Ctrl-o: [`splitLine`](https://codemirror.net/6/docs/ref/#commands.splitLine) + - Ctrl-t: [`transposeChars`](https://codemirror.net/6/docs/ref/#commands.transposeChars) + - Ctrl-v: [`cursorPageDown`](https://codemirror.net/6/docs/ref/#commands.cursorPageDown) + - Alt-v: [`cursorPageUp`](https://codemirror.net/6/docs/ref/#commands.cursorPageUp) + */ + const emacsStyleKeymap = [ + { key: "Ctrl-b", run: cursorCharLeft, shift: selectCharLeft, preventDefault: true }, + { key: "Ctrl-f", run: cursorCharRight, shift: selectCharRight }, + { key: "Ctrl-p", run: cursorLineUp, shift: selectLineUp }, + { key: "Ctrl-n", run: cursorLineDown, shift: selectLineDown }, + { key: "Ctrl-a", run: cursorLineStart, shift: selectLineStart }, + { key: "Ctrl-e", run: cursorLineEnd, shift: selectLineEnd }, + { key: "Ctrl-d", run: deleteCharForward }, + { key: "Ctrl-h", run: deleteCharBackward }, + { key: "Ctrl-k", run: deleteToLineEnd }, + { key: "Ctrl-Alt-h", run: deleteGroupBackward }, + { key: "Ctrl-o", run: splitLine }, + { key: "Ctrl-t", run: transposeChars }, + { key: "Ctrl-v", run: cursorPageDown }, + ]; + /** + An array of key bindings closely sticking to platform-standard or + widely used bindings. (This includes the bindings from + [`emacsStyleKeymap`](https://codemirror.net/6/docs/ref/#commands.emacsStyleKeymap), with their `key` + property changed to `mac`.) + + - ArrowLeft: [`cursorCharLeft`](https://codemirror.net/6/docs/ref/#commands.cursorCharLeft) ([`selectCharLeft`](https://codemirror.net/6/docs/ref/#commands.selectCharLeft) with Shift) + - ArrowRight: [`cursorCharRight`](https://codemirror.net/6/docs/ref/#commands.cursorCharRight) ([`selectCharRight`](https://codemirror.net/6/docs/ref/#commands.selectCharRight) with Shift) + - Ctrl-ArrowLeft (Alt-ArrowLeft on macOS): [`cursorGroupLeft`](https://codemirror.net/6/docs/ref/#commands.cursorGroupLeft) ([`selectGroupLeft`](https://codemirror.net/6/docs/ref/#commands.selectGroupLeft) with Shift) + - Ctrl-ArrowRight (Alt-ArrowRight on macOS): [`cursorGroupRight`](https://codemirror.net/6/docs/ref/#commands.cursorGroupRight) ([`selectGroupRight`](https://codemirror.net/6/docs/ref/#commands.selectGroupRight) with Shift) + - Cmd-ArrowLeft (on macOS): [`cursorLineStart`](https://codemirror.net/6/docs/ref/#commands.cursorLineStart) ([`selectLineStart`](https://codemirror.net/6/docs/ref/#commands.selectLineStart) with Shift) + - Cmd-ArrowRight (on macOS): [`cursorLineEnd`](https://codemirror.net/6/docs/ref/#commands.cursorLineEnd) ([`selectLineEnd`](https://codemirror.net/6/docs/ref/#commands.selectLineEnd) with Shift) + - ArrowUp: [`cursorLineUp`](https://codemirror.net/6/docs/ref/#commands.cursorLineUp) ([`selectLineUp`](https://codemirror.net/6/docs/ref/#commands.selectLineUp) with Shift) + - ArrowDown: [`cursorLineDown`](https://codemirror.net/6/docs/ref/#commands.cursorLineDown) ([`selectLineDown`](https://codemirror.net/6/docs/ref/#commands.selectLineDown) with Shift) + - Cmd-ArrowUp (on macOS): [`cursorDocStart`](https://codemirror.net/6/docs/ref/#commands.cursorDocStart) ([`selectDocStart`](https://codemirror.net/6/docs/ref/#commands.selectDocStart) with Shift) + - Cmd-ArrowDown (on macOS): [`cursorDocEnd`](https://codemirror.net/6/docs/ref/#commands.cursorDocEnd) ([`selectDocEnd`](https://codemirror.net/6/docs/ref/#commands.selectDocEnd) with Shift) + - Ctrl-ArrowUp (on macOS): [`cursorPageUp`](https://codemirror.net/6/docs/ref/#commands.cursorPageUp) ([`selectPageUp`](https://codemirror.net/6/docs/ref/#commands.selectPageUp) with Shift) + - Ctrl-ArrowDown (on macOS): [`cursorPageDown`](https://codemirror.net/6/docs/ref/#commands.cursorPageDown) ([`selectPageDown`](https://codemirror.net/6/docs/ref/#commands.selectPageDown) with Shift) + - PageUp: [`cursorPageUp`](https://codemirror.net/6/docs/ref/#commands.cursorPageUp) ([`selectPageUp`](https://codemirror.net/6/docs/ref/#commands.selectPageUp) with Shift) + - PageDown: [`cursorPageDown`](https://codemirror.net/6/docs/ref/#commands.cursorPageDown) ([`selectPageDown`](https://codemirror.net/6/docs/ref/#commands.selectPageDown) with Shift) + - Home: [`cursorLineBoundaryBackward`](https://codemirror.net/6/docs/ref/#commands.cursorLineBoundaryBackward) ([`selectLineBoundaryBackward`](https://codemirror.net/6/docs/ref/#commands.selectLineBoundaryBackward) with Shift) + - End: [`cursorLineBoundaryForward`](https://codemirror.net/6/docs/ref/#commands.cursorLineBoundaryForward) ([`selectLineBoundaryForward`](https://codemirror.net/6/docs/ref/#commands.selectLineBoundaryForward) with Shift) + - Ctrl-Home (Cmd-Home on macOS): [`cursorDocStart`](https://codemirror.net/6/docs/ref/#commands.cursorDocStart) ([`selectDocStart`](https://codemirror.net/6/docs/ref/#commands.selectDocStart) with Shift) + - Ctrl-End (Cmd-Home on macOS): [`cursorDocEnd`](https://codemirror.net/6/docs/ref/#commands.cursorDocEnd) ([`selectDocEnd`](https://codemirror.net/6/docs/ref/#commands.selectDocEnd) with Shift) + - Enter: [`insertNewlineAndIndent`](https://codemirror.net/6/docs/ref/#commands.insertNewlineAndIndent) + - Ctrl-a (Cmd-a on macOS): [`selectAll`](https://codemirror.net/6/docs/ref/#commands.selectAll) + - Backspace: [`deleteCharBackward`](https://codemirror.net/6/docs/ref/#commands.deleteCharBackward) + - Delete: [`deleteCharForward`](https://codemirror.net/6/docs/ref/#commands.deleteCharForward) + - Ctrl-Backspace (Alt-Backspace on macOS): [`deleteGroupBackward`](https://codemirror.net/6/docs/ref/#commands.deleteGroupBackward) + - Ctrl-Delete (Alt-Delete on macOS): [`deleteGroupForward`](https://codemirror.net/6/docs/ref/#commands.deleteGroupForward) + - Cmd-Backspace (macOS): [`deleteToLineStart`](https://codemirror.net/6/docs/ref/#commands.deleteToLineStart). + - Cmd-Delete (macOS): [`deleteToLineEnd`](https://codemirror.net/6/docs/ref/#commands.deleteToLineEnd). + */ + const standardKeymap = /*@__PURE__*/[ + { key: "ArrowLeft", run: cursorCharLeft, shift: selectCharLeft, preventDefault: true }, + { key: "Mod-ArrowLeft", mac: "Alt-ArrowLeft", run: cursorGroupLeft, shift: selectGroupLeft, preventDefault: true }, + { mac: "Cmd-ArrowLeft", run: cursorLineBoundaryLeft, shift: selectLineBoundaryLeft, preventDefault: true }, + { key: "ArrowRight", run: cursorCharRight, shift: selectCharRight, preventDefault: true }, + { key: "Mod-ArrowRight", mac: "Alt-ArrowRight", run: cursorGroupRight, shift: selectGroupRight, preventDefault: true }, + { mac: "Cmd-ArrowRight", run: cursorLineBoundaryRight, shift: selectLineBoundaryRight, preventDefault: true }, + { key: "ArrowUp", run: cursorLineUp, shift: selectLineUp, preventDefault: true }, + { mac: "Cmd-ArrowUp", run: cursorDocStart, shift: selectDocStart }, + { mac: "Ctrl-ArrowUp", run: cursorPageUp, shift: selectPageUp }, + { key: "ArrowDown", run: cursorLineDown, shift: selectLineDown, preventDefault: true }, + { mac: "Cmd-ArrowDown", run: cursorDocEnd, shift: selectDocEnd }, + { mac: "Ctrl-ArrowDown", run: cursorPageDown, shift: selectPageDown }, + { key: "PageUp", run: cursorPageUp, shift: selectPageUp }, + { key: "PageDown", run: cursorPageDown, shift: selectPageDown }, + { key: "Home", run: cursorLineBoundaryBackward, shift: selectLineBoundaryBackward, preventDefault: true }, + { key: "Mod-Home", run: cursorDocStart, shift: selectDocStart }, + { key: "End", run: cursorLineBoundaryForward, shift: selectLineBoundaryForward, preventDefault: true }, + { key: "Mod-End", run: cursorDocEnd, shift: selectDocEnd }, + { key: "Enter", run: insertNewlineAndIndent }, + { key: "Mod-a", run: selectAll }, + { key: "Backspace", run: deleteCharBackward, shift: deleteCharBackward }, + { key: "Delete", run: deleteCharForward }, + { key: "Mod-Backspace", mac: "Alt-Backspace", run: deleteGroupBackward }, + { key: "Mod-Delete", mac: "Alt-Delete", run: deleteGroupForward }, + { mac: "Mod-Backspace", run: deleteToLineStart }, + { mac: "Mod-Delete", run: deleteToLineEnd } + ].concat(/*@__PURE__*/emacsStyleKeymap.map(b => ({ mac: b.key, run: b.run, shift: b.shift }))); + /** + The default keymap. Includes all bindings from + [`standardKeymap`](https://codemirror.net/6/docs/ref/#commands.standardKeymap) plus the following: + + - Alt-ArrowLeft (Ctrl-ArrowLeft on macOS): [`cursorSyntaxLeft`](https://codemirror.net/6/docs/ref/#commands.cursorSyntaxLeft) ([`selectSyntaxLeft`](https://codemirror.net/6/docs/ref/#commands.selectSyntaxLeft) with Shift) + - Alt-ArrowRight (Ctrl-ArrowRight on macOS): [`cursorSyntaxRight`](https://codemirror.net/6/docs/ref/#commands.cursorSyntaxRight) ([`selectSyntaxRight`](https://codemirror.net/6/docs/ref/#commands.selectSyntaxRight) with Shift) + - Alt-ArrowUp: [`moveLineUp`](https://codemirror.net/6/docs/ref/#commands.moveLineUp) + - Alt-ArrowDown: [`moveLineDown`](https://codemirror.net/6/docs/ref/#commands.moveLineDown) + - Shift-Alt-ArrowUp: [`copyLineUp`](https://codemirror.net/6/docs/ref/#commands.copyLineUp) + - Shift-Alt-ArrowDown: [`copyLineDown`](https://codemirror.net/6/docs/ref/#commands.copyLineDown) + - Escape: [`simplifySelection`](https://codemirror.net/6/docs/ref/#commands.simplifySelection) + - Ctrl-Enter (Comd-Enter on macOS): [`insertBlankLine`](https://codemirror.net/6/docs/ref/#commands.insertBlankLine) + - Alt-l (Ctrl-l on macOS): [`selectLine`](https://codemirror.net/6/docs/ref/#commands.selectLine) + - Ctrl-i (Cmd-i on macOS): [`selectParentSyntax`](https://codemirror.net/6/docs/ref/#commands.selectParentSyntax) + - Ctrl-[ (Cmd-[ on macOS): [`indentLess`](https://codemirror.net/6/docs/ref/#commands.indentLess) + - Ctrl-] (Cmd-] on macOS): [`indentMore`](https://codemirror.net/6/docs/ref/#commands.indentMore) + - Ctrl-Alt-\\ (Cmd-Alt-\\ on macOS): [`indentSelection`](https://codemirror.net/6/docs/ref/#commands.indentSelection) + - Shift-Ctrl-k (Shift-Cmd-k on macOS): [`deleteLine`](https://codemirror.net/6/docs/ref/#commands.deleteLine) + - Shift-Ctrl-\\ (Shift-Cmd-\\ on macOS): [`cursorMatchingBracket`](https://codemirror.net/6/docs/ref/#commands.cursorMatchingBracket) + - Ctrl-/ (Cmd-/ on macOS): [`toggleComment`](https://codemirror.net/6/docs/ref/#commands.toggleComment). + - Shift-Alt-a: [`toggleBlockComment`](https://codemirror.net/6/docs/ref/#commands.toggleBlockComment). + */ + const defaultKeymap = /*@__PURE__*/[ + { key: "Alt-ArrowLeft", mac: "Ctrl-ArrowLeft", run: cursorSyntaxLeft, shift: selectSyntaxLeft }, + { key: "Alt-ArrowRight", mac: "Ctrl-ArrowRight", run: cursorSyntaxRight, shift: selectSyntaxRight }, + { key: "Alt-ArrowUp", run: moveLineUp }, + { key: "Shift-Alt-ArrowUp", run: copyLineUp }, + { key: "Alt-ArrowDown", run: moveLineDown }, + { key: "Shift-Alt-ArrowDown", run: copyLineDown }, + { key: "Escape", run: simplifySelection }, + { key: "Mod-Enter", run: insertBlankLine }, + { key: "Alt-l", mac: "Ctrl-l", run: selectLine }, + { key: "Mod-i", run: selectParentSyntax, preventDefault: true }, + { key: "Mod-[", run: indentLess }, + { key: "Mod-]", run: indentMore }, + { key: "Mod-Alt-\\", run: indentSelection }, + { key: "Shift-Mod-k", run: deleteLine }, + { key: "Shift-Mod-\\", run: cursorMatchingBracket }, + { key: "Mod-/", run: toggleComment }, + { key: "Alt-A", run: toggleBlockComment } + ].concat(standardKeymap); + + function crelt() { + var elt = arguments[0]; + if (typeof elt == "string") elt = document.createElement(elt); + var i = 1, next = arguments[1]; + if (next && typeof next == "object" && next.nodeType == null && !Array.isArray(next)) { + for (var name in next) if (Object.prototype.hasOwnProperty.call(next, name)) { + var value = next[name]; + if (typeof value == "string") elt.setAttribute(name, value); + else if (value != null) elt[name] = value; + } + i++; } + for (; i < arguments.length; i++) add(elt, arguments[i]); + return elt + } - - var loadAll_1 = loadAll$1; - var load_1 = load$1; - - var loader$2 = { - loadAll: loadAll_1, - load: load_1 - }; - var load = loader$2.load; - - const logger$9 = getLogger('py-env'); - // Premise used to connect to the first available runtime (can be pyodide or others) - let runtime; - runtimeLoaded.subscribe(value => { - runtime = value; - }); - class PyEnv extends HTMLElement { - shadow; - wrapper; - code; - environment; - runtime; - env; - paths; - constructor() { - super(); - this.shadow = this.attachShadow({ mode: 'open' }); - this.wrapper = document.createElement('slot'); - } - connectedCallback() { - logger$9.info("The <py-env> tag is deprecated, please use <py-config> instead."); - this.code = this.innerHTML; - this.innerHTML = ''; - const env = []; - const paths = []; - this.environment = load(this.code); - if (this.environment === undefined) - return; - for (const entry of Array.isArray(this.environment) ? this.environment : []) { - if (typeof entry == 'string') { - env.push(entry); - } - else if (entry && typeof entry === 'object') { - const obj = entry; - for (const path of Array.isArray(obj.paths) ? obj.paths : []) { - if (typeof path === 'string') { - paths.push(path); - } - } - } - } - this.env = env; - this.paths = paths; - async function loadEnv() { - logger$9.info("Loading env: ", env); - await runtime.installPackage(env); - } - async function loadPaths() { - logger$9.info("Paths to load: ", paths); - for (const singleFile of paths) { - logger$9.info(` loading path: ${singleFile}`); - try { - await runtime.loadFromFile(singleFile); - } - catch (e) { - //Should we still export full error contents to console? - handleFetchError(e, singleFile); - } - } - logger$9.info("All paths loaded"); - } - addInitializer(loadEnv); - addInitializer(loadPaths); - } + function add(elt, child) { + if (typeof child == "string") { + elt.appendChild(document.createTextNode(child)); + } else if (child == null) ; else if (child.nodeType != null) { + elt.appendChild(child); + } else if (Array.isArray(child)) { + for (var i = 0; i < child.length; i++) add(elt, child[i]); + } else { + throw new RangeError("Unsupported child node: " + child) } + } - const logger$8 = getLogger('py-loader'); - class PyLoader extends BaseEvalElement { - widths; - label; - mount_name; - details; - operation; - constructor() { - super(); - } - connectedCallback() { - this.innerHTML = `<div id="pyscript_loading_splash" class="py-overlay"> + const basicNormalize = typeof String.prototype.normalize == "function" + ? x => x.normalize("NFKD") : x => x; + /** + A search cursor provides an iterator over text matches in a + document. + */ + class SearchCursor { + /** + Create a text cursor. The query is the search string, `from` to + `to` provides the region to search. + + When `normalize` is given, it will be called, on both the query + string and the content it is matched against, before comparing. + You can, for example, create a case-insensitive search by + passing `s => s.toLowerCase()`. + + Text is always normalized with + [`.normalize("NFKD")`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/normalize) + (when supported). + */ + constructor(text, query, from = 0, to = text.length, normalize, test) { + this.test = test; + /** + The current match (only holds a meaningful value after + [`next`](https://codemirror.net/6/docs/ref/#search.SearchCursor.next) has been called and when + `done` is false). + */ + this.value = { from: 0, to: 0 }; + /** + Whether the end of the iterated region has been reached. + */ + this.done = false; + this.matches = []; + this.buffer = ""; + this.bufferPos = 0; + this.iter = text.iterRange(from, to); + this.bufferStart = from; + this.normalize = normalize ? x => normalize(basicNormalize(x)) : basicNormalize; + this.query = this.normalize(query); + } + peek() { + if (this.bufferPos == this.buffer.length) { + this.bufferStart += this.buffer.length; + this.iter.next(); + if (this.iter.done) + return -1; + this.bufferPos = 0; + this.buffer = this.iter.value; + } + return codePointAt(this.buffer, this.bufferPos); + } + /** + Look for the next match. Updates the iterator's + [`value`](https://codemirror.net/6/docs/ref/#search.SearchCursor.value) and + [`done`](https://codemirror.net/6/docs/ref/#search.SearchCursor.done) properties. Should be called + at least once before using the cursor. + */ + next() { + while (this.matches.length) + this.matches.pop(); + return this.nextOverlapping(); + } + /** + The `next` method will ignore matches that partially overlap a + previous match. This method behaves like `next`, but includes + such matches. + */ + nextOverlapping() { + for (;;) { + let next = this.peek(); + if (next < 0) { + this.done = true; + return this; + } + let str = fromCodePoint(next), start = this.bufferStart + this.bufferPos; + this.bufferPos += codePointSize(next); + let norm = this.normalize(str); + for (let i = 0, pos = start;; i++) { + let code = norm.charCodeAt(i); + let match = this.match(code, pos); + if (match) { + this.value = match; + return this; + } + if (i == norm.length - 1) + break; + if (pos == start && i < str.length && str.charCodeAt(i) == code) + pos++; + } + } + } + match(code, pos) { + let match = null; + for (let i = 0; i < this.matches.length; i += 2) { + let index = this.matches[i], keep = false; + if (this.query.charCodeAt(index) == code) { + if (index == this.query.length - 1) { + match = { from: this.matches[i + 1], to: pos + 1 }; + } + else { + this.matches[i]++; + keep = true; + } + } + if (!keep) { + this.matches.splice(i, 2); + i -= 2; + } + } + if (this.query.charCodeAt(0) == code) { + if (this.query.length == 1) + match = { from: pos, to: pos + 1 }; + else + this.matches.push(1, pos); + } + if (match && this.test && !this.test(match.from, match.to, this.buffer, this.bufferPos)) + match = null; + return match; + } + } + if (typeof Symbol != "undefined") + SearchCursor.prototype[Symbol.iterator] = function () { return this; }; + + const empty = { from: -1, to: -1, match: /*@__PURE__*//.*/.exec("") }; + const baseFlags = "gm" + (/x/.unicode == null ? "" : "u"); + /** + This class is similar to [`SearchCursor`](https://codemirror.net/6/docs/ref/#search.SearchCursor) + but searches for a regular expression pattern instead of a plain + string. + */ + class RegExpCursor { + /** + Create a cursor that will search the given range in the given + document. `query` should be the raw pattern (as you'd pass it to + `new RegExp`). + */ + constructor(text, query, options, from = 0, to = text.length) { + this.text = text; + this.to = to; + this.curLine = ""; + /** + Set to `true` when the cursor has reached the end of the search + range. + */ + this.done = false; + /** + Will contain an object with the extent of the match and the + match object when [`next`](https://codemirror.net/6/docs/ref/#search.RegExpCursor.next) + sucessfully finds a match. + */ + this.value = empty; + if (/\\[sWDnr]|\n|\r|\[\^/.test(query)) + return new MultilineRegExpCursor(text, query, options, from, to); + this.re = new RegExp(query, baseFlags + ((options === null || options === void 0 ? void 0 : options.ignoreCase) ? "i" : "")); + this.test = options === null || options === void 0 ? void 0 : options.test; + this.iter = text.iter(); + let startLine = text.lineAt(from); + this.curLineStart = startLine.from; + this.matchPos = toCharEnd(text, from); + this.getLine(this.curLineStart); + } + getLine(skip) { + this.iter.next(skip); + if (this.iter.lineBreak) { + this.curLine = ""; + } + else { + this.curLine = this.iter.value; + if (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; + if (this.curLineStart > this.to) + this.curLine = ""; + else + this.getLine(0); + } + /** + Move to the next match, if there is one. + */ + next() { + for (let off = this.matchPos - this.curLineStart;;) { + this.re.lastIndex = off; + let match = this.matchPos <= this.to && this.re.exec(this.curLine); + if (match) { + let from = this.curLineStart + match.index, to = from + match[0].length; + this.matchPos = toCharEnd(this.text, to + (from == to ? 1 : 0)); + if (from == this.curLine.length) + this.nextLine(); + if ((from < to || from > this.value.to) && (!this.test || this.test(from, to, match))) { + this.value = { from, to, match }; + return this; + } + off = this.matchPos - this.curLineStart; + } + else if (this.curLineStart + this.curLine.length < this.to) { + this.nextLine(); + off = 0; + } + else { + this.done = true; + return this; + } + } + } + } + const flattened = /*@__PURE__*/new WeakMap(); + // Reusable (partially) flattened document strings + class FlattenedDoc { + constructor(from, text) { + this.from = from; + this.text = text; + } + get to() { return this.from + this.text.length; } + static get(doc, from, to) { + let cached = flattened.get(doc); + if (!cached || cached.from >= to || cached.to <= from) { + let flat = new FlattenedDoc(from, doc.sliceString(from, to)); + flattened.set(doc, flat); + return flat; + } + if (cached.from == from && cached.to == to) + return cached; + let { text, from: cachedFrom } = cached; + if (cachedFrom > from) { + text = doc.sliceString(from, cachedFrom) + text; + cachedFrom = from; + } + if (cached.to < to) + text += doc.sliceString(cached.to, to); + flattened.set(doc, new FlattenedDoc(cachedFrom, text)); + return new FlattenedDoc(from, text.slice(from - cachedFrom, to - cachedFrom)); + } + } + class MultilineRegExpCursor { + constructor(text, query, options, from, to) { + this.text = text; + this.to = to; + this.done = false; + this.value = empty; + this.matchPos = toCharEnd(text, from); + this.re = new RegExp(query, baseFlags + ((options === null || options === void 0 ? void 0 : options.ignoreCase) ? "i" : "")); + this.test = options === null || options === void 0 ? void 0 : options.test; + this.flat = FlattenedDoc.get(text, from, this.chunkEnd(from + 5000 /* Chunk.Base */)); + } + chunkEnd(pos) { + return pos >= this.to ? this.to : this.text.lineAt(pos).to; + } + next() { + for (;;) { + let off = this.re.lastIndex = this.matchPos - this.flat.from; + let match = this.re.exec(this.flat.text); + // Skip empty matches directly after the last match + if (match && !match[0] && match.index == off) { + this.re.lastIndex = off + 1; + match = this.re.exec(this.flat.text); + } + if (match) { + let from = this.flat.from + match.index, to = from + match[0].length; + // If a match goes almost to the end of a noncomplete chunk, try + // again, since it'll likely be able to match more + if ((this.flat.to >= this.to || match.index + match[0].length <= this.flat.text.length - 10) && + (!this.test || this.test(from, to, match))) { + this.value = { from, to, match }; + this.matchPos = toCharEnd(this.text, to + (from == to ? 1 : 0)); + return this; + } + } + if (this.flat.to == this.to) { + this.done = true; + return this; + } + // Grow the flattened doc + this.flat = FlattenedDoc.get(this.text, this.flat.from, this.chunkEnd(this.flat.from + this.flat.text.length * 2)); + } + } + } + if (typeof Symbol != "undefined") { + RegExpCursor.prototype[Symbol.iterator] = MultilineRegExpCursor.prototype[Symbol.iterator] = + function () { return this; }; + } + function validRegExp(source) { + try { + new RegExp(source, baseFlags); + return true; + } + catch (_a) { + return false; + } + } + function toCharEnd(text, pos) { + if (pos >= text.length) + return pos; + let line = text.lineAt(pos), next; + while (pos < line.to && (next = line.text.charCodeAt(pos - line.from)) >= 0xDC00 && next < 0xE000) + pos++; + return pos; + } + + function createLineDialog(view) { + let input = crelt("input", { class: "cm-textfield", name: "line" }); + let dom = crelt("form", { + class: "cm-gotoLine", + onkeydown: (event) => { + if (event.keyCode == 27) { // Escape + event.preventDefault(); + view.dispatch({ effects: dialogEffect.of(false) }); + view.focus(); + } + else if (event.keyCode == 13) { // Enter + event.preventDefault(); + go(); + } + }, + onsubmit: (event) => { + event.preventDefault(); + go(); + } + }, crelt("label", view.state.phrase("Go to line"), ": ", input), " ", crelt("button", { class: "cm-button", type: "submit" }, view.state.phrase("go"))); + function go() { + let match = /^([+-])?(\d+)?(:\d+)?(%)?$/.exec(input.value); + if (!match) + return; + let { state } = view, startLine = state.doc.lineAt(state.selection.main.head); + let [, sign, ln, cl, percent] = match; + let col = cl ? +cl.slice(1) : 0; + let line = ln ? +ln : startLine.number; + if (ln && percent) { + let pc = line / 100; + if (sign) + pc = pc * (sign == "-" ? -1 : 1) + (startLine.number / state.doc.lines); + line = Math.round(state.doc.lines * pc); + } + else if (ln && sign) { + line = line * (sign == "-" ? -1 : 1) + startLine.number; + } + let docLine = state.doc.line(Math.max(1, Math.min(state.doc.lines, line))); + view.dispatch({ + effects: dialogEffect.of(false), + selection: EditorSelection.cursor(docLine.from + Math.max(0, Math.min(col, docLine.length))), + scrollIntoView: true + }); + view.focus(); + } + return { dom }; + } + const dialogEffect = /*@__PURE__*/StateEffect.define(); + const dialogField = /*@__PURE__*/StateField.define({ + create() { return true; }, + update(value, tr) { + for (let e of tr.effects) + if (e.is(dialogEffect)) + value = e.value; + return value; + }, + provide: f => showPanel.from(f, val => val ? createLineDialog : null) + }); + /** + Command that shows a dialog asking the user for a line number, and + when a valid position is provided, moves the cursor to that line. + + Supports line numbers, relative line offsets prefixed with `+` or + `-`, document percentages suffixed with `%`, and an optional + column position by adding `:` and a second number after the line + number. + + The dialog can be styled with the `panel.gotoLine` theme + selector. + */ + const gotoLine = view => { + let panel = getPanel(view, createLineDialog); + if (!panel) { + let effects = [dialogEffect.of(true)]; + if (view.state.field(dialogField, false) == null) + effects.push(StateEffect.appendConfig.of([dialogField, baseTheme$1$1])); + view.dispatch({ effects }); + panel = getPanel(view, createLineDialog); + } + if (panel) + panel.dom.querySelector("input").focus(); + return true; + }; + const baseTheme$1$1 = /*@__PURE__*/EditorView.baseTheme({ + ".cm-panel.cm-gotoLine": { + padding: "2px 6px 4px", + "& label": { fontSize: "80%" } + } + }); + + const defaultHighlightOptions = { + highlightWordAroundCursor: false, + minSelectionLength: 1, + maxMatches: 100, + wholeWords: false + }; + const highlightConfig = /*@__PURE__*/Facet.define({ + combine(options) { + return combineConfig(options, defaultHighlightOptions, { + highlightWordAroundCursor: (a, b) => a || b, + minSelectionLength: Math.min, + maxMatches: Math.min + }); + } + }); + /** + This extension highlights text that matches the selection. It uses + the `"cm-selectionMatch"` class for the highlighting. When + `highlightWordAroundCursor` is enabled, the word at the cursor + itself will be highlighted with `"cm-selectionMatch-main"`. + */ + function highlightSelectionMatches(options) { + let ext = [defaultTheme, matchHighlighter]; + if (options) + ext.push(highlightConfig.of(options)); + return ext; + } + const matchDeco = /*@__PURE__*/Decoration.mark({ class: "cm-selectionMatch" }); + const mainMatchDeco = /*@__PURE__*/Decoration.mark({ class: "cm-selectionMatch cm-selectionMatch-main" }); + // Whether the characters directly outside the given positions are non-word characters + function insideWordBoundaries(check, state, from, to) { + return (from == 0 || check(state.sliceDoc(from - 1, from)) != CharCategory.Word) && + (to == state.doc.length || check(state.sliceDoc(to, to + 1)) != CharCategory.Word); + } + // Whether the characters directly at the given positions are word characters + function insideWord(check, state, from, to) { + return check(state.sliceDoc(from, from + 1)) == CharCategory.Word + && check(state.sliceDoc(to - 1, to)) == CharCategory.Word; + } + const matchHighlighter = /*@__PURE__*/ViewPlugin.fromClass(class { + constructor(view) { + this.decorations = this.getDeco(view); + } + update(update) { + if (update.selectionSet || update.docChanged || update.viewportChanged) + this.decorations = this.getDeco(update.view); + } + getDeco(view) { + let conf = view.state.facet(highlightConfig); + let { state } = view, sel = state.selection; + if (sel.ranges.length > 1) + return Decoration.none; + let range = sel.main, query, check = null; + if (range.empty) { + if (!conf.highlightWordAroundCursor) + return Decoration.none; + let word = state.wordAt(range.head); + if (!word) + return Decoration.none; + check = state.charCategorizer(range.head); + query = state.sliceDoc(word.from, word.to); + } + else { + let len = range.to - range.from; + if (len < conf.minSelectionLength || len > 200) + return Decoration.none; + if (conf.wholeWords) { + query = state.sliceDoc(range.from, range.to); // TODO: allow and include leading/trailing space? + check = state.charCategorizer(range.head); + if (!(insideWordBoundaries(check, state, range.from, range.to) + && insideWord(check, state, range.from, range.to))) + return Decoration.none; + } + else { + query = state.sliceDoc(range.from, range.to).trim(); + if (!query) + return Decoration.none; + } + } + let deco = []; + for (let part of view.visibleRanges) { + let cursor = new SearchCursor(state.doc, query, part.from, part.to); + while (!cursor.next().done) { + let { from, to } = cursor.value; + if (!check || insideWordBoundaries(check, state, from, to)) { + if (range.empty && from <= range.from && to >= range.to) + deco.push(mainMatchDeco.range(from, to)); + else if (from >= range.to || to <= range.from) + deco.push(matchDeco.range(from, to)); + if (deco.length > conf.maxMatches) + return Decoration.none; + } + } + } + return Decoration.set(deco); + } + }, { + decorations: v => v.decorations + }); + const defaultTheme = /*@__PURE__*/EditorView.baseTheme({ + ".cm-selectionMatch": { backgroundColor: "#99ff7780" }, + ".cm-searchMatch .cm-selectionMatch": { backgroundColor: "transparent" } + }); + // Select the words around the cursors. + const selectWord = ({ state, dispatch }) => { + let { selection } = state; + let newSel = EditorSelection.create(selection.ranges.map(range => state.wordAt(range.head) || EditorSelection.cursor(range.head)), selection.mainIndex); + if (newSel.eq(selection)) + return false; + dispatch(state.update({ selection: newSel })); + return true; + }; + // Find next occurrence of query relative to last cursor. Wrap around + // the document if there are no more matches. + function findNextOccurrence(state, query) { + let { main, ranges } = state.selection; + let word = state.wordAt(main.head), fullWord = word && word.from == main.from && word.to == main.to; + for (let cycled = false, cursor = new SearchCursor(state.doc, query, ranges[ranges.length - 1].to);;) { + cursor.next(); + if (cursor.done) { + if (cycled) + return null; + cursor = new SearchCursor(state.doc, query, 0, Math.max(0, ranges[ranges.length - 1].from - 1)); + cycled = true; + } + else { + if (cycled && ranges.some(r => r.from == cursor.value.from)) + continue; + if (fullWord) { + let word = state.wordAt(cursor.value.from); + if (!word || word.from != cursor.value.from || word.to != cursor.value.to) + continue; + } + return cursor.value; + } + } + } + /** + Select next occurrence of the current selection. Expand selection + to the surrounding word when the selection is empty. + */ + const selectNextOccurrence = ({ state, dispatch }) => { + let { ranges } = state.selection; + if (ranges.some(sel => sel.from === sel.to)) + return selectWord({ state, dispatch }); + let searchedText = state.sliceDoc(ranges[0].from, ranges[0].to); + if (state.selection.ranges.some(r => state.sliceDoc(r.from, r.to) != searchedText)) + return false; + let range = findNextOccurrence(state, searchedText); + if (!range) + return false; + dispatch(state.update({ + selection: state.selection.addRange(EditorSelection.range(range.from, range.to), false), + effects: EditorView.scrollIntoView(range.to) + })); + return true; + }; + + const searchConfigFacet = /*@__PURE__*/Facet.define({ + combine(configs) { + return combineConfig(configs, { + top: false, + caseSensitive: false, + literal: false, + wholeWord: false, + createPanel: view => new SearchPanel(view) + }); + } + }); + /** + A search query. Part of the editor's search state. + */ + class SearchQuery { + /** + Create a query object. + */ + constructor(config) { + this.search = config.search; + this.caseSensitive = !!config.caseSensitive; + this.literal = !!config.literal; + this.regexp = !!config.regexp; + this.replace = config.replace || ""; + this.valid = !!this.search && (!this.regexp || validRegExp(this.search)); + this.unquoted = this.literal ? this.search : this.search.replace(/\\([nrt\\])/g, (_, ch) => ch == "n" ? "\n" : ch == "r" ? "\r" : ch == "t" ? "\t" : "\\"); + this.wholeWord = !!config.wholeWord; + } + /** + Compare this query to another query. + */ + eq(other) { + return this.search == other.search && this.replace == other.replace && + this.caseSensitive == other.caseSensitive && this.regexp == other.regexp && + this.wholeWord == other.wholeWord; + } + /** + @internal + */ + create() { + return this.regexp ? new RegExpQuery(this) : new StringQuery(this); + } + /** + Get a search cursor for this query, searching through the given + range in the given state. + */ + getCursor(state, from = 0, to) { + let st = state.doc ? state : EditorState.create({ doc: state }); + if (to == null) + to = st.doc.length; + return this.regexp ? regexpCursor(this, st, from, to) : stringCursor(this, st, from, to); + } + } + class QueryType { + constructor(spec) { + this.spec = spec; + } + } + function stringCursor(spec, state, from, to) { + return new SearchCursor(state.doc, spec.unquoted, from, to, spec.caseSensitive ? undefined : x => x.toLowerCase(), spec.wholeWord ? stringWordTest(state.doc, state.charCategorizer(state.selection.main.head)) : undefined); + } + function stringWordTest(doc, categorizer) { + return (from, to, buf, bufPos) => { + if (bufPos > from || bufPos + buf.length < to) { + bufPos = Math.max(0, from - 2); + buf = doc.sliceString(bufPos, Math.min(doc.length, to + 2)); + } + return (categorizer(charBefore(buf, from - bufPos)) != CharCategory.Word || + categorizer(charAfter(buf, from - bufPos)) != CharCategory.Word) && + (categorizer(charAfter(buf, to - bufPos)) != CharCategory.Word || + categorizer(charBefore(buf, to - bufPos)) != CharCategory.Word); + }; + } + class StringQuery extends QueryType { + constructor(spec) { + super(spec); + } + nextMatch(state, curFrom, curTo) { + let cursor = stringCursor(this.spec, state, curTo, state.doc.length).nextOverlapping(); + if (cursor.done) + cursor = stringCursor(this.spec, state, 0, curFrom).nextOverlapping(); + return cursor.done ? null : cursor.value; + } + // Searching in reverse is, rather than implementing inverted search + // cursor, done by scanning chunk after chunk forward. + prevMatchInRange(state, from, to) { + for (let pos = to;;) { + let start = Math.max(from, pos - 10000 /* FindPrev.ChunkSize */ - this.spec.unquoted.length); + let cursor = stringCursor(this.spec, state, start, pos), range = null; + while (!cursor.nextOverlapping().done) + range = cursor.value; + if (range) + return range; + if (start == from) + return null; + pos -= 10000 /* FindPrev.ChunkSize */; + } + } + prevMatch(state, curFrom, curTo) { + return this.prevMatchInRange(state, 0, curFrom) || + this.prevMatchInRange(state, curTo, state.doc.length); + } + getReplacement(_result) { return this.spec.replace; } + matchAll(state, limit) { + let cursor = stringCursor(this.spec, state, 0, state.doc.length), ranges = []; + while (!cursor.next().done) { + if (ranges.length >= limit) + return null; + ranges.push(cursor.value); + } + return ranges; + } + highlight(state, from, to, add) { + let cursor = stringCursor(this.spec, state, Math.max(0, from - this.spec.unquoted.length), Math.min(to + this.spec.unquoted.length, state.doc.length)); + while (!cursor.next().done) + add(cursor.value.from, cursor.value.to); + } + } + function regexpCursor(spec, state, from, to) { + return new RegExpCursor(state.doc, spec.search, { + ignoreCase: !spec.caseSensitive, + test: spec.wholeWord ? regexpWordTest(state.charCategorizer(state.selection.main.head)) : undefined + }, from, to); + } + function charBefore(str, index) { + return str.slice(findClusterBreak(str, index, false), index); + } + function charAfter(str, index) { + return str.slice(index, findClusterBreak(str, index)); + } + function regexpWordTest(categorizer) { + return (_from, _to, match) => !match[0].length || + (categorizer(charBefore(match.input, match.index)) != CharCategory.Word || + categorizer(charAfter(match.input, match.index)) != CharCategory.Word) && + (categorizer(charAfter(match.input, match.index + match[0].length)) != CharCategory.Word || + categorizer(charBefore(match.input, match.index + match[0].length)) != CharCategory.Word); + } + class RegExpQuery extends QueryType { + nextMatch(state, curFrom, curTo) { + let cursor = regexpCursor(this.spec, state, curTo, state.doc.length).next(); + if (cursor.done) + cursor = regexpCursor(this.spec, state, 0, curFrom).next(); + return cursor.done ? null : cursor.value; + } + prevMatchInRange(state, from, to) { + for (let size = 1;; size++) { + let start = Math.max(from, to - size * 10000 /* FindPrev.ChunkSize */); + let cursor = regexpCursor(this.spec, state, start, to), range = null; + while (!cursor.next().done) + range = cursor.value; + if (range && (start == from || range.from > start + 10)) + return range; + if (start == from) + return null; + } + } + prevMatch(state, curFrom, curTo) { + return this.prevMatchInRange(state, 0, curFrom) || + this.prevMatchInRange(state, curTo, state.doc.length); + } + getReplacement(result) { + return this.spec.replace.replace(/\$([$&\d+])/g, (m, i) => i == "$" ? "$" + : i == "&" ? result.match[0] + : i != "0" && +i < result.match.length ? result.match[i] + : m); + } + matchAll(state, limit) { + let cursor = regexpCursor(this.spec, state, 0, state.doc.length), ranges = []; + while (!cursor.next().done) { + if (ranges.length >= limit) + return null; + ranges.push(cursor.value); + } + return ranges; + } + highlight(state, from, to, add) { + let cursor = regexpCursor(this.spec, state, Math.max(0, from - 250 /* RegExp.HighlightMargin */), Math.min(to + 250 /* RegExp.HighlightMargin */, state.doc.length)); + while (!cursor.next().done) + add(cursor.value.from, cursor.value.to); + } + } + /** + A state effect that updates the current search query. Note that + this only has an effect if the search state has been initialized + (by including [`search`](https://codemirror.net/6/docs/ref/#search.search) in your configuration or + by running [`openSearchPanel`](https://codemirror.net/6/docs/ref/#search.openSearchPanel) at least + once). + */ + const setSearchQuery = /*@__PURE__*/StateEffect.define(); + const togglePanel$1 = /*@__PURE__*/StateEffect.define(); + const searchState = /*@__PURE__*/StateField.define({ + create(state) { + return new SearchState(defaultQuery(state).create(), null); + }, + update(value, tr) { + for (let effect of tr.effects) { + if (effect.is(setSearchQuery)) + value = new SearchState(effect.value.create(), value.panel); + else if (effect.is(togglePanel$1)) + value = new SearchState(value.query, effect.value ? createSearchPanel : null); + } + return value; + }, + provide: f => showPanel.from(f, val => val.panel) + }); + class SearchState { + constructor(query, panel) { + this.query = query; + this.panel = panel; + } + } + const matchMark = /*@__PURE__*/Decoration.mark({ class: "cm-searchMatch" }), selectedMatchMark = /*@__PURE__*/Decoration.mark({ class: "cm-searchMatch cm-searchMatch-selected" }); + const searchHighlighter = /*@__PURE__*/ViewPlugin.fromClass(class { + constructor(view) { + this.view = view; + this.decorations = this.highlight(view.state.field(searchState)); + } + update(update) { + let state = update.state.field(searchState); + if (state != update.startState.field(searchState) || update.docChanged || update.selectionSet || update.viewportChanged) + this.decorations = this.highlight(state); + } + highlight({ query, panel }) { + if (!panel || !query.spec.valid) + return Decoration.none; + let { view } = this; + let builder = new RangeSetBuilder(); + for (let i = 0, ranges = view.visibleRanges, l = ranges.length; i < l; i++) { + let { from, to } = ranges[i]; + while (i < l - 1 && to > ranges[i + 1].from - 2 * 250 /* RegExp.HighlightMargin */) + to = ranges[++i].to; + query.highlight(view.state, from, to, (from, to) => { + let selected = view.state.selection.ranges.some(r => r.from == from && r.to == to); + builder.add(from, to, selected ? selectedMatchMark : matchMark); + }); + } + return builder.finish(); + } + }, { + decorations: v => v.decorations + }); + function searchCommand(f) { + return view => { + let state = view.state.field(searchState, false); + return state && state.query.spec.valid ? f(view, state) : openSearchPanel(view); + }; + } + /** + Open the search panel if it isn't already open, and move the + selection to the first match after the current main selection. + Will wrap around to the start of the document when it reaches the + end. + */ + const findNext = /*@__PURE__*/searchCommand((view, { query }) => { + let { to } = view.state.selection.main; + let next = query.nextMatch(view.state, to, to); + if (!next) + return false; + view.dispatch({ + selection: { anchor: next.from, head: next.to }, + scrollIntoView: true, + effects: announceMatch(view, next), + userEvent: "select.search" + }); + return true; + }); + /** + Move the selection to the previous instance of the search query, + before the current main selection. Will wrap past the start + of the document to start searching at the end again. + */ + const findPrevious = /*@__PURE__*/searchCommand((view, { query }) => { + let { state } = view, { from } = state.selection.main; + let range = query.prevMatch(state, from, from); + if (!range) + return false; + view.dispatch({ + selection: { anchor: range.from, head: range.to }, + scrollIntoView: true, + effects: announceMatch(view, range), + userEvent: "select.search" + }); + return true; + }); + /** + Select all instances of the search query. + */ + const selectMatches = /*@__PURE__*/searchCommand((view, { query }) => { + let ranges = query.matchAll(view.state, 1000); + if (!ranges || !ranges.length) + return false; + view.dispatch({ + selection: EditorSelection.create(ranges.map(r => EditorSelection.range(r.from, r.to))), + userEvent: "select.search.matches" + }); + return true; + }); + /** + Select all instances of the currently selected text. + */ + const selectSelectionMatches = ({ state, dispatch }) => { + let sel = state.selection; + if (sel.ranges.length > 1 || sel.main.empty) + return false; + let { from, to } = sel.main; + let ranges = [], main = 0; + for (let cur = new SearchCursor(state.doc, state.sliceDoc(from, to)); !cur.next().done;) { + if (ranges.length > 1000) + return false; + if (cur.value.from == from) + main = ranges.length; + ranges.push(EditorSelection.range(cur.value.from, cur.value.to)); + } + dispatch(state.update({ + selection: EditorSelection.create(ranges, main), + userEvent: "select.search.matches" + })); + return true; + }; + /** + Replace the current match of the search query. + */ + const replaceNext = /*@__PURE__*/searchCommand((view, { query }) => { + let { state } = view, { from, to } = state.selection.main; + if (state.readOnly) + return false; + let next = query.nextMatch(state, from, from); + if (!next) + return false; + let changes = [], selection, replacement; + let announce = []; + if (next.from == from && next.to == to) { + replacement = state.toText(query.getReplacement(next)); + changes.push({ from: next.from, to: next.to, insert: replacement }); + next = query.nextMatch(state, next.from, next.to); + announce.push(EditorView.announce.of(state.phrase("replaced match on line $", state.doc.lineAt(from).number) + ".")); + } + if (next) { + let off = changes.length == 0 || changes[0].from >= next.to ? 0 : next.to - next.from - replacement.length; + selection = { anchor: next.from - off, head: next.to - off }; + announce.push(announceMatch(view, next)); + } + view.dispatch({ + changes, selection, + scrollIntoView: !!selection, + effects: announce, + userEvent: "input.replace" + }); + return true; + }); + /** + Replace all instances of the search query with the given + replacement. + */ + const replaceAll = /*@__PURE__*/searchCommand((view, { query }) => { + if (view.state.readOnly) + return false; + let changes = query.matchAll(view.state, 1e9).map(match => { + let { from, to } = match; + return { from, to, insert: query.getReplacement(match) }; + }); + if (!changes.length) + return false; + let announceText = view.state.phrase("replaced $ matches", changes.length) + "."; + view.dispatch({ + changes, + effects: EditorView.announce.of(announceText), + userEvent: "input.replace.all" + }); + return true; + }); + function createSearchPanel(view) { + return view.state.facet(searchConfigFacet).createPanel(view); + } + function defaultQuery(state, fallback) { + var _a, _b, _c, _d; + let sel = state.selection.main; + let selText = sel.empty || sel.to > sel.from + 100 ? "" : state.sliceDoc(sel.from, sel.to); + if (fallback && !selText) + return fallback; + let config = state.facet(searchConfigFacet); + return new SearchQuery({ + search: ((_a = fallback === null || fallback === void 0 ? void 0 : fallback.literal) !== null && _a !== void 0 ? _a : config.literal) ? selText : selText.replace(/\n/g, "\\n"), + caseSensitive: (_b = fallback === null || fallback === void 0 ? void 0 : fallback.caseSensitive) !== null && _b !== void 0 ? _b : config.caseSensitive, + literal: (_c = fallback === null || fallback === void 0 ? void 0 : fallback.literal) !== null && _c !== void 0 ? _c : config.literal, + wholeWord: (_d = fallback === null || fallback === void 0 ? void 0 : fallback.wholeWord) !== null && _d !== void 0 ? _d : config.wholeWord + }); + } + /** + Make sure the search panel is open and focused. + */ + const openSearchPanel = view => { + let state = view.state.field(searchState, false); + if (state && state.panel) { + let panel = getPanel(view, createSearchPanel); + if (!panel) + return false; + let searchInput = panel.dom.querySelector("[main-field]"); + if (searchInput && searchInput != view.root.activeElement) { + let query = defaultQuery(view.state, state.query.spec); + if (query.valid) + view.dispatch({ effects: setSearchQuery.of(query) }); + searchInput.focus(); + searchInput.select(); + } + } + else { + view.dispatch({ effects: [ + togglePanel$1.of(true), + state ? setSearchQuery.of(defaultQuery(view.state, state.query.spec)) : StateEffect.appendConfig.of(searchExtensions) + ] }); + } + return true; + }; + /** + Close the search panel. + */ + const closeSearchPanel = view => { + let state = view.state.field(searchState, false); + if (!state || !state.panel) + return false; + let panel = getPanel(view, createSearchPanel); + if (panel && panel.dom.contains(view.root.activeElement)) + view.focus(); + view.dispatch({ effects: togglePanel$1.of(false) }); + return true; + }; + /** + Default search-related key bindings. + + - Mod-f: [`openSearchPanel`](https://codemirror.net/6/docs/ref/#search.openSearchPanel) + - F3, Mod-g: [`findNext`](https://codemirror.net/6/docs/ref/#search.findNext) + - Shift-F3, Shift-Mod-g: [`findPrevious`](https://codemirror.net/6/docs/ref/#search.findPrevious) + - Alt-g: [`gotoLine`](https://codemirror.net/6/docs/ref/#search.gotoLine) + - Mod-d: [`selectNextOccurrence`](https://codemirror.net/6/docs/ref/#search.selectNextOccurrence) + */ + const searchKeymap = [ + { key: "Mod-f", run: openSearchPanel, scope: "editor search-panel" }, + { key: "F3", run: findNext, shift: findPrevious, scope: "editor search-panel", preventDefault: true }, + { key: "Mod-g", run: findNext, shift: findPrevious, scope: "editor search-panel", preventDefault: true }, + { key: "Escape", run: closeSearchPanel, scope: "editor search-panel" }, + { key: "Mod-Shift-l", run: selectSelectionMatches }, + { key: "Alt-g", run: gotoLine }, + { key: "Mod-d", run: selectNextOccurrence, preventDefault: true }, + ]; + class SearchPanel { + constructor(view) { + this.view = view; + let query = this.query = view.state.field(searchState).query.spec; + this.commit = this.commit.bind(this); + this.searchField = crelt("input", { + value: query.search, + placeholder: phrase(view, "Find"), + "aria-label": phrase(view, "Find"), + class: "cm-textfield", + name: "search", + "main-field": "true", + onchange: this.commit, + onkeyup: this.commit + }); + this.replaceField = crelt("input", { + value: query.replace, + placeholder: phrase(view, "Replace"), + "aria-label": phrase(view, "Replace"), + class: "cm-textfield", + name: "replace", + onchange: this.commit, + onkeyup: this.commit + }); + this.caseField = crelt("input", { + type: "checkbox", + name: "case", + checked: query.caseSensitive, + onchange: this.commit + }); + this.reField = crelt("input", { + type: "checkbox", + name: "re", + checked: query.regexp, + onchange: this.commit + }); + this.wordField = crelt("input", { + type: "checkbox", + name: "word", + checked: query.wholeWord, + onchange: this.commit + }); + function button(name, onclick, content) { + return crelt("button", { class: "cm-button", name, onclick, type: "button" }, content); + } + this.dom = crelt("div", { onkeydown: (e) => this.keydown(e), class: "cm-search" }, [ + this.searchField, + button("next", () => findNext(view), [phrase(view, "next")]), + button("prev", () => findPrevious(view), [phrase(view, "previous")]), + button("select", () => selectMatches(view), [phrase(view, "all")]), + crelt("label", null, [this.caseField, phrase(view, "match case")]), + crelt("label", null, [this.reField, phrase(view, "regexp")]), + crelt("label", null, [this.wordField, phrase(view, "by word")]), + ...view.state.readOnly ? [] : [ + crelt("br"), + this.replaceField, + button("replace", () => replaceNext(view), [phrase(view, "replace")]), + button("replaceAll", () => replaceAll(view), [phrase(view, "replace all")]), + crelt("button", { + name: "close", + onclick: () => closeSearchPanel(view), + "aria-label": phrase(view, "close"), + type: "button" + }, ["×"]) + ] + ]); + } + commit() { + let query = new SearchQuery({ + search: this.searchField.value, + caseSensitive: this.caseField.checked, + regexp: this.reField.checked, + wholeWord: this.wordField.checked, + replace: this.replaceField.value, + }); + if (!query.eq(this.query)) { + this.query = query; + this.view.dispatch({ effects: setSearchQuery.of(query) }); + } + } + keydown(e) { + if (runScopeHandlers(this.view, e, "search-panel")) { + e.preventDefault(); + } + else if (e.keyCode == 13 && e.target == this.searchField) { + e.preventDefault(); + (e.shiftKey ? findPrevious : findNext)(this.view); + } + else if (e.keyCode == 13 && e.target == this.replaceField) { + e.preventDefault(); + replaceNext(this.view); + } + } + update(update) { + for (let tr of update.transactions) + for (let effect of tr.effects) { + if (effect.is(setSearchQuery) && !effect.value.eq(this.query)) + this.setQuery(effect.value); + } + } + setQuery(query) { + this.query = query; + this.searchField.value = query.search; + this.replaceField.value = query.replace; + this.caseField.checked = query.caseSensitive; + this.reField.checked = query.regexp; + this.wordField.checked = query.wholeWord; + } + mount() { + this.searchField.select(); + } + get pos() { return 80; } + get top() { return this.view.state.facet(searchConfigFacet).top; } + } + function phrase(view, phrase) { return view.state.phrase(phrase); } + const AnnounceMargin = 30; + const Break = /[\s\.,:;?!]/; + function announceMatch(view, { from, to }) { + let line = view.state.doc.lineAt(from), lineEnd = view.state.doc.lineAt(to).to; + let start = Math.max(line.from, from - AnnounceMargin), end = Math.min(lineEnd, to + AnnounceMargin); + let text = view.state.sliceDoc(start, end); + if (start != line.from) { + for (let i = 0; i < AnnounceMargin; i++) + if (!Break.test(text[i + 1]) && Break.test(text[i])) { + text = text.slice(i); + break; + } + } + if (end != lineEnd) { + for (let i = text.length - 1; i > text.length - AnnounceMargin; i--) + if (!Break.test(text[i - 1]) && Break.test(text[i])) { + text = text.slice(0, i); + break; + } + } + return EditorView.announce.of(`${view.state.phrase("current match")}. ${text} ${view.state.phrase("on line")} ${line.number}.`); + } + const baseTheme$2 = /*@__PURE__*/EditorView.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" } + }); + const searchExtensions = [ + searchState, + /*@__PURE__*/Prec.lowest(searchHighlighter), + baseTheme$2 + ]; + + /** + An instance of this is passed to completion source functions. + */ + class CompletionContext { + /** + Create a new completion context. (Mostly useful for testing + completion sources—in the editor, the extension will create + these for you.) + */ + constructor( + /** + The editor state that the completion happens in. + */ + state, + /** + The position at which the completion is happening. + */ + pos, + /** + Indicates whether completion was activated explicitly, or + implicitly by typing. The usual way to respond to this is to + only return completions when either there is part of a + completable entity before the cursor, or `explicit` is true. + */ + explicit) { + this.state = state; + this.pos = pos; + this.explicit = explicit; + /** + @internal + */ + this.abortListeners = []; + } + /** + Get the extent, content, and (if there is a token) type of the + token before `this.pos`. + */ + tokenBefore(types) { + let token = syntaxTree(this.state).resolveInner(this.pos, -1); + while (token && types.indexOf(token.name) < 0) + token = token.parent; + return token ? { from: token.from, to: this.pos, + text: this.state.sliceDoc(token.from, this.pos), + type: token.type } : null; + } + /** + Get the match of the given expression directly before the + cursor. + */ + matchBefore(expr) { + let line = this.state.doc.lineAt(this.pos); + let start = Math.max(line.from, this.pos - 250); + let str = line.text.slice(start - line.from, this.pos - line.from); + let found = str.search(ensureAnchor(expr, false)); + return found < 0 ? null : { from: start + found, to: this.pos, text: str.slice(found) }; + } + /** + Yields true when the query has been aborted. Can be useful in + asynchronous queries to avoid doing work that will be ignored. + */ + get aborted() { return this.abortListeners == null; } + /** + Allows you to register abort handlers, which will be called when + the query is + [aborted](https://codemirror.net/6/docs/ref/#autocomplete.CompletionContext.aborted). + */ + addEventListener(type, listener) { + if (type == "abort" && this.abortListeners) + this.abortListeners.push(listener); + } + } + function toSet(chars) { + let flat = Object.keys(chars).join(""); + let words = /\w/.test(flat); + if (words) + flat = flat.replace(/\w/g, ""); + return `[${words ? "\\w" : ""}${flat.replace(/[^\w\s]/g, "\\$&")}]`; + } + function prefixMatch(options) { + let first = Object.create(null), rest = Object.create(null); + for (let { label } of options) { + first[label[0]] = true; + for (let i = 1; i < label.length; i++) + rest[label[i]] = true; + } + let source = toSet(first) + toSet(rest) + "*$"; + return [new RegExp("^" + source), new RegExp(source)]; + } + /** + Given a a fixed array of options, return an autocompleter that + completes them. + */ + function completeFromList(list) { + let options = list.map(o => typeof o == "string" ? { label: o } : o); + let [validFor, match] = options.every(o => /^\w+$/.test(o.label)) ? [/\w*$/, /\w+$/] : prefixMatch(options); + return (context) => { + let token = context.matchBefore(match); + return token || context.explicit ? { from: token ? token.from : context.pos, options, validFor } : null; + }; + } + class Option { + constructor(completion, source, match) { + this.completion = completion; + this.source = source; + this.match = match; + } + } + function cur(state) { return state.selection.main.head; } + // Make sure the given regexp has a $ at its end and, if `start` is + // true, a ^ at its start. + function ensureAnchor(expr, start) { + var _a; + let { source } = expr; + let addStart = start && source[0] != "^", addEnd = source[source.length - 1] != "$"; + if (!addStart && !addEnd) + return expr; + return new RegExp(`${addStart ? "^" : ""}(?:${source})${addEnd ? "$" : ""}`, (_a = expr.flags) !== null && _a !== void 0 ? _a : (expr.ignoreCase ? "i" : "")); + } + /** + Helper function that returns a transaction spec which inserts a + completion's text in the main selection range, and any other + selection range that has the same text in front of it. + */ + function insertCompletionText(state, text, from, to) { + return Object.assign(Object.assign({}, state.changeByRange(range => { + if (range == state.selection.main) + return { + changes: { from: from, to: to, insert: text }, + range: EditorSelection.cursor(from + text.length) + }; + let len = to - from; + if (!range.empty || + len && state.sliceDoc(range.from - len, range.from) != state.sliceDoc(from, to)) + return { range }; + return { + changes: { from: range.from - len, to: range.from, insert: text }, + range: EditorSelection.cursor(range.from - len + text.length) + }; + })), { userEvent: "input.complete" }); + } + function applyCompletion(view, option) { + const apply = option.completion.apply || option.completion.label; + let result = option.source; + if (typeof apply == "string") + view.dispatch(insertCompletionText(view.state, apply, result.from, result.to)); + else + apply(view, option.completion, result.from, result.to); + } + const SourceCache = /*@__PURE__*/new WeakMap(); + function asSource(source) { + if (!Array.isArray(source)) + return source; + let known = SourceCache.get(source); + if (!known) + SourceCache.set(source, known = completeFromList(source)); + return known; + } + + // A pattern matcher for fuzzy completion matching. Create an instance + // once for a pattern, and then use that to match any number of + // completions. + class FuzzyMatcher { + constructor(pattern) { + this.pattern = pattern; + this.chars = []; + this.folded = []; + // Buffers reused by calls to `match` to track matched character + // positions. + this.any = []; + this.precise = []; + this.byWord = []; + for (let p = 0; p < pattern.length;) { + let char = codePointAt(pattern, p), size = codePointSize(char); + this.chars.push(char); + let part = pattern.slice(p, p + size), upper = part.toUpperCase(); + this.folded.push(codePointAt(upper == part ? part.toLowerCase() : upper, 0)); + p += size; + } + this.astral = pattern.length != this.chars.length; + } + // Matches a given word (completion) against the pattern (input). + // Will return null for no match, and otherwise an array that starts + // with the match score, followed by any number of `from, to` pairs + // indicating the matched parts of `word`. + // + // The score is a number that is more negative the worse the match + // is. See `Penalty` above. + match(word) { + if (this.pattern.length == 0) + return [0]; + if (word.length < this.pattern.length) + return null; + let { chars, folded, any, precise, byWord } = this; + // For single-character queries, only match when they occur right + // at the start + if (chars.length == 1) { + let first = codePointAt(word, 0); + return first == chars[0] ? [0, 0, codePointSize(first)] + : first == folded[0] ? [-200 /* Penalty.CaseFold */, 0, codePointSize(first)] : null; + } + let direct = word.indexOf(this.pattern); + if (direct == 0) + return [0, 0, this.pattern.length]; + let len = chars.length, anyTo = 0; + if (direct < 0) { + for (let i = 0, e = Math.min(word.length, 200); i < e && anyTo < len;) { + let next = codePointAt(word, i); + if (next == chars[anyTo] || next == folded[anyTo]) + any[anyTo++] = i; + i += codePointSize(next); + } + // No match, exit immediately + if (anyTo < len) + return null; + } + // This tracks the extent of the precise (non-folded, not + // necessarily adjacent) match + let preciseTo = 0; + // Tracks whether there is a match that hits only characters that + // appear to be starting words. `byWordFolded` is set to true when + // a case folded character is encountered in such a match + let byWordTo = 0, byWordFolded = false; + // If we've found a partial adjacent match, these track its state + let adjacentTo = 0, adjacentStart = -1, adjacentEnd = -1; + let hasLower = /[a-z]/.test(word), wordAdjacent = true; + // Go over the option's text, scanning for the various kinds of matches + for (let i = 0, e = Math.min(word.length, 200), prevType = 0 /* Tp.NonWord */; i < e && byWordTo < len;) { + let next = codePointAt(word, i); + if (direct < 0) { + if (preciseTo < len && next == chars[preciseTo]) + precise[preciseTo++] = i; + if (adjacentTo < len) { + if (next == chars[adjacentTo] || next == folded[adjacentTo]) { + if (adjacentTo == 0) + adjacentStart = i; + adjacentEnd = i + 1; + adjacentTo++; + } + else { + adjacentTo = 0; + } + } + } + let ch, type = next < 0xff + ? (next >= 48 && next <= 57 || next >= 97 && next <= 122 ? 2 /* Tp.Lower */ : next >= 65 && next <= 90 ? 1 /* Tp.Upper */ : 0 /* Tp.NonWord */) + : ((ch = fromCodePoint(next)) != ch.toLowerCase() ? 1 /* Tp.Upper */ : ch != ch.toUpperCase() ? 2 /* Tp.Lower */ : 0 /* Tp.NonWord */); + if (!i || type == 1 /* Tp.Upper */ && hasLower || prevType == 0 /* Tp.NonWord */ && type != 0 /* Tp.NonWord */) { + if (chars[byWordTo] == next || (folded[byWordTo] == next && (byWordFolded = true))) + byWord[byWordTo++] = i; + else if (byWord.length) + wordAdjacent = false; + } + prevType = type; + i += codePointSize(next); + } + if (byWordTo == len && byWord[0] == 0 && wordAdjacent) + return this.result(-100 /* Penalty.ByWord */ + (byWordFolded ? -200 /* Penalty.CaseFold */ : 0), byWord, word); + if (adjacentTo == len && adjacentStart == 0) + return [-200 /* Penalty.CaseFold */ - word.length, 0, adjacentEnd]; + if (direct > -1) + return [-700 /* Penalty.NotStart */ - word.length, direct, direct + this.pattern.length]; + if (adjacentTo == len) + return [-200 /* Penalty.CaseFold */ + -700 /* Penalty.NotStart */ - word.length, adjacentStart, adjacentEnd]; + if (byWordTo == len) + return this.result(-100 /* Penalty.ByWord */ + (byWordFolded ? -200 /* Penalty.CaseFold */ : 0) + -700 /* Penalty.NotStart */ + + (wordAdjacent ? 0 : -1100 /* Penalty.Gap */), byWord, word); + return chars.length == 2 ? null : this.result((any[0] ? -700 /* Penalty.NotStart */ : 0) + -200 /* Penalty.CaseFold */ + -1100 /* Penalty.Gap */, any, word); + } + result(score, positions, word) { + let result = [score - word.length], i = 1; + for (let pos of positions) { + let to = pos + (this.astral ? codePointSize(codePointAt(word, pos)) : 1); + if (i > 1 && result[i - 1] == pos) + result[i - 1] = to; + else { + result[i++] = pos; + result[i++] = to; + } + } + return result; + } + } + + const completionConfig = /*@__PURE__*/Facet.define({ + combine(configs) { + return combineConfig(configs, { + activateOnTyping: true, + selectOnOpen: true, + override: null, + closeOnBlur: true, + maxRenderedOptions: 100, + defaultKeymap: true, + optionClass: () => "", + aboveCursor: false, + icons: true, + addToOptions: [], + compareCompletions: (a, b) => a.label.localeCompare(b.label), + interactionDelay: 75 + }, { + defaultKeymap: (a, b) => a && b, + closeOnBlur: (a, b) => a && b, + icons: (a, b) => a && b, + optionClass: (a, b) => c => joinClass(a(c), b(c)), + addToOptions: (a, b) => a.concat(b) + }); + } + }); + function joinClass(a, b) { + return a ? b ? a + " " + b : a : b; + } + + function optionContent(config) { + let content = config.addToOptions.slice(); + if (config.icons) + content.push({ + render(completion) { + let icon = document.createElement("div"); + icon.classList.add("cm-completionIcon"); + if (completion.type) + icon.classList.add(...completion.type.split(/\s+/g).map(cls => "cm-completionIcon-" + cls)); + icon.setAttribute("aria-hidden", "true"); + return icon; + }, + position: 20 + }); + content.push({ + render(completion, _s, match) { + let labelElt = document.createElement("span"); + labelElt.className = "cm-completionLabel"; + let { label } = completion, off = 0; + for (let j = 1; j < match.length;) { + let from = match[j++], to = match[j++]; + if (from > off) + labelElt.appendChild(document.createTextNode(label.slice(off, from))); + let span = labelElt.appendChild(document.createElement("span")); + span.appendChild(document.createTextNode(label.slice(from, to))); + span.className = "cm-completionMatchedText"; + off = to; + } + if (off < label.length) + labelElt.appendChild(document.createTextNode(label.slice(off))); + return labelElt; + }, + position: 50 + }, { + render(completion) { + if (!completion.detail) + return null; + let detailElt = document.createElement("span"); + detailElt.className = "cm-completionDetail"; + detailElt.textContent = completion.detail; + return detailElt; + }, + position: 80 + }); + return content.sort((a, b) => a.position - b.position).map(a => a.render); + } + function rangeAroundSelected(total, selected, max) { + if (total <= max) + return { from: 0, to: total }; + if (selected < 0) + selected = 0; + if (selected <= (total >> 1)) { + let off = Math.floor(selected / max); + return { from: off * max, to: (off + 1) * max }; + } + let off = Math.floor((total - selected) / max); + return { from: total - (off + 1) * max, to: total - off * max }; + } + class CompletionTooltip { + constructor(view, stateField) { + this.view = view; + this.stateField = stateField; + this.info = null; + this.placeInfo = { + read: () => this.measureInfo(), + write: (pos) => this.positionInfo(pos), + key: this + }; + let cState = view.state.field(stateField); + let { options, selected } = cState.open; + let config = view.state.facet(completionConfig); + this.optionContent = optionContent(config); + this.optionClass = config.optionClass; + this.range = rangeAroundSelected(options.length, selected, config.maxRenderedOptions); + this.dom = document.createElement("div"); + this.dom.className = "cm-tooltip-autocomplete"; + this.dom.addEventListener("mousedown", (e) => { + for (let dom = e.target, match; dom && dom != this.dom; dom = dom.parentNode) { + if (dom.nodeName == "LI" && (match = /-(\d+)$/.exec(dom.id)) && +match[1] < options.length) { + applyCompletion(view, options[+match[1]]); + e.preventDefault(); + return; + } + } + }); + this.list = this.dom.appendChild(this.createListBox(options, cState.id, this.range)); + this.list.addEventListener("scroll", () => { + if (this.info) + this.view.requestMeasure(this.placeInfo); + }); + } + mount() { this.updateSel(); } + update(update) { + if (update.state.field(this.stateField) != update.startState.field(this.stateField)) + this.updateSel(); + } + positioned() { + if (this.info) + this.view.requestMeasure(this.placeInfo); + } + updateSel() { + let cState = this.view.state.field(this.stateField), open = cState.open; + if (open.selected > -1 && open.selected < this.range.from || open.selected >= this.range.to) { + this.range = rangeAroundSelected(open.options.length, open.selected, this.view.state.facet(completionConfig).maxRenderedOptions); + this.list.remove(); + this.list = this.dom.appendChild(this.createListBox(open.options, cState.id, this.range)); + this.list.addEventListener("scroll", () => { + if (this.info) + this.view.requestMeasure(this.placeInfo); + }); + } + if (this.updateSelectedOption(open.selected)) { + if (this.info) { + this.info.remove(); + this.info = null; + } + let { completion } = open.options[open.selected]; + let { info } = completion; + if (!info) + return; + let infoResult = typeof info === 'string' ? document.createTextNode(info) : info(completion); + if (!infoResult) + return; + if ('then' in infoResult) { + infoResult.then(node => { + if (node && this.view.state.field(this.stateField, false) == cState) + this.addInfoPane(node); + }).catch(e => logException(this.view.state, e, "completion info")); + } + else { + this.addInfoPane(infoResult); + } + } + } + addInfoPane(content) { + let dom = this.info = document.createElement("div"); + dom.className = "cm-tooltip cm-completionInfo"; + dom.appendChild(content); + this.dom.appendChild(dom); + this.view.requestMeasure(this.placeInfo); + } + updateSelectedOption(selected) { + let set = null; + for (let opt = this.list.firstChild, i = this.range.from; opt; opt = opt.nextSibling, i++) { + if (i == selected) { + if (!opt.hasAttribute("aria-selected")) { + opt.setAttribute("aria-selected", "true"); + set = opt; + } + } + else { + if (opt.hasAttribute("aria-selected")) + opt.removeAttribute("aria-selected"); + } + } + if (set) + scrollIntoView(this.list, set); + return set; + } + measureInfo() { + let sel = this.dom.querySelector("[aria-selected]"); + if (!sel || !this.info) + return null; + let win = this.dom.ownerDocument.defaultView || window; + let listRect = this.dom.getBoundingClientRect(); + let infoRect = this.info.getBoundingClientRect(); + let selRect = sel.getBoundingClientRect(); + if (selRect.top > Math.min(win.innerHeight, listRect.bottom) - 10 || selRect.bottom < Math.max(0, listRect.top) + 10) + return null; + let rtl = this.view.textDirection == Direction.RTL, left = rtl, narrow = false, maxWidth; + let top = "", bottom = ""; + let spaceLeft = listRect.left, spaceRight = win.innerWidth - listRect.right; + if (left && spaceLeft < Math.min(infoRect.width, spaceRight)) + left = false; + else if (!left && spaceRight < Math.min(infoRect.width, spaceLeft)) + left = true; + if (infoRect.width <= (left ? spaceLeft : spaceRight)) { + top = (Math.max(0, Math.min(selRect.top, win.innerHeight - infoRect.height)) - listRect.top) + "px"; + maxWidth = Math.min(400 /* Info.Width */, left ? spaceLeft : spaceRight) + "px"; + } + else { + narrow = true; + maxWidth = Math.min(400 /* Info.Width */, (rtl ? listRect.right : win.innerWidth - listRect.left) - 30 /* Info.Margin */) + "px"; + let spaceBelow = win.innerHeight - listRect.bottom; + if (spaceBelow >= infoRect.height || spaceBelow > listRect.top) // Below the completion + top = (selRect.bottom - listRect.top) + "px"; + else // Above it + bottom = (listRect.bottom - selRect.top) + "px"; + } + return { + top, bottom, maxWidth, + class: narrow ? (rtl ? "left-narrow" : "right-narrow") : left ? "left" : "right", + }; + } + positionInfo(pos) { + if (this.info) { + if (pos) { + this.info.style.top = pos.top; + this.info.style.bottom = pos.bottom; + this.info.style.maxWidth = pos.maxWidth; + this.info.className = "cm-tooltip cm-completionInfo cm-completionInfo-" + pos.class; + } + else { + this.info.style.top = "-1e6px"; + } + } + } + createListBox(options, id, range) { + const ul = document.createElement("ul"); + ul.id = id; + ul.setAttribute("role", "listbox"); + ul.setAttribute("aria-expanded", "true"); + ul.setAttribute("aria-label", this.view.state.phrase("Completions")); + for (let i = range.from; i < range.to; i++) { + let { completion, match } = options[i]; + const li = ul.appendChild(document.createElement("li")); + li.id = id + "-" + i; + li.setAttribute("role", "option"); + let cls = this.optionClass(completion); + if (cls) + li.className = cls; + for (let source of this.optionContent) { + let node = source(completion, this.view.state, match); + if (node) + li.appendChild(node); + } + } + if (range.from) + ul.classList.add("cm-completionListIncompleteTop"); + if (range.to < options.length) + ul.classList.add("cm-completionListIncompleteBottom"); + return ul; + } + } + // We allocate a new function instance every time the completion + // changes to force redrawing/repositioning of the tooltip + function completionTooltip(stateField) { + return (view) => new CompletionTooltip(view, stateField); + } + function scrollIntoView(container, element) { + let parent = container.getBoundingClientRect(); + let self = element.getBoundingClientRect(); + if (self.top < parent.top) + container.scrollTop -= parent.top - self.top; + else if (self.bottom > parent.bottom) + container.scrollTop += self.bottom - parent.bottom; + } + + // Used to pick a preferred option when two options with the same + // label occur in the result. + function score(option) { + return (option.boost || 0) * 100 + (option.apply ? 10 : 0) + (option.info ? 5 : 0) + + (option.type ? 1 : 0); + } + function sortOptions(active, state) { + let options = [], i = 0; + for (let a of active) + if (a.hasResult()) { + if (a.result.filter === false) { + let getMatch = a.result.getMatch; + for (let option of a.result.options) { + let match = [1e9 - i++]; + if (getMatch) + for (let n of getMatch(option)) + match.push(n); + options.push(new Option(option, a, match)); + } + } + else { + let matcher = new FuzzyMatcher(state.sliceDoc(a.from, a.to)), match; + for (let option of a.result.options) + if (match = matcher.match(option.label)) { + if (option.boost != null) + match[0] += option.boost; + options.push(new Option(option, a, match)); + } + } + } + let result = [], prev = null; + let compare = state.facet(completionConfig).compareCompletions; + for (let opt of options.sort((a, b) => (b.match[0] - a.match[0]) || compare(a.completion, b.completion))) { + if (!prev || prev.label != opt.completion.label || prev.detail != opt.completion.detail || + (prev.type != null && opt.completion.type != null && prev.type != opt.completion.type) || + prev.apply != opt.completion.apply) + result.push(opt); + else if (score(opt.completion) > score(prev)) + result[result.length - 1] = opt; + prev = opt.completion; + } + return result; + } + class CompletionDialog { + constructor(options, attrs, tooltip, timestamp, selected) { + this.options = options; + this.attrs = attrs; + this.tooltip = tooltip; + this.timestamp = timestamp; + this.selected = selected; + } + setSelected(selected, id) { + return selected == this.selected || selected >= this.options.length ? this + : new CompletionDialog(this.options, makeAttrs(id, selected), this.tooltip, this.timestamp, selected); + } + static build(active, state, id, prev, conf) { + let options = sortOptions(active, state); + if (!options.length) + return null; + let selected = state.facet(completionConfig).selectOnOpen ? 0 : -1; + if (prev && prev.selected != selected && prev.selected != -1) { + let selectedValue = prev.options[prev.selected].completion; + for (let i = 0; i < options.length; i++) + if (options[i].completion == selectedValue) { + selected = i; + break; + } + } + return new CompletionDialog(options, makeAttrs(id, selected), { + pos: active.reduce((a, b) => b.hasResult() ? Math.min(a, b.from) : a, 1e8), + create: completionTooltip(completionState), + above: conf.aboveCursor, + }, prev ? prev.timestamp : Date.now(), selected); + } + map(changes) { + return new CompletionDialog(this.options, this.attrs, Object.assign(Object.assign({}, this.tooltip), { pos: changes.mapPos(this.tooltip.pos) }), this.timestamp, this.selected); + } + } + class CompletionState { + constructor(active, id, open) { + this.active = active; + this.id = id; + this.open = open; + } + static start() { + return new CompletionState(none, "cm-ac-" + Math.floor(Math.random() * 2e6).toString(36), null); + } + update(tr) { + let { state } = tr, conf = state.facet(completionConfig); + let sources = conf.override || + state.languageDataAt("autocomplete", cur(state)).map(asSource); + let active = sources.map(source => { + let value = this.active.find(s => s.source == source) || + new ActiveSource(source, this.active.some(a => a.state != 0 /* State.Inactive */) ? 1 /* State.Pending */ : 0 /* State.Inactive */); + return value.update(tr, conf); + }); + if (active.length == this.active.length && active.every((a, i) => a == this.active[i])) + active = this.active; + let open = tr.selection || active.some(a => a.hasResult() && tr.changes.touchesRange(a.from, a.to)) || + !sameResults(active, this.active) ? CompletionDialog.build(active, state, this.id, this.open, conf) + : this.open && tr.docChanged ? this.open.map(tr.changes) : this.open; + if (!open && active.every(a => a.state != 1 /* State.Pending */) && active.some(a => a.hasResult())) + active = active.map(a => a.hasResult() ? new ActiveSource(a.source, 0 /* State.Inactive */) : a); + for (let effect of tr.effects) + if (effect.is(setSelectedEffect)) + open = open && open.setSelected(effect.value, this.id); + return active == this.active && open == this.open ? this : new CompletionState(active, this.id, open); + } + get tooltip() { return this.open ? this.open.tooltip : null; } + get attrs() { return this.open ? this.open.attrs : baseAttrs; } + } + function sameResults(a, b) { + if (a == b) + return true; + for (let iA = 0, iB = 0;;) { + while (iA < a.length && !a[iA].hasResult) + iA++; + while (iB < b.length && !b[iB].hasResult) + iB++; + let endA = iA == a.length, endB = iB == b.length; + if (endA || endB) + return endA == endB; + if (a[iA++].result != b[iB++].result) + return false; + } + } + const baseAttrs = { + "aria-autocomplete": "list" + }; + function makeAttrs(id, selected) { + let result = { + "aria-autocomplete": "list", + "aria-haspopup": "listbox", + "aria-controls": id + }; + if (selected > -1) + result["aria-activedescendant"] = id + "-" + selected; + return result; + } + const none = []; + function getUserEvent(tr) { + return tr.isUserEvent("input.type") ? "input" : tr.isUserEvent("delete.backward") ? "delete" : null; + } + class ActiveSource { + constructor(source, state, explicitPos = -1) { + this.source = source; + this.state = state; + this.explicitPos = explicitPos; + } + hasResult() { return false; } + update(tr, conf) { + let event = getUserEvent(tr), value = this; + if (event) + value = value.handleUserEvent(tr, event, conf); + else if (tr.docChanged) + value = value.handleChange(tr); + else if (tr.selection && value.state != 0 /* State.Inactive */) + value = new ActiveSource(value.source, 0 /* State.Inactive */); + for (let effect of tr.effects) { + if (effect.is(startCompletionEffect)) + value = new ActiveSource(value.source, 1 /* State.Pending */, effect.value ? cur(tr.state) : -1); + else if (effect.is(closeCompletionEffect)) + value = new ActiveSource(value.source, 0 /* State.Inactive */); + else if (effect.is(setActiveEffect)) + for (let active of effect.value) + if (active.source == value.source) + value = active; + } + return value; + } + handleUserEvent(tr, type, conf) { + return type == "delete" || !conf.activateOnTyping ? this.map(tr.changes) : new ActiveSource(this.source, 1 /* State.Pending */); + } + handleChange(tr) { + return tr.changes.touchesRange(cur(tr.startState)) ? new ActiveSource(this.source, 0 /* State.Inactive */) : this.map(tr.changes); + } + map(changes) { + return changes.empty || this.explicitPos < 0 ? this : new ActiveSource(this.source, this.state, changes.mapPos(this.explicitPos)); + } + } + class ActiveResult extends ActiveSource { + constructor(source, explicitPos, result, from, to) { + super(source, 2 /* State.Result */, explicitPos); + this.result = result; + this.from = from; + this.to = to; + } + hasResult() { return true; } + handleUserEvent(tr, type, conf) { + var _a; + let from = tr.changes.mapPos(this.from), to = tr.changes.mapPos(this.to, 1); + let pos = cur(tr.state); + if ((this.explicitPos < 0 ? pos <= from : pos < this.from) || + pos > to || + type == "delete" && cur(tr.startState) == this.from) + return new ActiveSource(this.source, type == "input" && conf.activateOnTyping ? 1 /* State.Pending */ : 0 /* State.Inactive */); + let explicitPos = this.explicitPos < 0 ? -1 : tr.changes.mapPos(this.explicitPos), updated; + if (checkValid(this.result.validFor, tr.state, from, to)) + return new ActiveResult(this.source, explicitPos, this.result, from, to); + if (this.result.update && + (updated = this.result.update(this.result, from, to, new CompletionContext(tr.state, pos, explicitPos >= 0)))) + return new ActiveResult(this.source, explicitPos, updated, updated.from, (_a = updated.to) !== null && _a !== void 0 ? _a : cur(tr.state)); + return new ActiveSource(this.source, 1 /* State.Pending */, explicitPos); + } + handleChange(tr) { + return tr.changes.touchesRange(this.from, this.to) ? new ActiveSource(this.source, 0 /* State.Inactive */) : this.map(tr.changes); + } + map(mapping) { + return mapping.empty ? this : + new ActiveResult(this.source, this.explicitPos < 0 ? -1 : mapping.mapPos(this.explicitPos), this.result, mapping.mapPos(this.from), mapping.mapPos(this.to, 1)); + } + } + function checkValid(validFor, state, from, to) { + if (!validFor) + return false; + let text = state.sliceDoc(from, to); + return typeof validFor == "function" ? validFor(text, from, to, state) : ensureAnchor(validFor, true).test(text); + } + const startCompletionEffect = /*@__PURE__*/StateEffect.define(); + const closeCompletionEffect = /*@__PURE__*/StateEffect.define(); + const setActiveEffect = /*@__PURE__*/StateEffect.define({ + map(sources, mapping) { return sources.map(s => s.map(mapping)); } + }); + const setSelectedEffect = /*@__PURE__*/StateEffect.define(); + const completionState = /*@__PURE__*/StateField.define({ + create() { return CompletionState.start(); }, + update(value, tr) { return value.update(tr); }, + provide: f => [ + showTooltip.from(f, val => val.tooltip), + EditorView.contentAttributes.from(f, state => state.attrs) + ] + }); + + /** + Returns a command that moves the completion selection forward or + backward by the given amount. + */ + function moveCompletionSelection(forward, by = "option") { + return (view) => { + let cState = view.state.field(completionState, false); + if (!cState || !cState.open || + Date.now() - cState.open.timestamp < view.state.facet(completionConfig).interactionDelay) + return false; + let step = 1, tooltip; + if (by == "page" && (tooltip = getTooltip(view, cState.open.tooltip))) + step = Math.max(2, Math.floor(tooltip.dom.offsetHeight / + tooltip.dom.querySelector("li").offsetHeight) - 1); + let { length } = cState.open.options; + let selected = cState.open.selected > -1 ? cState.open.selected + step * (forward ? 1 : -1) : forward ? 0 : length - 1; + if (selected < 0) + selected = by == "page" ? 0 : length - 1; + else if (selected >= length) + selected = by == "page" ? length - 1 : 0; + view.dispatch({ effects: setSelectedEffect.of(selected) }); + return true; + }; + } + /** + Accept the current completion. + */ + const acceptCompletion = (view) => { + let cState = view.state.field(completionState, false); + if (view.state.readOnly || !cState || !cState.open || cState.open.selected < 0 || + Date.now() - cState.open.timestamp < view.state.facet(completionConfig).interactionDelay) + return false; + applyCompletion(view, cState.open.options[cState.open.selected]); + return true; + }; + /** + Explicitly start autocompletion. + */ + const startCompletion = (view) => { + let cState = view.state.field(completionState, false); + if (!cState) + return false; + view.dispatch({ effects: startCompletionEffect.of(true) }); + return true; + }; + /** + Close the currently active completion. + */ + const closeCompletion = (view) => { + let cState = view.state.field(completionState, false); + if (!cState || !cState.active.some(a => a.state != 0 /* State.Inactive */)) + return false; + view.dispatch({ effects: closeCompletionEffect.of(null) }); + return true; + }; + class RunningQuery { + constructor(active, context) { + this.active = active; + this.context = context; + this.time = Date.now(); + this.updates = []; + // Note that 'undefined' means 'not done yet', whereas 'null' means + // 'query returned null'. + this.done = undefined; + } + } + const DebounceTime = 50, MaxUpdateCount = 50, MinAbortTime = 1000; + const completionPlugin = /*@__PURE__*/ViewPlugin.fromClass(class { + constructor(view) { + this.view = view; + this.debounceUpdate = -1; + this.running = []; + this.debounceAccept = -1; + this.composing = 0 /* CompositionState.None */; + for (let active of view.state.field(completionState).active) + if (active.state == 1 /* State.Pending */) + this.startQuery(active); + } + update(update) { + let cState = update.state.field(completionState); + if (!update.selectionSet && !update.docChanged && update.startState.field(completionState) == cState) + return; + let doesReset = update.transactions.some(tr => { + return (tr.selection || tr.docChanged) && !getUserEvent(tr); + }); + for (let i = 0; i < this.running.length; i++) { + let query = this.running[i]; + if (doesReset || + query.updates.length + update.transactions.length > MaxUpdateCount && Date.now() - query.time > MinAbortTime) { + for (let handler of query.context.abortListeners) { + try { + handler(); + } + catch (e) { + logException(this.view.state, e); + } + } + query.context.abortListeners = null; + this.running.splice(i--, 1); + } + else { + query.updates.push(...update.transactions); + } + } + if (this.debounceUpdate > -1) + clearTimeout(this.debounceUpdate); + this.debounceUpdate = cState.active.some(a => a.state == 1 /* State.Pending */ && !this.running.some(q => q.active.source == a.source)) + ? setTimeout(() => this.startUpdate(), DebounceTime) : -1; + if (this.composing != 0 /* CompositionState.None */) + for (let tr of update.transactions) { + if (getUserEvent(tr) == "input") + this.composing = 2 /* CompositionState.Changed */; + else if (this.composing == 2 /* CompositionState.Changed */ && tr.selection) + this.composing = 3 /* CompositionState.ChangedAndMoved */; + } + } + startUpdate() { + this.debounceUpdate = -1; + let { state } = this.view, cState = state.field(completionState); + for (let active of cState.active) { + if (active.state == 1 /* State.Pending */ && !this.running.some(r => r.active.source == active.source)) + this.startQuery(active); + } + } + startQuery(active) { + let { state } = this.view, pos = cur(state); + let context = new CompletionContext(state, pos, active.explicitPos == pos); + let pending = new RunningQuery(active, context); + this.running.push(pending); + Promise.resolve(active.source(context)).then(result => { + if (!pending.context.aborted) { + pending.done = result || null; + this.scheduleAccept(); + } + }, err => { + this.view.dispatch({ effects: closeCompletionEffect.of(null) }); + logException(this.view.state, err); + }); + } + scheduleAccept() { + if (this.running.every(q => q.done !== undefined)) + this.accept(); + else if (this.debounceAccept < 0) + this.debounceAccept = setTimeout(() => this.accept(), DebounceTime); + } + // For each finished query in this.running, try to create a result + // or, if appropriate, restart the query. + accept() { + var _a; + if (this.debounceAccept > -1) + clearTimeout(this.debounceAccept); + this.debounceAccept = -1; + let updated = []; + let conf = this.view.state.facet(completionConfig); + for (let i = 0; i < this.running.length; i++) { + let query = this.running[i]; + if (query.done === undefined) + continue; + this.running.splice(i--, 1); + if (query.done) { + let active = new ActiveResult(query.active.source, query.active.explicitPos, query.done, query.done.from, (_a = query.done.to) !== null && _a !== void 0 ? _a : cur(query.updates.length ? query.updates[0].startState : this.view.state)); + // Replay the transactions that happened since the start of + // the request and see if that preserves the result + for (let tr of query.updates) + active = active.update(tr, conf); + if (active.hasResult()) { + updated.push(active); + continue; + } + } + let current = this.view.state.field(completionState).active.find(a => a.source == query.active.source); + if (current && current.state == 1 /* State.Pending */) { + if (query.done == null) { + // Explicitly failed. Should clear the pending status if it + // hasn't been re-set in the meantime. + let active = new ActiveSource(query.active.source, 0 /* State.Inactive */); + for (let tr of query.updates) + active = active.update(tr, conf); + if (active.state != 1 /* State.Pending */) + updated.push(active); + } + else { + // Cleared by subsequent transactions. Restart. + this.startQuery(current); + } + } + } + if (updated.length) + this.view.dispatch({ effects: setActiveEffect.of(updated) }); + } + }, { + eventHandlers: { + blur() { + let state = this.view.state.field(completionState, false); + if (state && state.tooltip && this.view.state.facet(completionConfig).closeOnBlur) + this.view.dispatch({ effects: closeCompletionEffect.of(null) }); + }, + compositionstart() { + this.composing = 1 /* CompositionState.Started */; + }, + compositionend() { + if (this.composing == 3 /* CompositionState.ChangedAndMoved */) { + // Safari fires compositionend events synchronously, possibly + // from inside an update, so dispatch asynchronously to avoid reentrancy + setTimeout(() => this.view.dispatch({ effects: startCompletionEffect.of(false) }), 20); + } + this.composing = 0 /* CompositionState.None */; + } + } + }); + + const baseTheme$1 = /*@__PURE__*/EditorView.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", + listStyle: "none", + margin: 0, + padding: 0, + "& > li": { + overflowX: "hidden", + textOverflow: "ellipsis", + cursor: "pointer", + padding: "1px 3px", + lineHeight: 1.2 + }, + } + }, + "&light .cm-tooltip-autocomplete ul li[aria-selected]": { + background: "#17c", + color: "white", + }, + "&dark .cm-tooltip-autocomplete ul li[aria-selected]": { + background: "#347", + color: "white", + }, + ".cm-completionListIncompleteTop:before, .cm-completionListIncompleteBottom:after": { + content: '"···"', + opacity: 0.5, + display: "block", + textAlign: "center" + }, + ".cm-tooltip.cm-completionInfo": { + position: "absolute", + padding: "3px 9px", + width: "max-content", + maxWidth: `${400 /* Info.Width */}px`, + boxSizing: "border-box" + }, + ".cm-completionInfo.cm-completionInfo-left": { right: "100%" }, + ".cm-completionInfo.cm-completionInfo-right": { left: "100%" }, + ".cm-completionInfo.cm-completionInfo-left-narrow": { right: `${30 /* Info.Margin */}px` }, + ".cm-completionInfo.cm-completionInfo-right-narrow": { left: `${30 /* Info.Margin */}px` }, + "&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" + }, + ".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: "'🔑\uFE0E'" } // Disable emoji rendering + }, + ".cm-completionIcon-namespace": { + "&:after": { content: "'▢'" } + }, + ".cm-completionIcon-text": { + "&:after": { content: "'abc'", fontSize: "50%", verticalAlign: "middle" } + } + }); + + const defaults = { + brackets: ["(", "[", "{", "'", '"'], + before: ")]}:;>", + stringPrefixes: [] + }; + const closeBracketEffect = /*@__PURE__*/StateEffect.define({ + map(value, mapping) { + let mapped = mapping.mapPos(value, -1, MapMode.TrackAfter); + return mapped == null ? undefined : mapped; + } + }); + const skipBracketEffect = /*@__PURE__*/StateEffect.define({ + map(value, mapping) { return mapping.mapPos(value); } + }); + const closedBracket = /*@__PURE__*/new class extends RangeValue { + }; + closedBracket.startSide = 1; + closedBracket.endSide = -1; + const bracketState = /*@__PURE__*/StateField.define({ + create() { return RangeSet.empty; }, + update(value, tr) { + if (tr.selection) { + let lineStart = tr.state.doc.lineAt(tr.selection.main.head).from; + let prevLineStart = tr.startState.doc.lineAt(tr.startState.selection.main.head).from; + if (lineStart != tr.changes.mapPos(prevLineStart, -1)) + value = RangeSet.empty; + } + value = value.map(tr.changes); + for (let effect of tr.effects) { + if (effect.is(closeBracketEffect)) + value = value.update({ add: [closedBracket.range(effect.value, effect.value + 1)] }); + else if (effect.is(skipBracketEffect)) + value = value.update({ filter: from => from != effect.value }); + } + return value; + } + }); + /** + Extension to enable bracket-closing behavior. When a closeable + bracket is typed, its closing bracket is immediately inserted + after the cursor. When closing a bracket directly in front of a + closing bracket inserted by the extension, the cursor moves over + that bracket. + */ + function closeBrackets() { + return [inputHandler, bracketState]; + } + const definedClosing = "()[]{}<>"; + function closing(ch) { + for (let i = 0; i < definedClosing.length; i += 2) + if (definedClosing.charCodeAt(i) == ch) + return definedClosing.charAt(i + 1); + return fromCodePoint(ch < 128 ? ch : ch + 1); + } + function config(state, pos) { + return state.languageDataAt("closeBrackets", pos)[0] || defaults; + } + const android = typeof navigator == "object" && /*@__PURE__*//Android\b/.test(navigator.userAgent); + const inputHandler = /*@__PURE__*/EditorView.inputHandler.of((view, from, to, insert) => { + if ((android ? view.composing : view.compositionStarted) || view.state.readOnly) + return false; + let sel = view.state.selection.main; + if (insert.length > 2 || insert.length == 2 && codePointSize(codePointAt(insert, 0)) == 1 || + from != sel.from || to != sel.to) + return false; + let tr = insertBracket(view.state, insert); + if (!tr) + return false; + view.dispatch(tr); + return true; + }); + /** + Command that implements deleting a pair of matching brackets when + the cursor is between them. + */ + const deleteBracketPair = ({ state, dispatch }) => { + if (state.readOnly) + return false; + let conf = config(state, state.selection.main.head); + let tokens = conf.brackets || defaults.brackets; + let dont = null, changes = state.changeByRange(range => { + if (range.empty) { + let before = prevChar(state.doc, range.head); + for (let token of tokens) { + if (token == before && nextChar(state.doc, range.head) == closing(codePointAt(token, 0))) + return { changes: { from: range.head - token.length, to: range.head + token.length }, + range: EditorSelection.cursor(range.head - token.length) }; + } + } + return { range: dont = range }; + }); + if (!dont) + dispatch(state.update(changes, { scrollIntoView: true, userEvent: "delete.backward" })); + return !dont; + }; + /** + Close-brackets related key bindings. Binds Backspace to + [`deleteBracketPair`](https://codemirror.net/6/docs/ref/#autocomplete.deleteBracketPair). + */ + const closeBracketsKeymap = [ + { key: "Backspace", run: deleteBracketPair } + ]; + /** + Implements the extension's behavior on text insertion. If the + given string counts as a bracket in the language around the + selection, and replacing the selection with it requires custom + behavior (inserting a closing version or skipping past a + previously-closed bracket), this function returns a transaction + representing that custom behavior. (You only need this if you want + to programmatically insert brackets—the + [`closeBrackets`](https://codemirror.net/6/docs/ref/#autocomplete.closeBrackets) extension will + take care of running this for user input.) + */ + function insertBracket(state, bracket) { + let conf = config(state, state.selection.main.head); + let tokens = conf.brackets || defaults.brackets; + for (let tok of tokens) { + let closed = closing(codePointAt(tok, 0)); + if (bracket == tok) + return closed == tok ? handleSame(state, tok, tokens.indexOf(tok + tok + tok) > -1, conf) + : handleOpen(state, tok, closed, conf.before || defaults.before); + if (bracket == closed && closedBracketAt(state, state.selection.main.from)) + return handleClose(state, tok, closed); + } + return null; + } + function closedBracketAt(state, pos) { + let found = false; + state.field(bracketState).between(0, state.doc.length, from => { + if (from == pos) + found = true; + }); + return found; + } + function nextChar(doc, pos) { + let next = doc.sliceString(pos, pos + 2); + return next.slice(0, codePointSize(codePointAt(next, 0))); + } + function prevChar(doc, pos) { + let prev = doc.sliceString(pos - 2, pos); + return codePointSize(codePointAt(prev, 0)) == prev.length ? prev : prev.slice(1); + } + function handleOpen(state, open, close, closeBefore) { + let dont = null, changes = state.changeByRange(range => { + if (!range.empty) + return { changes: [{ insert: open, from: range.from }, { insert: close, from: range.to }], + effects: closeBracketEffect.of(range.to + open.length), + range: EditorSelection.range(range.anchor + open.length, range.head + open.length) }; + let next = nextChar(state.doc, range.head); + if (!next || /\s/.test(next) || closeBefore.indexOf(next) > -1) + return { changes: { insert: open + close, from: range.head }, + effects: closeBracketEffect.of(range.head + open.length), + range: EditorSelection.cursor(range.head + open.length) }; + return { range: dont = range }; + }); + return dont ? null : state.update(changes, { + scrollIntoView: true, + userEvent: "input.type" + }); + } + function handleClose(state, _open, close) { + let dont = null, moved = state.selection.ranges.map(range => { + if (range.empty && nextChar(state.doc, range.head) == close) + return EditorSelection.cursor(range.head + close.length); + return dont = range; + }); + return dont ? null : state.update({ + selection: EditorSelection.create(moved, state.selection.mainIndex), + scrollIntoView: true, + effects: state.selection.ranges.map(({ from }) => skipBracketEffect.of(from)) + }); + } + // Handles cases where the open and close token are the same, and + // possibly triple quotes (as in `"""abc"""`-style quoting). + function handleSame(state, token, allowTriple, config) { + let stringPrefixes = config.stringPrefixes || defaults.stringPrefixes; + let dont = null, changes = state.changeByRange(range => { + if (!range.empty) + return { changes: [{ insert: token, from: range.from }, { insert: token, from: range.to }], + effects: closeBracketEffect.of(range.to + token.length), + range: EditorSelection.range(range.anchor + token.length, range.head + token.length) }; + let pos = range.head, next = nextChar(state.doc, pos), start; + if (next == token) { + if (nodeStart(state, pos)) { + return { changes: { insert: token + token, from: pos }, + effects: closeBracketEffect.of(pos + token.length), + range: EditorSelection.cursor(pos + token.length) }; + } + else if (closedBracketAt(state, pos)) { + let isTriple = allowTriple && state.sliceDoc(pos, pos + token.length * 3) == token + token + token; + return { range: EditorSelection.cursor(pos + token.length * (isTriple ? 3 : 1)), + effects: skipBracketEffect.of(pos) }; + } + } + else if (allowTriple && state.sliceDoc(pos - 2 * token.length, pos) == token + token && + (start = canStartStringAt(state, pos - 2 * token.length, stringPrefixes)) > -1 && + nodeStart(state, start)) { + return { changes: { insert: token + token + token + token, from: pos }, + effects: closeBracketEffect.of(pos + token.length), + range: EditorSelection.cursor(pos + token.length) }; + } + else if (state.charCategorizer(pos)(next) != CharCategory.Word) { + if (canStartStringAt(state, pos, stringPrefixes) > -1 && !probablyInString(state, pos, token, stringPrefixes)) + return { changes: { insert: token + token, from: pos }, + effects: closeBracketEffect.of(pos + token.length), + range: EditorSelection.cursor(pos + token.length) }; + } + return { range: dont = range }; + }); + return dont ? null : state.update(changes, { + scrollIntoView: true, + userEvent: "input.type" + }); + } + function nodeStart(state, pos) { + let tree = syntaxTree(state).resolveInner(pos + 1); + return tree.parent && tree.from == pos; + } + function probablyInString(state, pos, quoteToken, prefixes) { + let node = syntaxTree(state).resolveInner(pos, -1); + let maxPrefix = prefixes.reduce((m, p) => Math.max(m, p.length), 0); + for (let i = 0; i < 5; i++) { + let start = state.sliceDoc(node.from, Math.min(node.to, node.from + quoteToken.length + maxPrefix)); + let quotePos = start.indexOf(quoteToken); + if (!quotePos || quotePos > -1 && prefixes.indexOf(start.slice(0, quotePos)) > -1) { + let first = node.firstChild; + while (first && first.from == node.from && first.to - first.from > quoteToken.length + quotePos) { + if (state.sliceDoc(first.to - quoteToken.length, first.to) == quoteToken) + return false; + first = first.firstChild; + } + return true; + } + let parent = node.to == pos && node.parent; + if (!parent) + break; + node = parent; + } + return false; + } + function canStartStringAt(state, pos, prefixes) { + let charCat = state.charCategorizer(pos); + if (charCat(state.sliceDoc(pos - 1, pos)) != CharCategory.Word) + return pos; + for (let prefix of prefixes) { + let start = pos - prefix.length; + if (state.sliceDoc(start, pos) == prefix && charCat(state.sliceDoc(start - 1, start)) != CharCategory.Word) + return start; + } + return -1; + } + + /** + Returns an extension that enables autocompletion. + */ + function autocompletion(config = {}) { + return [ + completionState, + completionConfig.of(config), + completionPlugin, + completionKeymapExt, + baseTheme$1 + ]; + } + /** + Basic keybindings for autocompletion. + + - Ctrl-Space: [`startCompletion`](https://codemirror.net/6/docs/ref/#autocomplete.startCompletion) + - Escape: [`closeCompletion`](https://codemirror.net/6/docs/ref/#autocomplete.closeCompletion) + - ArrowDown: [`moveCompletionSelection`](https://codemirror.net/6/docs/ref/#autocomplete.moveCompletionSelection)`(true)` + - ArrowUp: [`moveCompletionSelection`](https://codemirror.net/6/docs/ref/#autocomplete.moveCompletionSelection)`(false)` + - PageDown: [`moveCompletionSelection`](https://codemirror.net/6/docs/ref/#autocomplete.moveCompletionSelection)`(true, "page")` + - PageDown: [`moveCompletionSelection`](https://codemirror.net/6/docs/ref/#autocomplete.moveCompletionSelection)`(true, "page")` + - Enter: [`acceptCompletion`](https://codemirror.net/6/docs/ref/#autocomplete.acceptCompletion) + */ + const completionKeymap = [ + { key: "Ctrl-Space", run: startCompletion }, + { key: "Escape", run: closeCompletion }, + { key: "ArrowDown", run: /*@__PURE__*/moveCompletionSelection(true) }, + { key: "ArrowUp", run: /*@__PURE__*/moveCompletionSelection(false) }, + { key: "PageDown", run: /*@__PURE__*/moveCompletionSelection(true, "page") }, + { key: "PageUp", run: /*@__PURE__*/moveCompletionSelection(false, "page") }, + { key: "Enter", run: acceptCompletion } + ]; + const completionKeymapExt = /*@__PURE__*/Prec.highest(/*@__PURE__*/keymap.computeN([completionConfig], state => state.facet(completionConfig).defaultKeymap ? [completionKeymap] : [])); + + class SelectedDiagnostic { + constructor(from, to, diagnostic) { + this.from = from; + this.to = to; + this.diagnostic = diagnostic; + } + } + class LintState { + constructor(diagnostics, panel, selected) { + this.diagnostics = diagnostics; + this.panel = panel; + this.selected = selected; + } + static init(diagnostics, panel, state) { + // Filter the list of diagnostics for which to create markers + let markedDiagnostics = diagnostics; + let diagnosticFilter = state.facet(lintConfig).markerFilter; + if (diagnosticFilter) + markedDiagnostics = diagnosticFilter(markedDiagnostics); + let ranges = Decoration.set(markedDiagnostics.map((d) => { + // For zero-length ranges or ranges covering only a line break, create a widget + return d.from == d.to || (d.from == d.to - 1 && state.doc.lineAt(d.from).to == d.from) + ? Decoration.widget({ + widget: new DiagnosticWidget(d), + diagnostic: d + }).range(d.from) + : Decoration.mark({ + attributes: { class: "cm-lintRange cm-lintRange-" + d.severity }, + diagnostic: d + }).range(d.from, d.to); + }), true); + return new LintState(ranges, panel, findDiagnostic(ranges)); + } + } + function findDiagnostic(diagnostics, diagnostic = null, after = 0) { + let found = null; + diagnostics.between(after, 1e9, (from, to, { spec }) => { + if (diagnostic && spec.diagnostic != diagnostic) + return; + found = new SelectedDiagnostic(from, to, spec.diagnostic); + return false; + }); + return found; + } + function hideTooltip(tr, tooltip) { + return !!(tr.effects.some(e => e.is(setDiagnosticsEffect)) || tr.changes.touchesRange(tooltip.pos)); + } + function maybeEnableLint(state, effects) { + return state.field(lintState, false) ? effects : effects.concat(StateEffect.appendConfig.of([ + lintState, + EditorView.decorations.compute([lintState], state => { + let { selected, panel } = state.field(lintState); + return !selected || !panel || selected.from == selected.to ? Decoration.none : Decoration.set([ + activeMark.range(selected.from, selected.to) + ]); + }), + hoverTooltip(lintTooltip, { hideOn: hideTooltip }), + baseTheme + ])); + } + /** + Returns a transaction spec which updates the current set of + diagnostics, and enables the lint extension if if wasn't already + active. + */ + function setDiagnostics(state, diagnostics) { + return { + effects: maybeEnableLint(state, [setDiagnosticsEffect.of(diagnostics)]) + }; + } + /** + The state effect that updates the set of active diagnostics. Can + be useful when writing an extension that needs to track these. + */ + const setDiagnosticsEffect = /*@__PURE__*/StateEffect.define(); + const togglePanel = /*@__PURE__*/StateEffect.define(); + const movePanelSelection = /*@__PURE__*/StateEffect.define(); + const lintState = /*@__PURE__*/StateField.define({ + create() { + return new LintState(Decoration.none, null, null); + }, + update(value, tr) { + if (tr.docChanged) { + let mapped = value.diagnostics.map(tr.changes), selected = null; + if (value.selected) { + let selPos = tr.changes.mapPos(value.selected.from, 1); + selected = findDiagnostic(mapped, value.selected.diagnostic, selPos) || findDiagnostic(mapped, null, selPos); + } + value = new LintState(mapped, value.panel, selected); + } + for (let effect of tr.effects) { + if (effect.is(setDiagnosticsEffect)) { + value = LintState.init(effect.value, value.panel, tr.state); + } + else if (effect.is(togglePanel)) { + value = new LintState(value.diagnostics, effect.value ? LintPanel.open : null, value.selected); + } + else if (effect.is(movePanelSelection)) { + value = new LintState(value.diagnostics, value.panel, effect.value); + } + } + return value; + }, + provide: f => [showPanel.from(f, val => val.panel), + EditorView.decorations.from(f, s => s.diagnostics)] + }); + const activeMark = /*@__PURE__*/Decoration.mark({ class: "cm-lintRange cm-lintRange-active" }); + function lintTooltip(view, pos, side) { + let { diagnostics } = view.state.field(lintState); + let found = [], stackStart = 2e8, stackEnd = 0; + diagnostics.between(pos - (side < 0 ? 1 : 0), pos + (side > 0 ? 1 : 0), (from, to, { spec }) => { + if (pos >= from && pos <= to && + (from == to || ((pos > from || side > 0) && (pos < to || side < 0)))) { + found.push(spec.diagnostic); + stackStart = Math.min(from, stackStart); + stackEnd = Math.max(to, stackEnd); + } + }); + let diagnosticFilter = view.state.facet(lintConfig).tooltipFilter; + if (diagnosticFilter) + found = diagnosticFilter(found); + if (!found.length) + return null; + return { + pos: stackStart, + end: stackEnd, + above: view.state.doc.lineAt(stackStart).to < stackEnd, + create() { + return { dom: diagnosticsTooltip(view, found) }; + } + }; + } + function diagnosticsTooltip(view, diagnostics) { + return crelt("ul", { class: "cm-tooltip-lint" }, diagnostics.map(d => renderDiagnostic(view, d, false))); + } + /** + Command to open and focus the lint panel. + */ + const openLintPanel = (view) => { + let field = view.state.field(lintState, false); + if (!field || !field.panel) + view.dispatch({ effects: maybeEnableLint(view.state, [togglePanel.of(true)]) }); + let panel = getPanel(view, LintPanel.open); + if (panel) + panel.dom.querySelector(".cm-panel-lint ul").focus(); + return true; + }; + /** + Command to close the lint panel, when open. + */ + const closeLintPanel = (view) => { + let field = view.state.field(lintState, false); + if (!field || !field.panel) + return false; + view.dispatch({ effects: togglePanel.of(false) }); + return true; + }; + /** + Move the selection to the next diagnostic. + */ + const nextDiagnostic = (view) => { + let field = view.state.field(lintState, false); + if (!field) + return false; + let sel = view.state.selection.main, next = field.diagnostics.iter(sel.to + 1); + if (!next.value) { + next = field.diagnostics.iter(0); + if (!next.value || next.from == sel.from && next.to == sel.to) + return false; + } + view.dispatch({ selection: { anchor: next.from, head: next.to }, scrollIntoView: true }); + return true; + }; + /** + A set of default key bindings for the lint functionality. + + - Ctrl-Shift-m (Cmd-Shift-m on macOS): [`openLintPanel`](https://codemirror.net/6/docs/ref/#lint.openLintPanel) + - F8: [`nextDiagnostic`](https://codemirror.net/6/docs/ref/#lint.nextDiagnostic) + */ + const lintKeymap = [ + { key: "Mod-Shift-m", run: openLintPanel }, + { key: "F8", run: nextDiagnostic } + ]; + const lintPlugin = /*@__PURE__*/ViewPlugin.fromClass(class { + constructor(view) { + this.view = view; + this.timeout = -1; + this.set = true; + let { delay } = view.state.facet(lintConfig); + this.lintTime = Date.now() + delay; + this.run = this.run.bind(this); + this.timeout = setTimeout(this.run, delay); + } + run() { + let now = Date.now(); + if (now < this.lintTime - 10) { + setTimeout(this.run, this.lintTime - now); + } + else { + this.set = false; + let { state } = this.view, { sources } = state.facet(lintConfig); + Promise.all(sources.map(source => Promise.resolve(source(this.view)))).then(annotations => { + let all = annotations.reduce((a, b) => a.concat(b)); + if (this.view.state.doc == state.doc) + this.view.dispatch(setDiagnostics(this.view.state, all)); + }, error => { logException(this.view.state, error); }); + } + } + update(update) { + let config = update.state.facet(lintConfig); + if (update.docChanged || config != update.startState.facet(lintConfig)) { + this.lintTime = Date.now() + config.delay; + if (!this.set) { + this.set = true; + this.timeout = setTimeout(this.run, config.delay); + } + } + } + force() { + if (this.set) { + this.lintTime = Date.now(); + this.run(); + } + } + destroy() { + clearTimeout(this.timeout); + } + }); + const lintConfig = /*@__PURE__*/Facet.define({ + combine(input) { + return Object.assign({ sources: input.map(i => i.source) }, combineConfig(input.map(i => i.config), { + delay: 750, + markerFilter: null, + tooltipFilter: null + })); + }, + enables: lintPlugin + }); + function assignKeys(actions) { + let assigned = []; + if (actions) + actions: for (let { name } of actions) { + for (let i = 0; i < name.length; i++) { + let ch = name[i]; + if (/[a-zA-Z]/.test(ch) && !assigned.some(c => c.toLowerCase() == ch.toLowerCase())) { + assigned.push(ch); + continue actions; + } + } + assigned.push(""); + } + return assigned; + } + function renderDiagnostic(view, diagnostic, inPanel) { + var _a; + let keys = inPanel ? assignKeys(diagnostic.actions) : []; + return crelt("li", { class: "cm-diagnostic cm-diagnostic-" + diagnostic.severity }, crelt("span", { class: "cm-diagnosticText" }, diagnostic.renderMessage ? diagnostic.renderMessage() : diagnostic.message), (_a = diagnostic.actions) === null || _a === void 0 ? void 0 : _a.map((action, i) => { + let click = (e) => { + e.preventDefault(); + let found = findDiagnostic(view.state.field(lintState).diagnostics, diagnostic); + if (found) + action.apply(view, found.from, found.to); + }; + let { name } = action, keyIndex = keys[i] ? name.indexOf(keys[i]) : -1; + let nameElt = keyIndex < 0 ? name : [name.slice(0, keyIndex), + crelt("u", name.slice(keyIndex, keyIndex + 1)), + name.slice(keyIndex + 1)]; + return crelt("button", { + type: "button", + class: "cm-diagnosticAction", + onclick: click, + onmousedown: click, + "aria-label": ` Action: ${name}${keyIndex < 0 ? "" : ` (access key "${keys[i]})"`}.` + }, nameElt); + }), diagnostic.source && crelt("div", { class: "cm-diagnosticSource" }, diagnostic.source)); + } + class DiagnosticWidget extends WidgetType { + constructor(diagnostic) { + super(); + this.diagnostic = diagnostic; + } + eq(other) { return other.diagnostic == this.diagnostic; } + toDOM() { + return crelt("span", { class: "cm-lintPoint cm-lintPoint-" + this.diagnostic.severity }); + } + } + class PanelItem { + constructor(view, diagnostic) { + this.diagnostic = diagnostic; + this.id = "item_" + Math.floor(Math.random() * 0xffffffff).toString(16); + this.dom = renderDiagnostic(view, diagnostic, true); + this.dom.id = this.id; + this.dom.setAttribute("role", "option"); + } + } + class LintPanel { + constructor(view) { + this.view = view; + this.items = []; + let onkeydown = (event) => { + if (event.keyCode == 27) { // Escape + closeLintPanel(this.view); + this.view.focus(); + } + else if (event.keyCode == 38 || event.keyCode == 33) { // ArrowUp, PageUp + this.moveSelection((this.selectedIndex - 1 + this.items.length) % this.items.length); + } + else if (event.keyCode == 40 || event.keyCode == 34) { // ArrowDown, PageDown + this.moveSelection((this.selectedIndex + 1) % this.items.length); + } + else if (event.keyCode == 36) { // Home + this.moveSelection(0); + } + else if (event.keyCode == 35) { // End + this.moveSelection(this.items.length - 1); + } + else if (event.keyCode == 13) { // Enter + this.view.focus(); + } + else if (event.keyCode >= 65 && event.keyCode <= 90 && this.selectedIndex >= 0) { // A-Z + let { diagnostic } = this.items[this.selectedIndex], keys = assignKeys(diagnostic.actions); + for (let i = 0; i < keys.length; i++) + if (keys[i].toUpperCase().charCodeAt(0) == event.keyCode) { + let found = findDiagnostic(this.view.state.field(lintState).diagnostics, diagnostic); + if (found) + diagnostic.actions[i].apply(view, found.from, found.to); + } + } + else { + return; + } + event.preventDefault(); + }; + let onclick = (event) => { + for (let i = 0; i < this.items.length; i++) { + if (this.items[i].dom.contains(event.target)) + this.moveSelection(i); + } + }; + this.list = crelt("ul", { + tabIndex: 0, + role: "listbox", + "aria-label": this.view.state.phrase("Diagnostics"), + onkeydown, + onclick + }); + this.dom = crelt("div", { class: "cm-panel-lint" }, this.list, crelt("button", { + type: "button", + name: "close", + "aria-label": this.view.state.phrase("close"), + onclick: () => closeLintPanel(this.view) + }, "×")); + this.update(); + } + get selectedIndex() { + let selected = this.view.state.field(lintState).selected; + if (!selected) + return -1; + for (let i = 0; i < this.items.length; i++) + if (this.items[i].diagnostic == selected.diagnostic) + return i; + return -1; + } + update() { + let { diagnostics, selected } = this.view.state.field(lintState); + let i = 0, needsSync = false, newSelectedItem = null; + diagnostics.between(0, this.view.state.doc.length, (_start, _end, { spec }) => { + let found = -1, item; + for (let j = i; j < this.items.length; j++) + if (this.items[j].diagnostic == spec.diagnostic) { + found = j; + break; + } + if (found < 0) { + item = new PanelItem(this.view, spec.diagnostic); + this.items.splice(i, 0, item); + needsSync = true; + } + else { + item = this.items[found]; + if (found > i) { + this.items.splice(i, found - i); + needsSync = true; + } + } + if (selected && item.diagnostic == selected.diagnostic) { + if (!item.dom.hasAttribute("aria-selected")) { + item.dom.setAttribute("aria-selected", "true"); + newSelectedItem = item; + } + } + else if (item.dom.hasAttribute("aria-selected")) { + item.dom.removeAttribute("aria-selected"); + } + i++; + }); + while (i < this.items.length && !(this.items.length == 1 && this.items[0].diagnostic.from < 0)) { + needsSync = true; + this.items.pop(); + } + if (this.items.length == 0) { + this.items.push(new PanelItem(this.view, { + from: -1, to: -1, + severity: "info", + message: this.view.state.phrase("No diagnostics") + })); + needsSync = true; + } + if (newSelectedItem) { + this.list.setAttribute("aria-activedescendant", newSelectedItem.id); + this.view.requestMeasure({ + key: this, + read: () => ({ sel: newSelectedItem.dom.getBoundingClientRect(), panel: this.list.getBoundingClientRect() }), + write: ({ sel, panel }) => { + if (sel.top < panel.top) + this.list.scrollTop -= panel.top - sel.top; + else if (sel.bottom > panel.bottom) + this.list.scrollTop += sel.bottom - panel.bottom; + } + }); + } + else if (this.selectedIndex < 0) { + this.list.removeAttribute("aria-activedescendant"); + } + if (needsSync) + this.sync(); + } + sync() { + let domPos = this.list.firstChild; + function rm() { + let prev = domPos; + domPos = prev.nextSibling; + prev.remove(); + } + for (let item of this.items) { + if (item.dom.parentNode == this.list) { + while (domPos != item.dom) + rm(); + domPos = item.dom.nextSibling; + } + else { + this.list.insertBefore(item.dom, domPos); + } + } + while (domPos) + rm(); + } + moveSelection(selectedIndex) { + if (this.selectedIndex < 0) + return; + let field = this.view.state.field(lintState); + let selection = findDiagnostic(field.diagnostics, this.items[selectedIndex].diagnostic); + if (!selection) + return; + this.view.dispatch({ + selection: { anchor: selection.from, head: selection.to }, + scrollIntoView: true, + effects: movePanelSelection.of(selection) + }); + } + static open(view) { return new LintPanel(view); } + } + function svg(content, attrs = `viewBox="0 0 40 40"`) { + return `url('data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" ${attrs}>${encodeURIComponent(content)}</svg>')`; + } + function underline(color) { + return svg(`<path d="m0 2.5 l2 -1.5 l1 0 l2 1.5 l1 0" stroke="${color}" fill="none" stroke-width=".7"/>`, `width="6" height="3"`); + } + const baseTheme = /*@__PURE__*/EditorView.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-diagnosticAction": { + font: "inherit", + border: "none", + padding: "2px 4px", + backgroundColor: "#444", + color: "white", + borderRadius: "3px", + marginLeft: "8px" + }, + ".cm-diagnosticSource": { + fontSize: "70%", + opacity: .7 + }, + ".cm-lintRange": { + backgroundPosition: "left bottom", + backgroundRepeat: "repeat-x", + paddingBottom: "0.7px", + }, + ".cm-lintRange-error": { backgroundImage: /*@__PURE__*/underline("#d11") }, + ".cm-lintRange-warning": { backgroundImage: /*@__PURE__*/underline("orange") }, + ".cm-lintRange-info": { backgroundImage: /*@__PURE__*/underline("#999") }, + ".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-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 + } + } + }); + + // (The superfluous function calls around the list of extensions work + // around current limitations in tree-shaking software.) + /** + This is an extension value that just pulls together a number of + extensions that you might want in a basic editor. It is meant as a + convenient helper to quickly set up CodeMirror without installing + and importing a lot of separate packages. + + Specifically, it includes... + + - [the default command bindings](https://codemirror.net/6/docs/ref/#commands.defaultKeymap) + - [line numbers](https://codemirror.net/6/docs/ref/#view.lineNumbers) + - [special character highlighting](https://codemirror.net/6/docs/ref/#view.highlightSpecialChars) + - [the undo history](https://codemirror.net/6/docs/ref/#commands.history) + - [a fold gutter](https://codemirror.net/6/docs/ref/#language.foldGutter) + - [custom selection drawing](https://codemirror.net/6/docs/ref/#view.drawSelection) + - [drop cursor](https://codemirror.net/6/docs/ref/#view.dropCursor) + - [multiple selections](https://codemirror.net/6/docs/ref/#state.EditorState^allowMultipleSelections) + - [reindentation on input](https://codemirror.net/6/docs/ref/#language.indentOnInput) + - [the default highlight style](https://codemirror.net/6/docs/ref/#language.defaultHighlightStyle) (as fallback) + - [bracket matching](https://codemirror.net/6/docs/ref/#language.bracketMatching) + - [bracket closing](https://codemirror.net/6/docs/ref/#autocomplete.closeBrackets) + - [autocompletion](https://codemirror.net/6/docs/ref/#autocomplete.autocompletion) + - [rectangular selection](https://codemirror.net/6/docs/ref/#view.rectangularSelection) and [crosshair cursor](https://codemirror.net/6/docs/ref/#view.crosshairCursor) + - [active line highlighting](https://codemirror.net/6/docs/ref/#view.highlightActiveLine) + - [active line gutter highlighting](https://codemirror.net/6/docs/ref/#view.highlightActiveLineGutter) + - [selection match highlighting](https://codemirror.net/6/docs/ref/#search.highlightSelectionMatches) + - [search](https://codemirror.net/6/docs/ref/#search.searchKeymap) + - [linting](https://codemirror.net/6/docs/ref/#lint.lintKeymap) + + (You'll probably want to add some language package to your setup + too.) + + This extension does not allow customization. The idea is that, + once you decide you want to configure your editor more precisely, + you take this package's source (which is just a bunch of imports + and an array literal), copy it into your own code, and adjust it + as desired. + */ + const basicSetup = /*@__PURE__*/(() => [ + lineNumbers(), + highlightActiveLineGutter(), + highlightSpecialChars(), + history(), + foldGutter(), + drawSelection(), + dropCursor(), + EditorState.allowMultipleSelections.of(true), + indentOnInput(), + syntaxHighlighting(defaultHighlightStyle, { fallback: true }), + bracketMatching(), + closeBrackets(), + autocompletion(), + rectangularSelection(), + crosshairCursor(), + highlightActiveLine(), + highlightSelectionMatches(), + keymap.of([ + ...closeBracketsKeymap, + ...defaultKeymap, + ...searchKeymap, + ...historyKeymap, + ...foldKeymap, + ...completionKeymap, + ...lintKeymap + ]) + ])(); + + /// A parse stack. These are used internally by the parser to track + /// parsing progress. They also provide some properties and methods + /// that external code such as a tokenizer can use to get information + /// about the parse state. + class Stack { + /// @internal + constructor( + /// The parse that this stack is part of @internal + p, + /// Holds state, input pos, buffer index triplets for all but the + /// top state @internal + stack, + /// The current parse state @internal + state, + // The position at which the next reduce should take place. This + // can be less than `this.pos` when skipped expressions have been + // added to the stack (which should be moved outside of the next + // reduction) + /// @internal + reducePos, + /// The input position up to which this stack has parsed. + pos, + /// The dynamic score of the stack, including dynamic precedence + /// and error-recovery penalties + /// @internal + score, + // The output buffer. Holds (type, start, end, size) quads + // representing nodes created by the parser, where `size` is + // amount of buffer array entries covered by this node. + /// @internal + buffer, + // The base offset of the buffer. When stacks are split, the split + // instance shared the buffer history with its parent up to + // `bufferBase`, which is the absolute offset (including the + // offset of previous splits) into the buffer at which this stack + // starts writing. + /// @internal + bufferBase, + /// @internal + curContext, + /// @internal + lookAhead = 0, + // A parent stack from which this was split off, if any. This is + // set up so that it always points to a stack that has some + // additional buffer content, never to a stack with an equal + // `bufferBase`. + /// @internal + parent) { + this.p = p; + this.stack = stack; + this.state = state; + this.reducePos = reducePos; + this.pos = pos; + this.score = score; + this.buffer = buffer; + this.bufferBase = bufferBase; + this.curContext = curContext; + this.lookAhead = lookAhead; + this.parent = parent; + } + /// @internal + toString() { + return `[${this.stack.filter((_, i) => i % 3 == 0).concat(this.state)}]@${this.pos}${this.score ? "!" + this.score : ""}`; + } + // Start an empty stack + /// @internal + static start(p, state, pos = 0) { + let cx = p.parser.context; + return new Stack(p, [], state, pos, pos, 0, [], 0, cx ? new StackContext(cx, cx.start) : null, 0, null); + } + /// The stack's current [context](#lr.ContextTracker) value, if + /// any. Its type will depend on the context tracker's type + /// parameter, or it will be `null` if there is no context + /// tracker. + get context() { return this.curContext ? this.curContext.context : null; } + // Push a state onto the stack, tracking its start position as well + // as the buffer base at that point. + /// @internal + pushState(state, start) { + this.stack.push(this.state, start, this.bufferBase + this.buffer.length); + this.state = state; + } + // Apply a reduce action + /// @internal + reduce(action) { + let depth = action >> 19 /* ReduceDepthShift */, type = action & 65535 /* ValueMask */; + let { parser } = this.p; + let dPrec = parser.dynamicPrecedence(type); + if (dPrec) + this.score += dPrec; + if (depth == 0) { + this.pushState(parser.getGoto(this.state, type, true), this.reducePos); + // Zero-depth reductions are a special case—they add stuff to + // the stack without popping anything off. + if (type < parser.minRepeatTerm) + this.storeNode(type, this.reducePos, this.reducePos, 4, true); + this.reduceContext(type, this.reducePos); + return; + } + // Find the base index into `this.stack`, content after which will + // be dropped. Note that with `StayFlag` reductions we need to + // consume two extra frames (the dummy parent node for the skipped + // expression and the state that we'll be staying in, which should + // be moved to `this.state`). + let base = this.stack.length - ((depth - 1) * 3) - (action & 262144 /* StayFlag */ ? 6 : 0); + let start = this.stack[base - 2]; + let bufferBase = this.stack[base - 1], count = this.bufferBase + this.buffer.length - bufferBase; + // Store normal terms or `R -> R R` repeat reductions + if (type < parser.minRepeatTerm || (action & 131072 /* RepeatFlag */)) { + let pos = parser.stateFlag(this.state, 1 /* Skipped */) ? this.pos : this.reducePos; + this.storeNode(type, start, pos, count + 4, true); + } + if (action & 262144 /* StayFlag */) { + this.state = this.stack[base]; + } + else { + let baseStateID = this.stack[base - 3]; + this.state = parser.getGoto(baseStateID, type, true); + } + while (this.stack.length > base) + this.stack.pop(); + this.reduceContext(type, start); + } + // Shift a value into the buffer + /// @internal + storeNode(term, start, end, size = 4, isReduce = false) { + if (term == 0 /* Err */ && + (!this.stack.length || this.stack[this.stack.length - 1] < this.buffer.length + this.bufferBase)) { + // Try to omit/merge adjacent error nodes + let cur = this, top = this.buffer.length; + if (top == 0 && cur.parent) { + top = cur.bufferBase - cur.parent.bufferBase; + cur = cur.parent; + } + if (top > 0 && cur.buffer[top - 4] == 0 /* Err */ && cur.buffer[top - 1] > -1) { + if (start == end) + return; + if (cur.buffer[top - 2] >= start) { + cur.buffer[top - 2] = end; + return; + } + } + } + if (!isReduce || this.pos == end) { // Simple case, just append + this.buffer.push(term, start, end, size); + } + else { // There may be skipped nodes that have to be moved forward + let index = this.buffer.length; + if (index > 0 && this.buffer[index - 4] != 0 /* Err */) + while (index > 0 && this.buffer[index - 2] > end) { + // Move this record forward + this.buffer[index] = this.buffer[index - 4]; + this.buffer[index + 1] = this.buffer[index - 3]; + this.buffer[index + 2] = this.buffer[index - 2]; + this.buffer[index + 3] = this.buffer[index - 1]; + index -= 4; + if (size > 4) + size -= 4; + } + this.buffer[index] = term; + this.buffer[index + 1] = start; + this.buffer[index + 2] = end; + this.buffer[index + 3] = size; + } + } + // Apply a shift action + /// @internal + shift(action, next, nextEnd) { + let start = this.pos; + if (action & 131072 /* GotoFlag */) { + this.pushState(action & 65535 /* ValueMask */, this.pos); + } + else if ((action & 262144 /* StayFlag */) == 0) { // Regular shift + let nextState = action, { parser } = this.p; + if (nextEnd > this.pos || next <= parser.maxNode) { + this.pos = nextEnd; + if (!parser.stateFlag(nextState, 1 /* Skipped */)) + this.reducePos = nextEnd; + } + this.pushState(nextState, start); + this.shiftContext(next, start); + if (next <= parser.maxNode) + this.buffer.push(next, start, nextEnd, 4); + } + else { // Shift-and-stay, which means this is a skipped token + this.pos = nextEnd; + this.shiftContext(next, start); + if (next <= this.p.parser.maxNode) + this.buffer.push(next, start, nextEnd, 4); + } + } + // Apply an action + /// @internal + apply(action, next, nextEnd) { + if (action & 65536 /* ReduceFlag */) + this.reduce(action); + else + this.shift(action, next, nextEnd); + } + // Add a prebuilt (reused) node into the buffer. + /// @internal + useNode(value, next) { + let index = this.p.reused.length - 1; + if (index < 0 || this.p.reused[index] != value) { + this.p.reused.push(value); + index++; + } + let start = this.pos; + this.reducePos = this.pos = start + value.length; + this.pushState(next, start); + this.buffer.push(index, start, this.reducePos, -1 /* size == -1 means this is a reused value */); + if (this.curContext) + this.updateContext(this.curContext.tracker.reuse(this.curContext.context, value, this, this.p.stream.reset(this.pos - value.length))); + } + // Split the stack. Due to the buffer sharing and the fact + // that `this.stack` tends to stay quite shallow, this isn't very + // expensive. + /// @internal + split() { + let parent = this; + let off = parent.buffer.length; + // Because the top of the buffer (after this.pos) may be mutated + // to reorder reductions and skipped tokens, and shared buffers + // should be immutable, this copies any outstanding skipped tokens + // to the new buffer, and puts the base pointer before them. + while (off > 0 && parent.buffer[off - 2] > parent.reducePos) + off -= 4; + let buffer = parent.buffer.slice(off), base = parent.bufferBase + off; + // Make sure parent points to an actual parent with content, if there is such a parent. + while (parent && base == parent.bufferBase) + parent = parent.parent; + return new Stack(this.p, this.stack.slice(), this.state, this.reducePos, this.pos, this.score, buffer, base, this.curContext, this.lookAhead, parent); + } + // Try to recover from an error by 'deleting' (ignoring) one token. + /// @internal + recoverByDelete(next, nextEnd) { + let isNode = next <= this.p.parser.maxNode; + if (isNode) + this.storeNode(next, this.pos, nextEnd, 4); + this.storeNode(0 /* Err */, this.pos, nextEnd, isNode ? 8 : 4); + this.pos = this.reducePos = nextEnd; + this.score -= 190 /* Delete */; + } + /// Check if the given term would be able to be shifted (optionally + /// after some reductions) on this stack. This can be useful for + /// external tokenizers that want to make sure they only provide a + /// given token when it applies. + canShift(term) { + for (let sim = new SimulatedStack(this);;) { + let action = this.p.parser.stateSlot(sim.state, 4 /* DefaultReduce */) || this.p.parser.hasAction(sim.state, term); + if ((action & 65536 /* ReduceFlag */) == 0) + return true; + if (action == 0) + return false; + sim.reduce(action); + } + } + // Apply up to Recover.MaxNext recovery actions that conceptually + // inserts some missing token or rule. + /// @internal + recoverByInsert(next) { + if (this.stack.length >= 300 /* MaxInsertStackDepth */) + return []; + let nextStates = this.p.parser.nextStates(this.state); + if (nextStates.length > 4 /* MaxNext */ << 1 || this.stack.length >= 120 /* DampenInsertStackDepth */) { + let best = []; + for (let i = 0, s; i < nextStates.length; i += 2) { + if ((s = nextStates[i + 1]) != this.state && this.p.parser.hasAction(s, next)) + best.push(nextStates[i], s); + } + if (this.stack.length < 120 /* DampenInsertStackDepth */) + for (let i = 0; best.length < 4 /* MaxNext */ << 1 && i < nextStates.length; i += 2) { + let s = nextStates[i + 1]; + if (!best.some((v, i) => (i & 1) && v == s)) + best.push(nextStates[i], s); + } + nextStates = best; + } + let result = []; + for (let i = 0; i < nextStates.length && result.length < 4 /* MaxNext */; i += 2) { + let s = nextStates[i + 1]; + if (s == this.state) + continue; + let stack = this.split(); + stack.pushState(s, this.pos); + stack.storeNode(0 /* Err */, stack.pos, stack.pos, 4, true); + stack.shiftContext(nextStates[i], this.pos); + stack.score -= 200 /* Insert */; + result.push(stack); + } + return result; + } + // Force a reduce, if possible. Return false if that can't + // be done. + /// @internal + forceReduce() { + let reduce = this.p.parser.stateSlot(this.state, 5 /* ForcedReduce */); + if ((reduce & 65536 /* ReduceFlag */) == 0) + return false; + let { parser } = this.p; + if (!parser.validAction(this.state, reduce)) { + let depth = reduce >> 19 /* ReduceDepthShift */, term = reduce & 65535 /* ValueMask */; + let target = this.stack.length - depth * 3; + if (target < 0 || parser.getGoto(this.stack[target], term, false) < 0) + return false; + this.storeNode(0 /* Err */, this.reducePos, this.reducePos, 4, true); + this.score -= 100 /* Reduce */; + } + this.reducePos = this.pos; + this.reduce(reduce); + return true; + } + /// @internal + forceAll() { + while (!this.p.parser.stateFlag(this.state, 2 /* Accepting */)) { + if (!this.forceReduce()) { + this.storeNode(0 /* Err */, this.pos, this.pos, 4, true); + break; + } + } + return this; + } + /// Check whether this state has no further actions (assumed to be a direct descendant of the + /// top state, since any other states must be able to continue + /// somehow). @internal + get deadEnd() { + if (this.stack.length != 3) + return false; + let { parser } = this.p; + return parser.data[parser.stateSlot(this.state, 1 /* Actions */)] == 65535 /* End */ && + !parser.stateSlot(this.state, 4 /* DefaultReduce */); + } + /// Restart the stack (put it back in its start state). Only safe + /// when this.stack.length == 3 (state is directly below the top + /// state). @internal + restart() { + this.state = this.stack[0]; + this.stack.length = 0; + } + /// @internal + sameState(other) { + if (this.state != other.state || this.stack.length != other.stack.length) + return false; + for (let i = 0; i < this.stack.length; i += 3) + if (this.stack[i] != other.stack[i]) + return false; + return true; + } + /// Get the parser used by this stack. + get parser() { return this.p.parser; } + /// Test whether a given dialect (by numeric ID, as exported from + /// the terms file) is enabled. + dialectEnabled(dialectID) { return this.p.parser.dialect.flags[dialectID]; } + shiftContext(term, start) { + if (this.curContext) + this.updateContext(this.curContext.tracker.shift(this.curContext.context, term, this, this.p.stream.reset(start))); + } + reduceContext(term, start) { + if (this.curContext) + this.updateContext(this.curContext.tracker.reduce(this.curContext.context, term, this, this.p.stream.reset(start))); + } + /// @internal + emitContext() { + let last = this.buffer.length - 1; + if (last < 0 || this.buffer[last] != -3) + this.buffer.push(this.curContext.hash, this.reducePos, this.reducePos, -3); + } + /// @internal + emitLookAhead() { + let last = this.buffer.length - 1; + if (last < 0 || this.buffer[last] != -4) + this.buffer.push(this.lookAhead, this.reducePos, this.reducePos, -4); + } + updateContext(context) { + if (context != this.curContext.context) { + let newCx = new StackContext(this.curContext.tracker, context); + if (newCx.hash != this.curContext.hash) + this.emitContext(); + this.curContext = newCx; + } + } + /// @internal + setLookAhead(lookAhead) { + if (lookAhead > this.lookAhead) { + this.emitLookAhead(); + this.lookAhead = lookAhead; + } + } + /// @internal + close() { + if (this.curContext && this.curContext.tracker.strict) + this.emitContext(); + if (this.lookAhead > 0) + this.emitLookAhead(); + } + } + class StackContext { + constructor(tracker, context) { + this.tracker = tracker; + this.context = context; + this.hash = tracker.strict ? tracker.hash(context) : 0; + } + } + var Recover; + (function (Recover) { + Recover[Recover["Insert"] = 200] = "Insert"; + Recover[Recover["Delete"] = 190] = "Delete"; + Recover[Recover["Reduce"] = 100] = "Reduce"; + Recover[Recover["MaxNext"] = 4] = "MaxNext"; + Recover[Recover["MaxInsertStackDepth"] = 300] = "MaxInsertStackDepth"; + Recover[Recover["DampenInsertStackDepth"] = 120] = "DampenInsertStackDepth"; + })(Recover || (Recover = {})); + // Used to cheaply run some reductions to scan ahead without mutating + // an entire stack + class SimulatedStack { + constructor(start) { + this.start = start; + this.state = start.state; + this.stack = start.stack; + this.base = this.stack.length; + } + reduce(action) { + let term = action & 65535 /* ValueMask */, depth = action >> 19 /* ReduceDepthShift */; + if (depth == 0) { + if (this.stack == this.start.stack) + this.stack = this.stack.slice(); + this.stack.push(this.state, 0, 0); + this.base += 3; + } + else { + this.base -= (depth - 1) * 3; + } + let goto = this.start.p.parser.getGoto(this.stack[this.base - 3], term, true); + this.state = goto; + } + } + // This is given to `Tree.build` to build a buffer, and encapsulates + // the parent-stack-walking necessary to read the nodes. + class StackBufferCursor { + constructor(stack, pos, index) { + this.stack = stack; + this.pos = pos; + this.index = index; + this.buffer = stack.buffer; + if (this.index == 0) + this.maybeNext(); + } + static create(stack, pos = stack.bufferBase + stack.buffer.length) { + return new StackBufferCursor(stack, pos, pos - stack.bufferBase); + } + maybeNext() { + let next = this.stack.parent; + if (next != null) { + this.index = this.stack.bufferBase - next.bufferBase; + this.stack = next; + this.buffer = next.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; + if (this.index == 0) + this.maybeNext(); + } + fork() { + return new StackBufferCursor(this.stack, this.pos, this.index); + } + } + + class CachedToken { + constructor() { + this.start = -1; + this.value = -1; + this.end = -1; + this.extended = -1; + this.lookAhead = 0; + this.mask = 0; + this.context = 0; + } + } + const nullToken = new CachedToken; + /// [Tokenizers](#lr.ExternalTokenizer) interact with the input + /// through this interface. It presents the input as a stream of + /// characters, tracking lookahead and hiding the complexity of + /// [ranges](#common.Parser.parse^ranges) from tokenizer code. + class InputStream { + /// @internal + constructor( + /// @internal + input, + /// @internal + ranges) { + this.input = input; + this.ranges = ranges; + /// @internal + this.chunk = ""; + /// @internal + this.chunkOff = 0; + /// Backup chunk + this.chunk2 = ""; + this.chunk2Pos = 0; + /// The character code of the next code unit in the input, or -1 + /// when the stream is at the end of the input. + this.next = -1; + /// @internal + this.token = nullToken; + this.rangeIndex = 0; + this.pos = this.chunkPos = ranges[0].from; + this.range = ranges[0]; + this.end = ranges[ranges.length - 1].to; + this.readNext(); + } + /// @internal + resolveOffset(offset, assoc) { + let range = this.range, index = this.rangeIndex; + let pos = this.pos + offset; + while (pos < range.from) { + if (!index) + return null; + let next = this.ranges[--index]; + pos -= range.from - next.to; + range = next; + } + while (assoc < 0 ? pos > range.to : pos >= range.to) { + if (index == this.ranges.length - 1) + return null; + let next = this.ranges[++index]; + pos += next.from - range.to; + range = next; + } + return pos; + } + /// @internal + clipPos(pos) { + if (pos >= this.range.from && pos < this.range.to) + return pos; + for (let range of this.ranges) + if (range.to > pos) + return Math.max(pos, range.from); + return this.end; + } + /// Look at a code unit near the stream position. `.peek(0)` equals + /// `.next`, `.peek(-1)` gives you the previous character, and so + /// on. + /// + /// Note that looking around during tokenizing creates dependencies + /// on potentially far-away content, which may reduce the + /// effectiveness incremental parsing—when looking forward—or even + /// cause invalid reparses when looking backward more than 25 code + /// units, since the library does not track lookbehind. + peek(offset) { + let idx = this.chunkOff + offset, pos, result; + if (idx >= 0 && idx < this.chunk.length) { + pos = this.pos + offset; + result = this.chunk.charCodeAt(idx); + } + else { + let resolved = this.resolveOffset(offset, 1); + if (resolved == null) + return -1; + pos = resolved; + if (pos >= this.chunk2Pos && pos < this.chunk2Pos + this.chunk2.length) { + result = this.chunk2.charCodeAt(pos - this.chunk2Pos); + } + else { + let i = this.rangeIndex, range = this.range; + while (range.to <= pos) + range = this.ranges[++i]; + this.chunk2 = this.input.chunk(this.chunk2Pos = pos); + if (pos + this.chunk2.length > range.to) + this.chunk2 = this.chunk2.slice(0, range.to - pos); + result = this.chunk2.charCodeAt(0); + } + } + if (pos >= this.token.lookAhead) + this.token.lookAhead = pos + 1; + return result; + } + /// Accept a token. By default, the end of the token is set to the + /// current stream position, but you can pass an offset (relative to + /// the stream position) to change that. + acceptToken(token, endOffset = 0) { + let end = endOffset ? this.resolveOffset(endOffset, -1) : this.pos; + if (end == null || end < this.token.start) + throw new RangeError("Token end out of bounds"); + this.token.value = token; + this.token.end = end; + } + getChunk() { + if (this.pos >= this.chunk2Pos && this.pos < this.chunk2Pos + this.chunk2.length) { + let { chunk, chunkPos } = this; + this.chunk = this.chunk2; + this.chunkPos = this.chunk2Pos; + this.chunk2 = chunk; + this.chunk2Pos = chunkPos; + this.chunkOff = this.pos - this.chunkPos; + } + else { + this.chunk2 = this.chunk; + this.chunk2Pos = this.chunkPos; + let nextChunk = this.input.chunk(this.pos); + let end = this.pos + nextChunk.length; + this.chunk = end > this.range.to ? nextChunk.slice(0, this.range.to - this.pos) : nextChunk; + this.chunkPos = this.pos; + this.chunkOff = 0; + } + } + readNext() { + if (this.chunkOff >= this.chunk.length) { + this.getChunk(); + if (this.chunkOff == this.chunk.length) + return this.next = -1; + } + return this.next = this.chunk.charCodeAt(this.chunkOff); + } + /// Move the stream forward N (defaults to 1) code units. Returns + /// the new value of [`next`](#lr.InputStream.next). + advance(n = 1) { + this.chunkOff += n; + while (this.pos + n >= this.range.to) { + if (this.rangeIndex == this.ranges.length - 1) + return this.setDone(); + n -= this.range.to - this.pos; + this.range = this.ranges[++this.rangeIndex]; + this.pos = this.range.from; + } + this.pos += n; + if (this.pos >= this.token.lookAhead) + this.token.lookAhead = this.pos + 1; + return this.readNext(); + } + setDone() { + this.pos = this.chunkPos = this.end; + this.range = this.ranges[this.rangeIndex = this.ranges.length - 1]; + this.chunk = ""; + return this.next = -1; + } + /// @internal + reset(pos, token) { + if (token) { + this.token = token; + token.start = pos; + token.lookAhead = pos + 1; + token.value = token.extended = -1; + } + else { + this.token = nullToken; + } + if (this.pos != pos) { + this.pos = pos; + if (pos == this.end) { + this.setDone(); + return this; + } + while (pos < this.range.from) + this.range = this.ranges[--this.rangeIndex]; + while (pos >= this.range.to) + this.range = this.ranges[++this.rangeIndex]; + if (pos >= this.chunkPos && pos < this.chunkPos + this.chunk.length) { + this.chunkOff = pos - this.chunkPos; + } + else { + this.chunk = ""; + this.chunkOff = 0; + } + this.readNext(); + } + return this; + } + /// @internal + read(from, to) { + if (from >= this.chunkPos && to <= this.chunkPos + this.chunk.length) + return this.chunk.slice(from - this.chunkPos, to - this.chunkPos); + if (from >= this.chunk2Pos && to <= this.chunk2Pos + this.chunk2.length) + return this.chunk2.slice(from - this.chunk2Pos, to - this.chunk2Pos); + if (from >= this.range.from && to <= this.range.to) + return this.input.read(from, to); + let result = ""; + for (let r of this.ranges) { + if (r.from >= to) + break; + if (r.to > from) + result += this.input.read(Math.max(r.from, from), Math.min(r.to, to)); + } + return result; + } + } + /// @internal + class TokenGroup { + constructor(data, id) { + this.data = data; + this.id = id; + } + token(input, stack) { readToken(this.data, input, stack, this.id); } + } + TokenGroup.prototype.contextual = TokenGroup.prototype.fallback = TokenGroup.prototype.extend = false; + /// `@external tokens` declarations in the grammar should resolve to + /// an instance of this class. + class ExternalTokenizer { + /// Create a tokenizer. The first argument is the function that, + /// given an input stream, scans for the types of tokens it + /// recognizes at the stream's position, and calls + /// [`acceptToken`](#lr.InputStream.acceptToken) when it finds + /// one. + constructor( + /// @internal + token, options = {}) { + this.token = token; + this.contextual = !!options.contextual; + this.fallback = !!options.fallback; + this.extend = !!options.extend; + } + } + // Tokenizer data is stored a big uint16 array containing, for each + // state: + // + // - A group bitmask, indicating what token groups are reachable from + // this state, so that paths that can only lead to tokens not in + // any of the current groups can be cut off early. + // + // - The position of the end of the state's sequence of accepting + // tokens + // + // - The number of outgoing edges for the state + // + // - The accepting tokens, as (token id, group mask) pairs + // + // - The outgoing edges, as (start character, end character, state + // index) triples, with end character being exclusive + // + // This function interprets that data, running through a stream as + // long as new states with the a matching group mask can be reached, + // and updating `input.token` when it matches a token. + function readToken(data, input, stack, group) { + let state = 0, groupMask = 1 << group, { parser } = stack.p, { dialect } = parser; + scan: for (;;) { + if ((groupMask & data[state]) == 0) + break; + let accEnd = data[state + 1]; + // Check whether this state can lead to a token in the current group + // Accept tokens in this state, possibly overwriting + // lower-precedence / shorter tokens + for (let i = state + 3; i < accEnd; i += 2) + if ((data[i + 1] & groupMask) > 0) { + let term = data[i]; + if (dialect.allows(term) && + (input.token.value == -1 || input.token.value == term || parser.overrides(term, input.token.value))) { + input.acceptToken(term); + break; + } + } + let next = input.next, low = 0, high = data[state + 2]; + // Special case for EOF + if (input.next < 0 && high > low && data[accEnd + high * 3 - 3] == 65535 /* End */) { + state = data[accEnd + high * 3 - 1]; + continue scan; + } + // Do a binary search on the state's edges + for (; low < high;) { + let mid = (low + high) >> 1; + let index = accEnd + mid + (mid << 1); + let from = data[index], to = data[index + 1]; + if (next < from) + high = mid; + else if (next >= to) + low = mid + 1; + else { + state = data[index + 2]; + input.advance(); + continue scan; + } + } + break; + } + } + + // See lezer-generator/src/encode.ts for comments about the encoding + // used here + function decodeArray(input, Type = Uint16Array) { + if (typeof input != "string") + return input; + let array = null; + for (let pos = 0, out = 0; pos < input.length;) { + let value = 0; + for (;;) { + let next = input.charCodeAt(pos++), stop = false; + if (next == 126 /* BigValCode */) { + value = 65535 /* BigVal */; + break; + } + if (next >= 92 /* Gap2 */) + next--; + if (next >= 34 /* Gap1 */) + next--; + let digit = next - 32 /* Start */; + if (digit >= 46 /* Base */) { + digit -= 46 /* Base */; + stop = true; + } + value += digit; + if (stop) + break; + value *= 46 /* Base */; + } + if (array) + array[out++] = value; + else + array = new Type(value); + } + return array; + } + + // Environment variable used to control console output + const verbose = typeof process != "undefined" && process.env && /\bparse\b/.test(process.env.LOG); + let stackIDs = null; + var Safety; + (function (Safety) { + Safety[Safety["Margin"] = 25] = "Margin"; + })(Safety || (Safety = {})); + function cutAt(tree, pos, side) { + let cursor = tree.cursor(IterMode.IncludeAnonymous); + cursor.moveTo(pos); + for (;;) { + if (!(side < 0 ? cursor.childBefore(pos) : cursor.childAfter(pos))) + for (;;) { + if ((side < 0 ? cursor.to < pos : cursor.from > pos) && !cursor.type.isError) + return side < 0 ? Math.max(0, Math.min(cursor.to - 1, pos - 25 /* Margin */)) + : Math.min(tree.length, Math.max(cursor.from + 1, pos + 25 /* Margin */)); + if (side < 0 ? cursor.prevSibling() : cursor.nextSibling()) + break; + if (!cursor.parent()) + return side < 0 ? 0 : tree.length; + } + } + } + class FragmentCursor { + constructor(fragments, nodeSet) { + this.fragments = fragments; + this.nodeSet = nodeSet; + this.i = 0; + this.fragment = null; + this.safeFrom = -1; + this.safeTo = -1; + this.trees = []; + this.start = []; + this.index = []; + this.nextFragment(); + } + nextFragment() { + let fr = this.fragment = this.i == this.fragments.length ? null : this.fragments[this.i++]; + if (fr) { + this.safeFrom = fr.openStart ? cutAt(fr.tree, fr.from + fr.offset, 1) - fr.offset : fr.from; + this.safeTo = fr.openEnd ? cutAt(fr.tree, fr.to + fr.offset, -1) - fr.offset : fr.to; + while (this.trees.length) { + this.trees.pop(); + this.start.pop(); + this.index.pop(); + } + this.trees.push(fr.tree); + this.start.push(-fr.offset); + this.index.push(0); + this.nextStart = this.safeFrom; + } + else { + this.nextStart = 1e9; + } + } + // `pos` must be >= any previously given `pos` for this cursor + nodeAt(pos) { + if (pos < this.nextStart) + return null; + while (this.fragment && this.safeTo <= pos) + this.nextFragment(); + if (!this.fragment) + return null; + for (;;) { + let last = this.trees.length - 1; + if (last < 0) { // End of tree + this.nextFragment(); + return null; + } + let top = this.trees[last], index = this.index[last]; + if (index == top.children.length) { + this.trees.pop(); + this.start.pop(); + this.index.pop(); + continue; + } + let next = top.children[index]; + let start = this.start[last] + top.positions[index]; + if (start > pos) { + this.nextStart = start; + return null; + } + if (next instanceof Tree) { + if (start == pos) { + if (start < this.safeFrom) + return null; + let end = start + next.length; + if (end <= this.safeTo) { + let lookAhead = next.prop(NodeProp.lookAhead); + if (!lookAhead || end + lookAhead < this.fragment.to) + return next; + } + } + this.index[last]++; + if (start + next.length >= Math.max(this.safeFrom, pos)) { // Enter this node + this.trees.push(next); + this.start.push(start); + this.index.push(0); + } + } + else { + this.index[last]++; + this.nextStart = start + next.length; + } + } + } + } + class TokenCache { + constructor(parser, stream) { + this.stream = stream; + this.tokens = []; + this.mainToken = null; + this.actions = []; + this.tokens = parser.tokenizers.map(_ => new CachedToken); + } + getActions(stack) { + let actionIndex = 0; + let main = null; + let { parser } = stack.p, { tokenizers } = parser; + let mask = parser.stateSlot(stack.state, 3 /* TokenizerMask */); + let context = stack.curContext ? stack.curContext.hash : 0; + let lookAhead = 0; + for (let i = 0; i < tokenizers.length; i++) { + if (((1 << i) & mask) == 0) + continue; + let tokenizer = tokenizers[i], token = this.tokens[i]; + if (main && !tokenizer.fallback) + continue; + if (tokenizer.contextual || token.start != stack.pos || token.mask != mask || token.context != context) { + this.updateCachedToken(token, tokenizer, stack); + token.mask = mask; + token.context = context; + } + if (token.lookAhead > token.end + 25 /* Margin */) + lookAhead = Math.max(token.lookAhead, lookAhead); + if (token.value != 0 /* Err */) { + let startIndex = actionIndex; + if (token.extended > -1) + actionIndex = this.addActions(stack, token.extended, token.end, actionIndex); + actionIndex = this.addActions(stack, token.value, token.end, actionIndex); + if (!tokenizer.extend) { + main = token; + if (actionIndex > startIndex) + break; + } + } + } + while (this.actions.length > actionIndex) + this.actions.pop(); + if (lookAhead) + stack.setLookAhead(lookAhead); + if (!main && stack.pos == this.stream.end) { + main = new CachedToken; + main.value = stack.p.parser.eofTerm; + main.start = main.end = stack.pos; + actionIndex = this.addActions(stack, main.value, main.end, actionIndex); + } + this.mainToken = main; + return this.actions; + } + getMainToken(stack) { + if (this.mainToken) + return this.mainToken; + let main = new CachedToken, { pos, p } = stack; + main.start = pos; + main.end = Math.min(pos + 1, p.stream.end); + main.value = pos == p.stream.end ? p.parser.eofTerm : 0 /* Err */; + return main; + } + updateCachedToken(token, tokenizer, stack) { + let start = this.stream.clipPos(stack.pos); + tokenizer.token(this.stream.reset(start, token), stack); + if (token.value > -1) { + let { parser } = stack.p; + for (let i = 0; i < parser.specialized.length; i++) + if (parser.specialized[i] == token.value) { + let result = parser.specializers[i](this.stream.read(token.start, token.end), stack); + if (result >= 0 && stack.p.parser.dialect.allows(result >> 1)) { + if ((result & 1) == 0 /* Specialize */) + token.value = result >> 1; + else + token.extended = result >> 1; + break; + } + } + } + else { + token.value = 0 /* Err */; + token.end = this.stream.clipPos(start + 1); + } + } + putAction(action, token, end, index) { + // Don't add duplicate actions + for (let i = 0; i < index; i += 3) + if (this.actions[i] == action) + return index; + this.actions[index++] = action; + this.actions[index++] = token; + this.actions[index++] = end; + return index; + } + addActions(stack, token, end, index) { + let { state } = stack, { parser } = stack.p, { data } = parser; + for (let set = 0; set < 2; set++) { + for (let i = parser.stateSlot(state, set ? 2 /* Skip */ : 1 /* Actions */);; i += 3) { + if (data[i] == 65535 /* End */) { + if (data[i + 1] == 1 /* Next */) { + i = pair(data, i + 2); + } + else { + if (index == 0 && data[i + 1] == 2 /* Other */) + index = this.putAction(pair(data, i + 2), token, end, index); + break; + } + } + if (data[i] == token) + index = this.putAction(pair(data, i + 1), token, end, index); + } + } + return index; + } + } + var Rec; + (function (Rec) { + Rec[Rec["Distance"] = 5] = "Distance"; + Rec[Rec["MaxRemainingPerStep"] = 3] = "MaxRemainingPerStep"; + // When two stacks have been running independently long enough to + // add this many elements to their buffers, prune one. + Rec[Rec["MinBufferLengthPrune"] = 500] = "MinBufferLengthPrune"; + Rec[Rec["ForceReduceLimit"] = 10] = "ForceReduceLimit"; + // Once a stack reaches this depth (in .stack.length) force-reduce + // it back to CutTo to avoid creating trees that overflow the stack + // on recursive traversal. + Rec[Rec["CutDepth"] = 15000] = "CutDepth"; + Rec[Rec["CutTo"] = 9000] = "CutTo"; + })(Rec || (Rec = {})); + class Parse { + constructor(parser, input, fragments, ranges) { + this.parser = parser; + this.input = input; + this.ranges = ranges; + this.recovering = 0; + this.nextStackID = 0x2654; // ♔, ♕, ♖, ♗, ♘, ♙, ♠, ♡, ♢, ♣, ♤, ♥, ♦, ♧ + this.minStackPos = 0; + this.reused = []; + this.stoppedAt = null; + this.stream = new InputStream(input, ranges); + this.tokens = new TokenCache(parser, this.stream); + this.topTerm = parser.top[1]; + let { from } = ranges[0]; + this.stacks = [Stack.start(this, parser.top[0], from)]; + this.fragments = fragments.length && this.stream.end - from > parser.bufferLength * 4 + ? new FragmentCursor(fragments, parser.nodeSet) : null; + } + get parsedPos() { + return this.minStackPos; + } + // Move the parser forward. This will process all parse stacks at + // `this.pos` and try to advance them to a further position. If no + // stack for such a position is found, it'll start error-recovery. + // + // When the parse is finished, this will return a syntax tree. When + // not, it returns `null`. + advance() { + let stacks = this.stacks, pos = this.minStackPos; + // This will hold stacks beyond `pos`. + let newStacks = this.stacks = []; + let stopped, stoppedTokens; + // Keep advancing any stacks at `pos` until they either move + // forward or can't be advanced. Gather stacks that can't be + // advanced further in `stopped`. + for (let i = 0; i < stacks.length; i++) { + let stack = stacks[i]; + for (;;) { + this.tokens.mainToken = null; + if (stack.pos > pos) { + newStacks.push(stack); + } + else if (this.advanceStack(stack, newStacks, stacks)) { + continue; + } + else { + if (!stopped) { + stopped = []; + stoppedTokens = []; + } + stopped.push(stack); + let tok = this.tokens.getMainToken(stack); + stoppedTokens.push(tok.value, tok.end); + } + break; + } + } + if (!newStacks.length) { + let finished = stopped && findFinished(stopped); + if (finished) + return this.stackToTree(finished); + if (this.parser.strict) { + if (verbose && stopped) + console.log("Stuck with token " + (this.tokens.mainToken ? this.parser.getName(this.tokens.mainToken.value) : "none")); + throw new SyntaxError("No parse at " + pos); + } + if (!this.recovering) + this.recovering = 5 /* Distance */; + } + if (this.recovering && stopped) { + let finished = this.stoppedAt != null && stopped[0].pos > this.stoppedAt ? stopped[0] + : this.runRecovery(stopped, stoppedTokens, newStacks); + if (finished) + return this.stackToTree(finished.forceAll()); + } + if (this.recovering) { + let maxRemaining = this.recovering == 1 ? 1 : this.recovering * 3 /* MaxRemainingPerStep */; + if (newStacks.length > maxRemaining) { + newStacks.sort((a, b) => b.score - a.score); + while (newStacks.length > maxRemaining) + newStacks.pop(); + } + if (newStacks.some(s => s.reducePos > pos)) + this.recovering--; + } + else if (newStacks.length > 1) { + // Prune stacks that are in the same state, or that have been + // running without splitting for a while, to avoid getting stuck + // with multiple successful stacks running endlessly on. + outer: for (let i = 0; i < newStacks.length - 1; i++) { + let stack = newStacks[i]; + for (let j = i + 1; j < newStacks.length; j++) { + let other = newStacks[j]; + if (stack.sameState(other) || + stack.buffer.length > 500 /* MinBufferLengthPrune */ && other.buffer.length > 500 /* MinBufferLengthPrune */) { + if (((stack.score - other.score) || (stack.buffer.length - other.buffer.length)) > 0) { + newStacks.splice(j--, 1); + } + else { + newStacks.splice(i--, 1); + continue outer; + } + } + } + } + } + this.minStackPos = newStacks[0].pos; + for (let i = 1; i < newStacks.length; i++) + if (newStacks[i].pos < this.minStackPos) + this.minStackPos = newStacks[i].pos; + return null; + } + stopAt(pos) { + if (this.stoppedAt != null && this.stoppedAt < pos) + throw new RangeError("Can't move stoppedAt forward"); + this.stoppedAt = pos; + } + // Returns an updated version of the given stack, or null if the + // stack can't advance normally. When `split` and `stacks` are + // given, stacks split off by ambiguous operations will be pushed to + // `split`, or added to `stacks` if they move `pos` forward. + advanceStack(stack, stacks, split) { + let start = stack.pos, { parser } = this; + let base = verbose ? this.stackID(stack) + " -> " : ""; + if (this.stoppedAt != null && start > this.stoppedAt) + return stack.forceReduce() ? stack : null; + if (this.fragments) { + let strictCx = stack.curContext && stack.curContext.tracker.strict, cxHash = strictCx ? stack.curContext.hash : 0; + for (let cached = this.fragments.nodeAt(start); cached;) { + let match = this.parser.nodeSet.types[cached.type.id] == cached.type ? parser.getGoto(stack.state, cached.type.id) : -1; + if (match > -1 && cached.length && (!strictCx || (cached.prop(NodeProp.contextHash) || 0) == cxHash)) { + stack.useNode(cached, match); + if (verbose) + console.log(base + this.stackID(stack) + ` (via reuse of ${parser.getName(cached.type.id)})`); + return true; + } + if (!(cached instanceof Tree) || cached.children.length == 0 || cached.positions[0] > 0) + break; + let inner = cached.children[0]; + if (inner instanceof Tree && cached.positions[0] == 0) + cached = inner; + else + break; + } + } + let defaultReduce = parser.stateSlot(stack.state, 4 /* DefaultReduce */); + if (defaultReduce > 0) { + stack.reduce(defaultReduce); + if (verbose) + console.log(base + this.stackID(stack) + ` (via always-reduce ${parser.getName(defaultReduce & 65535 /* ValueMask */)})`); + return true; + } + if (stack.stack.length >= 15000 /* CutDepth */) { + while (stack.stack.length > 9000 /* CutTo */ && stack.forceReduce()) { } + } + let actions = this.tokens.getActions(stack); + for (let i = 0; i < actions.length;) { + let action = actions[i++], term = actions[i++], end = actions[i++]; + let last = i == actions.length || !split; + let localStack = last ? stack : stack.split(); + localStack.apply(action, term, end); + if (verbose) + console.log(base + this.stackID(localStack) + ` (via ${(action & 65536 /* ReduceFlag */) == 0 ? "shift" + : `reduce of ${parser.getName(action & 65535 /* ValueMask */)}`} for ${parser.getName(term)} @ ${start}${localStack == stack ? "" : ", split"})`); + if (last) + return true; + else if (localStack.pos > start) + stacks.push(localStack); + else + split.push(localStack); + } + return false; + } + // Advance a given stack forward as far as it will go. Returns the + // (possibly updated) stack if it got stuck, or null if it moved + // forward and was given to `pushStackDedup`. + advanceFully(stack, newStacks) { + let pos = stack.pos; + for (;;) { + if (!this.advanceStack(stack, null, null)) + return false; + if (stack.pos > pos) { + pushStackDedup(stack, newStacks); + return true; + } + } + } + runRecovery(stacks, tokens, newStacks) { + let finished = null, restarted = false; + for (let i = 0; i < stacks.length; i++) { + let stack = stacks[i], token = tokens[i << 1], tokenEnd = tokens[(i << 1) + 1]; + let base = verbose ? this.stackID(stack) + " -> " : ""; + if (stack.deadEnd) { + if (restarted) + continue; + restarted = true; + stack.restart(); + if (verbose) + console.log(base + this.stackID(stack) + " (restarted)"); + let done = this.advanceFully(stack, newStacks); + if (done) + continue; + } + let force = stack.split(), forceBase = base; + for (let j = 0; force.forceReduce() && j < 10 /* ForceReduceLimit */; j++) { + if (verbose) + console.log(forceBase + this.stackID(force) + " (via force-reduce)"); + let done = this.advanceFully(force, newStacks); + if (done) + break; + if (verbose) + forceBase = this.stackID(force) + " -> "; + } + for (let insert of stack.recoverByInsert(token)) { + if (verbose) + console.log(base + this.stackID(insert) + " (via recover-insert)"); + this.advanceFully(insert, newStacks); + } + if (this.stream.end > stack.pos) { + if (tokenEnd == stack.pos) { + tokenEnd++; + token = 0 /* Err */; + } + stack.recoverByDelete(token, tokenEnd); + if (verbose) + console.log(base + this.stackID(stack) + ` (via recover-delete ${this.parser.getName(token)})`); + pushStackDedup(stack, newStacks); + } + else if (!finished || finished.score < stack.score) { + finished = stack; + } + } + return finished; + } + // Convert the stack's buffer to a syntax tree. + stackToTree(stack) { + stack.close(); + return Tree.build({ buffer: StackBufferCursor.create(stack), + nodeSet: this.parser.nodeSet, + topID: this.topTerm, + maxBufferLength: this.parser.bufferLength, + reused: this.reused, + start: this.ranges[0].from, + length: stack.pos - this.ranges[0].from, + minRepeatType: this.parser.minRepeatTerm }); + } + stackID(stack) { + let id = (stackIDs || (stackIDs = new WeakMap)).get(stack); + if (!id) + stackIDs.set(stack, id = String.fromCodePoint(this.nextStackID++)); + return id + stack; + } + } + function pushStackDedup(stack, newStacks) { + for (let i = 0; i < newStacks.length; i++) { + let other = newStacks[i]; + if (other.pos == stack.pos && other.sameState(stack)) { + if (newStacks[i].score < stack.score) + newStacks[i] = stack; + return; + } + } + newStacks.push(stack); + } + class Dialect { + constructor(source, flags, disabled) { + this.source = source; + this.flags = flags; + this.disabled = disabled; + } + allows(term) { return !this.disabled || this.disabled[term] == 0; } + } + const id = x => x; + /// Context trackers are used to track stateful context (such as + /// indentation in the Python grammar, or parent elements in the XML + /// grammar) needed by external tokenizers. You declare them in a + /// grammar file as `@context exportName from "module"`. + /// + /// Context values should be immutable, and can be updated (replaced) + /// on shift or reduce actions. + /// + /// The export used in a `@context` declaration should be of this + /// type. + class ContextTracker { + /// Define a context tracker. + constructor(spec) { + this.start = spec.start; + this.shift = spec.shift || id; + this.reduce = spec.reduce || id; + this.reuse = spec.reuse || id; + this.hash = spec.hash || (() => 0); + this.strict = spec.strict !== false; + } + } + /// Holds the parse tables for a given grammar, as generated by + /// `lezer-generator`, and provides [methods](#common.Parser) to parse + /// content with. + class LRParser extends Parser { + /// @internal + constructor(spec) { + super(); + /// @internal + this.wrappers = []; + if (spec.version != 14 /* Version */) + throw new RangeError(`Parser version (${spec.version}) doesn't match runtime version (${14 /* Version */})`); + let nodeNames = spec.nodeNames.split(" "); + this.minRepeatTerm = nodeNames.length; + for (let i = 0; i < spec.repeatNodeCount; i++) + nodeNames.push(""); + let topTerms = Object.keys(spec.topRules).map(r => spec.topRules[r][1]); + let nodeProps = []; + for (let i = 0; i < nodeNames.length; i++) + nodeProps.push([]); + function setProp(nodeID, prop, value) { + nodeProps[nodeID].push([prop, prop.deserialize(String(value))]); + } + if (spec.nodeProps) + for (let propSpec of spec.nodeProps) { + let prop = propSpec[0]; + if (typeof prop == "string") + prop = NodeProp[prop]; + for (let i = 1; i < propSpec.length;) { + let next = propSpec[i++]; + if (next >= 0) { + setProp(next, prop, propSpec[i++]); + } + else { + let value = propSpec[i + -next]; + for (let j = -next; j > 0; j--) + setProp(propSpec[i++], prop, value); + i++; + } + } + } + this.nodeSet = new NodeSet(nodeNames.map((name, i) => NodeType.define({ + name: i >= this.minRepeatTerm ? undefined : name, + id: i, + props: nodeProps[i], + top: topTerms.indexOf(i) > -1, + error: i == 0, + skipped: spec.skippedNodes && spec.skippedNodes.indexOf(i) > -1 + }))); + if (spec.propSources) + this.nodeSet = this.nodeSet.extend(...spec.propSources); + this.strict = false; + this.bufferLength = DefaultBufferLength; + let tokenArray = decodeArray(spec.tokenData); + this.context = spec.context; + this.specializerSpecs = spec.specialized || []; + this.specialized = new Uint16Array(this.specializerSpecs.length); + for (let i = 0; i < this.specializerSpecs.length; i++) + this.specialized[i] = this.specializerSpecs[i].term; + this.specializers = this.specializerSpecs.map(getSpecializer); + this.states = decodeArray(spec.states, Uint32Array); + this.data = decodeArray(spec.stateData); + this.goto = decodeArray(spec.goto); + this.maxTerm = spec.maxTerm; + this.tokenizers = spec.tokenizers.map(value => typeof value == "number" ? new TokenGroup(tokenArray, value) : value); + this.topRules = spec.topRules; + this.dialects = spec.dialects || {}; + this.dynamicPrecedences = spec.dynamicPrecedences || null; + this.tokenPrecTable = spec.tokenPrec; + this.termNames = spec.termNames || null; + this.maxNode = this.nodeSet.types.length - 1; + this.dialect = this.parseDialect(); + this.top = this.topRules[Object.keys(this.topRules)[0]]; + } + createParse(input, fragments, ranges) { + let parse = new Parse(this, input, fragments, ranges); + for (let w of this.wrappers) + parse = w(parse, input, fragments, ranges); + return parse; + } + /// Get a goto table entry @internal + getGoto(state, term, loose = false) { + let table = this.goto; + if (term >= table[0]) + return -1; + for (let pos = table[term + 1];;) { + let groupTag = table[pos++], last = groupTag & 1; + let target = table[pos++]; + if (last && loose) + return target; + for (let end = pos + (groupTag >> 1); pos < end; pos++) + if (table[pos] == state) + return target; + if (last) + return -1; + } + } + /// Check if this state has an action for a given terminal @internal + hasAction(state, terminal) { + let data = this.data; + for (let set = 0; set < 2; set++) { + for (let i = this.stateSlot(state, set ? 2 /* Skip */ : 1 /* Actions */), next;; i += 3) { + if ((next = data[i]) == 65535 /* End */) { + if (data[i + 1] == 1 /* Next */) + next = data[i = pair(data, i + 2)]; + else if (data[i + 1] == 2 /* Other */) + return pair(data, i + 2); + else + break; + } + if (next == terminal || next == 0 /* Err */) + return pair(data, i + 1); + } + } + return 0; + } + /// @internal + stateSlot(state, slot) { + return this.states[(state * 6 /* Size */) + slot]; + } + /// @internal + stateFlag(state, flag) { + return (this.stateSlot(state, 0 /* Flags */) & flag) > 0; + } + /// @internal + validAction(state, action) { + if (action == this.stateSlot(state, 4 /* DefaultReduce */)) + return true; + for (let i = this.stateSlot(state, 1 /* Actions */);; i += 3) { + if (this.data[i] == 65535 /* End */) { + if (this.data[i + 1] == 1 /* Next */) + i = pair(this.data, i + 2); + else + return false; + } + if (action == pair(this.data, i + 1)) + return true; + } + } + /// Get the states that can follow this one through shift actions or + /// goto jumps. @internal + nextStates(state) { + let result = []; + for (let i = this.stateSlot(state, 1 /* Actions */);; i += 3) { + if (this.data[i] == 65535 /* End */) { + if (this.data[i + 1] == 1 /* Next */) + i = pair(this.data, i + 2); + else + break; + } + if ((this.data[i + 2] & (65536 /* ReduceFlag */ >> 16)) == 0) { + let value = this.data[i + 1]; + if (!result.some((v, i) => (i & 1) && v == value)) + result.push(this.data[i], value); + } + } + return result; + } + /// @internal + overrides(token, prev) { + let iPrev = findOffset(this.data, this.tokenPrecTable, prev); + return iPrev < 0 || findOffset(this.data, this.tokenPrecTable, token) < iPrev; + } + /// Configure the parser. Returns a new parser instance that has the + /// given settings modified. Settings not provided in `config` are + /// kept from the original parser. + configure(config) { + // Hideous reflection-based kludge to make it easy to create a + // slightly modified copy of a parser. + let copy = Object.assign(Object.create(LRParser.prototype), this); + if (config.props) + copy.nodeSet = this.nodeSet.extend(...config.props); + if (config.top) { + let info = this.topRules[config.top]; + if (!info) + throw new RangeError(`Invalid top rule name ${config.top}`); + copy.top = info; + } + if (config.tokenizers) + copy.tokenizers = this.tokenizers.map(t => { + let found = config.tokenizers.find(r => r.from == t); + return found ? found.to : t; + }); + if (config.specializers) { + copy.specializers = this.specializers.slice(); + copy.specializerSpecs = this.specializerSpecs.map((s, i) => { + let found = config.specializers.find(r => r.from == s.external); + if (!found) + return s; + let spec = Object.assign(Object.assign({}, s), { external: found.to }); + copy.specializers[i] = getSpecializer(spec); + return spec; + }); + } + if (config.contextTracker) + copy.context = config.contextTracker; + if (config.dialect) + copy.dialect = this.parseDialect(config.dialect); + if (config.strict != null) + copy.strict = config.strict; + if (config.wrap) + copy.wrappers = copy.wrappers.concat(config.wrap); + if (config.bufferLength != null) + copy.bufferLength = config.bufferLength; + return copy; + } + /// Tells you whether any [parse wrappers](#lr.ParserConfig.wrap) + /// are registered for this parser. + hasWrappers() { + return this.wrappers.length > 0; + } + /// Returns the name associated with a given term. This will only + /// work for all terms when the parser was generated with the + /// `--names` option. By default, only the names of tagged terms are + /// stored. + getName(term) { + return this.termNames ? this.termNames[term] : String(term <= this.maxNode && this.nodeSet.types[term].name || term); + } + /// The eof term id is always allocated directly after the node + /// types. @internal + get eofTerm() { return this.maxNode + 1; } + /// The type of top node produced by the parser. + get topNode() { return this.nodeSet.types[this.top[1]]; } + /// @internal + dynamicPrecedence(term) { + let prec = this.dynamicPrecedences; + return prec == null ? 0 : prec[term] || 0; + } + /// @internal + parseDialect(dialect) { + let values = Object.keys(this.dialects), flags = values.map(() => false); + if (dialect) + for (let part of dialect.split(" ")) { + let id = values.indexOf(part); + if (id >= 0) + flags[id] = true; + } + let disabled = null; + for (let i = 0; i < values.length; i++) + if (!flags[i]) { + for (let j = this.dialects[values[i]], id; (id = this.data[j++]) != 65535 /* End */;) + (disabled || (disabled = new Uint8Array(this.maxTerm + 1)))[id] = 1; + } + return new Dialect(dialect, flags, disabled); + } + /// Used by the output of the parser generator. Not available to + /// user code. + static deserialize(spec) { + return new LRParser(spec); + } + } + function pair(data, off) { return data[off] | (data[off + 1] << 16); } + function findOffset(data, start, term) { + for (let i = start, next; (next = data[i]) != 65535 /* End */; i++) + if (next == term) + return i - start; + return -1; + } + function findFinished(stacks) { + let best = null; + for (let stack of stacks) { + let stopped = stack.p.stoppedAt; + if ((stack.pos == stack.p.stream.end || stopped != null && stack.pos > stopped) && + stack.p.parser.stateFlag(stack.state, 2 /* Accepting */) && + (!best || best.score < stack.score)) + best = stack; + } + return best; + } + function getSpecializer(spec) { + if (spec.external) { + let mask = spec.extend ? 1 /* Extend */ : 0 /* Specialize */; + return (value, stack) => (spec.external(value, stack) << 1) | mask; + } + return spec.get; + } + + // This file was generated by lezer-generator. You probably shouldn't edit it. + const printKeyword = 1, + indent = 189, + dedent = 190, + newline$1 = 191, + newlineBracketed = 192, + newlineEmpty = 193, + eof = 194, + ParenL = 22, + ParenthesizedExpression = 23, + TupleExpression = 47, + ComprehensionExpression = 48, + BracketL = 53, + ArrayExpression = 54, + ArrayComprehensionExpression = 55, + BraceL = 57, + DictionaryExpression = 58, + DictionaryComprehensionExpression = 59, + SetExpression = 60, + SetComprehensionExpression = 61, + ArgList = 63, + subscript = 230, + FormatReplacement = 71, + importList = 255, + ParamList = 121, + SequencePattern = 142, + MappingPattern = 143, + PatternArgList = 146; + + const newline = 10, carriageReturn = 13, space = 32, tab = 9, hash = 35, parenOpen = 40, dot = 46; + + const bracketed = new Set([ + ParenthesizedExpression, TupleExpression, ComprehensionExpression, importList, ArgList, ParamList, + ArrayExpression, ArrayComprehensionExpression, subscript, + SetExpression, SetComprehensionExpression, + DictionaryExpression, DictionaryComprehensionExpression, FormatReplacement, + SequencePattern, MappingPattern, PatternArgList + ]); + + const newlines = new ExternalTokenizer((input, stack) => { + if (input.next < 0) { + input.acceptToken(eof); + } else if (input.next != newline && input.next != carriageReturn) ; else if (stack.context.depth < 0) { + input.acceptToken(newlineBracketed, 1); + } else { + input.advance(); + let spaces = 0; + while (input.next == space || input.next == tab) { input.advance(); spaces++; } + let empty = input.next == newline || input.next == carriageReturn || input.next == hash; + input.acceptToken(empty ? newlineEmpty : newline$1, -spaces); + } + }, {contextual: true, fallback: true}); + + const indentation = new ExternalTokenizer((input, stack) => { + let cDepth = stack.context.depth; + if (cDepth < 0) return + let prev = input.peek(-1); + if ((prev == newline || prev == carriageReturn) && stack.context.depth >= 0) { + let depth = 0, chars = 0; + for (;;) { + if (input.next == space) depth++; + else if (input.next == tab) depth += 8 - (depth % 8); + else break + input.advance(); + chars++; + } + if (depth != cDepth && + input.next != newline && input.next != carriageReturn && input.next != hash) { + if (depth < cDepth) input.acceptToken(dedent, -chars); + else input.acceptToken(indent); + } + } + }); + + function IndentLevel(parent, depth) { + this.parent = parent; + // -1 means this is not an actual indent level but a set of brackets + this.depth = depth; + this.hash = (parent ? parent.hash + parent.hash << 8 : 0) + depth + (depth << 4); + } + + const topIndent = new IndentLevel(null, 0); + + function countIndent(space) { + let depth = 0; + for (let i = 0; i < space.length; i++) + depth += space.charCodeAt(i) == tab ? 8 - (depth % 8) : 1; + return depth + } + + const trackIndent = new ContextTracker({ + start: topIndent, + reduce(context, term) { + return context.depth < 0 && bracketed.has(term) ? context.parent : context + }, + shift(context, term, stack, input) { + if (term == indent) return new IndentLevel(context, countIndent(input.read(input.pos, stack.pos))) + if (term == dedent) return context.parent + if (term == ParenL || term == BracketL || term == BraceL) return new IndentLevel(context, -1) + return context + }, + hash(context) { return context.hash } + }); + + const legacyPrint = new ExternalTokenizer(input => { + for (let i = 0; i < 5; i++) { + if (input.next != "print".charCodeAt(i)) return + input.advance(); + } + if (/\w/.test(String.fromCharCode(input.next))) return + for (let off = 0;; off++) { + let next = input.peek(off); + if (next == space || next == tab) continue + if (next != parenOpen && next != dot && next != newline && next != carriageReturn && next != hash) + input.acceptToken(printKeyword); + return + } + }); + + const pythonHighlighting = styleTags({ + "async \"*\" \"**\" FormatConversion FormatSpec": tags.modifier, + "for while if elif else try except finally return raise break continue with pass assert await yield": tags.controlKeyword, + "in not and or is del": tags.operatorKeyword, + "from def class global nonlocal lambda": tags.definitionKeyword, + import: tags.moduleKeyword, + "with as print": tags.keyword, + Boolean: tags.bool, + None: tags.null, + VariableName: tags.variableName, + "CallExpression/VariableName": tags.function(tags.variableName), + "FunctionDefinition/VariableName": tags.function(tags.definition(tags.variableName)), + "ClassDefinition/VariableName": tags.definition(tags.className), + PropertyName: tags.propertyName, + "CallExpression/MemberExpression/PropertyName": tags.function(tags.propertyName), + Comment: tags.lineComment, + Number: tags.number, + String: tags.string, + FormatString: tags.special(tags.string), + UpdateOp: tags.updateOperator, + ArithOp: tags.arithmeticOperator, + BitOp: tags.bitwiseOperator, + CompareOp: tags.compareOperator, + AssignOp: tags.definitionOperator, + Ellipsis: tags.punctuation, + At: tags.meta, + "( )": tags.paren, + "[ ]": tags.squareBracket, + "{ }": tags.brace, + ".": tags.derefOperator, + ", ;": tags.separator + }); + + // This file was generated by lezer-generator. You probably shouldn't edit it. + const spec_identifier = {__proto__:null,await:40, or:50, and:52, in:56, not:58, is:60, if:66, else:68, lambda:72, yield:90, from:92, async:98, for:100, None:152, True:154, False:154, del:168, pass:172, break:176, continue:180, return:184, raise:192, import:196, as:198, global:202, nonlocal:204, assert:208, elif:218, while:222, try:228, except:230, finally:232, with:236, def:240, class:250, match:261, case:267}; + const parser = LRParser.deserialize({ + version: 14, + states: "!L`O`Q$IXOOO%fQ$I[O'#G|OOQ$IS'#Cm'#CmOOQ$IS'#Cn'#CnO'UQ$IWO'#ClO(wQ$I[O'#G{OOQ$IS'#G|'#G|OOQ$IS'#DS'#DSOOQ$IS'#G{'#G{O)eQ$IWO'#CsO)uQ$IWO'#DdO*VQ$IWO'#DhOOQ$IS'#Ds'#DsO*jO`O'#DsO*rOpO'#DsO*zO!bO'#DtO+VO#tO'#DtO+bO&jO'#DtO+mO,UO'#DtO-oQ$I[O'#GmOOQ$IS'#Gm'#GmO'UQ$IWO'#GlO/RQ$I[O'#GlOOQ$IS'#E]'#E]O/jQ$IWO'#E^OOQ$IS'#Gk'#GkO/tQ$IWO'#GjOOQ$IV'#Gj'#GjO0PQ$IWO'#FPOOQ$IS'#GX'#GXO0UQ$IWO'#FOOOQ$IV'#Hx'#HxOOQ$IV'#Gi'#GiOOQ$IT'#Fh'#FhQ`Q$IXOOO'UQ$IWO'#CoO0dQ$IWO'#C{O0kQ$IWO'#DPO0yQ$IWO'#HQO1ZQ$I[O'#EQO'UQ$IWO'#EROOQ$IS'#ET'#ETOOQ$IS'#EV'#EVOOQ$IS'#EX'#EXO1oQ$IWO'#EZO2VQ$IWO'#E_O0PQ$IWO'#EaO2jQ$I[O'#EaO0PQ$IWO'#EdO/jQ$IWO'#EgO/jQ$IWO'#EkO/jQ$IWO'#EnO2uQ$IWO'#EpO2|Q$IWO'#EuO3XQ$IWO'#EqO/jQ$IWO'#EuO0PQ$IWO'#EwO0PQ$IWO'#E|O3^Q$IWO'#FROOQ$IS'#Cc'#CcOOQ$IS'#Cd'#CdOOQ$IS'#Ce'#CeOOQ$IS'#Cf'#CfOOQ$IS'#Cg'#CgOOQ$IS'#Ch'#ChOOQ$IS'#Cj'#CjO'UQ$IWO,58|O'UQ$IWO,58|O'UQ$IWO,58|O'UQ$IWO,58|O'UQ$IWO,58|O'UQ$IWO,58|O3eQ$IWO'#DmOOQ$IS,5:W,5:WO3xQ$IWO'#H[OOQ$IS,5:Z,5:ZO4VQ%1`O,5:ZO4[Q$I[O,59WO0dQ$IWO,59`O0dQ$IWO,59`O0dQ$IWO,59`O6zQ$IWO,59`O7PQ$IWO,59`O7WQ$IWO,59hO7_Q$IWO'#G{O8eQ$IWO'#GzOOQ$IS'#Gz'#GzOOQ$IS'#DY'#DYO8|Q$IWO,59_O'UQ$IWO,59_O9[Q$IWO,59_O9aQ$IWO,5:PO'UQ$IWO,5:POOQ$IS,5:O,5:OO9oQ$IWO,5:OO9tQ$IWO,5:VO'UQ$IWO,5:VO'UQ$IWO,5:TOOQ$IS,5:S,5:SO:VQ$IWO,5:SO:[Q$IWO,5:UOOOO'#Fp'#FpO:aO`O,5:_OOQ$IS,5:_,5:_OOOO'#Fq'#FqO:iOpO,5:_O:qQ$IWO'#DuOOOO'#Fr'#FrO;RO!bO,5:`OOQ$IS,5:`,5:`OOOO'#Fu'#FuO;^O#tO,5:`OOOO'#Fv'#FvO;iO&jO,5:`OOOO'#Fw'#FwO;tO,UO,5:`OOQ$IS'#Fx'#FxO<PQ$I[O,5:dO>qQ$I[O,5=WO?[Q%GlO,5=WO?{Q$I[O,5=WOOQ$IS,5:x,5:xO@dQ$IXO'#GQOAsQ$IWO,5;TOOQ$IV,5=U,5=UOBOQ$I[O'#HtOBgQ$IWO,5;kOOQ$IS-E:V-E:VOOQ$IV,5;j,5;jO3SQ$IWO'#EwOOQ$IT-E9f-E9fOBoQ$I[O,59ZODvQ$I[O,59gOEaQ$IWO'#G}OElQ$IWO'#G}O0PQ$IWO'#G}OEwQ$IWO'#DROFPQ$IWO,59kOFUQ$IWO'#HRO'UQ$IWO'#HRO/jQ$IWO,5=lOOQ$IS,5=l,5=lO/jQ$IWO'#D|OOQ$IS'#D}'#D}OFsQ$IWO'#FzOGTQ$IWO,58zOGTQ$IWO,58zO)hQ$IWO,5:jOGcQ$I[O'#HTOOQ$IS,5:m,5:mOOQ$IS,5:u,5:uOGvQ$IWO,5:yOHXQ$IWO,5:{OOQ$IS'#F}'#F}OHgQ$I[O,5:{OHuQ$IWO,5:{OHzQ$IWO'#HwOOQ$IS,5;O,5;OOIYQ$IWO'#HsOOQ$IS,5;R,5;RO3XQ$IWO,5;VO3XQ$IWO,5;YOIkQ$I[O'#HyO'UQ$IWO'#HyOIuQ$IWO,5;[O2uQ$IWO,5;[O/jQ$IWO,5;aO0PQ$IWO,5;cOIzQ$IXO'#ElOKTQ$IZO,5;]ONiQ$IWO'#HzO3XQ$IWO,5;aONtQ$IWO,5;cONyQ$IWO,5;hO! RQ$I[O,5;mO'UQ$IWO,5;mO!#uQ$I[O1G.hO!#|Q$I[O1G.hO!&mQ$I[O1G.hO!&wQ$I[O1G.hO!)bQ$I[O1G.hO!)uQ$I[O1G.hO!*YQ$IWO'#HZO!*hQ$I[O'#GmO/jQ$IWO'#HZO!*rQ$IWO'#HYOOQ$IS,5:X,5:XO!*zQ$IWO,5:XO!+PQ$IWO'#H]O!+[Q$IWO'#H]O!+oQ$IWO,5=vOOQ$IS'#Dq'#DqOOQ$IS1G/u1G/uOOQ$IS1G.z1G.zO!,oQ$I[O1G.zO!,vQ$I[O1G.zO0dQ$IWO1G.zO!-cQ$IWO1G/SOOQ$IS'#DX'#DXO/jQ$IWO,59rOOQ$IS1G.y1G.yO!-jQ$IWO1G/cO!-zQ$IWO1G/cO!.SQ$IWO1G/dO'UQ$IWO'#HSO!.XQ$IWO'#HSO!.^Q$I[O1G.yO!.nQ$IWO,59gO!/tQ$IWO,5=rO!0UQ$IWO,5=rO!0^Q$IWO1G/kO!0cQ$I[O1G/kOOQ$IS1G/j1G/jO!0sQ$IWO,5=mO!1jQ$IWO,5=mO/jQ$IWO1G/oO!2XQ$IWO1G/qO!2^Q$I[O1G/qO!2nQ$I[O1G/oOOQ$IS1G/n1G/nOOQ$IS1G/p1G/pOOOO-E9n-E9nOOQ$IS1G/y1G/yOOOO-E9o-E9oO!3OQ$IWO'#HhO/jQ$IWO'#HhO!3^Q$IWO,5:aOOOO-E9p-E9pOOQ$IS1G/z1G/zOOOO-E9s-E9sOOOO-E9t-E9tOOOO-E9u-E9uOOQ$IS-E9v-E9vO!3iQ%GlO1G2rO!4YQ$I[O1G2rO'UQ$IWO,5<eOOQ$IS,5<e,5<eOOQ$IS-E9w-E9wOOQ$IS,5<l,5<lOOQ$IS-E:O-E:OOOQ$IV1G0o1G0oO0PQ$IWO'#F|O!4qQ$I[O,5>`OOQ$IS1G1V1G1VO!5YQ$IWO1G1VOOQ$IS'#DT'#DTO/jQ$IWO,5=iOOQ$IS,5=i,5=iO!5_Q$IWO'#FiO!5jQ$IWO,59mO!5rQ$IWO1G/VO!5|Q$I[O,5=mOOQ$IS1G3W1G3WOOQ$IS,5:h,5:hO!6mQ$IWO'#GlOOQ$IS,5<f,5<fOOQ$IS-E9x-E9xO!7OQ$IWO1G.fOOQ$IS1G0U1G0UO!7^Q$IWO,5=oO!7nQ$IWO,5=oO/jQ$IWO1G0eO/jQ$IWO1G0eO0PQ$IWO1G0gOOQ$IS-E9{-E9{O!8PQ$IWO1G0gO!8[Q$IWO1G0gO!8aQ$IWO,5>cO!8oQ$IWO,5>cO!8}Q$IWO,5>_O!9eQ$IWO,5>_O!9vQ$IZO1G0qO!=XQ$IZO1G0tO!@gQ$IWO,5>eO!@qQ$IWO,5>eO!@yQ$I[O,5>eO/jQ$IWO1G0vO!ATQ$IWO1G0vO3XQ$IWO1G0{ONtQ$IWO1G0}OOQ$IV,5;W,5;WO!AYQ$IYO,5;WO!A_Q$IZO1G0wO!DsQ$IWO'#GUO3XQ$IWO1G0wO3XQ$IWO1G0wO!EQQ$IWO,5>fO!E_Q$IWO,5>fO0PQ$IWO,5>fOOQ$IV1G0{1G0{O!EgQ$IWO'#EyO!ExQ%1`O1G0}OOQ$IV1G1S1G1SO3XQ$IWO1G1SO!FQQ$IWO'#FTOOQ$IV1G1X1G1XO! RQ$I[O1G1XOOQ$IS,5=u,5=uOOQ$IS'#Dn'#DnO/jQ$IWO,5=uO!FVQ$IWO,5=tO!FjQ$IWO,5=tOOQ$IS1G/s1G/sO!FrQ$IWO,5=wO!GSQ$IWO,5=wO!G[Q$IWO,5=wO!GoQ$IWO,5=wO!HPQ$IWO,5=wOOQ$IS1G3b1G3bOOQ$IS7+$f7+$fO!5rQ$IWO7+$nO!IrQ$IWO1G.zO!IyQ$IWO1G.zOOQ$IS1G/^1G/^OOQ$IS,5<V,5<VO'UQ$IWO,5<VOOQ$IS7+$}7+$}O!JQQ$IWO7+$}OOQ$IS-E9i-E9iOOQ$IS7+%O7+%OO!JbQ$IWO,5=nO'UQ$IWO,5=nOOQ$IS7+$e7+$eO!JgQ$IWO7+$}O!JoQ$IWO7+%OO!JtQ$IWO1G3^OOQ$IS7+%V7+%VO!KUQ$IWO1G3^O!K^Q$IWO7+%VOOQ$IS,5<U,5<UO'UQ$IWO,5<UO!KcQ$IWO1G3XOOQ$IS-E9h-E9hO!LYQ$IWO7+%ZOOQ$IS7+%]7+%]O!LhQ$IWO1G3XO!MVQ$IWO7+%]O!M[Q$IWO1G3_O!MlQ$IWO1G3_O!MtQ$IWO7+%ZO!MyQ$IWO,5>SO!NaQ$IWO,5>SO!NaQ$IWO,5>SO!NoO!LQO'#DwO!NzOSO'#HiOOOO1G/{1G/{O# PQ$IWO1G/{O# XQ%GlO7+(^O# xQ$I[O1G2PP#!cQ$IWO'#FyOOQ$IS,5<h,5<hOOQ$IS-E9z-E9zOOQ$IS7+&q7+&qOOQ$IS1G3T1G3TOOQ$IS,5<T,5<TOOQ$IS-E9g-E9gOOQ$IS7+$q7+$qO#!pQ$IWO,5=WO##ZQ$IWO,5=WO##lQ$I[O,5<WO#$PQ$IWO1G3ZOOQ$IS-E9j-E9jOOQ$IS7+&P7+&PO#$aQ$IWO7+&POOQ$IS7+&R7+&RO#$oQ$IWO'#HvO0PQ$IWO'#HuO#%TQ$IWO7+&ROOQ$IS,5<k,5<kO#%`Q$IWO1G3}OOQ$IS-E9}-E9}OOQ$IS,5<g,5<gO#%nQ$IWO1G3yOOQ$IS-E9y-E9yO#&UQ$IZO7+&]O!DsQ$IWO'#GSO3XQ$IWO7+&]O3XQ$IWO7+&`O#)gQ$I[O,5<oO'UQ$IWO,5<oO#)qQ$IWO1G4POOQ$IS-E:R-E:RO#){Q$IWO1G4PO3XQ$IWO7+&bO/jQ$IWO7+&bOOQ$IV7+&g7+&gO!ExQ%1`O7+&iO#*TQ$IXO1G0rOOQ$IV-E:S-E:SO3XQ$IWO7+&cO3XQ$IWO7+&cOOQ$IV,5<p,5<pO#+yQ$IWO,5<pOOQ$IV7+&c7+&cO#,UQ$IZO7+&cO#/dQ$IWO,5<qO#/oQ$IWO1G4QOOQ$IS-E:T-E:TO#/|Q$IWO1G4QO#0UQ$IWO'#H|O#0dQ$IWO'#H|O0PQ$IWO'#H|OOQ$IS'#H|'#H|O#0oQ$IWO'#H{OOQ$IS,5;e,5;eO#0wQ$IWO,5;eO/jQ$IWO'#E{OOQ$IV7+&i7+&iO3XQ$IWO7+&iOOQ$IV7+&n7+&nO#0|Q$IYO,5;oOOQ$IV7+&s7+&sOOQ$IS1G3a1G3aOOQ$IS,5<Y,5<YO#1RQ$IWO1G3`OOQ$IS-E9l-E9lO#1fQ$IWO,5<ZO#1qQ$IWO,5<ZO#2UQ$IWO1G3cOOQ$IS-E9m-E9mO#2fQ$IWO1G3cO#2nQ$IWO1G3cO#3OQ$IWO1G3cO#2fQ$IWO1G3cOOQ$IS<<HY<<HYO#3ZQ$I[O1G1qOOQ$IS<<Hi<<HiP#3hQ$IWO'#FkO7WQ$IWO1G3YO#3uQ$IWO1G3YO#3zQ$IWO<<HiOOQ$IS<<Hj<<HjO#4[Q$IWO7+(xOOQ$IS<<Hq<<HqO#4lQ$I[O1G1pP#5]Q$IWO'#FjO#5jQ$IWO7+(yO#5zQ$IWO7+(yO#6SQ$IWO<<HuO#6XQ$IWO7+(sOOQ$IS<<Hw<<HwO#7OQ$IWO,5<XO'UQ$IWO,5<XOOQ$IS-E9k-E9kOOQ$IS<<Hu<<HuOOQ$IS,5<_,5<_O/jQ$IWO,5<_O#7TQ$IWO1G3nOOQ$IS-E9q-E9qO#7kQ$IWO1G3nOOOO'#Ft'#FtO#7yO!LQO,5:cOOOO,5>T,5>TOOOO7+%g7+%gO#8UQ$IWO1G2rO#8oQ$IWO1G2rP'UQ$IWO'#FlO/jQ$IWO<<IkO#9QQ$IWO,5>bO#9cQ$IWO,5>bO0PQ$IWO,5>bO#9tQ$IWO,5>aOOQ$IS<<Im<<ImP0PQ$IWO'#GPP/jQ$IWO'#F{OOQ$IV-E:Q-E:QO3XQ$IWO<<IwOOQ$IV,5<n,5<nO3XQ$IWO,5<nOOQ$IV<<Iw<<IwOOQ$IV<<Iz<<IzO#9yQ$I[O1G2ZP#:TQ$IWO'#GTO#:[Q$IWO7+)kO#:fQ$IZO<<I|O3XQ$IWO<<I|OOQ$IV<<JT<<JTO3XQ$IWO<<JTOOQ$IV'#GR'#GRO#=tQ$IZO7+&^OOQ$IV<<I}<<I}O#?pQ$IZO<<I}OOQ$IV1G2[1G2[O0PQ$IWO1G2[O3XQ$IWO<<I}O0PQ$IWO1G2]P/jQ$IWO'#GVO#COQ$IWO7+)lO#C]Q$IWO7+)lOOQ$IS'#Ez'#EzO/jQ$IWO,5>hO#CeQ$IWO,5>hOOQ$IS,5>h,5>hO#CpQ$IWO,5>gO#DRQ$IWO,5>gOOQ$IS1G1P1G1POOQ$IS,5;g,5;gO#DZQ$IWO1G1ZP#D`Q$IWO'#FnO#DpQ$IWO1G1uO#ETQ$IWO1G1uO#EeQ$IWO1G1uP#EpQ$IWO'#FoO#E}Q$IWO7+(}O#F_Q$IWO7+(}O#F_Q$IWO7+(}O#FgQ$IWO7+(}O#FwQ$IWO7+(tO7WQ$IWO7+(tOOQ$ISAN>TAN>TO#GbQ$IWO<<LeOOQ$ISAN>aAN>aO/jQ$IWO1G1sO#GrQ$I[O1G1sP#G|Q$IWO'#FmOOQ$IS1G1y1G1yP#HZQ$IWO'#FsO#HhQ$IWO7+)YOOOO-E9r-E9rO#IOQ$IWO7+(^OOQ$ISAN?VAN?VO#IiQ$IWO,5<jO#I}Q$IWO1G3|OOQ$IS-E9|-E9|O#J`Q$IWO1G3|OOQ$IS1G3{1G3{OOQ$IVAN?cAN?cOOQ$IV1G2Y1G2YO3XQ$IWOAN?hO#JqQ$IZOAN?hOOQ$IVAN?oAN?oOOQ$IV-E:P-E:POOQ$IV<<Ix<<IxO3XQ$IWOAN?iO3XQ$IWO7+'vOOQ$IVAN?iAN?iOOQ$IS7+'w7+'wO#NPQ$IWO<<MWOOQ$IS1G4S1G4SO/jQ$IWO1G4SOOQ$IS,5<r,5<rO#N^Q$IWO1G4ROOQ$IS-E:U-E:UOOQ$IU'#GY'#GYO#NoQ$IYO7+&uO#NzQ$IWO'#FUO$ rQ$IWO7+'aO$!SQ$IWO7+'aOOQ$IS7+'a7+'aO$!_Q$IWO<<LiO$!oQ$IWO<<LiO$!oQ$IWO<<LiO$!wQ$IWO'#HUOOQ$IS<<L`<<L`O$#RQ$IWO<<L`OOQ$IS7+'_7+'_O0PQ$IWO1G2UP0PQ$IWO'#GOO$#lQ$IWO7+)hO$#}Q$IWO7+)hOOQ$IVG25SG25SO3XQ$IWOG25SOOQ$IVG25TG25TOOQ$IV<<Kb<<KbOOQ$IS7+)n7+)nP$$`Q$IWO'#GWOOQ$IU-E:W-E:WOOQ$IV<<Ja<<JaO$%SQ$I[O'#FWOOQ$IS'#FY'#FYO$%dQ$IWO'#FXO$&UQ$IWO'#FXOOQ$IS'#FX'#FXO$&ZQ$IWO'#IOO#NzQ$IWO'#F`O#NzQ$IWO'#F`O$&rQ$IWO'#FaO#NzQ$IWO'#FbO$&yQ$IWO'#IPOOQ$IS'#IP'#IPO$'hQ$IWO,5;pOOQ$IS<<J{<<J{O$'pQ$IWO<<J{O$(QQ$IWOANBTO$(bQ$IWOANBTO$(jQ$IWO'#HVOOQ$IS'#HV'#HVO0kQ$IWO'#DaO$)TQ$IWO,5=pOOQ$ISANAzANAzOOQ$IS7+'p7+'pO$)lQ$IWO<<MSOOQ$IVLD*nLD*nO4VQ%1`O'#G[O$)}Q$I[O,5;yO#NzQ$IWO'#FdOOQ$IS,5;},5;}OOQ$IS'#FZ'#FZO$*oQ$IWO,5;sO$*tQ$IWO,5;sOOQ$IS'#F^'#F^O#NzQ$IWO'#GZO$+fQ$IWO,5;wO$,QQ$IWO,5>jO$,bQ$IWO,5>jO0PQ$IWO,5;vO$,sQ$IWO,5;zO$,xQ$IWO,5;zO#NzQ$IWO'#IQO$,}Q$IWO'#IQO$-SQ$IWO,5;{OOQ$IS,5;|,5;|O'UQ$IWO'#FgOOQ$IU1G1[1G1[O3XQ$IWO1G1[OOQ$ISAN@gAN@gO$-XQ$IWOG27oO$-iQ$IWO,59{OOQ$IS1G3[1G3[OOQ$IS,5<v,5<vOOQ$IS-E:Y-E:YO$-nQ$I[O'#FWO$-uQ$IWO'#IRO$.TQ$IWO'#IRO$.]Q$IWO,5<OOOQ$IS1G1_1G1_O$.bQ$IWO1G1_O$.gQ$IWO,5<uOOQ$IS-E:X-E:XO$/RQ$IWO,5<yO$/jQ$IWO1G4UOOQ$IS-E:]-E:]OOQ$IS1G1b1G1bOOQ$IS1G1f1G1fO$/zQ$IWO,5>lO#NzQ$IWO,5>lOOQ$IS1G1g1G1gO$0YQ$I[O,5<ROOQ$IU7+&v7+&vO$!wQ$IWO1G/gO#NzQ$IWO,5<PO$0aQ$IWO,5>mO$0hQ$IWO,5>mOOQ$IS1G1j1G1jOOQ$IS7+&y7+&yP#NzQ$IWO'#G_O$0pQ$IWO1G4WO$0zQ$IWO1G4WO$1SQ$IWO1G4WOOQ$IS7+%R7+%RO$1bQ$IWO1G1kO$1pQ$I[O'#FWO$1wQ$IWO,5<xOOQ$IS,5<x,5<xO$2VQ$IWO1G4XOOQ$IS-E:[-E:[O#NzQ$IWO,5<wO$2^Q$IWO,5<wO$2cQ$IWO7+)rOOQ$IS-E:Z-E:ZO$2mQ$IWO7+)rO#NzQ$IWO,5<QP#NzQ$IWO'#G^O$2uQ$IWO1G2cO#NzQ$IWO1G2cP$3TQ$IWO'#G]O$3[Q$IWO<<M^O$3fQ$IWO1G1lO$3tQ$IWO7+'}O7WQ$IWO'#C{O7WQ$IWO,59`O7WQ$IWO,59`O7WQ$IWO,59`O$4SQ$I[O,5=WO7WQ$IWO1G.zO/jQ$IWO1G/VO/jQ$IWO7+$nP$4gQ$IWO'#FyO'UQ$IWO'#GlO$4tQ$IWO,59`O$4yQ$IWO,59`O$5QQ$IWO,59kO$5VQ$IWO1G/SO0kQ$IWO'#DPO7WQ$IWO,59h", + stateData: "$5m~O%[OS%XOS%WOSQOS~OPhOTeOdsOfXOmtOq!SOtuO}vO!O!PO!R!VO!S!UO!VYO!ZZO!fdO!mdO!ndO!odO!vxO!xyO!zzO!|{O#O|O#S}O#U!OO#X!QO#Y!QO#[!RO#c!TO#f!WO#j!XO#l!YO#q!ZO#tlO#v![O%VqO%gQO%hQO%lRO%mVO&R[O&S]O&V^O&Y_O&``O&caO&ebO~OT!bO]!bO_!cOf!jO!V!lO!d!nO%b!]O%c!^O%d!_O%e!`O%f!`O%g!aO%h!aO%i!bO%j!bO%k!bO~Oi%pXj%pXk%pXl%pXm%pXn%pXq%pXx%pXy%pX!s%pX#^%pX%V%pX%Y%pX%r%pXe%pX!R%pX!S%pX%s%pX!U%pX!Y%pX!O%pX#V%pXr%pX!j%pX~P$bOdsOfXO!VYO!ZZO!fdO!mdO!ndO!odO%gQO%hQO%lRO%mVO&R[O&S]O&V^O&Y_O&``O&caO&ebO~Ox%oXy%oX#^%oX%V%oX%Y%oX%r%oX~Oi!qOj!rOk!pOl!pOm!sOn!tOq!uO!s%oX~P(cOT!{Om/iOt/wO}vO~P'UOT#OOm/iOt/wO!U#PO~P'UOT#SO_#TOm/iOt/wO!Y#UO~P'UO&T#XO&U#ZO~O&W#[O&X#ZO~O!Z#^O&Z#_O&_#aO~O!Z#^O&a#bO&b#aO~O!Z#^O&U#aO&d#dO~O!Z#^O&X#aO&f#fO~OT%aX]%aX_%aXf%aXi%aXj%aXk%aXl%aXm%aXn%aXq%aXx%aX!V%aX!d%aX%b%aX%c%aX%d%aX%e%aX%f%aX%g%aX%h%aX%i%aX%j%aX%k%aXe%aX!R%aX!S%aX~O&R[O&S]O&V^O&Y_O&``O&caO&ebOy%aX!s%aX#^%aX%V%aX%Y%aX%r%aX%s%aX!U%aX!Y%aX!O%aX#V%aXr%aX!j%aX~P+xOx#kOy%`X!s%`X#^%`X%V%`X%Y%`X%r%`X~Om/iOt/wO~P'UO#^#nO%V#pO%Y#pO~O%mVO~O!R#uO#l!YO#q!ZO#tlO~OmtO~P'UOT#zO_#{O%mVOyuP~OT$POm/iOt/wO!O$QO~P'UOy$SO!s$XO%r$TO#^!tX%V!tX%Y!tX~OT$POm/iOt/wO#^!}X%V!}X%Y!}X~P'UOm/iOt/wO#^#RX%V#RX%Y#RX~P'UO!d$_O!m$_O%mVO~OT$iO~P'UO!S$kO#j$lO#l$mO~Oy$nO~OT$uO~P'UOT%OO_%OOe%QOm/iOt/wO~P'UOm/iOt/wOy%TO~P'UO&Q%VO~O_!cOf!jO!V!lO!d!nOT`a]`ai`aj`ak`al`am`an`aq`ax`ay`a!s`a#^`a%V`a%Y`a%b`a%c`a%d`a%e`a%f`a%g`a%h`a%i`a%j`a%k`a%r`ae`a!R`a!S`a%s`a!U`a!Y`a!O`a#V`ar`a!j`a~Ol%[O~Om%[O~P'UOm/iO~P'UOi/kOj/lOk/jOl/jOm/sOn/tOq/xOe%oX!R%oX!S%oX%s%oX!U%oX!Y%oX!O%oX#V%oX!j%oX~P(cO%s%^Oe%nXx%nX!R%nX!S%nX!U%nXy%nX~Oe%`Ox%aO!R%eO!S%dO~Oe%`O~Ox%hO!R%eO!S%dO!U%zX~O!U%lO~Ox%mOy%oO!R%eO!S%dO!Y%uX~O!Y%sO~O!Y%tO~O&T#XO&U%vO~O&W#[O&X%vO~OT%yOm/iOt/wO}vO~P'UO!Z#^O&Z#_O&_%|O~O!Z#^O&a#bO&b%|O~O!Z#^O&U%|O&d#dO~O!Z#^O&X%|O&f#fO~OT!la]!la_!laf!lai!laj!lak!lal!lam!lan!laq!lax!lay!la!V!la!d!la!s!la#^!la%V!la%Y!la%b!la%c!la%d!la%e!la%f!la%g!la%h!la%i!la%j!la%k!la%r!lae!la!R!la!S!la%s!la!U!la!Y!la!O!la#V!lar!la!j!la~P#yOx&ROy%`a!s%`a#^%`a%V%`a%Y%`a%r%`a~P$bOT&TOmtOtuOy%`a!s%`a#^%`a%V%`a%Y%`a%r%`a~P'UOx&ROy%`a!s%`a#^%`a%V%`a%Y%`a%r%`a~OPhOTeOmtOtuO}vO!O!PO!vxO!xyO!zzO!|{O#O|O#S}O#U!OO#X!QO#Y!QO#[!RO#^$tX%V$tX%Y$tX~P'UO#^#nO%V&YO%Y&YO~O!d&ZOf&hX%V&hX#V&hX#^&hX%Y&hX#U&hX~Of!jO%V&]O~Oicajcakcalcamcancaqcaxcayca!sca#^ca%Vca%Yca%rcaeca!Rca!Sca%sca!Uca!Yca!Oca#Vcarca!jca~P$bOqoaxoayoa#^oa%Voa%Yoa%roa~Oi!qOj!rOk!pOl!pOm!sOn!tO!soa~PD_O%r&_Ox%qXy%qX~O%mVOx%qXy%qX~Ox&bOyuX~Oy&dO~Ox%mO#^%uX%V%uX%Y%uXe%uXy%uX!Y%uX!j%uX%r%uX~OT/rOm/iOt/wO}vO~P'UO%r$TO#^Sa%VSa%YSa~Ox&mO#^%wX%V%wX%Y%wXl%wX~P$bOx&pO!O&oO#^#Ra%V#Ra%Y#Ra~O#V&qO#^#Ta%V#Ta%Y#Ta~O!d$_O!m$_O#U&sO%mVO~O#U&sO~Ox&uO#^&kX%V&kX%Y&kX~Ox&wO#^&gX%V&gX%Y&gXy&gX~Ox&{Ol&mX~P$bOl'OO~OPhOTeOmtOtuO}vO!O!PO!vxO!xyO!zzO!|{O#O|O#S}O#U!OO#X!QO#Y!QO#[!RO%V'TO~P'UOr'XO#g'VO#h'WOP#eaT#ead#eaf#eam#eaq#eat#ea}#ea!O#ea!R#ea!S#ea!V#ea!Z#ea!f#ea!m#ea!n#ea!o#ea!v#ea!x#ea!z#ea!|#ea#O#ea#S#ea#U#ea#X#ea#Y#ea#[#ea#c#ea#f#ea#j#ea#l#ea#q#ea#t#ea#v#ea%S#ea%V#ea%g#ea%h#ea%l#ea%m#ea&R#ea&S#ea&V#ea&Y#ea&`#ea&c#ea&e#ea%U#ea%Y#ea~Ox'YO#V'[Oy&nX~Of'^O~Of!jOy$nO~Oy'bO~P$bOT!bO]!bO_!cOf!jO!V!lO!d!nO%d!_O%e!`O%f!`O%g!aO%h!aO%i!bO%j!bO%k!bOiUijUikUilUimUinUiqUixUiyUi!sUi#^Ui%VUi%YUi%bUi%rUieUi!RUi!SUi%sUi!UUi!YUi!OUi#VUirUi!jUi~O%c!^O~P! YO%cUi~P! YOT!bO]!bO_!cOf!jO!V!lO!d!nO%g!aO%h!aO%i!bO%j!bO%k!bOiUijUikUilUimUinUiqUixUiyUi!sUi#^Ui%VUi%YUi%bUi%cUi%dUi%rUieUi!RUi!SUi%sUi!UUi!YUi!OUi#VUirUi!jUi~O%e!`O%f!`O~P!$TO%eUi%fUi~P!$TO_!cOf!jO!V!lO!d!nOiUijUikUilUimUinUiqUixUiyUi!sUi#^Ui%VUi%YUi%bUi%cUi%dUi%eUi%fUi%gUi%hUi%rUieUi!RUi!SUi%sUi!UUi!YUi!OUi#VUirUi!jUi~OT!bO]!bO%i!bO%j!bO%k!bO~P!'ROTUi]Ui%iUi%jUi%kUi~P!'RO!R%eO!S%dOe%}Xx%}X~O%r'fO%s'fO~P+xOx'hOe%|X~Oe'jO~Ox'kOy'mO!U&PX~Om/iOt/wOx'kOy'nO!U&PX~P'UO!U'pO~Ok!pOl!pOm!sOn!tOihiqhixhiyhi!shi#^hi%Vhi%Yhi%rhi~Oj!rO~P!+tOjhi~P!+tOi/kOj/lOk/jOl/jOm/sOn/tO~Or'rO~P!,}OT'wOe'xOm/iOt/wO~P'UOe'xOx'yO~Oe'{O~O!S'}O~Oe(OOx'yO!R%eO!S%dO~P$bOi/kOj/lOk/jOl/jOm/sOn/tOeoa!Roa!Soa%soa!Uoa!Yoa!Ooa#Voaroa!joa~PD_OT'wOm/iOt/wO!U%za~P'UOx(RO!U%za~O!U(SO~Ox(RO!R%eO!S%dO!U%za~P$bOT(WOm/iOt/wO!Y%ua#^%ua%V%ua%Y%uae%uay%ua!j%ua%r%ua~P'UOx(XO!Y%ua#^%ua%V%ua%Y%uae%uay%ua!j%ua%r%ua~O!Y([O~Ox(XO!R%eO!S%dO!Y%ua~P$bOx(_O!R%eO!S%dO!Y%{a~P$bOx(bOy&[X!Y&[X!j&[X~Oy(eO!Y(gO!j(hO~OT&TOmtOtuOy%`i!s%`i#^%`i%V%`i%Y%`i%r%`i~P'UOx(iOy%`i!s%`i#^%`i%V%`i%Y%`i%r%`i~O!d&ZOf&ha%V&ha#V&ha#^&ha%Y&ha#U&ha~O%V(nO~OT#zO_#{O%mVO~Ox&bOyua~OmtOtuO~P'UOx(XO#^%ua%V%ua%Y%uae%uay%ua!Y%ua!j%ua%r%ua~P$bOx(sO#^%`X%V%`X%Y%`X%r%`X~O%r$TO#^Si%VSi%YSi~O#^%wa%V%wa%Y%wal%wa~P'UOx(vO#^%wa%V%wa%Y%wal%wa~OT(zOf(|O%mVO~O#U(}O~O%mVO#^&ka%V&ka%Y&ka~Ox)PO#^&ka%V&ka%Y&ka~Om/iOt/wO#^&ga%V&ga%Y&gay&ga~P'UOx)SO#^&ga%V&ga%Y&gay&ga~Or)WO#a)VOP#_iT#_id#_if#_im#_iq#_it#_i}#_i!O#_i!R#_i!S#_i!V#_i!Z#_i!f#_i!m#_i!n#_i!o#_i!v#_i!x#_i!z#_i!|#_i#O#_i#S#_i#U#_i#X#_i#Y#_i#[#_i#c#_i#f#_i#j#_i#l#_i#q#_i#t#_i#v#_i%S#_i%V#_i%g#_i%h#_i%l#_i%m#_i&R#_i&S#_i&V#_i&Y#_i&`#_i&c#_i&e#_i%U#_i%Y#_i~Or)XOP#biT#bid#bif#bim#biq#bit#bi}#bi!O#bi!R#bi!S#bi!V#bi!Z#bi!f#bi!m#bi!n#bi!o#bi!v#bi!x#bi!z#bi!|#bi#O#bi#S#bi#U#bi#X#bi#Y#bi#[#bi#c#bi#f#bi#j#bi#l#bi#q#bi#t#bi#v#bi%S#bi%V#bi%g#bi%h#bi%l#bi%m#bi&R#bi&S#bi&V#bi&Y#bi&`#bi&c#bi&e#bi%U#bi%Y#bi~OT)ZOl&ma~P'UOx)[Ol&ma~Ox)[Ol&ma~P$bOl)`O~O%T)cO~Or)fO#g'VO#h)eOP#eiT#eid#eif#eim#eiq#eit#ei}#ei!O#ei!R#ei!S#ei!V#ei!Z#ei!f#ei!m#ei!n#ei!o#ei!v#ei!x#ei!z#ei!|#ei#O#ei#S#ei#U#ei#X#ei#Y#ei#[#ei#c#ei#f#ei#j#ei#l#ei#q#ei#t#ei#v#ei%S#ei%V#ei%g#ei%h#ei%l#ei%m#ei&R#ei&S#ei&V#ei&Y#ei&`#ei&c#ei&e#ei%U#ei%Y#ei~Om/iOt/wOy$nO~P'UOm/iOt/wOy&na~P'UOx)lOy&na~OT)pO_)qOe)tO%i)rO%mVO~Oy$nO&q)vO~O%V)zO~OT%OO_%OOm/iOt/wOe%|a~P'UOx*OOe%|a~Om/iOt/wOy*RO!U&Pa~P'UOx*SO!U&Pa~Om/iOt/wOx*SOy*VO!U&Pa~P'UOm/iOt/wOx*SO!U&Pa~P'UOx*SOy*VO!U&Pa~Ok/jOl/jOm/sOn/tOehiihiqhixhi!Rhi!Shi%shi!Uhiyhi!Yhi#^hi%Vhi%Yhi!Ohi#Vhirhi!jhi%rhi~Oj/lO~P!H[Ojhi~P!H[OT'wOe*[Om/iOt/wO~P'UOl*^O~Oe*[Ox*`O~Oe*aO~OT'wOm/iOt/wO!U%zi~P'UOx*bO!U%zi~O!U*cO~OT(WOm/iOt/wO!Y%ui#^%ui%V%ui%Y%uie%uiy%ui!j%ui%r%ui~P'UOx*fO!R%eO!S%dO!Y%{i~Ox*iO!Y%ui#^%ui%V%ui%Y%uie%uiy%ui!j%ui%r%ui~O!Y*jO~O_*lOm/iOt/wO!Y%{i~P'UOx*fO!Y%{i~O!Y*nO~OT*pOm/iOt/wOy&[a!Y&[a!j&[a~P'UOx*qOy&[a!Y&[a!j&[a~O!Z#^O&^*tO!Y!kX~O!Y*vO~Oy(eO!Y*wO~OT&TOmtOtuOy%`q!s%`q#^%`q%V%`q%Y%`q%r%`q~P'UOx$miy$mi!s$mi#^$mi%V$mi%Y$mi%r$mi~P$bOT&TOmtOtuO~P'UOT&TOm/iOt/wO#^%`a%V%`a%Y%`a%r%`a~P'UOx*xO#^%`a%V%`a%Y%`a%r%`a~Ox$`a#^$`a%V$`a%Y$`al$`a~P$bO#^%wi%V%wi%Y%wil%wi~P'UOx*{O#^#Rq%V#Rq%Y#Rq~Ox*|O#V+OO#^&jX%V&jX%Y&jXe&jX~OT+QOf(|O%mVO~O%mVO#^&ki%V&ki%Y&ki~Om/iOt/wO#^&gi%V&gi%Y&giy&gi~P'UOr+UO#a)VOP#_qT#_qd#_qf#_qm#_qq#_qt#_q}#_q!O#_q!R#_q!S#_q!V#_q!Z#_q!f#_q!m#_q!n#_q!o#_q!v#_q!x#_q!z#_q!|#_q#O#_q#S#_q#U#_q#X#_q#Y#_q#[#_q#c#_q#f#_q#j#_q#l#_q#q#_q#t#_q#v#_q%S#_q%V#_q%g#_q%h#_q%l#_q%m#_q&R#_q&S#_q&V#_q&Y#_q&`#_q&c#_q&e#_q%U#_q%Y#_q~Ol$wax$wa~P$bOT)ZOl&mi~P'UOx+]Ol&mi~OPhOTeOmtOq!SOtuO}vO!O!PO!R!VO!S!UO!vxO!xyO!zzO!|{O#O|O#S}O#U!OO#X!QO#Y!QO#[!RO#c!TO#f!WO#j!XO#l!YO#q!ZO#tlO#v![O~P'UOx+gOy$nO#V+gO~O#h+hOP#eqT#eqd#eqf#eqm#eqq#eqt#eq}#eq!O#eq!R#eq!S#eq!V#eq!Z#eq!f#eq!m#eq!n#eq!o#eq!v#eq!x#eq!z#eq!|#eq#O#eq#S#eq#U#eq#X#eq#Y#eq#[#eq#c#eq#f#eq#j#eq#l#eq#q#eq#t#eq#v#eq%S#eq%V#eq%g#eq%h#eq%l#eq%m#eq&R#eq&S#eq&V#eq&Y#eq&`#eq&c#eq&e#eq%U#eq%Y#eq~O#V+iOx$yay$ya~Om/iOt/wOy&ni~P'UOx+kOy&ni~Oy$SO%r+mOe&pXx&pX~O%mVOe&pXx&pX~Ox+qOe&oX~Oe+sO~O%T+uO~OT%OO_%OOm/iOt/wOe%|i~P'UOy+wOx$ca!U$ca~Om/iOt/wOy+xOx$ca!U$ca~P'UOm/iOt/wOy*RO!U&Pi~P'UOx+{O!U&Pi~Om/iOt/wOx+{O!U&Pi~P'UOx+{Oy,OO!U&Pi~Oe$_ix$_i!U$_i~P$bOT'wOm/iOt/wO~P'UOl,QO~OT'wOe,ROm/iOt/wO~P'UOT'wOm/iOt/wO!U%zq~P'UOx$^i!Y$^i#^$^i%V$^i%Y$^ie$^iy$^i!j$^i%r$^i~P$bOT(WOm/iOt/wO~P'UO_*lOm/iOt/wO!Y%{q~P'UOx,SO!Y%{q~O!Y,TO~OT(WOm/iOt/wO!Y%uq#^%uq%V%uq%Y%uqe%uqy%uq!j%uq%r%uq~P'UOy,UO~OT*pOm/iOt/wOy&[i!Y&[i!j&[i~P'UOx,ZOy&[i!Y&[i!j&[i~O!Z#^O&^*tO!Y!ka~OT&TOm/iOt/wO#^%`i%V%`i%Y%`i%r%`i~P'UOx,]O#^%`i%V%`i%Y%`i%r%`i~O%mVO#^&ja%V&ja%Y&jae&ja~Ox,`O#^&ja%V&ja%Y&jae&ja~Oe,cO~Ol$wix$wi~P$bOT)ZO~P'UOT)ZOl&mq~P'UOr,fOP#dyT#dyd#dyf#dym#dyq#dyt#dy}#dy!O#dy!R#dy!S#dy!V#dy!Z#dy!f#dy!m#dy!n#dy!o#dy!v#dy!x#dy!z#dy!|#dy#O#dy#S#dy#U#dy#X#dy#Y#dy#[#dy#c#dy#f#dy#j#dy#l#dy#q#dy#t#dy#v#dy%S#dy%V#dy%g#dy%h#dy%l#dy%m#dy&R#dy&S#dy&V#dy&Y#dy&`#dy&c#dy&e#dy%U#dy%Y#dy~OPhOTeOmtOq!SOtuO}vO!O!PO!R!VO!S!UO!vxO!xyO!zzO!|{O#O|O#S}O#U!OO#X!QO#Y!QO#[!RO#c!TO#f!WO#j!XO#l!YO#q!ZO#tlO#v![O%U,jO%Y,jO~P'UO#h,kOP#eyT#eyd#eyf#eym#eyq#eyt#ey}#ey!O#ey!R#ey!S#ey!V#ey!Z#ey!f#ey!m#ey!n#ey!o#ey!v#ey!x#ey!z#ey!|#ey#O#ey#S#ey#U#ey#X#ey#Y#ey#[#ey#c#ey#f#ey#j#ey#l#ey#q#ey#t#ey#v#ey%S#ey%V#ey%g#ey%h#ey%l#ey%m#ey&R#ey&S#ey&V#ey&Y#ey&`#ey&c#ey&e#ey%U#ey%Y#ey~Om/iOt/wOy&nq~P'UOx,oOy&nq~O%r+mOe&pax&pa~OT)pO_)qO%i)rO%mVOe&oa~Ox,sOe&oa~O#y,wO~OT%OO_%OOm/iOt/wO~P'UOm/iOt/wOy,xOx$ci!U$ci~P'UOm/iOt/wOx$ci!U$ci~P'UOy,xOx$ci!U$ci~Om/iOt/wOy*RO~P'UOm/iOt/wOy*RO!U&Pq~P'UOx,{O!U&Pq~Om/iOt/wOx,{O!U&Pq~P'UOq-OO!R%eO!S%dOe%vq!U%vq!Y%vqx%vq~P!,}O_*lOm/iOt/wO!Y%{y~P'UOx$ai!Y$ai~P$bO_*lOm/iOt/wO~P'UOT*pOm/iOt/wO~P'UOT*pOm/iOt/wOy&[q!Y&[q!j&[q~P'UOT&TOm/iOt/wO#^%`q%V%`q%Y%`q%r%`q~P'UO#V-SOx$ra#^$ra%V$ra%Y$rae$ra~O%mVO#^&ji%V&ji%Y&jie&ji~Ox-UO#^&ji%V&ji%Y&jie&ji~Or-XOP#d!RT#d!Rd#d!Rf#d!Rm#d!Rq#d!Rt#d!R}#d!R!O#d!R!R#d!R!S#d!R!V#d!R!Z#d!R!f#d!R!m#d!R!n#d!R!o#d!R!v#d!R!x#d!R!z#d!R!|#d!R#O#d!R#S#d!R#U#d!R#X#d!R#Y#d!R#[#d!R#c#d!R#f#d!R#j#d!R#l#d!R#q#d!R#t#d!R#v#d!R%S#d!R%V#d!R%g#d!R%h#d!R%l#d!R%m#d!R&R#d!R&S#d!R&V#d!R&Y#d!R&`#d!R&c#d!R&e#d!R%U#d!R%Y#d!R~Om/iOt/wOy&ny~P'UOT)pO_)qO%i)rO%mVOe&oi~O#y,wO%U-_O%Y-_O~OT-iOf-gO!V-fO!Z-hO!f-bO!n-dO!o-dO%h-aO%mVO&R[O&S]O&V^O~Om/iOt/wOx$cq!U$cq~P'UOy-nOx$cq!U$cq~Om/iOt/wOy*RO!U&Py~P'UOx-oO!U&Py~Om/iOt-sO~P'UOq-OO!R%eO!S%dOe%vy!U%vy!Y%vyx%vy~P!,}O%mVO#^&jq%V&jq%Y&jqe&jq~Ox-wO#^&jq%V&jq%Y&jqe&jq~OT)pO_)qO%i)rO%mVO~Of-{O!d-yOx#zX#V#zX%b#zXe#zX~Oq#zXy#zX!U#zX!Y#zX~P$$nO%g-}O%h-}Oq#{Xx#{Xy#{X#V#{X%b#{X!U#{Xe#{X!Y#{X~O!f.PO~Ox.TO#V.VO%b.QOq&rXy&rX!U&rXe&rX~O_.YO~P$ WOf-{Oq&sXx&sXy&sX#V&sX%b&sX!U&sXe&sX!Y&sX~Oq.^Oy$nO~Om/iOt/wOx$cy!U$cy~P'UOm/iOt/wOy*RO!U&P!R~P'UOx.bO!U&P!R~Oe%yXq%yX!R%yX!S%yX!U%yX!Y%yXx%yX~P!,}Oq-OO!R%eO!S%dOe%xa!U%xa!Y%xax%xa~O%mVO#^&jy%V&jy%Y&jye&jy~O!d-yOf$Raq$Rax$Ray$Ra#V$Ra%b$Ra!U$Rae$Ra!Y$Ra~O!f.kO~O%g-}O%h-}Oq#{ax#{ay#{a#V#{a%b#{a!U#{ae#{a!Y#{a~O%b.QOq$Pax$Pay$Pa#V$Pa!U$Pae$Pa!Y$Pa~Oq&ray&ra!U&rae&ra~P#NzOx.pOq&ray&ra!U&rae&ra~O!U.sO~Oe.sO~Oy.uO~O!Y.vO~Om/iOt/wOy*RO!U&P!Z~P'UOy.yO~O%r.zO~P$$nOx.{O#V.VO%b.QOe&uX~Ox.{Oe&uX~Oe.}O~O!f/OO~O#V.VOq$}ax$}ay$}a%b$}a!U$}ae$}a!Y$}a~O#V.VO%b.QOq%Rax%Ray%Ra!U%Rae%Ra~Oq&riy&ri!U&rie&ri~P#NzOx/QO#V.VO%b.QO!Y&ta~Oy$Za~P$bOe&ua~P#NzOx/YOe&ua~O_/[O!Y&ti~P$ WOx/^O!Y&ti~Ox/^O#V.VO%b.QO!Y&ti~O#V.VO%b.QOe$Xix$Xi~O%r/aO~P$$nO#V.VO%b.QOe%Qax%Qa~Oe&ui~P#NzOy/dO~O_/[O!Y&tq~P$ WOx/fO!Y&tq~O#V.VO%b.QOx%Pi!Y%Pi~O_/[O~P$ WO_/[O!Y&ty~P$ WO#V.VO%b.QOe$Yix$Yi~O#V.VO%b.QOx%Pq!Y%Pq~Ox*xO#^%`a%V%`a%Y%`a%r%`a~P$bOT&TOm/iOt/wO~P'UOl/nO~Om/nO~P'UOy/oO~Or/pO~P!,}O&S&V&c&e&R!Z&Z&a&d&f&Y&`&Y%m~", + goto: "!9p&vPPPP&wP'P*e*}+h,S,o-]P-zP'P.k.k'PPPP'P2PPPPPPP2P4oPP4oP6{7U=QPP=T=c=fPP'P'PPP=rPP'P'PPP'P'P'P'P'P=v>m'PP>pP>vByFcPFw'PPPPF{GR&wP&w&wP&wP&wP&wP&wP&w&w&wP&wPP&wPP&wPGXPG`GfPG`PG`G`PPPG`PIePInItIzIePG`JQPG`PJXJ_PJcJwKfLPJcJcLVLdJcJcJcJcLxMOMRMWMZMaMgMsNVN]NgNm! Z! a! g! m! w! }!!T!!Z!!a!!g!!y!#T!#Z!#a!#g!#q!#w!#}!$T!$Z!$e!$k!$u!${!%U!%[!%k!%s!%}!&UPPPPPPPPP!&[!&d!&m!&w!'SPPPPPPPPPPPP!+r!,[!0j!3vPP!4O!4^!4g!5]!5S!5f!5l!5o!5r!5u!5}!6nPPPPPPPPPP!6q!6tPPPPPPPPP!6z!7W!7d!7j!7s!7v!7|!8S!8Y!8]P!8e!8n!9j!9m]iOr#n$n)c+c'udOSXYZehrstvx|}!R!S!T!U!X![!d!e!f!g!h!i!j!l!p!q!r!t!u!{#O#S#T#^#k#n$P$Q$S$U$X$i$k$l$n$u%O%T%[%_%a%d%h%m%o%y&R&T&`&d&m&o&p&w&{'O'V'Y'g'h'k'm'n'r'w'y'}(R(W(X(_(b(i(k(s(v)S)V)Z)[)`)c)l)v*O*R*S*V*]*^*`*b*e*f*i*l*p*q*x*z*{+S+[+]+c+j+k+n+v+w+x+z+{,O,Q,S,U,W,Y,Z,],o,q,x,{-O-n-o.^.b.y/i/j/k/l/n/o/p/q/r/t/x}!dP#j#w$Y$h$t%f%k%q%r&e&}'d(j(u)Y*Z*d+Z,V.w/m!P!eP#j#w$Y$h$t$v%f%k%q%r&e&}'d(j(u)Y*Z*d+Z,V.w/m!R!fP#j#w$Y$h$t$v$w%f%k%q%r&e&}'d(j(u)Y*Z*d+Z,V.w/m!T!gP#j#w$Y$h$t$v$w$x%f%k%q%r&e&}'d(j(u)Y*Z*d+Z,V.w/m!V!hP#j#w$Y$h$t$v$w$x$y%f%k%q%r&e&}'d(j(u)Y*Z*d+Z,V.w/m!X!iP#j#w$Y$h$t$v$w$x$y$z%f%k%q%r&e&}'d(j(u)Y*Z*d+Z,V.w/m!]!iP!o#j#w$Y$h$t$v$w$x$y$z${%f%k%q%r&e&}'d(j(u)Y*Z*d+Z,V.w/m'uSOSXYZehrstvx|}!R!S!T!U!X![!d!e!f!g!h!i!j!l!p!q!r!t!u!{#O#S#T#^#k#n$P$Q$S$U$X$i$k$l$n$u%O%T%[%_%a%d%h%m%o%y&R&T&`&d&m&o&p&w&{'O'V'Y'g'h'k'm'n'r'w'y'}(R(W(X(_(b(i(k(s(v)S)V)Z)[)`)c)l)v*O*R*S*V*]*^*`*b*e*f*i*l*p*q*x*z*{+S+[+]+c+j+k+n+v+w+x+z+{,O,Q,S,U,W,Y,Z,],o,q,x,{-O-n-o.^.b.y/i/j/k/l/n/o/p/q/r/t/x&ZUOXYZhrtv|}!R!S!T!X!j!l!p!q!r!t!u#^#k#n$Q$S$U$X$l$n%O%T%[%_%a%h%m%o%y&R&`&d&o&p&w'O'V'Y'g'h'k'm'n'r'y(R(X(_(b(i(k(s)S)V)`)c)l)v*O*R*S*V*]*^*`*b*e*f*i*p*q*x*{+S+c+j+k+n+v+w+x+z+{,O,Q,S,U,W,Y,Z,],o,q,x,{-O-n-o.b.y/i/j/k/l/n/o/p/q/t/x%eWOXYZhrv|}!R!S!T!X!j!l#^#k#n$Q$S$U$X$l$n%O%T%_%a%h%m%o%y&R&`&d&o&p&w'O'V'Y'g'h'k'm'n'r'y(R(X(_(b(i(k(s)S)V)`)c)l)v*O*R*S*V*]*`*b*e*f*i*p*q*x*{+S+c+j+k+n+v+w+x+z+{,O,S,U,W,Y,Z,],o,q,x,{-n-o.b/o/p/qQ#}uQ.c-sR/u/w'ldOSXYZehrstvx|}!R!S!T!U!X![!d!e!f!g!h!i!l!p!q!r!t!u!{#O#S#T#^#k#n$P$Q$S$U$X$i$k$l$n$u%O%T%[%_%a%d%h%m%o%y&R&T&`&d&m&o&p&w&{'O'V'Y'g'k'm'n'r'w'y'}(R(W(X(_(b(i(k(s(v)S)V)Z)[)`)c)l)v*R*S*V*]*^*`*b*e*f*i*l*p*q*x*z*{+S+[+]+c+j+k+n+w+x+z+{,O,Q,S,U,W,Y,Z,],o,q,x,{-O-n-o.^.b.y/i/j/k/l/n/o/p/q/r/t/xW#ql!O!P$`W#yu&b-s/wQ$b!QQ$r!YQ$s!ZW$}!j'h*O+vS&a#z#{Q'R$mQ(l&ZQ(z&qU({&s(|(}U)O&u)P+RQ)n'[W)o'^+q,s-]S+p)p)qY,_*|,`-T-U-wQ,b+OQ,l+gQ,n+il-`,w-f-g-i.R.T.Y.p.u.z/P/[/a/dQ-v-SQ.Z-hQ.g-{Q.r.VU/V.{/Y/bX/]/Q/^/e/fR&`#yi!xXY!S!T%a%h'y(R)V*]*`*bR%_!wQ!|XQ%z#^Q&i$UR&l$XT-r-O.y![!kP!o#j#w$Y$h$t$v$w$x$y$z${%f%k%q%r&e&}'d(j(u)Y*Z*d+Z,V.w/mQ&^#rR'a$sR'g$}Q%W!nR.e-y'tcOSXYZehrstvx|}!R!S!T!U!X![!d!e!f!g!h!i!j!l!p!q!r!t!u!{#O#S#T#^#k#n$P$Q$S$U$X$i$k$l$n$u%O%T%[%_%a%d%h%m%o%y&R&T&`&d&m&o&p&w&{'O'V'Y'g'h'k'm'n'r'w'y'}(R(W(X(_(b(i(k(s(v)S)V)Z)[)`)c)l)v*O*R*S*V*]*^*`*b*e*f*i*l*p*q*x*z*{+S+[+]+c+j+k+n+v+w+x+z+{,O,Q,S,U,W,Y,Z,],o,q,x,{-O-n-o.^.b.y/i/j/k/l/n/o/p/q/r/t/xS#hc#i!P-d,w-f-g-h-i-{.R.T.Y.p.u.z.{/P/Q/Y/[/^/a/b/d/e/f'tcOSXYZehrstvx|}!R!S!T!U!X![!d!e!f!g!h!i!j!l!p!q!r!t!u!{#O#S#T#^#k#n$P$Q$S$U$X$i$k$l$n$u%O%T%[%_%a%d%h%m%o%y&R&T&`&d&m&o&p&w&{'O'V'Y'g'h'k'm'n'r'w'y'}(R(W(X(_(b(i(k(s(v)S)V)Z)[)`)c)l)v*O*R*S*V*]*^*`*b*e*f*i*l*p*q*x*z*{+S+[+]+c+j+k+n+v+w+x+z+{,O,Q,S,U,W,Y,Z,],o,q,x,{-O-n-o.^.b.y/i/j/k/l/n/o/p/q/r/t/xT#hc#iS#__#`S#b`#cS#da#eS#fb#gT*t(e*uT(f%z(hQ$WwR+o)oX$Uw$V$W&kZkOr$n)c+cXoOr)c+cQ$o!WQ&y$fQ&z$gQ']$qQ'`$sQ)a'QQ)g'VQ)i'WQ)j'XQ)w'_Q)y'aQ+V)VQ+X)WQ+Y)XQ+^)_S+`)b)xQ+d)eQ+e)fQ+f)hQ,d+UQ,e+WQ,g+_Q,h+aQ,m+hQ-W,fQ-Y,kQ-Z,lQ-x-XQ._-lR.x.`WoOr)c+cR#tnQ'_$rR)b'RQ+n)oR,q+oQ)x'_R+a)bZmOnr)c+cQ'c$tR){'dT,u+u,vu-k,w-f-g-i-{.R.T.Y.p.u.z.{/P/Y/[/a/b/dt-k,w-f-g-i-{.R.T.Y.p.u.z.{/P/Y/[/a/b/dQ.Z-hX/]/Q/^/e/f!P-c,w-f-g-h-i-{.R.T.Y.p.u.z.{/P/Q/Y/[/^/a/b/d/e/fQ.O-bR.l.Pg.R-e.S.h.o.t/S/U/W/c/g/hu-j,w-f-g-i-{.R.T.Y.p.u.z.{/P/Y/[/a/b/dX-|-`-j.g/VR.i-{V/X.{/Y/bR.`-lQrOR#vrQ&c#|R(q&cS%n#R$OS(Y%n(]T(]%q&eQ%b!zQ%i!}W'z%b%i(P(TQ(P%fR(T%kQ&n$YR(w&nQ(`%rQ*g(ZT*m(`*gQ'i%PR*P'iS'l%S%TY*T'l*U+|,|-pU*U'm'n'oU+|*V*W*XS,|+},OR-p,}Q#Y]R%u#YQ#]^R%w#]Q#`_R%{#`Q(c%xS*r(c*sR*s(dQ*u(eR,[*uQ#c`R%}#cQ#eaR&O#eQ#gbR&P#gQ#icR&Q#iQ#lfQ&S#jW&V#l&S(t*yQ(t&hR*y/mQ$VwS&j$V&kR&k$WQ&x$dR)T&xQ&[#qR(m&[Q$`!PR&r$`Q*}({S,a*}-VR-V,bQ&v$bR)Q&vQ#ojR&X#oQ+c)cR,i+cQ)U&yR+T)UQ&|$hS)]&|)^R)^&}Q'U$oR)d'UQ'Z$pS)m'Z+lR+l)nQ+r)sR,t+rWnOr)c+cR#snQ,v+uR-^,vd.S-e.h.o.t/S/U/W/c/g/hR.n.SU-z-`.g/VR.f-zQ/R.tS/_/R/`R/`/SS.|.h.iR/Z.|Q.U-eR.q.USqOrT+b)c+cWpOr)c+cR'S$nYjOr$n)c+cR&W#n[wOr#n$n)c+cR&i$U&YPOXYZhrtv|}!R!S!T!X!j!l!p!q!r!t!u#^#k#n$Q$S$U$X$l$n%O%T%[%_%a%h%m%o%y&R&`&d&o&p&w'O'V'Y'g'h'k'm'n'r'y(R(X(_(b(i(k(s)S)V)`)c)l)v*O*R*S*V*]*^*`*b*e*f*i*p*q*x*{+S+c+j+k+n+v+w+x+z+{,O,Q,S,U,W,Y,Z,],o,q,x,{-O-n-o.b.y/i/j/k/l/n/o/p/q/t/xQ!oSQ#jeQ#wsU$Yx%d'}S$h!U$kQ$t![Q$v!dQ$w!eQ$x!fQ$y!gQ$z!hQ${!iQ%f!{Q%k#OQ%q#SQ%r#TQ&e$PQ&}$iQ'd$uQ(j&TU(u&m(v*zW)Y&{)[+[+]Q*Z'wQ*d(WQ+Z)ZQ,V*lQ.w.^R/m/rQ!zXQ!}YQ$f!SQ$g!T^'v%a%h'y(R*]*`*bR+W)V[fOr#n$n)c+ch!wXY!S!T%a%h'y(R)V*]*`*bQ#RZQ#mhS$Ov|Q$]}W$d!R$X'O)`S$p!X$lW$|!j'h*O+vQ%S!lQ%x#^`&U#k&R(i(k(s*x,]/qQ&f$QQ&g$SQ&h$UQ'e%OQ'o%TQ'u%_W(V%m(X*e*iQ(Z%oQ(d%yQ(o&`S(r&d/oQ(x&oQ(y&pU)R&w)S+SQ)h'VY)k'Y)l+j+k,oQ)|'g^*Q'k*S+z+{,{-o.bQ*W'mQ*X'nS*Y'r/pW*k(_*f,S,WW*o(b*q,Y,ZQ+t)vQ+y*RQ+}*VQ,X*pQ,^*{Q,p+nQ,y+wQ,z+xQ,},OQ-R,UQ-[,qQ-m,xR.a-nhTOr#k#n$n&R&d'r(i(k)c+c$z!vXYZhv|}!R!S!T!X!j!l#^$Q$S$U$X$l%O%T%_%a%h%m%o%y&`&o&p&w'O'V'Y'g'h'k'm'n'y(R(X(_(b(s)S)V)`)l)v*O*R*S*V*]*`*b*e*f*i*p*q*x*{+S+j+k+n+v+w+x+z+{,O,S,U,W,Y,Z,],o,q,x,{-n-o.b/o/p/qQ#xtW%X!p!t/j/tQ%Y!qQ%Z!rQ%]!uQ%g/iS'q%[/nQ's/kQ't/lQ,P*^Q-Q,QS-q-O.yR/v/xU#|u-s/wR(p&b[gOr#n$n)c+cX!yX#^$U$XQ#WZQ$RvR$[|Q%c!zQ%j!}Q%p#RQ'e$|Q(Q%fQ(U%kQ(^%qQ(a%rQ*h(ZQ-P,PQ-u-QR.d-tQ$ZxQ'|%dR*_'}Q-t-OR/T.yR#QYR#VZR%R!jQ%P!jV)}'h*O+v!]!mP!o#j#w$Y$h$t$v$w$x$y$z${%f%k%q%r&e&}'d(j(u)Y*Z*d+Z,V.w/mR%U!lR%z#^Q(g%zR*w(hQ$e!RQ&l$XQ)_'OR+_)`Q#rlQ$^!OQ$a!PR&t$`Q(z&sR+Q(}Q(z&sQ+P(|R+Q(}R$c!QXpOr)c+cQ$j!UR'P$kQ$q!XR'Q$lR)u'^Q)s'^V,r+q,s-]Q-l,wQ.W-fR.X-gU-e,w-f-gQ.]-iQ.h-{Q.m.RU.o.T.p/PQ.t.YQ/S.uQ/U.zU/W.{/Y/bQ/c/[Q/g/aR/h/dR.[-hR.j-{", + nodeNames: "⚠ print Comment Script AssignStatement * BinaryExpression BitOp BitOp BitOp BitOp ArithOp ArithOp @ ArithOp ** UnaryExpression ArithOp BitOp AwaitExpression await ) ( ParenthesizedExpression BinaryExpression or and CompareOp in not is UnaryExpression ConditionalExpression if else LambdaExpression lambda ParamList VariableName AssignOp , : NamedExpression AssignOp YieldExpression yield from TupleExpression ComprehensionExpression async for LambdaExpression ] [ ArrayExpression ArrayComprehensionExpression } { DictionaryExpression DictionaryComprehensionExpression SetExpression SetComprehensionExpression CallExpression ArgList AssignOp MemberExpression . PropertyName Number String FormatString FormatReplacement FormatConversion FormatSpec ContinuedString Ellipsis None Boolean TypeDef AssignOp UpdateStatement UpdateOp ExpressionStatement DeleteStatement del PassStatement pass BreakStatement break ContinueStatement continue ReturnStatement return YieldStatement PrintStatement RaiseStatement raise ImportStatement import as ScopeStatement global nonlocal AssertStatement assert StatementGroup ; IfStatement Body elif WhileStatement while ForStatement TryStatement try except finally WithStatement with FunctionDefinition def ParamList AssignOp TypeDef ClassDefinition class DecoratedStatement Decorator At MatchStatement match MatchBody MatchClause case CapturePattern LiteralPattern ArithOp ArithOp AsPattern OrPattern LogicOp AttributePattern SequencePattern MappingPattern StarPattern ClassPattern PatternArgList KeywordPattern KeywordPattern Guard", + maxTerm: 267, + context: trackIndent, + nodeProps: [ + ["group", -14,4,80,82,83,85,87,89,91,93,94,95,97,100,103,"Statement Statement",-22,6,16,19,23,38,47,48,54,55,58,59,60,61,62,65,68,69,70,74,75,76,77,"Expression",-10,105,107,110,112,113,117,119,124,126,129,"Statement",-9,134,135,138,139,141,142,143,144,145,"Pattern"], + ["openedBy", 21,"(",52,"[",56,"{"], + ["closedBy", 22,")",53,"]",57,"}"] + ], + propSources: [pythonHighlighting], + skippedNodes: [0,2], + repeatNodeCount: 38, + tokenData: "&JdMgR!^OX$}XY!&]Y[$}[]!&]]p$}pq!&]qr!(grs!,^st!IYtu$}uv$5[vw$7nwx$8zxy%'vyz%(|z{%*S{|%,r|}%.O}!O%/U!O!P%1k!P!Q%<q!Q!R%?a!R![%Cc![!]%N_!]!^&!q!^!_&#w!_!`&&g!`!a&'s!a!b$}!b!c&*`!c!d&+n!d!e&-`!e!h&+n!h!i&7[!i!t&+n!t!u&@j!u!w&+n!w!x&5j!x!}&+n!}#O&Bt#O#P!'u#P#Q&Cz#Q#R&EQ#R#S&+n#S#T$}#T#U&+n#U#V&-`#V#Y&+n#Y#Z&7[#Z#f&+n#f#g&@j#g#i&+n#i#j&5j#j#o&+n#o#p&F^#p#q&GS#q#r&H`#r#s&I^#s$g$}$g~&+n<r%`Z&^7[&TS&WW&Z`&ap&d!b&f#tOr$}rs&Rsw$}wxHsx#O$}#O#P!$R#P#o$}#o#p!%i#p#q$}#q#r!$g#r~$}<Q&^Z&^7[&TS&Z`&d!bOr'PrsFisw'Pwx(Rx#O'P#O#PAe#P#o'P#o#pEu#p#q'P#q#rAy#r~'P<Q'`Z&^7[&TS&WW&Z`&d!b&f#tOr'Prs&Rsw'Pwx(Rx#O'P#O#PAe#P#o'P#o#pEu#p#q'P#q#rAy#r~'P;p([Z&^7[&WW&f#tOr(}rs)}sw(}wx={x#O(}#O#P2]#P#o(}#o#p:X#p#q(}#q#r2q#r~(};p)[Z&^7[&TS&WW&d!b&f#tOr(}rs)}sw(}wx(Rx#O(}#O#P2]#P#o(}#o#p:X#p#q(}#q#r2q#r~(};p*WZ&^7[&TS&d!bOr(}rs*ysw(}wx(Rx#O(}#O#P2]#P#o(}#o#p:X#p#q(}#q#r2q#r~(};p+SZ&^7[&TS&d!bOr(}rs+usw(}wx(Rx#O(}#O#P2]#P#o(}#o#p:X#p#q(}#q#r2q#r~(}8r,OX&^7[&TS&d!bOw+uwx,kx#O+u#O#P.]#P#o+u#o#p0d#p#q+u#q#r.q#r~+u8r,pX&^7[Ow+uwx-]x#O+u#O#P.]#P#o+u#o#p0d#p#q+u#q#r.q#r~+u8r-bX&^7[Ow+uwx-}x#O+u#O#P.]#P#o+u#o#p0d#p#q+u#q#r.q#r~+u7[.SR&^7[O#o-}#p#q-}#r~-}8r.bT&^7[O#o+u#o#p.q#p#q+u#q#r.q#r~+u!f.xV&TS&d!bOw.qwx/_x#O.q#O#P0^#P#o.q#o#p0d#p~.q!f/bVOw.qwx/wx#O.q#O#P0^#P#o.q#o#p0d#p~.q!f/zUOw.qx#O.q#O#P0^#P#o.q#o#p0d#p~.q!f0aPO~.q!f0iV&TSOw1Owx1dx#O1O#O#P2V#P#o1O#o#p.q#p~1OS1TT&TSOw1Owx1dx#O1O#O#P2V#P~1OS1gTOw1Owx1vx#O1O#O#P2V#P~1OS1ySOw1Ox#O1O#O#P2V#P~1OS2YPO~1O;p2bT&^7[O#o(}#o#p2q#p#q(}#q#r2q#r~(}%d2|X&TS&WW&d!b&f#tOr2qrs3isw2qwx5Px#O2q#O#P:R#P#o2q#o#p:X#p~2q%d3pX&TS&d!bOr2qrs4]sw2qwx5Px#O2q#O#P:R#P#o2q#o#p:X#p~2q%d4dX&TS&d!bOr2qrs.qsw2qwx5Px#O2q#O#P:R#P#o2q#o#p:X#p~2q%d5WX&WW&f#tOr2qrs3isw2qwx5sx#O2q#O#P:R#P#o2q#o#p:X#p~2q%d5zX&WW&f#tOr2qrs3isw2qwx6gx#O2q#O#P:R#P#o2q#o#p:X#p~2q#|6nV&WW&f#tOr6grs7Ts#O6g#O#P8S#P#o6g#o#p8Y#p~6g#|7WVOr6grs7ms#O6g#O#P8S#P#o6g#o#p8Y#p~6g#|7pUOr6gs#O6g#O#P8S#P#o6g#o#p8Y#p~6g#|8VPO~6g#|8_V&WWOr8trs9Ys#O8t#O#P9{#P#o8t#o#p6g#p~8tW8yT&WWOr8trs9Ys#O8t#O#P9{#P~8tW9]TOr8trs9ls#O8t#O#P9{#P~8tW9oSOr8ts#O8t#O#P9{#P~8tW:OPO~8t%d:UPO~2q%d:`X&TS&WWOr:{rs;isw:{wx<ox#O:{#O#P=u#P#o:{#o#p2q#p~:{[;SV&TS&WWOr:{rs;isw:{wx<ox#O:{#O#P=u#P~:{[;nV&TSOr:{rs<Tsw:{wx<ox#O:{#O#P=u#P~:{[<YV&TSOr:{rs1Osw:{wx<ox#O:{#O#P=u#P~:{[<tV&WWOr:{rs;isw:{wx=Zx#O:{#O#P=u#P~:{[=`V&WWOr:{rs;isw:{wx8tx#O:{#O#P=u#P~:{[=xPO~:{;p>UZ&^7[&WW&f#tOr(}rs)}sw(}wx>wx#O(}#O#P2]#P#o(}#o#p:X#p#q(}#q#r2q#r~(}:Y?QX&^7[&WW&f#tOr>wrs?ms#O>w#O#PAP#P#o>w#o#p8Y#p#q>w#q#r6g#r~>w:Y?rX&^7[Or>wrs@_s#O>w#O#PAP#P#o>w#o#p8Y#p#q>w#q#r6g#r~>w:Y@dX&^7[Or>wrs-}s#O>w#O#PAP#P#o>w#o#p8Y#p#q>w#q#r6g#r~>w:YAUT&^7[O#o>w#o#p6g#p#q>w#q#r6g#r~>w<QAjT&^7[O#o'P#o#pAy#p#q'P#q#rAy#r~'P%tBWX&TS&WW&Z`&d!b&f#tOrAyrsBsswAywx5Px#OAy#O#PEo#P#oAy#o#pEu#p~Ay%tB|X&TS&Z`&d!bOrAyrsCiswAywx5Px#OAy#O#PEo#P#oAy#o#pEu#p~Ay%tCrX&TS&Z`&d!bOrAyrsD_swAywx5Px#OAy#O#PEo#P#oAy#o#pEu#p~Ay!vDhV&TS&Z`&d!bOwD_wx/_x#OD_#O#PD}#P#oD_#o#pET#p~D_!vEQPO~D_!vEYV&TSOw1Owx1dx#O1O#O#P2V#P#o1O#o#pD_#p~1O%tErPO~Ay%tE|X&TS&WWOr:{rs;isw:{wx<ox#O:{#O#P=u#P#o:{#o#pAy#p~:{<QFtZ&^7[&TS&Z`&d!bOr'PrsGgsw'Pwx(Rx#O'P#O#PAe#P#o'P#o#pEu#p#q'P#q#rAy#r~'P9SGrX&^7[&TS&Z`&d!bOwGgwx,kx#OGg#O#PH_#P#oGg#o#pET#p#qGg#q#rD_#r~Gg9SHdT&^7[O#oGg#o#pD_#p#qGg#q#rD_#r~Gg<bIOZ&^7[&WW&ap&f#tOrIqrs)}swIqwx! wx#OIq#O#PJs#P#oIq#o#p! T#p#qIq#q#rKX#r~Iq<bJQZ&^7[&TS&WW&ap&d!b&f#tOrIqrs)}swIqwxHsx#OIq#O#PJs#P#oIq#o#p! T#p#qIq#q#rKX#r~Iq<bJxT&^7[O#oIq#o#pKX#p#qIq#q#rKX#r~Iq&UKfX&TS&WW&ap&d!b&f#tOrKXrs3iswKXwxLRx#OKX#O#PN}#P#oKX#o#p! T#p~KX&UL[X&WW&ap&f#tOrKXrs3iswKXwxLwx#OKX#O#PN}#P#oKX#o#p! T#p~KX&UMQX&WW&ap&f#tOrKXrs3iswKXwxMmx#OKX#O#PN}#P#oKX#o#p! T#p~KX$nMvV&WW&ap&f#tOrMmrs7Ts#OMm#O#PN]#P#oMm#o#pNc#p~Mm$nN`PO~Mm$nNhV&WWOr8trs9Ys#O8t#O#P9{#P#o8t#o#pMm#p~8t&U! QPO~KX&U! [X&TS&WWOr:{rs;isw:{wx<ox#O:{#O#P=u#P#o:{#o#pKX#p~:{<b!!SZ&^7[&WW&ap&f#tOrIqrs)}swIqwx!!ux#OIq#O#PJs#P#oIq#o#p! T#p#qIq#q#rKX#r~Iq:z!#QX&^7[&WW&ap&f#tOr!!urs?ms#O!!u#O#P!#m#P#o!!u#o#pNc#p#q!!u#q#rMm#r~!!u:z!#rT&^7[O#o!!u#o#pMm#p#q!!u#q#rMm#r~!!u<r!$WT&^7[O#o$}#o#p!$g#p#q$}#q#r!$g#r~$}&f!$vX&TS&WW&Z`&ap&d!b&f#tOr!$grsBssw!$gwxLRx#O!$g#O#P!%c#P#o!$g#o#p!%i#p~!$g&f!%fPO~!$g&f!%pX&TS&WWOr:{rs;isw:{wx<ox#O:{#O#P=u#P#o:{#o#p!$g#p~:{Mg!&pa&^7[&TS&WW%[1s&Z`&ap&d!b&f#tOX$}XY!&]Y[$}[]!&]]p$}pq!&]qr$}rs&Rsw$}wxHsx#O$}#O#P!'u#P#o$}#o#p!%i#p#q$}#q#r!$g#r~$}Mg!'zX&^7[OY$}YZ!&]Z]$}]^!&]^#o$}#o#p!$g#p#q$}#q#r!$g#r~$}<u!(xb&^7[&TS&WW&Z`&ap&d!b&f#tOr$}rs&Rsw$}wxHsx!_$}!_!`!*Q!`#O$}#O#P!$R#P#T$}#T#U!+W#U#f$}#f#g!+W#g#h!+W#h#o$}#o#p!%i#p#q$}#q#r!$g#r~$}<u!*eZkR&^7[&TS&WW&Z`&ap&d!b&f#tOr$}rs&Rsw$}wxHsx#O$}#O#P!$R#P#o$}#o#p!%i#p#q$}#q#r!$g#r~$}<u!+kZ!jR&^7[&TS&WW&Z`&ap&d!b&f#tOr$}rs&Rsw$}wxHsx#O$}#O#P!$R#P#o$}#o#p!%i#p#q$}#q#r!$g#r~$}G{!,m_&bp&^7[&TS&R,X&Z`&d!bOY!-lYZ'PZ]!-l]^'P^r!-lrs!G^sw!-lwx!/|x#O!-l#O#P!Cp#P#o!-l#o#p!F[#p#q!-l#q#r!DU#r~!-lGZ!-}_&^7[&TS&WW&R,X&Z`&d!b&f#tOY!-lYZ'PZ]!-l]^'P^r!-lrs!.|sw!-lwx!/|x#O!-l#O#P!Cp#P#o!-l#o#p!F[#p#q!-l#q#r!DU#r~!-lGZ!/ZZ&^7[&TS&R,X&Z`&d!bOr'PrsFisw'Pwx(Rx#O'P#O#PAe#P#o'P#o#pEu#p#q'P#q#rAy#r~'PFy!0X_&^7[&WW&R,X&f#tOY!1WYZ(}Z]!1W]^(}^r!1Wrs!2fsw!1Wwx!@Yx#O!1W#O#P!3d#P#o!1W#o#p!;t#p#q!1W#q#r!3x#r~!1WFy!1g_&^7[&TS&WW&R,X&d!b&f#tOY!1WYZ(}Z]!1W]^(}^r!1Wrs!2fsw!1Wwx!/|x#O!1W#O#P!3d#P#o!1W#o#p!;t#p#q!1W#q#r!3x#r~!1WFy!2qZ&^7[&TS&R,X&d!bOr(}rs*ysw(}wx(Rx#O(}#O#P2]#P#o(}#o#p:X#p#q(}#q#r2q#r~(}Fy!3iT&^7[O#o!1W#o#p!3x#p#q!1W#q#r!3x#r~!1W0m!4V]&TS&WW&R,X&d!b&f#tOY!3xYZ2qZ]!3x]^2q^r!3xrs!5Osw!3xwx!5tx#O!3x#O#P!;n#P#o!3x#o#p!;t#p~!3x0m!5XX&TS&R,X&d!bOr2qrs4]sw2qwx5Px#O2q#O#P:R#P#o2q#o#p:X#p~2q0m!5}]&WW&R,X&f#tOY!3xYZ2qZ]!3x]^2q^r!3xrs!5Osw!3xwx!6vx#O!3x#O#P!;n#P#o!3x#o#p!;t#p~!3x0m!7P]&WW&R,X&f#tOY!3xYZ2qZ]!3x]^2q^r!3xrs!5Osw!3xwx!7xx#O!3x#O#P!;n#P#o!3x#o#p!;t#p~!3x/V!8RZ&WW&R,X&f#tOY!7xYZ6gZ]!7x]^6g^r!7xrs!8ts#O!7x#O#P!9`#P#o!7x#o#p!9f#p~!7x/V!8yV&R,XOr6grs7ms#O6g#O#P8S#P#o6g#o#p8Y#p~6g/V!9cPO~!7x/V!9mZ&WW&R,XOY!:`YZ8tZ]!:`]^8t^r!:`rs!;Ss#O!:`#O#P!;h#P#o!:`#o#p!7x#p~!:`,a!:gX&WW&R,XOY!:`YZ8tZ]!:`]^8t^r!:`rs!;Ss#O!:`#O#P!;h#P~!:`,a!;XT&R,XOr8trs9ls#O8t#O#P9{#P~8t,a!;kPO~!:`0m!;qPO~!3x0m!;}]&TS&WW&R,XOY!<vYZ:{Z]!<v]^:{^r!<vrs!=rsw!<vwx!>`x#O!<v#O#P!@S#P#o!<v#o#p!3x#p~!<v,e!=PZ&TS&WW&R,XOY!<vYZ:{Z]!<v]^:{^r!<vrs!=rsw!<vwx!>`x#O!<v#O#P!@S#P~!<v,e!=yV&TS&R,XOr:{rs<Tsw:{wx<ox#O:{#O#P=u#P~:{,e!>gZ&WW&R,XOY!<vYZ:{Z]!<v]^:{^r!<vrs!=rsw!<vwx!?Yx#O!<v#O#P!@S#P~!<v,e!?aZ&WW&R,XOY!<vYZ:{Z]!<v]^:{^r!<vrs!=rsw!<vwx!:`x#O!<v#O#P!@S#P~!<v,e!@VPO~!<vFy!@e_&^7[&WW&R,X&f#tOY!1WYZ(}Z]!1W]^(}^r!1Wrs!2fsw!1Wwx!Adx#O!1W#O#P!3d#P#o!1W#o#p!;t#p#q!1W#q#r!3x#r~!1WEc!Ao]&^7[&WW&R,X&f#tOY!AdYZ>wZ]!Ad]^>w^r!Adrs!Bhs#O!Ad#O#P!C[#P#o!Ad#o#p!9f#p#q!Ad#q#r!7x#r~!AdEc!BoX&^7[&R,XOr>wrs@_s#O>w#O#PAP#P#o>w#o#p8Y#p#q>w#q#r6g#r~>wEc!CaT&^7[O#o!Ad#o#p!7x#p#q!Ad#q#r!7x#r~!AdGZ!CuT&^7[O#o!-l#o#p!DU#p#q!-l#q#r!DU#r~!-l0}!De]&TS&WW&R,X&Z`&d!b&f#tOY!DUYZAyZ]!DU]^Ay^r!DUrs!E^sw!DUwx!5tx#O!DU#O#P!FU#P#o!DU#o#p!F[#p~!DU0}!EiX&TS&R,X&Z`&d!bOrAyrsCiswAywx5Px#OAy#O#PEo#P#oAy#o#pEu#p~Ay0}!FXPO~!DU0}!Fe]&TS&WW&R,XOY!<vYZ:{Z]!<v]^:{^r!<vrs!=rsw!<vwx!>`x#O!<v#O#P!@S#P#o!<v#o#p!DU#p~!<vGZ!GkZ&^7[&TS&R,X&Z`&d!bOr'Prs!H^sw'Pwx(Rx#O'P#O#PAe#P#o'P#o#pEu#p#q'P#q#rAy#r~'PGZ!HmX&X#|&^7[&TS&V,X&Z`&d!bOwGgwx,kx#OGg#O#PH_#P#oGg#o#pET#p#qGg#q#rD_#r~GgMg!Im_Q1s&^7[&TS&WW&Z`&ap&d!b&f#tOY!IYYZ$}Z]!IY]^$}^r!IYrs!Jlsw!IYwx$$[x#O!IY#O#P$1v#P#o!IY#o#p$4Y#p#q!IY#q#r$2j#r~!IYLu!Jy_Q1s&^7[&TS&Z`&d!bOY!KxYZ'PZ]!Kx]^'P^r!Kxrs$ Usw!Kxwx!MYx#O!Kx#O#P#G^#P#o!Kx#o#p#NS#p#q!Kx#q#r#HQ#r~!KxLu!LZ_Q1s&^7[&TS&WW&Z`&d!b&f#tOY!KxYZ'PZ]!Kx]^'P^r!Kxrs!Jlsw!Kxwx!MYx#O!Kx#O#P#G^#P#o!Kx#o#p#NS#p#q!Kx#q#r#HQ#r~!KxLe!Me_Q1s&^7[&WW&f#tOY!NdYZ(}Z]!Nd]^(}^r!Ndrs# rsw!Ndwx#B[x#O!Nd#O#P#/f#P#o!Nd#o#p#<b#p#q!Nd#q#r#0Y#r~!NdLe!Ns_Q1s&^7[&TS&WW&d!b&f#tOY!NdYZ(}Z]!Nd]^(}^r!Ndrs# rsw!Ndwx!MYx#O!Nd#O#P#/f#P#o!Nd#o#p#<b#p#q!Nd#q#r#0Y#r~!NdLe# }_Q1s&^7[&TS&d!bOY!NdYZ(}Z]!Nd]^(}^r!Ndrs#!|sw!Ndwx!MYx#O!Nd#O#P#/f#P#o!Nd#o#p#<b#p#q!Nd#q#r#0Y#r~!NdLe##X_Q1s&^7[&TS&d!bOY!NdYZ(}Z]!Nd]^(}^r!Ndrs#$Wsw!Ndwx!MYx#O!Nd#O#P#/f#P#o!Nd#o#p#<b#p#q!Nd#q#r#0Y#r~!NdIg#$c]Q1s&^7[&TS&d!bOY#$WYZ+uZ]#$W]^+u^w#$Wwx#%[x#O#$W#O#P#(^#P#o#$W#o#p#,Q#p#q#$W#q#r#)Q#r~#$WIg#%c]Q1s&^7[OY#$WYZ+uZ]#$W]^+u^w#$Wwx#&[x#O#$W#O#P#(^#P#o#$W#o#p#,Q#p#q#$W#q#r#)Q#r~#$WIg#&c]Q1s&^7[OY#$WYZ+uZ]#$W]^+u^w#$Wwx#'[x#O#$W#O#P#(^#P#o#$W#o#p#,Q#p#q#$W#q#r#)Q#r~#$WHP#'cXQ1s&^7[OY#'[YZ-}Z]#'[]^-}^#o#'[#o#p#(O#p#q#'[#q#r#(O#r~#'[1s#(TRQ1sOY#(OZ]#(O^~#(OIg#(eXQ1s&^7[OY#$WYZ+uZ]#$W]^+u^#o#$W#o#p#)Q#p#q#$W#q#r#)Q#r~#$W3Z#)ZZQ1s&TS&d!bOY#)QYZ.qZ]#)Q]^.q^w#)Qwx#)|x#O#)Q#O#P#+l#P#o#)Q#o#p#,Q#p~#)Q3Z#*RZQ1sOY#)QYZ.qZ]#)Q]^.q^w#)Qwx#*tx#O#)Q#O#P#+l#P#o#)Q#o#p#,Q#p~#)Q3Z#*yZQ1sOY#)QYZ.qZ]#)Q]^.q^w#)Qwx#(Ox#O#)Q#O#P#+l#P#o#)Q#o#p#,Q#p~#)Q3Z#+qTQ1sOY#)QYZ.qZ]#)Q]^.q^~#)Q3Z#,XZQ1s&TSOY#,zYZ1OZ]#,z]^1O^w#,zwx#-nx#O#,z#O#P#/Q#P#o#,z#o#p#)Q#p~#,z1w#-RXQ1s&TSOY#,zYZ1OZ]#,z]^1O^w#,zwx#-nx#O#,z#O#P#/Q#P~#,z1w#-sXQ1sOY#,zYZ1OZ]#,z]^1O^w#,zwx#.`x#O#,z#O#P#/Q#P~#,z1w#.eXQ1sOY#,zYZ1OZ]#,z]^1O^w#,zwx#(Ox#O#,z#O#P#/Q#P~#,z1w#/VTQ1sOY#,zYZ1OZ]#,z]^1O^~#,zLe#/mXQ1s&^7[OY!NdYZ(}Z]!Nd]^(}^#o!Nd#o#p#0Y#p#q!Nd#q#r#0Y#r~!Nd6X#0g]Q1s&TS&WW&d!b&f#tOY#0YYZ2qZ]#0Y]^2q^r#0Yrs#1`sw#0Ywx#3dx#O#0Y#O#P#;|#P#o#0Y#o#p#<b#p~#0Y6X#1i]Q1s&TS&d!bOY#0YYZ2qZ]#0Y]^2q^r#0Yrs#2bsw#0Ywx#3dx#O#0Y#O#P#;|#P#o#0Y#o#p#<b#p~#0Y6X#2k]Q1s&TS&d!bOY#0YYZ2qZ]#0Y]^2q^r#0Yrs#)Qsw#0Ywx#3dx#O#0Y#O#P#;|#P#o#0Y#o#p#<b#p~#0Y6X#3m]Q1s&WW&f#tOY#0YYZ2qZ]#0Y]^2q^r#0Yrs#1`sw#0Ywx#4fx#O#0Y#O#P#;|#P#o#0Y#o#p#<b#p~#0Y6X#4o]Q1s&WW&f#tOY#0YYZ2qZ]#0Y]^2q^r#0Yrs#1`sw#0Ywx#5hx#O#0Y#O#P#;|#P#o#0Y#o#p#<b#p~#0Y4q#5qZQ1s&WW&f#tOY#5hYZ6gZ]#5h]^6g^r#5hrs#6ds#O#5h#O#P#8S#P#o#5h#o#p#8h#p~#5h4q#6iZQ1sOY#5hYZ6gZ]#5h]^6g^r#5hrs#7[s#O#5h#O#P#8S#P#o#5h#o#p#8h#p~#5h4q#7aZQ1sOY#5hYZ6gZ]#5h]^6g^r#5hrs#(Os#O#5h#O#P#8S#P#o#5h#o#p#8h#p~#5h4q#8XTQ1sOY#5hYZ6gZ]#5h]^6g^~#5h4q#8oZQ1s&WWOY#9bYZ8tZ]#9b]^8t^r#9brs#:Us#O#9b#O#P#;h#P#o#9b#o#p#5h#p~#9b1{#9iXQ1s&WWOY#9bYZ8tZ]#9b]^8t^r#9brs#:Us#O#9b#O#P#;h#P~#9b1{#:ZXQ1sOY#9bYZ8tZ]#9b]^8t^r#9brs#:vs#O#9b#O#P#;h#P~#9b1{#:{XQ1sOY#9bYZ8tZ]#9b]^8t^r#9brs#(Os#O#9b#O#P#;h#P~#9b1{#;mTQ1sOY#9bYZ8tZ]#9b]^8t^~#9b6X#<RTQ1sOY#0YYZ2qZ]#0Y]^2q^~#0Y6X#<k]Q1s&TS&WWOY#=dYZ:{Z]#=d]^:{^r#=drs#>`sw#=dwx#@Sx#O#=d#O#P#Av#P#o#=d#o#p#0Y#p~#=d2P#=mZQ1s&TS&WWOY#=dYZ:{Z]#=d]^:{^r#=drs#>`sw#=dwx#@Sx#O#=d#O#P#Av#P~#=d2P#>gZQ1s&TSOY#=dYZ:{Z]#=d]^:{^r#=drs#?Ysw#=dwx#@Sx#O#=d#O#P#Av#P~#=d2P#?aZQ1s&TSOY#=dYZ:{Z]#=d]^:{^r#=drs#,zsw#=dwx#@Sx#O#=d#O#P#Av#P~#=d2P#@ZZQ1s&WWOY#=dYZ:{Z]#=d]^:{^r#=drs#>`sw#=dwx#@|x#O#=d#O#P#Av#P~#=d2P#ATZQ1s&WWOY#=dYZ:{Z]#=d]^:{^r#=drs#>`sw#=dwx#9bx#O#=d#O#P#Av#P~#=d2P#A{TQ1sOY#=dYZ:{Z]#=d]^:{^~#=dLe#Bg_Q1s&^7[&WW&f#tOY!NdYZ(}Z]!Nd]^(}^r!Ndrs# rsw!Ndwx#Cfx#O!Nd#O#P#/f#P#o!Nd#o#p#<b#p#q!Nd#q#r#0Y#r~!NdJ}#Cq]Q1s&^7[&WW&f#tOY#CfYZ>wZ]#Cf]^>w^r#Cfrs#Djs#O#Cf#O#P#Fj#P#o#Cf#o#p#8h#p#q#Cf#q#r#5h#r~#CfJ}#Dq]Q1s&^7[OY#CfYZ>wZ]#Cf]^>w^r#Cfrs#Ejs#O#Cf#O#P#Fj#P#o#Cf#o#p#8h#p#q#Cf#q#r#5h#r~#CfJ}#Eq]Q1s&^7[OY#CfYZ>wZ]#Cf]^>w^r#Cfrs#'[s#O#Cf#O#P#Fj#P#o#Cf#o#p#8h#p#q#Cf#q#r#5h#r~#CfJ}#FqXQ1s&^7[OY#CfYZ>wZ]#Cf]^>w^#o#Cf#o#p#5h#p#q#Cf#q#r#5h#r~#CfLu#GeXQ1s&^7[OY!KxYZ'PZ]!Kx]^'P^#o!Kx#o#p#HQ#p#q!Kx#q#r#HQ#r~!Kx6i#Ha]Q1s&TS&WW&Z`&d!b&f#tOY#HQYZAyZ]#HQ]^Ay^r#HQrs#IYsw#HQwx#3dx#O#HQ#O#P#Mn#P#o#HQ#o#p#NS#p~#HQ6i#Ie]Q1s&TS&Z`&d!bOY#HQYZAyZ]#HQ]^Ay^r#HQrs#J^sw#HQwx#3dx#O#HQ#O#P#Mn#P#o#HQ#o#p#NS#p~#HQ6i#Ji]Q1s&TS&Z`&d!bOY#HQYZAyZ]#HQ]^Ay^r#HQrs#Kbsw#HQwx#3dx#O#HQ#O#P#Mn#P#o#HQ#o#p#NS#p~#HQ3k#KmZQ1s&TS&Z`&d!bOY#KbYZD_Z]#Kb]^D_^w#Kbwx#)|x#O#Kb#O#P#L`#P#o#Kb#o#p#Lt#p~#Kb3k#LeTQ1sOY#KbYZD_Z]#Kb]^D_^~#Kb3k#L{ZQ1s&TSOY#,zYZ1OZ]#,z]^1O^w#,zwx#-nx#O#,z#O#P#/Q#P#o#,z#o#p#Kb#p~#,z6i#MsTQ1sOY#HQYZAyZ]#HQ]^Ay^~#HQ6i#N]]Q1s&TS&WWOY#=dYZ:{Z]#=d]^:{^r#=drs#>`sw#=dwx#@Sx#O#=d#O#P#Av#P#o#=d#o#p#HQ#p~#=dLu$ c_Q1s&^7[&TS&Z`&d!bOY!KxYZ'PZ]!Kx]^'P^r!Kxrs$!bsw!Kxwx!MYx#O!Kx#O#P#G^#P#o!Kx#o#p#NS#p#q!Kx#q#r#HQ#r~!KxIw$!o]Q1s&^7[&TS&Z`&d!bOY$!bYZGgZ]$!b]^Gg^w$!bwx#%[x#O$!b#O#P$#h#P#o$!b#o#p#Lt#p#q$!b#q#r#Kb#r~$!bIw$#oXQ1s&^7[OY$!bYZGgZ]$!b]^Gg^#o$!b#o#p#Kb#p#q$!b#q#r#Kb#r~$!bMV$$i_Q1s&^7[&WW&ap&f#tOY$%hYZIqZ]$%h]^Iq^r$%hrs# rsw$%hwx$.px#O$%h#O#P$&x#P#o$%h#o#p$-n#p#q$%h#q#r$'l#r~$%hMV$%y_Q1s&^7[&TS&WW&ap&d!b&f#tOY$%hYZIqZ]$%h]^Iq^r$%hrs# rsw$%hwx$$[x#O$%h#O#P$&x#P#o$%h#o#p$-n#p#q$%h#q#r$'l#r~$%hMV$'PXQ1s&^7[OY$%hYZIqZ]$%h]^Iq^#o$%h#o#p$'l#p#q$%h#q#r$'l#r~$%h6y$'{]Q1s&TS&WW&ap&d!b&f#tOY$'lYZKXZ]$'l]^KX^r$'lrs#1`sw$'lwx$(tx#O$'l#O#P$-Y#P#o$'l#o#p$-n#p~$'l6y$)P]Q1s&WW&ap&f#tOY$'lYZKXZ]$'l]^KX^r$'lrs#1`sw$'lwx$)xx#O$'l#O#P$-Y#P#o$'l#o#p$-n#p~$'l6y$*T]Q1s&WW&ap&f#tOY$'lYZKXZ]$'l]^KX^r$'lrs#1`sw$'lwx$*|x#O$'l#O#P$-Y#P#o$'l#o#p$-n#p~$'l5c$+XZQ1s&WW&ap&f#tOY$*|YZMmZ]$*|]^Mm^r$*|rs#6ds#O$*|#O#P$+z#P#o$*|#o#p$,`#p~$*|5c$,PTQ1sOY$*|YZMmZ]$*|]^Mm^~$*|5c$,gZQ1s&WWOY#9bYZ8tZ]#9b]^8t^r#9brs#:Us#O#9b#O#P#;h#P#o#9b#o#p$*|#p~#9b6y$-_TQ1sOY$'lYZKXZ]$'l]^KX^~$'l6y$-w]Q1s&TS&WWOY#=dYZ:{Z]#=d]^:{^r#=drs#>`sw#=dwx#@Sx#O#=d#O#P#Av#P#o#=d#o#p$'l#p~#=dMV$.}_Q1s&^7[&WW&ap&f#tOY$%hYZIqZ]$%h]^Iq^r$%hrs# rsw$%hwx$/|x#O$%h#O#P$&x#P#o$%h#o#p$-n#p#q$%h#q#r$'l#r~$%hKo$0Z]Q1s&^7[&WW&ap&f#tOY$/|YZ!!uZ]$/|]^!!u^r$/|rs#Djs#O$/|#O#P$1S#P#o$/|#o#p$,`#p#q$/|#q#r$*|#r~$/|Ko$1ZXQ1s&^7[OY$/|YZ!!uZ]$/|]^!!u^#o$/|#o#p$*|#p#q$/|#q#r$*|#r~$/|Mg$1}XQ1s&^7[OY!IYYZ$}Z]!IY]^$}^#o!IY#o#p$2j#p#q!IY#q#r$2j#r~!IY7Z$2{]Q1s&TS&WW&Z`&ap&d!b&f#tOY$2jYZ!$gZ]$2j]^!$g^r$2jrs#IYsw$2jwx$(tx#O$2j#O#P$3t#P#o$2j#o#p$4Y#p~$2j7Z$3yTQ1sOY$2jYZ!$gZ]$2j]^!$g^~$2j7Z$4c]Q1s&TS&WWOY#=dYZ:{Z]#=d]^:{^r#=drs#>`sw#=dwx#@Sx#O#=d#O#P#Av#P#o#=d#o#p$2j#p~#=dGz$5o]%jQ&^7[&TS&WW&Z`&ap&d!b&f#tOr$}rs&Rsw$}wxHsx!_$}!_!`$6h!`#O$}#O#P!$R#P#o$}#o#p!%i#p#q$}#q#r!$g#r~$}Gz$6{Z!s,W&^7[&TS&WW&Z`&ap&d!b&f#tOr$}rs&Rsw$}wxHsx#O$}#O#P!$R#P#o$}#o#p!%i#p#q$}#q#r!$g#r~$}Gz$8R]%dQ&^7[&TS&WW&Z`&ap&d!b&f#tOr$}rs&Rsw$}wxHsx!_$}!_!`$6h!`#O$}#O#P!$R#P#o$}#o#p!%i#p#q$}#q#r!$g#r~$}G{$9Z_&_`&^7[&WW&R,X&ap&f#tOY$:YYZIqZ]$:Y]^Iq^r$:Yrs$;jsw$:Ywx%%zx#O$:Y#O#P%!^#P#o$:Y#o#p%$x#p#q$:Y#q#r%!r#r~$:YGk$:k_&^7[&TS&WW&R,X&ap&d!b&f#tOY$:YYZIqZ]$:Y]^Iq^r$:Yrs$;jsw$:Ywx% ^x#O$:Y#O#P%!^#P#o$:Y#o#p%$x#p#q$:Y#q#r%!r#r~$:YFy$;u_&^7[&TS&R,X&d!bOY$<tYZ(}Z]$<t]^(}^r$<trs$Kvsw$<twx$>Sx#O$<t#O#P$?Q#P#o$<t#o#p$Gb#p#q$<t#q#r$?f#r~$<tFy$=T_&^7[&TS&WW&R,X&d!b&f#tOY$<tYZ(}Z]$<t]^(}^r$<trs$;jsw$<twx$>Sx#O$<t#O#P$?Q#P#o$<t#o#p$Gb#p#q$<t#q#r$?f#r~$<tFy$>_Z&^7[&WW&R,X&f#tOr(}rs)}sw(}wx={x#O(}#O#P2]#P#o(}#o#p:X#p#q(}#q#r2q#r~(}Fy$?VT&^7[O#o$<t#o#p$?f#p#q$<t#q#r$?f#r~$<t0m$?s]&TS&WW&R,X&d!b&f#tOY$?fYZ2qZ]$?f]^2q^r$?frs$@lsw$?fwx$Ffx#O$?f#O#P$G[#P#o$?f#o#p$Gb#p~$?f0m$@u]&TS&R,X&d!bOY$?fYZ2qZ]$?f]^2q^r$?frs$Answ$?fwx$Ffx#O$?f#O#P$G[#P#o$?f#o#p$Gb#p~$?f0m$Aw]&TS&R,X&d!bOY$?fYZ2qZ]$?f]^2q^r$?frs$Bpsw$?fwx$Ffx#O$?f#O#P$G[#P#o$?f#o#p$Gb#p~$?f-o$ByZ&TS&R,X&d!bOY$BpYZ.qZ]$Bp]^.q^w$Bpwx$Clx#O$Bp#O#P$DW#P#o$Bp#o#p$D^#p~$Bp-o$CqV&R,XOw.qwx/wx#O.q#O#P0^#P#o.q#o#p0d#p~.q-o$DZPO~$Bp-o$DeZ&TS&R,XOY$EWYZ1OZ]$EW]^1O^w$EWwx$Ezx#O$EW#O#P$F`#P#o$EW#o#p$Bp#p~$EW,]$E_X&TS&R,XOY$EWYZ1OZ]$EW]^1O^w$EWwx$Ezx#O$EW#O#P$F`#P~$EW,]$FPT&R,XOw1Owx1vx#O1O#O#P2V#P~1O,]$FcPO~$EW0m$FoX&WW&R,X&f#tOr2qrs3isw2qwx5sx#O2q#O#P:R#P#o2q#o#p:X#p~2q0m$G_PO~$?f0m$Gk]&TS&WW&R,XOY$HdYZ:{Z]$Hd]^:{^r$Hdrs$I`sw$Hdwx$KSx#O$Hd#O#P$Kp#P#o$Hd#o#p$?f#p~$Hd,e$HmZ&TS&WW&R,XOY$HdYZ:{Z]$Hd]^:{^r$Hdrs$I`sw$Hdwx$KSx#O$Hd#O#P$Kp#P~$Hd,e$IgZ&TS&R,XOY$HdYZ:{Z]$Hd]^:{^r$Hdrs$JYsw$Hdwx$KSx#O$Hd#O#P$Kp#P~$Hd,e$JaZ&TS&R,XOY$HdYZ:{Z]$Hd]^:{^r$Hdrs$EWsw$Hdwx$KSx#O$Hd#O#P$Kp#P~$Hd,e$KZV&WW&R,XOr:{rs;isw:{wx=Zx#O:{#O#P=u#P~:{,e$KsPO~$HdFy$LR_&^7[&TS&R,X&d!bOY$<tYZ(}Z]$<t]^(}^r$<trs$MQsw$<twx$>Sx#O$<t#O#P$?Q#P#o$<t#o#p$Gb#p#q$<t#q#r$?f#r~$<tC{$M]]&^7[&TS&R,X&d!bOY$MQYZ+uZ]$MQ]^+u^w$MQwx$NUx#O$MQ#O#P$Nx#P#o$MQ#o#p$D^#p#q$MQ#q#r$Bp#r~$MQC{$N]X&^7[&R,XOw+uwx-]x#O+u#O#P.]#P#o+u#o#p0d#p#q+u#q#r.q#r~+uC{$N}T&^7[O#o$MQ#o#p$Bp#p#q$MQ#q#r$Bp#r~$MQGk% kZ&^7[&WW&R,X&ap&f#tOrIqrs)}swIqwx! wx#OIq#O#PJs#P#oIq#o#p! T#p#qIq#q#rKX#r~IqGk%!cT&^7[O#o$:Y#o#p%!r#p#q$:Y#q#r%!r#r~$:Y1_%#R]&TS&WW&R,X&ap&d!b&f#tOY%!rYZKXZ]%!r]^KX^r%!rrs$@lsw%!rwx%#zx#O%!r#O#P%$r#P#o%!r#o#p%$x#p~%!r1_%$VX&WW&R,X&ap&f#tOrKXrs3iswKXwxLwx#OKX#O#PN}#P#oKX#o#p! T#p~KX1_%$uPO~%!r1_%%R]&TS&WW&R,XOY$HdYZ:{Z]$Hd]^:{^r$Hdrs$I`sw$Hdwx$KSx#O$Hd#O#P$Kp#P#o$Hd#o#p%!r#p~$HdGk%&XZ&^7[&WW&R,X&ap&f#tOrIqrs)}swIqwx%&zx#OIq#O#PJs#P#oIq#o#p! T#p#qIq#q#rKX#r~IqGk%'ZX&U!f&^7[&WW&S,X&ap&f#tOr!!urs?ms#O!!u#O#P!#m#P#o!!u#o#pNc#p#q!!u#q#rMm#r~!!uG{%(ZZf,X&^7[&TS&WW&Z`&ap&d!b&f#tOr$}rs&Rsw$}wxHsx#O$}#O#P!$R#P#o$}#o#p!%i#p#q$}#q#r!$g#r~$}<u%)aZeR&^7[&TS&WW&Z`&ap&d!b&f#tOr$}rs&Rsw$}wxHsx#O$}#O#P!$R#P#o$}#o#p!%i#p#q$}#q#r!$g#r~$}G{%*g_T,X&^7[&TS&WW&Z`&ap&d!b&f#tOr$}rs&Rsw$}wxHsxz$}z{%+f{!_$}!_!`$6h!`#O$}#O#P!$R#P#o$}#o#p!%i#p#q$}#q#r!$g#r~$}G{%+y]_R&^7[&TS&WW&Z`&ap&d!b&f#tOr$}rs&Rsw$}wxHsx!_$}!_!`$6h!`#O$}#O#P!$R#P#o$}#o#p!%i#p#q$}#q#r!$g#r~$}G{%-V]%g,X&^7[&TS&WW&Z`&ap&d!b&f#tOr$}rs&Rsw$}wxHsx!_$}!_!`$6h!`#O$}#O#P!$R#P#o$}#o#p!%i#p#q$}#q#r!$g#r~$}<u%.cZxR&^7[&TS&WW&Z`&ap&d!b&f#tOr$}rs&Rsw$}wxHsx#O$}#O#P!$R#P#o$}#o#p!%i#p#q$}#q#r!$g#r~$}Mg%/i^%h,X&^7[&TS&WW&Z`&ap&d!b&f#tOr$}rs&Rsw$}wxHsx!_$}!_!`$6h!`!a%0e!a#O$}#O#P!$R#P#o$}#o#p!%i#p#q$}#q#r!$g#r~$}B^%0xZ&q&j&^7[&TS&WW&Z`&ap&d!b&f#tOr$}rs&Rsw$}wxHsx#O$}#O#P!$R#P#o$}#o#p!%i#p#q$}#q#r!$g#r~$}G{%2O_!dQ&^7[&TS&WW&Z`&ap&d!b&f#tOr$}rs&Rsw$}wxHsx!O$}!O!P%2}!P!Q$}!Q![%5_![#O$}#O#P!$R#P#o$}#o#p!%i#p#q$}#q#r!$g#r~$}G{%3`]&^7[&TS&WW&Z`&ap&d!b&f#tOr$}rs&Rsw$}wxHsx!O$}!O!P%4X!P#O$}#O#P!$R#P#o$}#o#p!%i#p#q$}#q#r!$g#r~$}G{%4lZ!m,X&^7[&TS&WW&Z`&ap&d!b&f#tOr$}rs&Rsw$}wxHsx#O$}#O#P!$R#P#o$}#o#p!%i#p#q$}#q#r!$g#r~$}Gy%5rg!f,V&^7[&TS&WW&Z`&ap&d!b&f#tOr$}rs&Rsw$}wxHsx!Q$}!Q![%5_![!g$}!g!h%7Z!h!l$}!l!m%;k!m#O$}#O#P!$R#P#R$}#R#S%5_#S#X$}#X#Y%7Z#Y#^$}#^#_%;k#_#o$}#o#p!%i#p#q$}#q#r!$g#r~$}Gy%7la&^7[&TS&WW&Z`&ap&d!b&f#tOr$}rs&Rsw$}wxHsx{$}{|%8q|}$}}!O%8q!O!Q$}!Q![%9{![#O$}#O#P!$R#P#o$}#o#p!%i#p#q$}#q#r!$g#r~$}Gy%9S]&^7[&TS&WW&Z`&ap&d!b&f#tOr$}rs&Rsw$}wxHsx!Q$}!Q![%9{![#O$}#O#P!$R#P#o$}#o#p!%i#p#q$}#q#r!$g#r~$}Gy%:`c!f,V&^7[&TS&WW&Z`&ap&d!b&f#tOr$}rs&Rsw$}wxHsx!Q$}!Q![%9{![!l$}!l!m%;k!m#O$}#O#P!$R#P#R$}#R#S%9{#S#^$}#^#_%;k#_#o$}#o#p!%i#p#q$}#q#r!$g#r~$}Gy%<OZ!f,V&^7[&TS&WW&Z`&ap&d!b&f#tOr$}rs&Rsw$}wxHsx#O$}#O#P!$R#P#o$}#o#p!%i#p#q$}#q#r!$g#r~$}G{%=U_%iR&^7[&TS&WW&Z`&ap&d!b&f#tOr$}rs&Rsw$}wxHsx!P$}!P!Q%>T!Q!_$}!_!`$6h!`#O$}#O#P!$R#P#o$}#o#p!%i#p#q$}#q#r!$g#r~$}Gz%>h]%kQ&^7[&TS&WW&Z`&ap&d!b&f#tOr$}rs&Rsw$}wxHsx!_$}!_!`$6h!`#O$}#O#P!$R#P#o$}#o#p!%i#p#q$}#q#r!$g#r~$}Gy%?tu!f,V&^7[&TS&WW&Z`&ap&d!b&f#tOr$}rs&Rsw$}wxHsx!O$}!O!P%BX!P!Q$}!Q![%Cc![!d$}!d!e%Ee!e!g$}!g!h%7Z!h!l$}!l!m%;k!m!q$}!q!r%H_!r!z$}!z!{%KR!{#O$}#O#P!$R#P#R$}#R#S%Cc#S#U$}#U#V%Ee#V#X$}#X#Y%7Z#Y#^$}#^#_%;k#_#c$}#c#d%H_#d#l$}#l#m%KR#m#o$}#o#p!%i#p#q$}#q#r!$g#r~$}Gy%Bj]&^7[&TS&WW&Z`&ap&d!b&f#tOr$}rs&Rsw$}wxHsx!Q$}!Q![%5_![#O$}#O#P!$R#P#o$}#o#p!%i#p#q$}#q#r!$g#r~$}Gy%Cvi!f,V&^7[&TS&WW&Z`&ap&d!b&f#tOr$}rs&Rsw$}wxHsx!O$}!O!P%BX!P!Q$}!Q![%Cc![!g$}!g!h%7Z!h!l$}!l!m%;k!m#O$}#O#P!$R#P#R$}#R#S%Cc#S#X$}#X#Y%7Z#Y#^$}#^#_%;k#_#o$}#o#p!%i#p#q$}#q#r!$g#r~$}Gy%Ev`&^7[&TS&WW&Z`&ap&d!b&f#tOr$}rs&Rsw$}wxHsx!Q$}!Q!R%Fx!R!S%Fx!S#O$}#O#P!$R#P#R$}#R#S%Fx#S#o$}#o#p!%i#p#q$}#q#r!$g#r~$}Gy%G]`!f,V&^7[&TS&WW&Z`&ap&d!b&f#tOr$}rs&Rsw$}wxHsx!Q$}!Q!R%Fx!R!S%Fx!S#O$}#O#P!$R#P#R$}#R#S%Fx#S#o$}#o#p!%i#p#q$}#q#r!$g#r~$}Gy%Hp_&^7[&TS&WW&Z`&ap&d!b&f#tOr$}rs&Rsw$}wxHsx!Q$}!Q!Y%Io!Y#O$}#O#P!$R#P#R$}#R#S%Io#S#o$}#o#p!%i#p#q$}#q#r!$g#r~$}Gy%JS_!f,V&^7[&TS&WW&Z`&ap&d!b&f#tOr$}rs&Rsw$}wxHsx!Q$}!Q!Y%Io!Y#O$}#O#P!$R#P#R$}#R#S%Io#S#o$}#o#p!%i#p#q$}#q#r!$g#r~$}Gy%Kdc&^7[&TS&WW&Z`&ap&d!b&f#tOr$}rs&Rsw$}wxHsx!Q$}!Q![%Lo![!c$}!c!i%Lo!i#O$}#O#P!$R#P#R$}#R#S%Lo#S#T$}#T#Z%Lo#Z#o$}#o#p!%i#p#q$}#q#r!$g#r~$}Gy%MSc!f,V&^7[&TS&WW&Z`&ap&d!b&f#tOr$}rs&Rsw$}wxHsx!Q$}!Q![%Lo![!c$}!c!i%Lo!i#O$}#O#P!$R#P#R$}#R#S%Lo#S#T$}#T#Z%Lo#Z#o$}#o#p!%i#p#q$}#q#r!$g#r~$}Mg%Nr]y1s&^7[&TS&WW&Z`&ap&d!b&f#tOr$}rs&Rsw$}wxHsx!_$}!_!`& k!`#O$}#O#P!$R#P#o$}#o#p!%i#p#q$}#q#r!$g#r~$}<u&!OZ%sR&^7[&TS&WW&Z`&ap&d!b&f#tOr$}rs&Rsw$}wxHsx#O$}#O#P!$R#P#o$}#o#p!%i#p#q$}#q#r!$g#r~$}G{&#UZ#^,X&^7[&TS&WW&Z`&ap&d!b&f#tOr$}rs&Rsw$}wxHsx#O$}#O#P!$R#P#o$}#o#p!%i#p#q$}#q#r!$g#r~$}G{&$[_kR&^7[&TS&WW&Z`&ap&d!b&f#tOr$}rs&Rsw$}wxHsx!^$}!^!_&%Z!_!`!*Q!`!a!*Q!a#O$}#O#P!$R#P#o$}#o#p!%i#p#q$}#q#r!$g#r~$}Gz&%n]%eQ&^7[&TS&WW&Z`&ap&d!b&f#tOr$}rs&Rsw$}wxHsx!_$}!_!`$6h!`#O$}#O#P!$R#P#o$}#o#p!%i#p#q$}#q#r!$g#r~$}G{&&z]%r,X&^7[&TS&WW&Z`&ap&d!b&f#tOr$}rs&Rsw$}wxHsx!_$}!_!`!*Q!`#O$}#O#P!$R#P#o$}#o#p!%i#p#q$}#q#r!$g#r~$}G{&(W^kR&^7[&TS&WW&Z`&ap&d!b&f#tOr$}rs&Rsw$}wxHsx!_$}!_!`!*Q!`!a&)S!a#O$}#O#P!$R#P#o$}#o#p!%i#p#q$}#q#r!$g#r~$}Gz&)g]%fQ&^7[&TS&WW&Z`&ap&d!b&f#tOr$}rs&Rsw$}wxHsx!_$}!_!`$6h!`#O$}#O#P!$R#P#o$}#o#p!%i#p#q$}#q#r!$g#r~$}G{&*u]]Q#tP&^7[&TS&WW&Z`&ap&d!b&f#tOr$}rs&Rsw$}wxHsx!_$}!_!`$6h!`#O$}#O#P!$R#P#o$}#o#p!%i#p#q$}#q#r!$g#r~$}Mg&,Tc&^7[&TS&WW&Q&j&Z`&ap&d!b&f#t%m,XOr$}rs&Rsw$}wxHsx!Q$}!Q![&+n![!c$}!c!}&+n!}#O$}#O#P!$R#P#R$}#R#S&+n#S#T$}#T#o&+n#o#p!%i#p#q$}#q#r!$g#r$g$}$g~&+nMg&-ug&^7[&TS&WW&Q&j&Z`&ap&d!b&f#t%m,XOr$}rs&/^sw$}wx&2dx!Q$}!Q![&+n![!c$}!c!t&+n!t!u&5j!u!}&+n!}#O$}#O#P!$R#P#R$}#R#S&+n#S#T$}#T#f&+n#f#g&5j#g#o&+n#o#p!%i#p#q$}#q#r!$g#r$g$}$g~&+nGZ&/k_&^7[&TS&R,X&Z`&d!bOY!-lYZ'PZ]!-l]^'P^r!-lrs&0jsw!-lwx!/|x#O!-l#O#P!Cp#P#o!-l#o#p!F[#p#q!-l#q#r!DU#r~!-lGZ&0wZ&^7[&TS&R,X&Z`&d!bOr'Prs&1jsw'Pwx(Rx#O'P#O#PAe#P#o'P#o#pEu#p#q'P#q#rAy#r~'PD]&1wX&^7[&TS&V,X&Z`&d!bOwGgwx,kx#OGg#O#PH_#P#oGg#o#pET#p#qGg#q#rD_#r~GgGk&2q_&^7[&WW&R,X&ap&f#tOY$:YYZIqZ]$:Y]^Iq^r$:Yrs$;jsw$:Ywx&3px#O$:Y#O#P%!^#P#o$:Y#o#p%$x#p#q$:Y#q#r%!r#r~$:YGk&3}Z&^7[&WW&R,X&ap&f#tOrIqrs)}swIqwx&4px#OIq#O#PJs#P#oIq#o#p! T#p#qIq#q#rKX#r~IqFT&4}X&^7[&WW&S,X&ap&f#tOr!!urs?ms#O!!u#O#P!#m#P#o!!u#o#pNc#p#q!!u#q#rMm#r~!!uMg&6Pc&^7[&TS&WW&Q&j&Z`&ap&d!b&f#t%m,XOr$}rs&/^sw$}wx&2dx!Q$}!Q![&+n![!c$}!c!}&+n!}#O$}#O#P!$R#P#R$}#R#S&+n#S#T$}#T#o&+n#o#p!%i#p#q$}#q#r!$g#r$g$}$g~&+nMg&7qg&^7[&TS&WW&Q&j&Z`&ap&d!b&f#t%m,XOr$}rs&9Ysw$}wx&<Qx!Q$}!Q![&+n![!c$}!c!t&+n!t!u&>x!u!}&+n!}#O$}#O#P!$R#P#R$}#R#S&+n#S#T$}#T#f&+n#f#g&>x#g#o&+n#o#p!%i#p#q$}#q#r!$g#r$g$}$g~&+nGZ&9gZ&^7[&TS&Z`&d!b&`,XOr'Prs&:Ysw'Pwx(Rx#O'P#O#PAe#P#o'P#o#pEu#p#q'P#q#rAy#r~'PGZ&:eZ&^7[&TS&Z`&d!bOr'Prs&;Wsw'Pwx(Rx#O'P#O#PAe#P#o'P#o#pEu#p#q'P#q#rAy#r~'PD]&;eX&^7[&TS&e,X&Z`&d!bOwGgwx,kx#OGg#O#PH_#P#oGg#o#pET#p#qGg#q#rD_#r~GgGk&<_Z&^7[&WW&ap&f#t&Y,XOrIqrs)}swIqwx&=Qx#OIq#O#PJs#P#oIq#o#p! T#p#qIq#q#rKX#r~IqGk&=]Z&^7[&WW&ap&f#tOrIqrs)}swIqwx&>Ox#OIq#O#PJs#P#oIq#o#p! T#p#qIq#q#rKX#r~IqFT&>]X&^7[&WW&c,X&ap&f#tOr!!urs?ms#O!!u#O#P!#m#P#o!!u#o#pNc#p#q!!u#q#rMm#r~!!uMg&?_c&^7[&TS&WW&Q&j&Z`&ap&d!b&f#t%m,XOr$}rs&9Ysw$}wx&<Qx!Q$}!Q![&+n![!c$}!c!}&+n!}#O$}#O#P!$R#P#R$}#R#S&+n#S#T$}#T#o&+n#o#p!%i#p#q$}#q#r!$g#r$g$}$g~&+nMg&APk&^7[&TS&WW&Q&j&Z`&ap&d!b&f#t%m,XOr$}rs&/^sw$}wx&2dx!Q$}!Q![&+n![!c$}!c!h&+n!h!i&>x!i!t&+n!t!u&5j!u!}&+n!}#O$}#O#P!$R#P#R$}#R#S&+n#S#T$}#T#U&+n#U#V&5j#V#Y&+n#Y#Z&>x#Z#o&+n#o#p!%i#p#q$}#q#r!$g#r$g$}$g~&+nG{&CXZ!V,X&^7[&TS&WW&Z`&ap&d!b&f#tOr$}rs&Rsw$}wxHsx#O$}#O#P!$R#P#o$}#o#p!%i#p#q$}#q#r!$g#r~$}<u&D_Z!UR&^7[&TS&WW&Z`&ap&d!b&f#tOr$}rs&Rsw$}wxHsx#O$}#O#P!$R#P#o$}#o#p!%i#p#q$}#q#r!$g#r~$}Gz&Ee]%cQ&^7[&TS&WW&Z`&ap&d!b&f#tOr$}rs&Rsw$}wxHsx!_$}!_!`$6h!`#O$}#O#P!$R#P#o$}#o#p!%i#p#q$}#q#r!$g#r~$}Gy&FgX&TS&WW!ZGmOr:{rs;isw:{wx<ox#O:{#O#P=u#P#o:{#o#p!$g#p~:{G{&Gg]%bR&^7[&TS&WW&Z`&ap&d!b&f#tOr$}rs&Rsw$}wxHsx!_$}!_!`$6h!`#O$}#O#P!$R#P#o$}#o#p!%i#p#q$}#q#r!$g#r~$}<u&HqX!Y7_&TS&WW&Z`&ap&d!b&f#tOr!$grsBssw!$gwxLRx#O!$g#O#P!%c#P#o!$g#o#p!%i#p~!$gGy&IqZ%l,V&^7[&TS&WW&Z`&ap&d!b&f#tOr$}rs&Rsw$}wxHsx#O$}#O#P!$R#P#o$}#o#p!%i#p#q$}#q#r!$g#r~$}", + tokenizers: [legacyPrint, indentation, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, newlines], + topRules: {"Script":[0,3]}, + specialized: [{term: 213, get: value => spec_identifier[value] || -1}], + tokenPrec: 7282 + }); + + function indentBody(context, node) { + let base = context.lineIndent(node.from); + let line = context.lineAt(context.pos, -1), to = line.from + line.text.length; + // Don't consider blank, deindented lines at the end of the + // block part of the block + if (!/\S/.test(line.text) && + context.node.to < to + 100 && + !/\S/.test(context.state.sliceDoc(to, context.node.to)) && + context.lineIndent(context.pos, -1) <= base) + return null; + // A normally deindenting keyword that appears at a higher + // indentation than the block should probably be handled by the next + // level + if (/^\s*(else:|elif |except |finally:)/.test(context.textAfter) && context.lineIndent(context.pos, -1) > base) + return null; + return base + context.unit; + } + /** + A language provider based on the [Lezer Python + parser](https://github.com/lezer-parser/python), extended with + highlighting and indentation information. + */ + const pythonLanguage = /*@__PURE__*/LRLanguage.define({ + parser: /*@__PURE__*/parser.configure({ + props: [ + /*@__PURE__*/indentNodeProp.add({ + Body: context => { var _a; return (_a = indentBody(context, context.node)) !== null && _a !== void 0 ? _a : context.continue(); }, + IfStatement: cx => /^\s*(else:|elif )/.test(cx.textAfter) ? cx.baseIndent : cx.continue(), + TryStatement: cx => /^\s*(except |finally:)/.test(cx.textAfter) ? cx.baseIndent : cx.continue(), + "TupleExpression ComprehensionExpression ParamList ArgList ParenthesizedExpression": /*@__PURE__*/delimitedIndent({ closing: ")" }), + "DictionaryExpression DictionaryComprehensionExpression SetExpression SetComprehensionExpression": /*@__PURE__*/delimitedIndent({ closing: "}" }), + "ArrayExpression ArrayComprehensionExpression": /*@__PURE__*/delimitedIndent({ closing: "]" }), + "String FormatString": () => null, + Script: context => { + if (context.pos + /\s*/.exec(context.textAfter)[0].length >= context.node.to) { + let endBody = null; + for (let cur = context.node, to = cur.to;;) { + cur = cur.lastChild; + if (!cur || cur.to != to) + break; + if (cur.type.name == "Body") + endBody = cur; + } + if (endBody) { + let bodyIndent = indentBody(context, endBody); + if (bodyIndent != null) + return bodyIndent; + } + } + return context.continue(); + } + }), + /*@__PURE__*/foldNodeProp.add({ + "ArrayExpression DictionaryExpression SetExpression TupleExpression": foldInside, + Body: (node, state) => ({ from: node.from + 1, to: node.to - (node.to == state.doc.length ? 0 : 1) }) + }) + ], + }), + languageData: { + closeBrackets: { + brackets: ["(", "[", "{", "'", '"', "'''", '"""'], + stringPrefixes: ["f", "fr", "rf", "r", "u", "b", "br", "rb", + "F", "FR", "RF", "R", "U", "B", "BR", "RB"] + }, + commentTokens: { line: "#" }, + indentOnInput: /^\s*([\}\]\)]|else:|elif |except |finally:)$/ + } + }); + /** + Python language support. + */ + function python() { + return new LanguageSupport(pythonLanguage); + } + + // Using https://github.com/one-dark/vscode-one-dark-theme/ as reference for the colors + const ivory = "#abb2bf", stone = "#7d8799", // Brightened compared to original to increase contrast + darkBackground = "#21252b", highlightBackground = "#2c313a", background = "#282c34", tooltipBackground = "#353a42", selection = "#3E4451", cursor = "#528bff"; + /** + The editor theme styles for One Dark. + */ + const oneDarkTheme = /*@__PURE__*/EditorView.theme({ + "&": { + color: ivory, + backgroundColor: background + }, + ".cm-content": { + caretColor: cursor + }, + ".cm-cursor, .cm-dropCursor": { borderLeftColor: cursor }, + "&.cm-focused .cm-selectionBackground, .cm-selectionBackground, .cm-content ::selection": { backgroundColor: selection }, + ".cm-panels": { backgroundColor: darkBackground, color: ivory }, + ".cm-panels.cm-panels-top": { borderBottom: "2px solid black" }, + ".cm-panels.cm-panels-bottom": { borderTop: "2px solid black" }, + ".cm-searchMatch": { + backgroundColor: "#72a1ff59", + outline: "1px solid #457dff" + }, + ".cm-searchMatch.cm-searchMatch-selected": { + backgroundColor: "#6199ff2f" + }, + ".cm-activeLine": { backgroundColor: "#6699ff0b" }, + ".cm-selectionMatch": { backgroundColor: "#aafe661a" }, + "&.cm-focused .cm-matchingBracket, &.cm-focused .cm-nonmatchingBracket": { + backgroundColor: "#bad0f847", + outline: "1px solid #515a6b" + }, + ".cm-gutters": { + backgroundColor: background, + color: stone, + border: "none" + }, + ".cm-activeLineGutter": { + backgroundColor: highlightBackground + }, + ".cm-foldPlaceholder": { + backgroundColor: "transparent", + border: "none", + color: "#ddd" + }, + ".cm-tooltip": { + border: "none", + backgroundColor: tooltipBackground + }, + ".cm-tooltip .cm-tooltip-arrow:before": { + borderTopColor: "transparent", + borderBottomColor: "transparent" + }, + ".cm-tooltip .cm-tooltip-arrow:after": { + borderTopColor: tooltipBackground, + borderBottomColor: tooltipBackground + }, + ".cm-tooltip-autocomplete": { + "& > ul > li[aria-selected]": { + backgroundColor: highlightBackground, + color: ivory + } + } + }, { dark: true }); + + const logger$5 = getLogger('py-repl'); + const RUNBUTTON = `<svg style="height:20px;width:20px;vertical-align:-.125em;transform-origin:center;overflow:visible;color:green" viewBox="0 0 384 512" aria-hidden="true" role="img" xmlns="http://www.w3.org/2000/svg"><g transform="translate(192 256)" transform-origin="96 0"><g transform="translate(0,0) scale(1,1)"><path d="M361 215C375.3 223.8 384 239.3 384 256C384 272.7 375.3 288.2 361 296.1L73.03 472.1C58.21 482 39.66 482.4 24.52 473.9C9.377 465.4 0 449.4 0 432V80C0 62.64 9.377 46.63 24.52 38.13C39.66 29.64 58.21 29.99 73.03 39.04L361 215z" fill="currentColor" transform="translate(-192 -256)"></path></g></g></svg>`; + function make_PyRepl(interpreter) { + /* High level structure of py-repl DOM, and the corresponding JS names. + + this <py-repl> + shadow #shadow-root + <slot></slot> + boxDiv <div class='py-repl-box'> + editorLabel <label>...</label> + editorDiv <div class="py-repl-editor"></div> + outDiv <div class="py-repl-output"></div> + </div> + </py-repl> + */ + class PyRepl extends HTMLElement { + constructor() { + super(); + } + connectedCallback() { + ensureUniqueId(this); + this.shadow = this.attachShadow({ mode: 'open' }); + const slot = document.createElement('slot'); + this.shadow.appendChild(slot); + if (!this.hasAttribute('exec-id')) { + this.setAttribute('exec-id', '0'); + } + if (!this.hasAttribute('root')) { + this.setAttribute('root', this.id); + } + const pySrc = htmlDecode(this.innerHTML).trim(); + this.innerHTML = ''; + this.editor = this.makeEditor(pySrc); + const boxDiv = this.makeBoxDiv(); + this.appendChild(boxDiv); + this.editor.focus(); + logger$5.debug(`element ${this.id} successfully connected`); + } + /** Create and configure the codemirror editor + */ + makeEditor(pySrc) { + const languageConf = new Compartment(); + const extensions = [ + indentUnit.of(' '), + basicSetup, + languageConf.of(python()), + keymap.of([ + ...defaultKeymap, + { key: 'Ctrl-Enter', run: this.execute.bind(this), preventDefault: true }, + { key: 'Shift-Enter', run: this.execute.bind(this), preventDefault: true }, + ]), + ]; + if (getAttribute(this, 'theme') === 'dark') { + extensions.push(oneDarkTheme); + } + return new EditorView({ + doc: pySrc, + extensions, + }); + } + // ******** main entry point for py-repl DOM building ********** + // + // The following functions are written in a top-down, depth-first + // order (so that the order of code roughly matches the order of + // execution) + makeBoxDiv() { + const boxDiv = document.createElement('div'); + boxDiv.className = 'py-repl-box'; + const editorDiv = this.makeEditorDiv(); + const editorLabel = this.makeLabel('Python Script Area', editorDiv); + this.outDiv = this.makeOutDiv(); + boxDiv.append(editorLabel); + boxDiv.appendChild(editorDiv); + boxDiv.appendChild(this.outDiv); + return boxDiv; + } + makeEditorDiv() { + const editorDiv = document.createElement('div'); + editorDiv.id = 'code-editor'; + editorDiv.className = 'py-repl-editor'; + editorDiv.appendChild(this.editor.dom); + const runButton = this.makeRunButton(); + const runLabel = this.makeLabel('Python Script Run Button', runButton); + editorDiv.appendChild(runLabel); + editorDiv.appendChild(runButton); + return editorDiv; + } + makeLabel(text, elementFor) { + ensureUniqueId(elementFor); + const lbl = document.createElement('label'); + lbl.innerHTML = text; + lbl.htmlFor = elementFor.id; + // XXX this should be a CSS class + // Styles that we use to hide the labels whilst also keeping it accessible for screen readers + const labelStyle = 'overflow:hidden; display:block; width:1px; height:1px'; + lbl.setAttribute('style', labelStyle); + return lbl; + } + makeRunButton() { + const runButton = document.createElement('button'); + runButton.id = 'runButton'; + runButton.className = 'absolute py-repl-run-button'; + runButton.innerHTML = RUNBUTTON; + runButton.addEventListener('click', this.execute.bind(this)); + return runButton; + } + makeOutDiv() { + const outDiv = document.createElement('div'); + outDiv.className = 'py-repl-output'; + outDiv.id = this.id + '-repl-output'; + return outDiv; + } + // ********************* execution logic ********************* + /** Execute the python code written in the editor, and automatically + * display() the last evaluated expression + */ + async execute() { + const pySrc = this.getPySrc(); + // determine the output element + const outEl = this.getOutputElement(); + if (outEl === undefined) { + // this happens if we specified output="..." but we couldn't + // find the ID. We already displayed an error message inside + // getOutputElement, stop the execution. + return; + } + // clear the old output before executing the new code + outEl.innerHTML = ''; + // execute the python code + const pyResult = (await pyExec(interpreter, pySrc, outEl)).result; + // display the value of the last evaluated expression (REPL-style) + if (pyResult !== undefined) { + pyDisplay(interpreter, pyResult, { target: outEl.id }); + } + this.autogenerateMaybe(); + } + getPySrc() { + return this.editor.state.doc.toString(); + } + getOutputElement() { + const outputID = getAttribute(this, 'output'); + if (outputID !== null) { + const el = document.getElementById(outputID); + if (el === null) { + const err = `py-repl ERROR: cannot find the output element #${outputID} in the DOM`; + this.outDiv.innerText = err; + return undefined; + } + return el; + } + else { + return this.outDiv; + } + } + // XXX the autogenerate logic is very messy. We should redo it, and it + // should be the default. + autogenerateMaybe() { + if (this.hasAttribute('auto-generate')) { + const allPyRepls = document.querySelectorAll(`py-repl[root='${this.getAttribute('root')}'][exec-id]`); + const lastRepl = allPyRepls[allPyRepls.length - 1]; + const lastExecId = lastRepl.getAttribute('exec-id'); + const nextExecId = parseInt(lastExecId) + 1; + const newPyRepl = document.createElement('py-repl'); + newPyRepl.setAttribute('root', this.getAttribute('root')); + newPyRepl.id = this.getAttribute('root') + '-' + nextExecId.toString(); + if (this.hasAttribute('auto-generate')) { + newPyRepl.setAttribute('auto-generate', ''); + this.removeAttribute('auto-generate'); + } + const outputMode = getAttribute(this, 'output-mode'); + if (outputMode) { + newPyRepl.setAttribute('output-mode', outputMode); + } + const addReplAttribute = (attribute) => { + const attr = getAttribute(this, attribute); + if (attr) { + newPyRepl.setAttribute(attribute, attr); + } + }; + addReplAttribute('output'); + newPyRepl.setAttribute('exec-id', nextExecId.toString()); + if (this.parentElement) { + this.parentElement.appendChild(newPyRepl); + } + } + } + } + return PyRepl; + } + + const logger$4 = getLogger('py-register-widget'); + function createWidget(interpreter, name, code, klass) { + class CustomWidget extends HTMLElement { + constructor() { + super(); + this.name = name; + this.klass = klass; + this.code = code; + // attach shadow so we can preserve the element original innerHtml content + this.shadow = this.attachShadow({ mode: 'open' }); + this.wrapper = document.createElement('slot'); + this.shadow.appendChild(this.wrapper); + } + async connectedCallback() { + await interpreter.runButDontRaise(this.code); + this.proxyClass = interpreter.globals.get(this.klass); + this.proxy = this.proxyClass(this); + this.proxy.connect(); + this.registerWidget(); + } + registerWidget() { + logger$4.info('new widget registered:', this.name); + interpreter.globals.set(this.id, this.proxy); + } + } + /* eslint-disable @typescript-eslint/no-unused-vars */ + customElements.define(name, CustomWidget); + /* eslint-enable @typescript-eslint/no-unused-vars */ + } + function make_PyWidget(interpreter) { + class PyWidget extends HTMLElement { + constructor() { + super(); + // attach shadow so we can preserve the element original innerHtml content + this.shadow = this.attachShadow({ mode: 'open' }); + this.wrapper = document.createElement('slot'); + this.shadow.appendChild(this.wrapper); + this.addAttributes('src', 'name', 'klass'); + } + addAttributes(...attrs) { + for (const each of attrs) { + const property = each === 'src' ? 'source' : each; + if (this.hasAttribute(each)) { + this[property] = this.getAttribute(each); + } + } + } + async connectedCallback() { + if (this.id === undefined) { + throw new ReferenceError(`No id specified for component. Components must have an explicit id. Please use id="" to specify your component id.`); + } + const mainDiv = document.createElement('div'); + mainDiv.id = this.id + '-main'; + this.appendChild(mainDiv); + logger$4.debug('PyWidget: reading source', this.source); + this.code = await this.getSourceFromFile(this.source); + createWidget(interpreter, this.name, this.code, this.klass); + } + async getSourceFromFile(s) { + const response = await robustFetch(s); + return await response.text(); + } + } + return PyWidget; + } + + function createCustomElements(interpreter) { + const PyWidget = make_PyWidget(interpreter); + const PyRepl = make_PyRepl(interpreter); + /* eslint-disable @typescript-eslint/no-unused-vars */ + customElements.define('py-repl', PyRepl); + customElements.define('py-register-widget', PyWidget); + /* eslint-enable @typescript-eslint/no-unused-vars */ + } + + /** Default implementation of Stdio: stdout and stderr are both sent to the + * console + */ + const DEFAULT_STDIO = { + stdout_writeline: console.log, + stderr_writeline: console.log, + }; + /** Stdio provider for sending output to DOM element + * specified by ID. Used with "output" keyword. + * + */ + class TargetedStdio { + constructor(source_element, source_attribute, capture_stdout = true, capture_stderr = true) { + this.source_element = source_element; + this.source_attribute = source_attribute; + this.capture_stdout = capture_stdout; + this.capture_stderr = capture_stderr; + } + /** Writes the given msg to an element with a given ID. The ID is the value an attribute + * of the source_element specified by source_attribute. + * Both the element to be targeted and the ID of the element to write to + * are determined at write-time, not when the TargetdStdio object is + * created. This way, if either the 'output' attribute of the HTML tag + * or the ID of the target element changes during execution of the Python + * code, the output is still routed (or not) as expected + * + * @param msg The output to be written + */ + writeline_by_attribute(msg) { + const target_id = this.source_element.getAttribute(this.source_attribute); + const target = document.getElementById(target_id); + if (target === null) { + // No matching ID + createSingularWarning(`${this.source_attribute} = "${target_id}" does not match the id of any element on the page.`); + } + else { + msg = escape(msg).replace('\n', '<br>'); + if (!msg.endsWith('<br/>') && !msg.endsWith('<br>')) { + msg = msg + '<br>'; + } + target.innerHTML += msg; + } + } + stdout_writeline(msg) { + if (this.capture_stdout) { + this.writeline_by_attribute(msg); + } + } + stderr_writeline(msg) { + if (this.capture_stderr) { + this.writeline_by_attribute(msg); + } + } + } + /** Redirect stdio streams to multiple listeners + */ + class StdioMultiplexer { + constructor() { + this._listeners = []; + } + addListener(obj) { + this._listeners.push(obj); + } + removeListener(obj) { + const index = this._listeners.indexOf(obj); + if (index > -1) { + this._listeners.splice(index, 1); + } + } + stdout_writeline(msg) { + for (const obj of this._listeners) + obj.stdout_writeline(msg); + } + stderr_writeline(msg) { + for (const obj of this._listeners) + obj.stderr_writeline(msg); + } + } + + const logger$3 = getLogger('py-terminal'); + class PyTerminalPlugin extends Plugin { + constructor(app) { + super(); + this.app = app; + } + configure(config) { + // validate the terminal config and handle default values + const t = config.terminal; + if (t !== undefined && t !== true && t !== false && t !== 'auto') { + const got = JSON.stringify(t); + throw new UserError(ErrorCode.BAD_CONFIG, 'Invalid value for config.terminal: the only accepted' + + `values are true, false and "auto", got "${got}".`); + } + if (t === undefined) { + config.terminal = 'auto'; // default value + } + } + beforeLaunch(config) { + // if config.terminal is "yes" or "auto", let's add a <py-terminal> to + // the document, unless it's already present. + const t = config.terminal; + if (t === true || t === 'auto') { + if (document.querySelector('py-terminal') === null) { + logger$3.info('No <py-terminal> found, adding one'); + const termElem = document.createElement('py-terminal'); + if (t === 'auto') + termElem.setAttribute('auto', ''); + document.body.appendChild(termElem); + } + } + } + afterSetup(interpreter) { + // the Python interpreter has been initialized and we are ready to + // execute user code: + // + // 1. define the "py-terminal" custom element + // + // 2. if there is a <py-terminal> tag on the page, it will register + // a Stdio listener just before the user code executes, ensuring + // that we capture all the output + // + // 3. everything which was written to stdout BEFORE this moment will + // NOT be shown on the py-terminal; in particular, pyodide + // startup messages will not be shown (but they will go to the + // console as usual). This is by design, else we would display + // e.g. "Python initialization complete" on every page, which we + // don't want. + // + // 4. (in the future we might want to add an option to start the + // capture earlier, but I don't think it's important now). + const PyTerminal = make_PyTerminal(this.app); + customElements.define('py-terminal', PyTerminal); + } + } + function make_PyTerminal(app) { + /** The <py-terminal> custom element, which automatically register a stdio + * listener to capture and display stdout/stderr + */ + class PyTerminal extends HTMLElement { + connectedCallback() { + // should we use a shadowRoot instead? It looks unnecessarily + // complicated to me, but I'm not really sure about the + // implications + this.outElem = document.createElement('pre'); + this.outElem.className = 'py-terminal'; + this.appendChild(this.outElem); + if (this.isAuto()) { + this.classList.add('py-terminal-hidden'); + this.autoShowOnNextLine = true; + } + else { + this.autoShowOnNextLine = false; + } + logger$3.info('Registering stdio listener'); + app.registerStdioListener(this); + } + isAuto() { + return this.hasAttribute('auto'); + } + // implementation of the Stdio interface + stdout_writeline(msg) { + this.outElem.innerText += msg + '\n'; + if (this.autoShowOnNextLine) { + this.classList.remove('py-terminal-hidden'); + this.autoShowOnNextLine = false; + } + } + stderr_writeline(msg) { + this.stdout_writeline(msg); + } + } + return PyTerminal; + } + + const logger$2 = getLogger('py-splashscreen'); + const AUTOCLOSE_LOADER_DEPRECATED = ` +The setting autoclose_loader is deprecated. Please use the +following instead:<br> +<pre> +<py-config> +[splashscreen] +autoclose = false +</py-config> +</pre>`; + class SplashscreenPlugin extends Plugin { + configure(config) { + // the officially supported setting is config.splashscreen.autoclose, + // but we still also support the old config.autoclose_loader (with a + // deprecation warning) + this.autoclose = true; + this.enabled = true; + if ('autoclose_loader' in config) { + this.autoclose = config.autoclose_loader; + showWarning(AUTOCLOSE_LOADER_DEPRECATED, 'html'); + } + if (config.splashscreen) { + this.autoclose = config.splashscreen.autoclose ?? true; + this.enabled = config.splashscreen.enabled ?? true; + } + } + beforeLaunch(config) { + if (!this.enabled) { + return; + } + // add the splashscreen to the DOM + logger$2.info('add py-splashscreen'); + customElements.define('py-splashscreen', PySplashscreen); + this.elem = document.createElement('py-splashscreen'); + document.body.append(this.elem); + document.addEventListener('py-status-message', (e) => { + const msg = e.detail; + this.elem.log(msg); + }); + } + afterStartup(interpreter) { + if (this.autoclose && this.enabled) { + this.elem.close(); + } + } + onUserError(error) { + if (this.elem !== undefined && this.enabled) { + // Remove the splashscreen so users can see the banner better + this.elem.close(); + } + } + } + class PySplashscreen extends HTMLElement { + constructor() { + super(); + } + connectedCallback() { + this.innerHTML = `<div id="pyscript_loading_splash" class="py-overlay"> <div class="py-pop-up"> <div class="smooth spinner"></div> <div id="pyscript-loading-label" class="label"> @@ -4170,23687 +28474,434 @@ </div> </div> </div>`; - this.mount_name = this.id.split('-').join('_'); - this.operation = document.getElementById('pyscript-operation'); - this.details = document.getElementById('pyscript-operation-details'); - } - log(msg) { - // loader messages are showed both in the HTML and in the console - logger$8.info(msg); - const newLog = document.createElement('p'); - newLog.innerText = msg; - this.details.appendChild(newLog); - } - close() { - logger$8.info('Closing'); - this.remove(); - } - } + this.mount_name = this.id.split('-').join('_'); + this.operation = document.getElementById('pyscript-operation'); + this.details = document.getElementById('pyscript-operation-details'); + } + log(msg) { + const newLog = document.createElement('p'); + newLog.innerText = msg; + this.details.appendChild(newLog); + } + close() { + logger$2.info('Closing'); + this.remove(); + } + } - // Compressed representation of the Grapheme_Cluster_Break=Extend - // information from - // http://www.unicode.org/Public/13.0.0/ucd/auxiliary/GraphemeBreakProperty.txt. - // Each pair of elements represents a range, as an offet from the - // previous range and a length. Numbers are in base-36, with the empty - // string being a shorthand for 1. - let extend = /*@__PURE__*/"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(s => s ? parseInt(s, 36) : 1); - // Convert offsets into absolute values - for (let i = 1; i < extend.length; i++) - extend[i] += extend[i - 1]; - function isExtendingChar(code) { - for (let i = 1; i < extend.length; i += 2) - if (extend[i] > code) - return extend[i - 1] <= code; - return false; - } - function isRegionalIndicator(code) { - return code >= 0x1F1E6 && code <= 0x1F1FF; - } - const ZWJ = 0x200d; - /** - Returns a next grapheme cluster break _after_ (not equal to) - `pos`, if `forward` is true, or before otherwise. Returns `pos` - itself if no further cluster break is available in the string. - Moves across surrogate pairs, extending characters (when - `includeExtending` is true), characters joined with zero-width - joiners, and flag emoji. - */ - function findClusterBreak(str, pos, forward = true, includeExtending = true) { - return (forward ? nextClusterBreak : prevClusterBreak)(str, pos, includeExtending); - } - function nextClusterBreak(str, pos, includeExtending) { - if (pos == str.length) - return pos; - // If pos is in the middle of a surrogate pair, move to its start - if (pos && surrogateLow(str.charCodeAt(pos)) && surrogateHigh(str.charCodeAt(pos - 1))) - pos--; - let prev = codePointAt(str, pos); - pos += codePointSize(prev); - while (pos < str.length) { - let next = codePointAt(str, pos); - if (prev == ZWJ || next == ZWJ || includeExtending && isExtendingChar(next)) { - pos += codePointSize(next); - prev = next; - } - else if (isRegionalIndicator(next)) { - let countBefore = 0, i = pos - 2; - while (i >= 0 && isRegionalIndicator(codePointAt(str, i))) { - countBefore++; - i -= 2; - } - if (countBefore % 2 == 0) - break; - else - pos += 2; - } - else { - break; - } - } - return pos; - } - function prevClusterBreak(str, pos, includeExtending) { - while (pos > 0) { - let found = nextClusterBreak(str, pos - 2, includeExtending); - if (found < pos) - return found; - pos--; - } - return 0; - } - function surrogateLow(ch) { return ch >= 0xDC00 && ch < 0xE000; } - function surrogateHigh(ch) { return ch >= 0xD800 && ch < 0xDC00; } - /** - Find the code point at the given position in a string (like the - [`codePointAt`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/codePointAt) - string method). - */ - function codePointAt(str, pos) { - let code0 = str.charCodeAt(pos); - if (!surrogateHigh(code0) || pos + 1 == str.length) - return code0; - let code1 = str.charCodeAt(pos + 1); - if (!surrogateLow(code1)) - return code0; - return ((code0 - 0xd800) << 10) + (code1 - 0xdc00) + 0x10000; - } - /** - Given a Unicode codepoint, return the JavaScript string that - respresents it (like - [`String.fromCodePoint`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/fromCodePoint)). - */ - function fromCodePoint(code) { - if (code <= 0xffff) - return String.fromCharCode(code); - code -= 0x10000; - return String.fromCharCode((code >> 10) + 0xd800, (code & 1023) + 0xdc00); - } - /** - The first character that takes up two positions in a JavaScript - string. It is often useful to compare with this after calling - `codePointAt`, to figure out whether your character takes up 1 or - 2 index positions. - */ - function codePointSize(code) { return code < 0x10000 ? 1 : 2; } + const logger$1 = getLogger('plugins/importmap'); + class ImportmapPlugin extends Plugin { + async afterSetup(interpreter) { + // make importmap ES modules available from python using 'import'. + // + // XXX: this code can probably be improved because errors are silently + // ignored. + // + // Moreover, it's also wrong because it's async and currently we don't + // await the module to be fully registered before executing the code + // inside py-script. It's also unclear whether we want to wait or not + // (or maybe only wait only if we do an actual 'import'?) + for (const node of document.querySelectorAll("script[type='importmap']")) { + const importmap = (() => { + try { + return JSON.parse(node.textContent); + } + catch (error) { + showWarning('Failed to parse import map: ' + error.message); + } + })(); + if (importmap?.imports == null) + continue; + for (const [name, url] of Object.entries(importmap.imports)) { + if (typeof name != 'string' || typeof url != 'string') + continue; + let exports; + try { + // XXX: pyodide doesn't like Module(), failing with + // "can't read 'name' of undefined" at import time + exports = { ...(await import(url)) }; + } + catch { + logger$1.warn(`failed to fetch '${url}' for '${name}'`); + continue; + } + logger$1.info('Registering JS module', name); + interpreter._remote.registerJsModule(name, exports); + } + } + } + } - /** - Count the column position at the given offset into the string, - taking extending characters and tab size into account. - */ - function countColumn(string, tabSize, to = string.length) { - let n = 0; - for (let i = 0; i < to;) { - if (string.charCodeAt(i) == 9) { - n += tabSize - (n % tabSize); - i++; - } - else { - n++; - i = findClusterBreak(string, i); - } - } - return n; - } - /** - Find the offset that corresponds to the given column position in a - string, taking extending characters and tab size into account. By - default, the string length is returned when it is too short to - reach the column. Pass `strict` true to make it return -1 in that - situation. - */ - function findColumn(string, col, tabSize, strict) { - for (let i = 0, n = 0;;) { - if (n >= col) - return i; - if (i == string.length) - break; - n += string.charCodeAt(i) == 9 ? tabSize - (n % tabSize) : 1; - i = findClusterBreak(string, i); - } - return strict === true ? -1 : string.length; - } + /** + * The StdioDirector plugin captures the output to Python's sys.stdio and + * sys.stderr and writes it to a specific element in the DOM. It does this by + * creating a new TargetedStdio manager and adding it to the global stdioMultiplexer's + * list of listeners prior to executing the Python in a specific tag. Following + * execution of the Python in that tag, it removes the TargetedStdio as a listener + * + */ + class StdioDirector extends Plugin { + constructor(stdio) { + super(); + this._stdioMultiplexer = stdio; + } + /** Prior to a <py-script> tag being evaluated, if that tag itself has + * an 'output' attribute, a new TargetedStdio object is created and added + * to the stdioMultiplexer to route sys.stdout and sys.stdout to the DOM object + * with that ID for the duration of the evaluation. + * + */ + beforePyScriptExec(options) { + if (options.pyScriptTag.hasAttribute('output')) { + const targeted_io = new TargetedStdio(options.pyScriptTag, 'output', true, true); + options.pyScriptTag.stdout_manager = targeted_io; + this._stdioMultiplexer.addListener(targeted_io); + } + if (options.pyScriptTag.hasAttribute('stderr')) { + const targeted_io = new TargetedStdio(options.pyScriptTag, 'stderr', false, true); + options.pyScriptTag.stderr_manager = targeted_io; + this._stdioMultiplexer.addListener(targeted_io); + } + } + /** After a <py-script> tag is evaluated, if that tag has a 'stdout_manager' + * (presumably TargetedStdio, or some other future IO handler), it is removed. + */ + afterPyScriptExec(options) { + if (options.pyScriptTag.stdout_manager != null) { + this._stdioMultiplexer.removeListener(options.pyScriptTag.stdout_manager); + options.pyScriptTag.stdout_manager = null; + } + if (options.pyScriptTag.stderr_manager != null) { + this._stdioMultiplexer.removeListener(options.pyScriptTag.stderr_manager); + options.pyScriptTag.stderr_manager = null; + } + } + } - /** - The data structure for documents. - */ - class Text { - /** - @internal - */ - constructor() { } - /** - Get the line description around the given position. - */ - lineAt(pos) { - if (pos < 0 || pos > this.length) - throw new RangeError(`Invalid position ${pos} in document of length ${this.length}`); - return this.lineInner(pos, false, 1, 0); - } - /** - Get the description for the given (1-based) line number. - */ - line(n) { - if (n < 1 || n > this.lines) - throw new RangeError(`Invalid line number ${n} in ${this.lines}-line document`); - return this.lineInner(n, true, 1, 0); - } - /** - Replace a range of the text with the given content. - */ - replace(from, to, text) { - let parts = []; - this.decompose(0, from, parts, 2 /* To */); - if (text.length) - text.decompose(0, text.length, parts, 1 /* From */ | 2 /* To */); - this.decompose(to, this.length, parts, 1 /* From */); - return TextNode.from(parts, this.length - (to - from) + text.length); - } - /** - Append another document to this one. - */ - append(other) { - return this.replace(this.length, this.length, other); - } - /** - Retrieve the text between the given points. - */ - slice(from, to = this.length) { - let parts = []; - this.decompose(from, to, parts, 0); - return TextNode.from(parts, to - from); - } - /** - Test whether this text is equal to another instance. - */ - eq(other) { - if (other == this) - return true; - if (other.length != this.length || other.lines != this.lines) - return false; - let start = this.scanIdentical(other, 1), end = this.length - this.scanIdentical(other, -1); - let a = new RawTextCursor(this), b = new RawTextCursor(other); - for (let skip = start, pos = start;;) { - a.next(skip); - b.next(skip); - skip = 0; - if (a.lineBreak != b.lineBreak || a.done != b.done || a.value != b.value) - return false; - pos += a.value.length; - if (a.done || pos >= end) - return true; - } - } - /** - Iterate over the text. When `dir` is `-1`, iteration happens - from end to start. This will return lines and the breaks between - them as separate strings, and for long lines, might split lines - themselves into multiple chunks as well. - */ - iter(dir = 1) { return new RawTextCursor(this, dir); } - /** - Iterate over a range of the text. When `from` > `to`, the - iterator will run in reverse. - */ - iterRange(from, to = this.length) { return new PartialTextCursor(this, from, to); } - /** - Return a cursor that iterates over the given range of lines, - _without_ returning the line breaks between, and yielding empty - strings for empty lines. - - When `from` and `to` are given, they should be 1-based line numbers. - */ - iterLines(from, to) { - let inner; - if (from == null) { - inner = this.iter(); - } - else { - if (to == null) - to = this.lines + 1; - let start = this.line(from).from; - inner = this.iterRange(start, Math.max(start, to == this.lines + 1 ? this.length : to <= 1 ? 0 : this.line(to - 1).to)); - } - return new LineCursor(inner); - } - /** - @internal - */ - toString() { return this.sliceString(0); } - /** - Convert the document to an array of lines (which can be - deserialized again via [`Text.of`](https://codemirror.net/6/docs/ref/#text.Text^of)). - */ - toJSON() { - let lines = []; - this.flatten(lines); - return lines; - } - /** - Create a `Text` instance for the given array of lines. - */ - static of(text) { - if (text.length == 0) - throw new RangeError("A document must have at least one line"); - if (text.length == 1 && !text[0]) - return Text.empty; - return text.length <= 32 /* Branch */ ? new TextLeaf(text) : TextNode.from(TextLeaf.split(text, [])); - } - } - // Leaves store an array of line strings. There are always line breaks - // between these strings. Leaves are limited in size and have to be - // contained in TextNode instances for bigger documents. - class TextLeaf extends Text { - constructor(text, length = textLength(text)) { - super(); - this.text = text; - this.length = length; - } - get lines() { return this.text.length; } - get children() { return null; } - lineInner(target, isLine, line, offset) { - for (let i = 0;; i++) { - let string = this.text[i], end = offset + string.length; - if ((isLine ? line : end) >= target) - return new Line(offset, end, line, string); - offset = end + 1; - line++; - } - } - decompose(from, to, target, open) { - let text = from <= 0 && to >= this.length ? this - : new TextLeaf(sliceText(this.text, from, to), Math.min(to, this.length) - Math.max(0, from)); - if (open & 1 /* From */) { - let prev = target.pop(); - let joined = appendText(text.text, prev.text.slice(), 0, text.length); - if (joined.length <= 32 /* Branch */) { - target.push(new TextLeaf(joined, prev.length + text.length)); - } - else { - let mid = joined.length >> 1; - target.push(new TextLeaf(joined.slice(0, mid)), new TextLeaf(joined.slice(mid))); - } - } - else { - target.push(text); - } - } - replace(from, to, text) { - if (!(text instanceof TextLeaf)) - return super.replace(from, to, text); - let lines = appendText(this.text, appendText(text.text, sliceText(this.text, 0, from)), to); - let newLen = this.length + text.length - (to - from); - if (lines.length <= 32 /* Branch */) - return new TextLeaf(lines, newLen); - return TextNode.from(TextLeaf.split(lines, []), newLen); - } - sliceString(from, to = this.length, lineSep = "\n") { - let result = ""; - for (let pos = 0, i = 0; pos <= to && i < this.text.length; i++) { - let line = this.text[i], end = pos + line.length; - if (pos > from && i) - result += lineSep; - if (from < end && to > pos) - result += line.slice(Math.max(0, from - pos), to - pos); - pos = end + 1; - } - return result; - } - flatten(target) { - for (let line of this.text) - target.push(line); - } - scanIdentical() { return 0; } - static split(text, target) { - let part = [], len = -1; - for (let line of text) { - part.push(line); - len += line.length + 1; - if (part.length == 32 /* Branch */) { - target.push(new TextLeaf(part, len)); - part = []; - len = -1; - } - } - if (len > -1) - target.push(new TextLeaf(part, len)); - return target; - } - } - // Nodes provide the tree structure of the `Text` type. They store a - // number of other nodes or leaves, taking care to balance themselves - // on changes. There are implied line breaks _between_ the children of - // a node (but not before the first or after the last child). - class TextNode extends Text { - constructor(children, length) { - super(); - this.children = children; - this.length = length; - this.lines = 0; - for (let child of children) - this.lines += child.lines; - } - lineInner(target, isLine, line, offset) { - for (let i = 0;; i++) { - let child = this.children[i], end = offset + child.length, endLine = line + child.lines - 1; - if ((isLine ? endLine : end) >= target) - return child.lineInner(target, isLine, line, offset); - offset = end + 1; - line = endLine + 1; - } - } - decompose(from, to, target, open) { - for (let i = 0, pos = 0; pos <= to && i < this.children.length; i++) { - let child = this.children[i], end = pos + child.length; - if (from <= end && to >= pos) { - let childOpen = open & ((pos <= from ? 1 /* From */ : 0) | (end >= to ? 2 /* To */ : 0)); - if (pos >= from && end <= to && !childOpen) - target.push(child); - else - child.decompose(from - pos, to - pos, target, childOpen); - } - pos = end + 1; - } - } - replace(from, to, text) { - if (text.lines < this.lines) - for (let i = 0, pos = 0; i < this.children.length; i++) { - let child = this.children[i], end = pos + child.length; - // Fast path: if the change only affects one child and the - // child's size remains in the acceptable range, only update - // that child - if (from >= pos && to <= end) { - let updated = child.replace(from - pos, to - pos, text); - let totalLines = this.lines - child.lines + updated.lines; - if (updated.lines < (totalLines >> (5 /* BranchShift */ - 1)) && - updated.lines > (totalLines >> (5 /* BranchShift */ + 1))) { - let copy = this.children.slice(); - copy[i] = updated; - return new TextNode(copy, this.length - (to - from) + text.length); - } - return super.replace(pos, end, updated); - } - pos = end + 1; - } - return super.replace(from, to, text); - } - sliceString(from, to = this.length, lineSep = "\n") { - let result = ""; - for (let i = 0, pos = 0; i < this.children.length && pos <= to; i++) { - let child = this.children[i], end = pos + child.length; - if (pos > from && i) - result += lineSep; - if (from < end && to > pos) - result += child.sliceString(from - pos, to - pos, lineSep); - pos = end + 1; - } - return result; - } - flatten(target) { - for (let child of this.children) - child.flatten(target); - } - scanIdentical(other, dir) { - if (!(other instanceof TextNode)) - return 0; - let length = 0; - let [iA, iB, eA, eB] = dir > 0 ? [0, 0, this.children.length, other.children.length] - : [this.children.length - 1, other.children.length - 1, -1, -1]; - for (;; iA += dir, iB += dir) { - if (iA == eA || iB == eB) - return length; - let chA = this.children[iA], chB = other.children[iB]; - if (chA != chB) - return length + chA.scanIdentical(chB, dir); - length += chA.length + 1; - } - } - static from(children, length = children.reduce((l, ch) => l + ch.length + 1, -1)) { - let lines = 0; - for (let ch of children) - lines += ch.lines; - if (lines < 32 /* Branch */) { - let flat = []; - for (let ch of children) - ch.flatten(flat); - return new TextLeaf(flat, length); - } - let chunk = Math.max(32 /* Branch */, lines >> 5 /* BranchShift */), maxChunk = chunk << 1, minChunk = chunk >> 1; - let chunked = [], currentLines = 0, currentLen = -1, currentChunk = []; - function add(child) { - let last; - if (child.lines > maxChunk && child instanceof TextNode) { - for (let node of child.children) - add(node); - } - else if (child.lines > minChunk && (currentLines > minChunk || !currentLines)) { - flush(); - chunked.push(child); - } - else if (child instanceof TextLeaf && currentLines && - (last = currentChunk[currentChunk.length - 1]) instanceof TextLeaf && - child.lines + last.lines <= 32 /* Branch */) { - currentLines += child.lines; - currentLen += child.length + 1; - currentChunk[currentChunk.length - 1] = new TextLeaf(last.text.concat(child.text), last.length + 1 + child.length); - } - else { - if (currentLines + child.lines > chunk) - flush(); - currentLines += child.lines; - currentLen += child.length + 1; - currentChunk.push(child); - } - } - function flush() { - if (currentLines == 0) - return; - chunked.push(currentChunk.length == 1 ? currentChunk[0] : TextNode.from(currentChunk, currentLen)); - currentLen = -1; - currentLines = currentChunk.length = 0; - } - for (let child of children) - add(child); - flush(); - return chunked.length == 1 ? chunked[0] : new TextNode(chunked, length); - } - } - Text.empty = /*@__PURE__*/new TextLeaf([""], 0); - function textLength(text) { - let length = -1; - for (let line of text) - length += line.length + 1; - return length; - } - function appendText(text, target, from = 0, to = 1e9) { - for (let pos = 0, i = 0, first = true; i < text.length && pos <= to; i++) { - let line = text[i], end = pos + line.length; - if (end >= from) { - if (end > to) - line = line.slice(0, to - pos); - if (pos < from) - line = line.slice(from - pos); - if (first) { - target[target.length - 1] += line; - first = false; - } - else - target.push(line); - } - pos = end + 1; - } - return target; - } - function sliceText(text, from, to) { - return appendText(text, [""], from, to); - } - class RawTextCursor { - constructor(text, dir = 1) { - this.dir = dir; - this.done = false; - this.lineBreak = false; - this.value = ""; - this.nodes = [text]; - this.offsets = [dir > 0 ? 1 : (text instanceof TextLeaf ? text.text.length : text.children.length) << 1]; - } - nextInner(skip, dir) { - this.done = this.lineBreak = false; - for (;;) { - let last = this.nodes.length - 1; - let top = this.nodes[last], offsetValue = this.offsets[last], offset = offsetValue >> 1; - let size = top instanceof TextLeaf ? top.text.length : top.children.length; - if (offset == (dir > 0 ? size : 0)) { - if (last == 0) { - this.done = true; - this.value = ""; - return this; - } - if (dir > 0) - this.offsets[last - 1]++; - this.nodes.pop(); - this.offsets.pop(); - } - else if ((offsetValue & 1) == (dir > 0 ? 0 : 1)) { - this.offsets[last] += dir; - if (skip == 0) { - this.lineBreak = true; - this.value = "\n"; - return this; - } - skip--; - } - else if (top instanceof TextLeaf) { - // Move to the next string - let next = top.text[offset + (dir < 0 ? -1 : 0)]; - this.offsets[last] += dir; - if (next.length > Math.max(0, skip)) { - this.value = skip == 0 ? next : dir > 0 ? next.slice(skip) : next.slice(0, next.length - skip); - return this; - } - skip -= next.length; - } - else { - let next = top.children[offset + (dir < 0 ? -1 : 0)]; - if (skip > next.length) { - skip -= next.length; - this.offsets[last] += dir; - } - else { - if (dir < 0) - this.offsets[last]--; - this.nodes.push(next); - this.offsets.push(dir > 0 ? 1 : (next instanceof TextLeaf ? next.text.length : next.children.length) << 1); - } - } - } - } - next(skip = 0) { - if (skip < 0) { - this.nextInner(-skip, (-this.dir)); - skip = this.value.length; - } - return this.nextInner(skip, this.dir); - } - } - class PartialTextCursor { - constructor(text, start, end) { - this.value = ""; - this.done = false; - this.cursor = new RawTextCursor(text, start > end ? -1 : 1); - this.pos = start > end ? text.length : 0; - this.from = Math.min(start, end); - this.to = Math.max(start, end); - } - nextInner(skip, dir) { - if (dir < 0 ? this.pos <= this.from : this.pos >= this.to) { - this.value = ""; - this.done = true; - return this; - } - skip += Math.max(0, dir < 0 ? this.pos - this.to : this.from - this.pos); - let limit = dir < 0 ? this.pos - this.from : this.to - this.pos; - if (skip > limit) - skip = limit; - limit -= skip; - let { value } = this.cursor.next(skip); - this.pos += (value.length + skip) * dir; - this.value = value.length <= limit ? value : dir < 0 ? value.slice(value.length - limit) : value.slice(0, limit); - this.done = !this.value; - return this; - } - next(skip = 0) { - if (skip < 0) - skip = Math.max(skip, this.from - this.pos); - else if (skip > 0) - skip = Math.min(skip, this.to - this.pos); - return this.nextInner(skip, this.cursor.dir); - } - get lineBreak() { return this.cursor.lineBreak && this.value != ""; } - } - class LineCursor { - constructor(inner) { - this.inner = inner; - this.afterBreak = true; - this.value = ""; - this.done = false; - } - next(skip = 0) { - let { done, lineBreak, value } = this.inner.next(skip); - if (done) { - this.done = true; - this.value = ""; - } - else if (lineBreak) { - if (this.afterBreak) { - this.value = ""; - } - else { - this.afterBreak = true; - this.next(); - } - } - else { - this.value = value; - this.afterBreak = false; - } - return this; - } - get lineBreak() { return false; } - } - if (typeof Symbol != "undefined") { - Text.prototype[Symbol.iterator] = function () { return this.iter(); }; - RawTextCursor.prototype[Symbol.iterator] = PartialTextCursor.prototype[Symbol.iterator] = - LineCursor.prototype[Symbol.iterator] = function () { return this; }; - } - /** - This type describes a line in the document. It is created - on-demand when lines are [queried](https://codemirror.net/6/docs/ref/#text.Text.lineAt). - */ - class Line { - /** - @internal - */ - constructor( - /** - The position of the start of the line. - */ - from, - /** - The position at the end of the line (_before_ the line break, - or at the end of document for the last line). - */ - to, - /** - This line's line number (1-based). - */ - number, - /** - The line's content. - */ - text) { - this.from = from; - this.to = to; - this.number = number; - this.text = text; - } - /** - The length of the line (not including any line break after it). - */ - get length() { return this.to - this.from; } - } + var pyscript = "import ast\nimport asyncio\nimport base64\nimport html\nimport io\nimport re\nimport time\nfrom collections import namedtuple\nfrom textwrap import dedent\n\nimport js\n\ntry:\n from pyodide.ffi import create_proxy\nexcept ImportError:\n from pyodide import create_proxy\n\nloop = asyncio.get_event_loop()\n\nMIME_METHODS = {\n \"__repr__\": \"text/plain\",\n \"_repr_html_\": \"text/html\",\n \"_repr_markdown_\": \"text/markdown\",\n \"_repr_svg_\": \"image/svg+xml\",\n \"_repr_png_\": \"image/png\",\n \"_repr_pdf_\": \"application/pdf\",\n \"_repr_jpeg_\": \"image/jpeg\",\n \"_repr_latex\": \"text/latex\",\n \"_repr_json_\": \"application/json\",\n \"_repr_javascript_\": \"application/javascript\",\n \"savefig\": \"image/png\",\n}\n\n\ndef render_image(mime, value, meta):\n # If the image value is using bytes we should convert it to base64\n # otherwise it will return raw bytes and the browser will not be able to\n # render it.\n if isinstance(value, bytes):\n value = base64.b64encode(value).decode(\"utf-8\")\n\n # This is the pattern of base64 strings\n base64_pattern = re.compile(\n r\"^([A-Za-z0-9+/]{4})*([A-Za-z0-9+/]{3}=|[A-Za-z0-9+/]{2}==)?$\"\n )\n # If value doesn't match the base64 pattern we should encode it to base64\n if len(value) > 0 and not base64_pattern.match(value):\n value = base64.b64encode(value.encode(\"utf-8\")).decode(\"utf-8\")\n\n data = f\"data:{mime};charset=utf-8;base64,{value}\"\n attrs = \" \".join(['{k}=\"{v}\"' for k, v in meta.items()])\n return f'<img src=\"{data}\" {attrs}></img>'\n\n\ndef identity(value, meta):\n return value\n\n\nMIME_RENDERERS = {\n \"text/plain\": html.escape,\n \"text/html\": identity,\n \"image/png\": lambda value, meta: render_image(\"image/png\", value, meta),\n \"image/jpeg\": lambda value, meta: render_image(\"image/jpeg\", value, meta),\n \"image/svg+xml\": identity,\n \"application/json\": identity,\n \"application/javascript\": lambda value, meta: f\"<script>{value}</script>\",\n}\n\n\n# these are set by _set_version_info\n__version__ = None\nversion_info = None\n\n\ndef _set_version_info(version_from_interpreter: str):\n \"\"\"Sets the __version__ and version_info properties from provided JSON data\n Args:\n version_from_interpreter (str): A \"dotted\" representation of the version:\n YYYY.MM.m(m).releaselevel\n Year, Month, and Minor should be integers; releaselevel can be any string\n \"\"\"\n global __version__\n global version_info\n\n __version__ = version_from_interpreter\n\n version_parts = version_from_interpreter.split(\".\")\n year = int(version_parts[0])\n month = int(version_parts[1])\n minor = int(version_parts[2])\n if len(version_parts) > 3:\n releaselevel = version_parts[3]\n else:\n releaselevel = \"\"\n\n VersionInfo = namedtuple(\"version_info\", (\"year\", \"month\", \"minor\", \"releaselevel\"))\n version_info = VersionInfo(year, month, minor, releaselevel)\n\n # we ALSO set PyScript.__version__ and version_info for backwards\n # compatibility. Should be killed eventually.\n PyScript.__version__ = __version__\n PyScript.version_info = version_info\n\n\nclass HTML:\n \"\"\"\n Wrap a string so that display() can render it as plain HTML\n \"\"\"\n\n def __init__(self, html):\n self._html = html\n\n def _repr_html_(self):\n return self._html\n\n\ndef eval_formatter(obj, print_method):\n \"\"\"\n Evaluates a formatter method.\n \"\"\"\n if print_method == \"__repr__\":\n return repr(obj)\n elif hasattr(obj, print_method):\n if print_method == \"savefig\":\n buf = io.BytesIO()\n obj.savefig(buf, format=\"png\")\n buf.seek(0)\n return base64.b64encode(buf.read()).decode(\"utf-8\")\n return getattr(obj, print_method)()\n elif print_method == \"_repr_mimebundle_\":\n return {}, {}\n return None\n\n\ndef format_mime(obj):\n \"\"\"\n Formats object using _repr_x_ methods.\n \"\"\"\n if isinstance(obj, str):\n return html.escape(obj), \"text/plain\"\n\n mimebundle = eval_formatter(obj, \"_repr_mimebundle_\")\n if isinstance(mimebundle, tuple):\n format_dict, _ = mimebundle\n else:\n format_dict = mimebundle\n\n output, not_available = None, []\n for method, mime_type in reversed(MIME_METHODS.items()):\n if mime_type in format_dict:\n output = format_dict[mime_type]\n else:\n output = eval_formatter(obj, method)\n\n if output is None:\n continue\n elif mime_type not in MIME_RENDERERS:\n not_available.append(mime_type)\n continue\n break\n if output is None:\n if not_available:\n js.console.warn(\n f\"Rendered object requested unavailable MIME renderers: {not_available}\"\n )\n output = repr(output)\n mime_type = \"text/plain\"\n elif isinstance(output, tuple):\n output, meta = output\n else:\n meta = {}\n return MIME_RENDERERS[mime_type](output, meta), mime_type\n\n\ndef run_until_complete(f):\n _ = loop.run_until_complete(f)\n\n\ndef write(element_id, value, append=False, exec_id=0):\n \"\"\"Writes value to the element with id \"element_id\"\"\"\n Element(element_id).write(value=value, append=append)\n js.console.warn(\n dedent(\n \"\"\"PyScript Deprecation Warning: PyScript.write is\n marked as deprecated and will be removed sometime soon. Please, use\n Element(<id>).write instead.\"\"\"\n )\n )\n\n\ndef set_current_display_target(target_id):\n get_current_display_target._id = target_id\n\n\ndef get_current_display_target():\n return get_current_display_target._id\n\n\nget_current_display_target._id = None\n\n\ndef display(*values, target=None, append=True):\n default_target = get_current_display_target()\n if default_target is None and target is None:\n raise Exception(\n \"Implicit target not allowed here. Please use display(..., target=...)\"\n )\n if target is not None:\n for v in values:\n Element(target).write(v, append=append)\n else:\n for v in values:\n Element(default_target).write(v, append=append)\n\n\nclass Element:\n def __init__(self, element_id, element=None):\n self._id = element_id\n self._element = element\n\n @property\n def id(self):\n return self._id\n\n @property\n def element(self):\n \"\"\"Return the dom element\"\"\"\n if not self._element:\n self._element = js.document.querySelector(f\"#{self._id}\")\n return self._element\n\n @property\n def value(self):\n return self.element.value\n\n @property\n def innerHtml(self):\n return self.element.innerHTML\n\n def write(self, value, append=False):\n html, mime_type = format_mime(value)\n if html == \"\\n\":\n return\n\n if append:\n child = js.document.createElement(\"div\")\n self.element.appendChild(child)\n\n if append and self.element.children:\n out_element = self.element.children[-1]\n else:\n out_element = self.element\n\n if mime_type in (\"application/javascript\", \"text/html\"):\n script_element = js.document.createRange().createContextualFragment(html)\n out_element.appendChild(script_element)\n else:\n out_element.innerHTML = html\n\n def clear(self):\n if hasattr(self.element, \"value\"):\n self.element.value = \"\"\n else:\n self.write(\"\", append=False)\n\n def select(self, query, from_content=False):\n el = self.element\n\n if from_content:\n el = el.content\n\n _el = el.querySelector(query)\n if _el:\n return Element(_el.id, _el)\n else:\n js.console.warn(f\"WARNING: can't find element matching query {query}\")\n\n def clone(self, new_id=None, to=None):\n if new_id is None:\n new_id = self.element.id\n\n clone = self.element.cloneNode(True)\n clone.id = new_id\n\n if to:\n to.element.appendChild(clone)\n # Inject it into the DOM\n to.element.after(clone)\n else:\n # Inject it into the DOM\n self.element.after(clone)\n\n return Element(clone.id, clone)\n\n def remove_class(self, classname):\n if isinstance(classname, list):\n for cl in classname:\n self.remove_class(cl)\n else:\n self.element.classList.remove(classname)\n\n def add_class(self, classname):\n if isinstance(classname, list):\n for cl in classname:\n self.element.classList.add(cl)\n else:\n self.element.classList.add(classname)\n\n\ndef add_classes(element, class_list):\n for klass in class_list.split(\" \"):\n element.classList.add(klass)\n\n\ndef create(what, id_=None, classes=\"\"):\n element = js.document.createElement(what)\n if id_:\n element.id = id_\n add_classes(element, classes)\n return Element(id_, element)\n\n\nclass PyWidgetTheme:\n def __init__(self, main_style_classes):\n self.main_style_classes = main_style_classes\n\n def theme_it(self, widget):\n for klass in self.main_style_classes.split(\" \"):\n widget.classList.add(klass)\n\n\nclass PyItemTemplate(Element):\n label_fields = None\n\n def __init__(self, data, labels=None, state_key=None, parent=None):\n self.data = data\n\n self.register_parent(parent)\n\n if not labels:\n labels = list(self.data.keys())\n self.labels = labels\n\n self.state_key = state_key\n\n super().__init__(self._id)\n\n def register_parent(self, parent):\n self._parent = parent\n if parent:\n self._id = f\"{self._parent._id}-c-{len(self._parent._children)}\"\n self.data[\"id\"] = self._id\n else:\n self._id = None\n\n def create(self):\n new_child = create(\"div\", self._id, \"py-li-element\")\n new_child._element.innerHTML = dedent(\n f\"\"\"\n <label id=\"{self._id}\" for=\"flex items-center p-2 \">\n <input class=\"mr-2\" type=\"checkbox\" class=\"task-check\">\n <p>{self.render_content()}</p>\n </label>\n \"\"\"\n )\n return new_child\n\n def on_click(self, evt):\n pass\n\n def pre_append(self):\n pass\n\n def post_append(self):\n self.element.click = self.on_click\n self.element.onclick = self.on_click\n\n self._post_append()\n\n def _post_append(self):\n pass\n\n def strike(self, value, extra=None):\n if value:\n self.add_class(\"line-through\")\n else:\n self.remove_class(\"line-through\")\n\n def render_content(self):\n return \" - \".join([self.data[f] for f in self.labels])\n\n\nclass PyListTemplate:\n theme = PyWidgetTheme(\"py-li-element\")\n item_class = PyItemTemplate\n\n def __init__(self, parent):\n self.parent = parent\n self._children = []\n self._id = self.parent.id\n\n @property\n def children(self):\n return self._children\n\n @property\n def data(self):\n return [c.data for c in self._children]\n\n def render_children(self):\n binds = {}\n for i, c in enumerate(self._children):\n txt = c.element.innerHTML\n rnd = str(time.time()).replace(\".\", \"\")[-5:]\n new_id = f\"{c.element.id}-{i}-{rnd}\"\n binds[new_id] = c.element.id\n txt = txt.replace(\">\", f\" id='{new_id}'>\")\n print(txt)\n\n def foo(evt):\n evtEl = evt.srcElement\n srcEl = Element(binds[evtEl.id])\n srcEl.element.onclick()\n evtEl.classList = srcEl.element.classList\n\n for new_id in binds:\n Element(new_id).element.onclick = foo\n\n def connect(self):\n self.md = main_div = js.document.createElement(\"div\")\n main_div.id = self._id + \"-list-tasks-container\"\n\n if self.theme:\n self.theme.theme_it(main_div)\n\n self.parent.appendChild(main_div)\n\n def add(self, *args, **kws):\n if not isinstance(args[0], self.item_class):\n child = self.item_class(*args, **kws)\n else:\n child = args[0]\n child.register_parent(self)\n return self._add(child)\n\n def _add(self, child_elem):\n self.pre_child_append(child_elem)\n child_elem.pre_append()\n self._children.append(child_elem)\n self.md.appendChild(child_elem.create().element)\n child_elem.post_append()\n self.child_appended(child_elem)\n return child_elem\n\n def pre_child_append(self, child):\n pass\n\n def child_appended(self, child):\n \"\"\"Overwrite me to define logic\"\"\"\n pass\n\n\nclass TopLevelAsyncFinder(ast.NodeVisitor):\n def is_source_top_level_await(self, source):\n self.async_found = False\n node = ast.parse(source)\n self.generic_visit(node)\n return self.async_found\n\n def visit_Await(self, node):\n self.async_found = True\n\n def visit_AsyncFor(self, node):\n self.async_found = True\n\n def visit_AsyncWith(self, node):\n self.async_found = True\n\n def visit_AsyncFunctionDef(self, node: ast.AsyncFunctionDef):\n pass # Do not visit children of async function defs\n\n\ndef uses_top_level_await(source: str) -> bool:\n return TopLevelAsyncFinder().is_source_top_level_await(source)\n\n\nclass Plugin:\n def __init__(self, name=None):\n if not name:\n name = self.__class__.__name__\n\n self.name = name\n self._custom_elements = []\n self.app = None\n\n def init(self, app):\n self.app = app\n\n def register_custom_element(self, tag):\n \"\"\"\n Decorator to register a new custom element as part of a Plugin and associate\n tag to it. Internally, it delegates the registration to the PyScript internal\n [JS] plugin manager, who actually creates the JS custom element that can be\n attached to the page and instantiate an instance of the class passing the custom\n element to the plugin constructor.\n\n Exammple:\n >> plugin = Plugin(\"PyTutorial\")\n >> @plugin.register_custom_element(\"py-tutor\")\n >> class PyTutor:\n >> def __init__(self, element):\n >> self.element = element\n \"\"\"\n # TODO: Ideally would be better to use the logger.\n js.console.info(f\"Defining new custom element {tag}\")\n\n def wrapper(class_):\n # TODO: this is very pyodide specific but will have to do\n # until we have JS interface that works across interpreters\n define_custom_element(tag, create_proxy(class_)) # noqa: F821\n\n self._custom_elements.append(tag)\n return create_proxy(wrapper)\n\n\nclass DeprecatedGlobal:\n \"\"\"\n Proxy for globals which are deprecated.\n\n The intendend usage is as follows:\n\n # in the global namespace\n Element = pyscript.DeprecatedGlobal('Element', pyscript.Element, \"...\")\n console = pyscript.DeprecatedGlobal('console', js.console, \"...\")\n ...\n\n The proxy forwards __getattr__ and __call__ to the underlying object, and\n emit a warning on the first usage.\n\n This way users see a warning only if they actually access the top-level\n name.\n \"\"\"\n\n def __init__(self, name, obj, message):\n self.__name = name\n self.__obj = obj\n self.__message = message\n self.__warning_already_shown = False\n\n def __repr__(self):\n return f\"<DeprecatedGlobal({self.__name!r})>\"\n\n def _show_warning(self, message):\n \"\"\"\n NOTE: this is overridden by unit tests\n \"\"\"\n # this showWarning is implemented in js and injected into this\n # namespace by main.ts\n showWarning(message, \"html\") # noqa: F821\n\n def _show_warning_maybe(self):\n if self.__warning_already_shown:\n return\n self._show_warning(self.__message)\n self.__warning_already_shown = True\n\n def __getattr__(self, attr):\n self._show_warning_maybe()\n return getattr(self.__obj, attr)\n\n def __call__(self, *args, **kwargs):\n self._show_warning_maybe()\n return self.__obj(*args, **kwargs)\n\n def __iter__(self):\n self._show_warning_maybe()\n return iter(self.__obj)\n\n def __getitem__(self, key):\n self._show_warning_maybe()\n return self.__obj[key]\n\n def __setitem__(self, key, value):\n self._show_warning_maybe()\n self.__obj[key] = value\n\n\nclass PyScript:\n \"\"\"\n This class is deprecated since 2022.12.1.\n\n All its old functionalities are available as module-level functions. This\n class should be killed eventually.\n \"\"\"\n\n loop = loop\n\n @staticmethod\n def run_until_complete(f):\n run_until_complete(f)\n\n @staticmethod\n def write(element_id, value, append=False, exec_id=0):\n write(element_id, value, append, exec_id)\n\n\ndef _install_deprecated_globals_2022_12_1(ns):\n \"\"\"\n Install into the given namespace all the globals which have been\n deprecated since the 2022.12.1 release. Eventually they should be killed.\n \"\"\"\n\n def deprecate(name, obj, instead):\n message = f\"Direct usage of <code>{name}</code> is deprecated. \" + instead\n ns[name] = DeprecatedGlobal(name, obj, message)\n\n # function/classes defined in pyscript.py ===> pyscript.XXX\n pyscript_names = [\n \"PyItemTemplate\",\n \"PyListTemplate\",\n \"PyWidgetTheme\",\n \"add_classes\",\n \"create\",\n \"loop\",\n ]\n for name in pyscript_names:\n deprecate(\n name, globals()[name], f\"Please use <code>pyscript.{name}</code> instead.\"\n )\n\n # stdlib modules ===> import XXX\n stdlib_names = [\n \"asyncio\",\n \"base64\",\n \"io\",\n \"sys\",\n \"time\",\n \"datetime\",\n \"pyodide\",\n \"micropip\",\n ]\n for name in stdlib_names:\n obj = __import__(name)\n deprecate(name, obj, f\"Please use <code>import {name}</code> instead.\")\n\n # special case\n deprecate(\n \"dedent\", dedent, \"Please use <code>from textwrap import dedent</code> instead.\"\n )\n\n # these are names that used to leak in the globals but they are just\n # implementation details. People should not use them.\n private_names = [\n \"eval_formatter\",\n \"format_mime\",\n \"identity\",\n \"render_image\",\n \"MIME_RENDERERS\",\n \"MIME_METHODS\",\n ]\n for name in private_names:\n obj = globals()[name]\n message = (\n f\"<code>{name}</code> is deprecated. \"\n \"This is a private implementation detail of pyscript. \"\n \"You should not use it.\"\n )\n ns[name] = DeprecatedGlobal(name, obj, message)\n\n # these names are available as js.XXX\n for name in [\"document\", \"console\"]:\n obj = getattr(js, name)\n deprecate(name, obj, f\"Please use <code>js.{name}</code> instead.\")\n\n # PyScript is special, use a different message\n message = (\n \"The <code>PyScript</code> object is deprecated. \"\n \"Please use <code>pyscript</code> instead.\"\n )\n ns[\"PyScript\"] = DeprecatedGlobal(\"PyScript\", PyScript, message)\n"; - const DefaultSplit = /\r\n?|\n/; - /** - Distinguishes different ways in which positions can be mapped. - */ - var MapMode = /*@__PURE__*/(function (MapMode) { - /** - Map a position to a valid new position, even when its context - was deleted. - */ - MapMode[MapMode["Simple"] = 0] = "Simple"; - /** - Return null if deletion happens across the position. - */ - MapMode[MapMode["TrackDel"] = 1] = "TrackDel"; - /** - Return null if the character _before_ the position is deleted. - */ - MapMode[MapMode["TrackBefore"] = 2] = "TrackBefore"; - /** - Return null if the character _after_ the position is deleted. - */ - MapMode[MapMode["TrackAfter"] = 3] = "TrackAfter"; - return MapMode})(MapMode || (MapMode = {})); - /** - A change description is a variant of [change set](https://codemirror.net/6/docs/ref/#state.ChangeSet) - that doesn't store the inserted text. As such, it can't be - applied, but is cheaper to store and manipulate. - */ - class ChangeDesc { - // Sections are encoded as pairs of integers. The first is the - // length in the current document, and the second is -1 for - // unaffected sections, and the length of the replacement content - // otherwise. So an insertion would be (0, n>0), a deletion (n>0, - // 0), and a replacement two positive numbers. - /** - @internal - */ - constructor( - /** - @internal - */ - sections) { - this.sections = sections; - } - /** - The length of the document before the change. - */ - get length() { - let result = 0; - for (let i = 0; i < this.sections.length; i += 2) - result += this.sections[i]; - return result; - } - /** - The length of the document after the change. - */ - get newLength() { - let result = 0; - for (let i = 0; i < this.sections.length; i += 2) { - let ins = this.sections[i + 1]; - result += ins < 0 ? this.sections[i] : ins; - } - return result; - } - /** - False when there are actual changes in this set. - */ - get empty() { return this.sections.length == 0 || this.sections.length == 2 && this.sections[1] < 0; } - /** - Iterate over the unchanged parts left by these changes. - */ - iterGaps(f) { - for (let i = 0, posA = 0, posB = 0; i < this.sections.length;) { - let len = this.sections[i++], ins = this.sections[i++]; - if (ins < 0) { - f(posA, posB, len); - posB += len; - } - else { - posB += ins; - } - posA += len; - } - } - /** - Iterate over the ranges changed by these changes. (See - [`ChangeSet.iterChanges`](https://codemirror.net/6/docs/ref/#state.ChangeSet.iterChanges) for a - variant that also provides you with the inserted text.) - - When `individual` is true, adjacent changes (which are kept - separate for [position mapping](https://codemirror.net/6/docs/ref/#state.ChangeDesc.mapPos)) are - reported separately. - */ - iterChangedRanges(f, individual = false) { - iterChanges(this, f, individual); - } - /** - Get a description of the inverted form of these changes. - */ - get invertedDesc() { - let sections = []; - for (let i = 0; i < this.sections.length;) { - let len = this.sections[i++], ins = this.sections[i++]; - if (ins < 0) - sections.push(len, ins); - else - sections.push(ins, len); - } - return new ChangeDesc(sections); - } - /** - Compute the combined effect of applying another set of changes - after this one. The length of the document after this set should - match the length before `other`. - */ - composeDesc(other) { return this.empty ? other : other.empty ? this : composeSets(this, other); } - /** - Map this description, which should start with the same document - as `other`, over another set of changes, so that it can be - applied after it. When `before` is true, map as if the changes - in `other` happened before the ones in `this`. - */ - mapDesc(other, before = false) { return other.empty ? this : mapSet(this, other, before); } - mapPos(pos, assoc = -1, mode = MapMode.Simple) { - let posA = 0, posB = 0; - for (let i = 0; i < this.sections.length;) { - let len = this.sections[i++], ins = this.sections[i++], endA = posA + len; - if (ins < 0) { - if (endA > pos) - return posB + (pos - posA); - posB += len; - } - else { - if (mode != MapMode.Simple && endA >= pos && - (mode == MapMode.TrackDel && posA < pos && endA > pos || - mode == MapMode.TrackBefore && posA < pos || - mode == MapMode.TrackAfter && endA > pos)) - return null; - if (endA > pos || endA == pos && assoc < 0 && !len) - return pos == posA || assoc < 0 ? posB : posB + ins; - posB += ins; - } - posA = endA; - } - if (pos > posA) - throw new RangeError(`Position ${pos} is out of range for changeset of length ${posA}`); - return posB; - } - /** - Check whether these changes touch a given range. When one of the - changes entirely covers the range, the string `"cover"` is - returned. - */ - touchesRange(from, to = from) { - for (let i = 0, pos = 0; i < this.sections.length && pos <= to;) { - let len = this.sections[i++], ins = this.sections[i++], end = pos + len; - if (ins >= 0 && pos <= to && end >= from) - return pos < from && end > to ? "cover" : true; - pos = end; - } - return false; - } - /** - @internal - */ - toString() { - let result = ""; - for (let i = 0; i < this.sections.length;) { - let len = this.sections[i++], ins = this.sections[i++]; - result += (result ? " " : "") + len + (ins >= 0 ? ":" + ins : ""); - } - return result; - } - /** - Serialize this change desc to a JSON-representable value. - */ - toJSON() { return this.sections; } - /** - Create a change desc from its JSON representation (as produced - by [`toJSON`](https://codemirror.net/6/docs/ref/#state.ChangeDesc.toJSON). - */ - static fromJSON(json) { - if (!Array.isArray(json) || json.length % 2 || json.some(a => typeof a != "number")) - throw new RangeError("Invalid JSON representation of ChangeDesc"); - return new ChangeDesc(json); - } - } - /** - A change set represents a group of modifications to a document. It - stores the document length, and can only be applied to documents - with exactly that length. - */ - class ChangeSet extends ChangeDesc { - /** - @internal - */ - constructor(sections, - /** - @internal - */ - inserted) { - super(sections); - this.inserted = inserted; - } - /** - Apply the changes to a document, returning the modified - document. - */ - apply(doc) { - if (this.length != doc.length) - throw new RangeError("Applying change set to a document with the wrong length"); - iterChanges(this, (fromA, toA, fromB, _toB, text) => doc = doc.replace(fromB, fromB + (toA - fromA), text), false); - return doc; - } - mapDesc(other, before = false) { return mapSet(this, other, before, true); } - /** - Given the document as it existed _before_ the changes, return a - change set that represents the inverse of this set, which could - be used to go from the document created by the changes back to - the document as it existed before the changes. - */ - invert(doc) { - let sections = this.sections.slice(), inserted = []; - for (let i = 0, pos = 0; i < sections.length; i += 2) { - let len = sections[i], ins = sections[i + 1]; - if (ins >= 0) { - sections[i] = ins; - sections[i + 1] = len; - let index = i >> 1; - while (inserted.length < index) - inserted.push(Text.empty); - inserted.push(len ? doc.slice(pos, pos + len) : Text.empty); - } - pos += len; - } - return new ChangeSet(sections, inserted); - } - /** - Combine two subsequent change sets into a single set. `other` - must start in the document produced by `this`. If `this` goes - `docA` → `docB` and `other` represents `docB` → `docC`, the - returned value will represent the change `docA` → `docC`. - */ - compose(other) { return this.empty ? other : other.empty ? this : composeSets(this, other, true); } - /** - Given another change set starting in the same document, maps this - change set over the other, producing a new change set that can be - applied to the document produced by applying `other`. When - `before` is `true`, order changes as if `this` comes before - `other`, otherwise (the default) treat `other` as coming first. - - Given two changes `A` and `B`, `A.compose(B.map(A))` and - `B.compose(A.map(B, true))` will produce the same document. This - provides a basic form of [operational - transformation](https://en.wikipedia.org/wiki/Operational_transformation), - and can be used for collaborative editing. - */ - map(other, before = false) { return other.empty ? this : mapSet(this, other, before, true); } - /** - Iterate over the changed ranges in the document, calling `f` for - each, with the range in the original document (`fromA`-`toA`) - and the range that replaces it in the new document - (`fromB`-`toB`). - - When `individual` is true, adjacent changes are reported - separately. - */ - iterChanges(f, individual = false) { - iterChanges(this, f, individual); - } - /** - Get a [change description](https://codemirror.net/6/docs/ref/#state.ChangeDesc) for this change - set. - */ - get desc() { return new ChangeDesc(this.sections); } - /** - @internal - */ - filter(ranges) { - let resultSections = [], resultInserted = [], filteredSections = []; - let iter = new SectionIter(this); - done: for (let i = 0, pos = 0;;) { - let next = i == ranges.length ? 1e9 : ranges[i++]; - while (pos < next || pos == next && iter.len == 0) { - if (iter.done) - break done; - let len = Math.min(iter.len, next - pos); - addSection(filteredSections, len, -1); - let ins = iter.ins == -1 ? -1 : iter.off == 0 ? iter.ins : 0; - addSection(resultSections, len, ins); - if (ins > 0) - addInsert(resultInserted, resultSections, iter.text); - iter.forward(len); - pos += len; - } - let end = ranges[i++]; - while (pos < end) { - if (iter.done) - break done; - let len = Math.min(iter.len, end - pos); - addSection(resultSections, len, -1); - addSection(filteredSections, len, iter.ins == -1 ? -1 : iter.off == 0 ? iter.ins : 0); - iter.forward(len); - pos += len; - } - } - return { changes: new ChangeSet(resultSections, resultInserted), - filtered: new ChangeDesc(filteredSections) }; - } - /** - Serialize this change set to a JSON-representable value. - */ - toJSON() { - let parts = []; - for (let i = 0; i < this.sections.length; i += 2) { - let len = this.sections[i], ins = this.sections[i + 1]; - if (ins < 0) - parts.push(len); - else if (ins == 0) - parts.push([len]); - else - parts.push([len].concat(this.inserted[i >> 1].toJSON())); - } - return parts; - } - /** - Create a change set for the given changes, for a document of the - given length, using `lineSep` as line separator. - */ - static of(changes, length, lineSep) { - let sections = [], inserted = [], pos = 0; - let total = null; - function flush(force = false) { - if (!force && !sections.length) - return; - if (pos < length) - addSection(sections, length - pos, -1); - let set = new ChangeSet(sections, inserted); - total = total ? total.compose(set.map(total)) : set; - sections = []; - inserted = []; - pos = 0; - } - function process(spec) { - if (Array.isArray(spec)) { - for (let sub of spec) - process(sub); - } - else if (spec instanceof ChangeSet) { - if (spec.length != length) - throw new RangeError(`Mismatched change set length (got ${spec.length}, expected ${length})`); - flush(); - total = total ? total.compose(spec.map(total)) : spec; - } - else { - let { from, to = from, insert } = spec; - if (from > to || from < 0 || to > length) - throw new RangeError(`Invalid change range ${from} to ${to} (in doc of length ${length})`); - let insText = !insert ? Text.empty : typeof insert == "string" ? Text.of(insert.split(lineSep || DefaultSplit)) : insert; - let insLen = insText.length; - if (from == to && insLen == 0) - return; - if (from < pos) - flush(); - if (from > pos) - addSection(sections, from - pos, -1); - addSection(sections, to - from, insLen); - addInsert(inserted, sections, insText); - pos = to; - } - } - process(changes); - flush(!total); - return total; - } - /** - Create an empty changeset of the given length. - */ - static empty(length) { - return new ChangeSet(length ? [length, -1] : [], []); - } - /** - Create a changeset from its JSON representation (as produced by - [`toJSON`](https://codemirror.net/6/docs/ref/#state.ChangeSet.toJSON). - */ - static fromJSON(json) { - if (!Array.isArray(json)) - throw new RangeError("Invalid JSON representation of ChangeSet"); - let sections = [], inserted = []; - for (let i = 0; i < json.length; i++) { - let part = json[i]; - if (typeof part == "number") { - sections.push(part, -1); - } - else if (!Array.isArray(part) || typeof part[0] != "number" || part.some((e, i) => i && typeof e != "string")) { - throw new RangeError("Invalid JSON representation of ChangeSet"); - } - else if (part.length == 1) { - sections.push(part[0], 0); - } - else { - while (inserted.length < i) - inserted.push(Text.empty); - inserted[i] = Text.of(part.slice(1)); - sections.push(part[0], inserted[i].length); - } - } - return new ChangeSet(sections, inserted); - } - } - function addSection(sections, len, ins, forceJoin = false) { - if (len == 0 && ins <= 0) - return; - let last = sections.length - 2; - if (last >= 0 && ins <= 0 && ins == sections[last + 1]) - sections[last] += len; - else if (len == 0 && sections[last] == 0) - sections[last + 1] += ins; - else if (forceJoin) { - sections[last] += len; - sections[last + 1] += ins; - } - else - sections.push(len, ins); - } - function addInsert(values, sections, value) { - if (value.length == 0) - return; - let index = (sections.length - 2) >> 1; - if (index < values.length) { - values[values.length - 1] = values[values.length - 1].append(value); - } - else { - while (values.length < index) - values.push(Text.empty); - values.push(value); - } - } - function iterChanges(desc, f, individual) { - let inserted = desc.inserted; - for (let posA = 0, posB = 0, i = 0; i < desc.sections.length;) { - let len = desc.sections[i++], ins = desc.sections[i++]; - if (ins < 0) { - posA += len; - posB += len; - } - else { - let endA = posA, endB = posB, text = Text.empty; - for (;;) { - endA += len; - endB += ins; - if (ins && inserted) - text = text.append(inserted[(i - 2) >> 1]); - if (individual || i == desc.sections.length || desc.sections[i + 1] < 0) - break; - len = desc.sections[i++]; - ins = desc.sections[i++]; - } - f(posA, endA, posB, endB, text); - posA = endA; - posB = endB; - } - } - } - function mapSet(setA, setB, before, mkSet = false) { - let sections = [], insert = mkSet ? [] : null; - let a = new SectionIter(setA), b = new SectionIter(setB); - for (let posA = 0, posB = 0;;) { - if (a.ins == -1) { - posA += a.len; - a.next(); - } - else if (b.ins == -1 && posB < posA) { - let skip = Math.min(b.len, posA - posB); - b.forward(skip); - addSection(sections, skip, -1); - posB += skip; - } - else if (b.ins >= 0 && (a.done || posB < posA || posB == posA && (b.len < a.len || b.len == a.len && !before))) { - addSection(sections, b.ins, -1); - while (posA > posB && !a.done && posA + a.len < posB + b.len) { - posA += a.len; - a.next(); - } - posB += b.len; - b.next(); - } - else if (a.ins >= 0) { - let len = 0, end = posA + a.len; - for (;;) { - if (b.ins >= 0 && posB > posA && posB + b.len < end) { - len += b.ins; - posB += b.len; - b.next(); - } - else if (b.ins == -1 && posB < end) { - let skip = Math.min(b.len, end - posB); - len += skip; - b.forward(skip); - posB += skip; - } - else { - break; - } - } - addSection(sections, len, a.ins); - if (insert) - addInsert(insert, sections, a.text); - posA = end; - a.next(); - } - else if (a.done && b.done) { - return insert ? new ChangeSet(sections, insert) : new ChangeDesc(sections); - } - else { - throw new Error("Mismatched change set lengths"); - } - } - } - function composeSets(setA, setB, mkSet = false) { - let sections = []; - let insert = mkSet ? [] : null; - let a = new SectionIter(setA), b = new SectionIter(setB); - for (let open = false;;) { - if (a.done && b.done) { - return insert ? new ChangeSet(sections, insert) : new ChangeDesc(sections); - } - else if (a.ins == 0) { // Deletion in A - addSection(sections, a.len, 0, open); - a.next(); - } - else if (b.len == 0 && !b.done) { // Insertion in B - addSection(sections, 0, b.ins, open); - if (insert) - addInsert(insert, sections, b.text); - b.next(); - } - else if (a.done || b.done) { - throw new Error("Mismatched change set lengths"); - } - else { - let len = Math.min(a.len2, b.len), sectionLen = sections.length; - if (a.ins == -1) { - let insB = b.ins == -1 ? -1 : b.off ? 0 : b.ins; - addSection(sections, len, insB, open); - if (insert && insB) - addInsert(insert, sections, b.text); - } - else if (b.ins == -1) { - addSection(sections, a.off ? 0 : a.len, len, open); - if (insert) - addInsert(insert, sections, a.textBit(len)); - } - else { - addSection(sections, a.off ? 0 : a.len, b.off ? 0 : b.ins, open); - if (insert && !b.off) - addInsert(insert, sections, b.text); - } - open = (a.ins > len || b.ins >= 0 && b.len > len) && (open || sections.length > sectionLen); - a.forward2(len); - b.forward(len); - } - } - } - class SectionIter { - constructor(set) { - this.set = set; - this.i = 0; - this.next(); - } - next() { - let { sections } = this.set; - if (this.i < sections.length) { - this.len = sections[this.i++]; - this.ins = sections[this.i++]; - } - else { - this.len = 0; - this.ins = -2; - } - this.off = 0; - } - get done() { return this.ins == -2; } - get len2() { return this.ins < 0 ? this.len : this.ins; } - get text() { - let { inserted } = this.set, index = (this.i - 2) >> 1; - return index >= inserted.length ? Text.empty : inserted[index]; - } - textBit(len) { - let { inserted } = this.set, index = (this.i - 2) >> 1; - return index >= inserted.length && !len ? Text.empty - : inserted[index].slice(this.off, len == null ? undefined : this.off + len); - } - forward(len) { - if (len == this.len) - this.next(); - else { - this.len -= len; - this.off += len; - } - } - forward2(len) { - if (this.ins == -1) - this.forward(len); - else if (len == this.ins) - this.next(); - else { - this.ins -= len; - this.off += len; - } - } - } + const logger = getLogger('pyscript/main'); + /* High-level overview of the lifecycle of a PyScript App: - /** - A single selection range. When - [`allowMultipleSelections`](https://codemirror.net/6/docs/ref/#state.EditorState^allowMultipleSelections) - is enabled, a [selection](https://codemirror.net/6/docs/ref/#state.EditorSelection) may hold - multiple ranges. By default, selections hold exactly one range. - */ - class SelectionRange { - /** - @internal - */ - constructor( - /** - The lower boundary of the range. - */ - from, - /** - The upper boundary of the range. - */ - to, flags) { - this.from = from; - this.to = to; - this.flags = flags; - } - /** - The anchor of the range—the side that doesn't move when you - extend it. - */ - get anchor() { return this.flags & 16 /* Inverted */ ? this.to : this.from; } - /** - The head of the range, which is moved when the range is - [extended](https://codemirror.net/6/docs/ref/#state.SelectionRange.extend). - */ - get head() { return this.flags & 16 /* Inverted */ ? this.from : this.to; } - /** - True when `anchor` and `head` are at the same position. - */ - get empty() { return this.from == this.to; } - /** - If this is a cursor that is explicitly associated with the - character on one of its sides, this returns the side. -1 means - the character before its position, 1 the character after, and 0 - means no association. - */ - get assoc() { return this.flags & 4 /* AssocBefore */ ? -1 : this.flags & 8 /* AssocAfter */ ? 1 : 0; } - /** - The bidirectional text level associated with this cursor, if - any. - */ - get bidiLevel() { - let level = this.flags & 3 /* BidiLevelMask */; - return level == 3 ? null : level; - } - /** - The goal column (stored vertical offset) associated with a - cursor. This is used to preserve the vertical position when - [moving](https://codemirror.net/6/docs/ref/#view.EditorView.moveVertically) across - lines of different length. - */ - get goalColumn() { - let value = this.flags >> 5 /* GoalColumnOffset */; - return value == 33554431 /* NoGoalColumn */ ? undefined : value; - } - /** - Map this range through a change, producing a valid range in the - updated document. - */ - map(change, assoc = -1) { - let from, to; - if (this.empty) { - from = to = change.mapPos(this.from, assoc); - } - else { - from = change.mapPos(this.from, 1); - to = change.mapPos(this.to, -1); - } - return from == this.from && to == this.to ? this : new SelectionRange(from, to, this.flags); - } - /** - Extend this range to cover at least `from` to `to`. - */ - extend(from, to = from) { - if (from <= this.anchor && to >= this.anchor) - return EditorSelection.range(from, to); - let head = Math.abs(from - this.anchor) > Math.abs(to - this.anchor) ? from : to; - return EditorSelection.range(this.anchor, head); - } - /** - Compare this range to another range. - */ - eq(other) { - return this.anchor == other.anchor && this.head == other.head; - } - /** - Return a JSON-serializable object representing the range. - */ - toJSON() { return { anchor: this.anchor, head: this.head }; } - /** - Convert a JSON representation of a range to a `SelectionRange` - instance. - */ - static fromJSON(json) { - if (!json || typeof json.anchor != "number" || typeof json.head != "number") - throw new RangeError("Invalid JSON representation for SelectionRange"); - return EditorSelection.range(json.anchor, json.head); - } - } - /** - An editor selection holds one or more selection ranges. - */ - class EditorSelection { - /** - @internal - */ - constructor( - /** - The ranges in the selection, sorted by position. Ranges cannot - overlap (but they may touch, if they aren't empty). - */ - ranges, - /** - The index of the _main_ range in the selection (which is - usually the range that was added last). - */ - mainIndex = 0) { - this.ranges = ranges; - this.mainIndex = mainIndex; - } - /** - Map a selection through a change. Used to adjust the selection - position for changes. - */ - map(change, assoc = -1) { - if (change.empty) - return this; - return EditorSelection.create(this.ranges.map(r => r.map(change, assoc)), this.mainIndex); - } - /** - Compare this selection to another selection. - */ - eq(other) { - if (this.ranges.length != other.ranges.length || - this.mainIndex != other.mainIndex) - return false; - for (let i = 0; i < this.ranges.length; i++) - if (!this.ranges[i].eq(other.ranges[i])) - return false; - return true; - } - /** - Get the primary selection range. Usually, you should make sure - your code applies to _all_ ranges, by using methods like - [`changeByRange`](https://codemirror.net/6/docs/ref/#state.EditorState.changeByRange). - */ - get main() { return this.ranges[this.mainIndex]; } - /** - Make sure the selection only has one range. Returns a selection - holding only the main range from this selection. - */ - asSingle() { - return this.ranges.length == 1 ? this : new EditorSelection([this.main]); - } - /** - Extend this selection with an extra range. - */ - addRange(range, main = true) { - return EditorSelection.create([range].concat(this.ranges), main ? 0 : this.mainIndex + 1); - } - /** - Replace a given range with another range, and then normalize the - selection to merge and sort ranges if necessary. - */ - replaceRange(range, which = this.mainIndex) { - let ranges = this.ranges.slice(); - ranges[which] = range; - return EditorSelection.create(ranges, this.mainIndex); - } - /** - Convert this selection to an object that can be serialized to - JSON. - */ - toJSON() { - return { ranges: this.ranges.map(r => r.toJSON()), main: this.mainIndex }; - } - /** - Create a selection from a JSON representation. - */ - static fromJSON(json) { - if (!json || !Array.isArray(json.ranges) || typeof json.main != "number" || json.main >= json.ranges.length) - throw new RangeError("Invalid JSON representation for EditorSelection"); - return new EditorSelection(json.ranges.map((r) => SelectionRange.fromJSON(r)), json.main); - } - /** - Create a selection holding a single range. - */ - static single(anchor, head = anchor) { - return new EditorSelection([EditorSelection.range(anchor, head)], 0); - } - /** - Sort and merge the given set of ranges, creating a valid - selection. - */ - static create(ranges, mainIndex = 0) { - if (ranges.length == 0) - throw new RangeError("A selection needs at least one range"); - for (let pos = 0, i = 0; i < ranges.length; i++) { - let range = ranges[i]; - if (range.empty ? range.from <= pos : range.from < pos) - return normalized(ranges.slice(), mainIndex); - pos = range.to; - } - return new EditorSelection(ranges, mainIndex); - } - /** - Create a cursor selection range at the given position. You can - safely ignore the optional arguments in most situations. - */ - static cursor(pos, assoc = 0, bidiLevel, goalColumn) { - return new SelectionRange(pos, pos, (assoc == 0 ? 0 : assoc < 0 ? 4 /* AssocBefore */ : 8 /* AssocAfter */) | - (bidiLevel == null ? 3 : Math.min(2, bidiLevel)) | - ((goalColumn !== null && goalColumn !== void 0 ? goalColumn : 33554431 /* NoGoalColumn */) << 5 /* GoalColumnOffset */)); - } - /** - Create a selection range. - */ - static range(anchor, head, goalColumn) { - let goal = (goalColumn !== null && goalColumn !== void 0 ? goalColumn : 33554431 /* NoGoalColumn */) << 5 /* GoalColumnOffset */; - return head < anchor ? new SelectionRange(head, anchor, 16 /* Inverted */ | goal | 8 /* AssocAfter */) - : new SelectionRange(anchor, head, goal | (head > anchor ? 4 /* AssocBefore */ : 0)); - } - } - function normalized(ranges, mainIndex = 0) { - let main = ranges[mainIndex]; - ranges.sort((a, b) => a.from - b.from); - mainIndex = ranges.indexOf(main); - for (let i = 1; i < ranges.length; i++) { - let range = ranges[i], prev = ranges[i - 1]; - if (range.empty ? range.from <= prev.to : range.from < prev.to) { - let from = prev.from, to = Math.max(range.to, prev.to); - if (i <= mainIndex) - mainIndex--; - ranges.splice(--i, 2, range.anchor > range.head ? EditorSelection.range(to, from) : EditorSelection.range(from, to)); - } - } - return new EditorSelection(ranges, mainIndex); - } - function checkSelection(selection, docLength) { - for (let range of selection.ranges) - if (range.to > docLength) - throw new RangeError("Selection points outside of document"); - } + 1. pyscript.js is loaded by the browser. PyScriptApp().main() is called - let nextID = 0; - /** - A facet is a labeled value that is associated with an editor - state. It takes inputs from any number of extensions, and combines - those into a single output value. + 2. loadConfig(): search for py-config and compute the config for the app - Examples of facets are the [theme](https://codemirror.net/6/docs/ref/#view.EditorView^theme) styles - associated with an editor or the [tab - size](https://codemirror.net/6/docs/ref/#state.EditorState^tabSize) (which is reduced to a single - value, using the input with the hightest precedence). - */ - class Facet { - constructor( - /** - @internal - */ - combine, - /** - @internal - */ - compareInput, - /** - @internal - */ - compare, isStatic, - /** - @internal - */ - extensions) { - this.combine = combine; - this.compareInput = compareInput; - this.compare = compare; - this.isStatic = isStatic; - this.extensions = extensions; - /** - @internal - */ - this.id = nextID++; - this.default = combine([]); - } - /** - Define a new facet. - */ - static define(config = {}) { - return new Facet(config.combine || ((a) => a), config.compareInput || ((a, b) => a === b), config.compare || (!config.combine ? sameArray$1 : (a, b) => a === b), !!config.static, config.enables); - } - /** - Returns an extension that adds the given value for this facet. - */ - of(value) { - return new FacetProvider([], this, 0 /* Static */, value); - } - /** - Create an extension that computes a value for the facet from a - state. You must take care to declare the parts of the state that - this value depends on, since your function is only called again - for a new state when one of those parts changed. - - In most cases, you'll want to use the - [`provide`](https://codemirror.net/6/docs/ref/#state.StateField^define^config.provide) option when - defining a field instead. - */ - compute(deps, get) { - if (this.isStatic) - throw new Error("Can't compute a static facet"); - return new FacetProvider(deps, this, 1 /* Single */, get); - } - /** - Create an extension that computes zero or more values for this - facet from a state. - */ - computeN(deps, get) { - if (this.isStatic) - throw new Error("Can't compute a static facet"); - return new FacetProvider(deps, this, 2 /* Multi */, get); - } - from(field, get) { - if (!get) - get = x => x; - return this.compute([field], state => get(state.field(field))); - } - } - function sameArray$1(a, b) { - return a == b || a.length == b.length && a.every((e, i) => e === b[i]); - } - class FacetProvider { - constructor(dependencies, facet, type, value) { - this.dependencies = dependencies; - this.facet = facet; - this.type = type; - this.value = value; - this.id = nextID++; - } - dynamicSlot(addresses) { - var _a; - let getter = this.value; - let compare = this.facet.compareInput; - let id = this.id, idx = addresses[id] >> 1, multi = this.type == 2 /* Multi */; - let depDoc = false, depSel = false, depAddrs = []; - for (let dep of this.dependencies) { - if (dep == "doc") - depDoc = true; - else if (dep == "selection") - depSel = true; - else if ((((_a = addresses[dep.id]) !== null && _a !== void 0 ? _a : 1) & 1) == 0) - depAddrs.push(addresses[dep.id]); - } - return { - create(state) { - state.values[idx] = getter(state); - return 1 /* Changed */; - }, - update(state, tr) { - if ((depDoc && tr.docChanged) || (depSel && (tr.docChanged || tr.selection)) || - depAddrs.some(addr => (ensureAddr(state, addr) & 1 /* Changed */) > 0)) { - let newVal = getter(state); - if (multi ? !compareArray(newVal, state.values[idx], compare) : !compare(newVal, state.values[idx])) { - state.values[idx] = newVal; - return 1 /* Changed */; - } - } - return 0; - }, - reconfigure(state, oldState) { - let newVal = getter(state); - let oldAddr = oldState.config.address[id]; - if (oldAddr != null) { - let oldVal = getAddr(oldState, oldAddr); - if (multi ? compareArray(newVal, oldVal, compare) : compare(newVal, oldVal)) { - state.values[idx] = oldVal; - return 0; - } - } - state.values[idx] = newVal; - return 1 /* Changed */; - } - }; - } - } - function compareArray(a, b, compare) { - if (a.length != b.length) - return false; - for (let i = 0; i < a.length; i++) - if (!compare(a[i], b[i])) - return false; - return true; - } - function dynamicFacetSlot(addresses, facet, providers) { - let providerAddrs = providers.map(p => addresses[p.id]); - let providerTypes = providers.map(p => p.type); - let dynamic = providerAddrs.filter(p => !(p & 1)); - let idx = addresses[facet.id] >> 1; - function get(state) { - let values = []; - for (let i = 0; i < providerAddrs.length; i++) { - let value = getAddr(state, providerAddrs[i]); - if (providerTypes[i] == 2 /* Multi */) - for (let val of value) - values.push(val); - else - values.push(value); - } - return facet.combine(values); - } - return { - create(state) { - for (let addr of providerAddrs) - ensureAddr(state, addr); - state.values[idx] = get(state); - return 1 /* Changed */; - }, - update(state, tr) { - if (!dynamic.some(dynAddr => ensureAddr(state, dynAddr) & 1 /* Changed */)) - return 0; - let value = get(state); - if (facet.compare(value, state.values[idx])) - return 0; - state.values[idx] = value; - return 1 /* Changed */; - }, - reconfigure(state, oldState) { - let depChanged = providerAddrs.some(addr => ensureAddr(state, addr) & 1 /* Changed */); - let oldProviders = oldState.config.facets[facet.id], oldValue = oldState.facet(facet); - if (oldProviders && !depChanged && sameArray$1(providers, oldProviders)) { - state.values[idx] = oldValue; - return 0; - } - let value = get(state); - if (facet.compare(value, oldValue)) { - state.values[idx] = oldValue; - return 0; - } - state.values[idx] = value; - return 1 /* Changed */; - } - }; - } - const initField = /*@__PURE__*/Facet.define({ static: true }); - /** - Fields can store additional information in an editor state, and - keep it in sync with the rest of the state. - */ - class StateField { - constructor( - /** - @internal - */ - id, createF, updateF, compareF, - /** - @internal - */ - spec) { - this.id = id; - this.createF = createF; - this.updateF = updateF; - this.compareF = compareF; - this.spec = spec; - /** - @internal - */ - this.provides = undefined; - } - /** - Define a state field. - */ - static define(config) { - let field = new StateField(nextID++, config.create, config.update, config.compare || ((a, b) => a === b), config); - if (config.provide) - field.provides = config.provide(field); - return field; - } - create(state) { - let init = state.facet(initField).find(i => i.field == this); - return ((init === null || init === void 0 ? void 0 : init.create) || this.createF)(state); - } - /** - @internal - */ - slot(addresses) { - let idx = addresses[this.id] >> 1; - return { - create: (state) => { - state.values[idx] = this.create(state); - return 1 /* Changed */; - }, - update: (state, tr) => { - let oldVal = state.values[idx]; - let value = this.updateF(oldVal, tr); - if (this.compareF(oldVal, value)) - return 0; - state.values[idx] = value; - return 1 /* Changed */; - }, - reconfigure: (state, oldState) => { - if (oldState.config.address[this.id] != null) { - state.values[idx] = oldState.field(this); - return 0; - } - state.values[idx] = this.create(state); - return 1 /* Changed */; - } - }; - } - /** - Returns an extension that enables this field and overrides the - way it is initialized. Can be useful when you need to provide a - non-default starting value for the field. - */ - init(create) { - return [this, initField.of({ field: this, create })]; - } - /** - State field instances can be used as - [`Extension`](https://codemirror.net/6/docs/ref/#state.Extension) values to enable the field in a - given state. - */ - get extension() { return this; } - } - const Prec_ = { lowest: 4, low: 3, default: 2, high: 1, highest: 0 }; - function prec(value) { - return (ext) => new PrecExtension(ext, value); - } - /** - By default extensions are registered in the order they are found - in the flattened form of nested array that was provided. - Individual extension values can be assigned a precedence to - override this. Extensions that do not have a precedence set get - the precedence of the nearest parent with a precedence, or - [`default`](https://codemirror.net/6/docs/ref/#state.Prec.default) if there is no such parent. The - final ordering of extensions is determined by first sorting by - precedence and then by order within each precedence. - */ - const Prec = { - /** - The lowest precedence level. Meant for things that should end up - near the end of the extension order. - */ - lowest: /*@__PURE__*/prec(Prec_.lowest), - /** - A lower-than-default precedence, for extensions. - */ - low: /*@__PURE__*/prec(Prec_.low), - /** - The default precedence, which is also used for extensions - without an explicit precedence. - */ - default: /*@__PURE__*/prec(Prec_.default), - /** - A higher-than-default precedence, for extensions that should - come before those with default precedence. - */ - high: /*@__PURE__*/prec(Prec_.high), - /** - The highest precedence level, for extensions that should end up - near the start of the precedence ordering. - */ - highest: /*@__PURE__*/prec(Prec_.highest), - // FIXME Drop these in some future breaking version - /** - Backwards-compatible synonym for `Prec.lowest`. - */ - fallback: /*@__PURE__*/prec(Prec_.lowest), - /** - Backwards-compatible synonym for `Prec.high`. - */ - extend: /*@__PURE__*/prec(Prec_.high), - /** - Backwards-compatible synonym for `Prec.highest`. - */ - override: /*@__PURE__*/prec(Prec_.highest) - }; - class PrecExtension { - constructor(inner, prec) { - this.inner = inner; - this.prec = prec; - } - } - /** - Extension compartments can be used to make a configuration - dynamic. By [wrapping](https://codemirror.net/6/docs/ref/#state.Compartment.of) part of your - configuration in a compartment, you can later - [replace](https://codemirror.net/6/docs/ref/#state.Compartment.reconfigure) that part through a - transaction. - */ - class Compartment { - /** - Create an instance of this compartment to add to your [state - configuration](https://codemirror.net/6/docs/ref/#state.EditorStateConfig.extensions). - */ - of(ext) { return new CompartmentInstance(this, ext); } - /** - Create an [effect](https://codemirror.net/6/docs/ref/#state.TransactionSpec.effects) that - reconfigures this compartment. - */ - reconfigure(content) { - return Compartment.reconfigure.of({ compartment: this, extension: content }); - } - /** - Get the current content of the compartment in the state, or - `undefined` if it isn't present. - */ - get(state) { - return state.config.compartments.get(this); - } - } - class CompartmentInstance { - constructor(compartment, inner) { - this.compartment = compartment; - this.inner = inner; - } - } - class Configuration { - constructor(base, compartments, dynamicSlots, address, staticValues, facets) { - this.base = base; - this.compartments = compartments; - this.dynamicSlots = dynamicSlots; - this.address = address; - this.staticValues = staticValues; - this.facets = facets; - this.statusTemplate = []; - while (this.statusTemplate.length < dynamicSlots.length) - this.statusTemplate.push(0 /* Unresolved */); - } - staticFacet(facet) { - let addr = this.address[facet.id]; - return addr == null ? facet.default : this.staticValues[addr >> 1]; - } - static resolve(base, compartments, oldState) { - let fields = []; - let facets = Object.create(null); - let newCompartments = new Map(); - for (let ext of flatten(base, compartments, newCompartments)) { - if (ext instanceof StateField) - fields.push(ext); - else - (facets[ext.facet.id] || (facets[ext.facet.id] = [])).push(ext); - } - let address = Object.create(null); - let staticValues = []; - let dynamicSlots = []; - for (let field of fields) { - address[field.id] = dynamicSlots.length << 1; - dynamicSlots.push(a => field.slot(a)); - } - let oldFacets = oldState === null || oldState === void 0 ? void 0 : oldState.config.facets; - for (let id in facets) { - let providers = facets[id], facet = providers[0].facet; - let oldProviders = oldFacets && oldFacets[id] || []; - if (providers.every(p => p.type == 0 /* Static */)) { - address[facet.id] = (staticValues.length << 1) | 1; - if (sameArray$1(oldProviders, providers)) { - staticValues.push(oldState.facet(facet)); - } - else { - let value = facet.combine(providers.map(p => p.value)); - staticValues.push(oldState && facet.compare(value, oldState.facet(facet)) ? oldState.facet(facet) : value); - } - } - else { - for (let p of providers) { - if (p.type == 0 /* Static */) { - address[p.id] = (staticValues.length << 1) | 1; - staticValues.push(p.value); - } - else { - address[p.id] = dynamicSlots.length << 1; - dynamicSlots.push(a => p.dynamicSlot(a)); - } - } - address[facet.id] = dynamicSlots.length << 1; - dynamicSlots.push(a => dynamicFacetSlot(a, facet, providers)); - } - } - let dynamic = dynamicSlots.map(f => f(address)); - return new Configuration(base, newCompartments, dynamic, address, staticValues, facets); - } - } - function flatten(extension, compartments, newCompartments) { - let result = [[], [], [], [], []]; - let seen = new Map(); - function inner(ext, prec) { - let known = seen.get(ext); - if (known != null) { - if (known >= prec) - return; - let found = result[known].indexOf(ext); - if (found > -1) - result[known].splice(found, 1); - if (ext instanceof CompartmentInstance) - newCompartments.delete(ext.compartment); - } - seen.set(ext, prec); - if (Array.isArray(ext)) { - for (let e of ext) - inner(e, prec); - } - else if (ext instanceof CompartmentInstance) { - if (newCompartments.has(ext.compartment)) - throw new RangeError(`Duplicate use of compartment in extensions`); - let content = compartments.get(ext.compartment) || ext.inner; - newCompartments.set(ext.compartment, content); - inner(content, prec); - } - else if (ext instanceof PrecExtension) { - inner(ext.inner, ext.prec); - } - else if (ext instanceof StateField) { - result[prec].push(ext); - if (ext.provides) - inner(ext.provides, prec); - } - else if (ext instanceof FacetProvider) { - result[prec].push(ext); - if (ext.facet.extensions) - inner(ext.facet.extensions, prec); - } - else { - let content = ext.extension; - if (!content) - throw new Error(`Unrecognized extension value in extension set (${ext}). This sometimes happens because multiple instances of @codemirror/state are loaded, breaking instanceof checks.`); - inner(content, prec); - } - } - inner(extension, Prec_.default); - return result.reduce((a, b) => a.concat(b)); - } - function ensureAddr(state, addr) { - if (addr & 1) - return 2 /* Computed */; - let idx = addr >> 1; - let status = state.status[idx]; - if (status == 4 /* Computing */) - throw new Error("Cyclic dependency between fields and/or facets"); - if (status & 2 /* Computed */) - return status; - state.status[idx] = 4 /* Computing */; - let changed = state.computeSlot(state, state.config.dynamicSlots[idx]); - return state.status[idx] = 2 /* Computed */ | changed; - } - function getAddr(state, addr) { - return addr & 1 ? state.config.staticValues[addr >> 1] : state.values[addr >> 1]; - } + 3. (it used to be "show the splashscreen", but now it's a plugin) - const languageData = /*@__PURE__*/Facet.define(); - const allowMultipleSelections = /*@__PURE__*/Facet.define({ - combine: values => values.some(v => v), - static: true - }); - const lineSeparator = /*@__PURE__*/Facet.define({ - combine: values => values.length ? values[0] : undefined, - static: true - }); - const changeFilter = /*@__PURE__*/Facet.define(); - const transactionFilter = /*@__PURE__*/Facet.define(); - const transactionExtender = /*@__PURE__*/Facet.define(); - const readOnly = /*@__PURE__*/Facet.define({ - combine: values => values.length ? values[0] : false - }); + 4. loadInterpreter(): start downloading the actual interpreter (e.g. pyodide.js) - /** - Annotations are tagged values that are used to add metadata to - transactions in an extensible way. They should be used to model - things that effect the entire transaction (such as its [time - stamp](https://codemirror.net/6/docs/ref/#state.Transaction^time) or information about its - [origin](https://codemirror.net/6/docs/ref/#state.Transaction^userEvent)). For effects that happen - _alongside_ the other changes made by the transaction, [state - effects](https://codemirror.net/6/docs/ref/#state.StateEffect) are more appropriate. - */ - class Annotation { - /** - @internal - */ - constructor( - /** - The annotation type. - */ - type, - /** - The value of this annotation. - */ - value) { - this.type = type; - this.value = value; - } - /** - Define a new type of annotation. - */ - static define() { return new AnnotationType(); } - } - /** - Marker that identifies a type of [annotation](https://codemirror.net/6/docs/ref/#state.Annotation). - */ - class AnnotationType { - /** - Create an instance of this annotation. - */ - of(value) { return new Annotation(this, value); } - } - /** - Representation of a type of state effect. Defined with - [`StateEffect.define`](https://codemirror.net/6/docs/ref/#state.StateEffect^define). - */ - class StateEffectType { - /** - @internal - */ - constructor( - // The `any` types in these function types are there to work - // around TypeScript issue #37631, where the type guard on - // `StateEffect.is` mysteriously stops working when these properly - // have type `Value`. - /** - @internal - */ - map) { - this.map = map; - } - /** - Create a [state effect](https://codemirror.net/6/docs/ref/#state.StateEffect) instance of this - type. - */ - of(value) { return new StateEffect(this, value); } - } - /** - State effects can be used to represent additional effects - associated with a [transaction](https://codemirror.net/6/docs/ref/#state.Transaction.effects). They - are often useful to model changes to custom [state - fields](https://codemirror.net/6/docs/ref/#state.StateField), when those changes aren't implicit in - document or selection changes. - */ - class StateEffect { - /** - @internal - */ - constructor( - /** - @internal - */ - type, - /** - The value of this effect. - */ - value) { - this.type = type; - this.value = value; - } - /** - Map this effect through a position mapping. Will return - `undefined` when that ends up deleting the effect. - */ - map(mapping) { - let mapped = this.type.map(this.value, mapping); - return mapped === undefined ? undefined : mapped == this.value ? this : new StateEffect(this.type, mapped); - } - /** - Tells you whether this effect object is of a given - [type](https://codemirror.net/6/docs/ref/#state.StateEffectType). - */ - is(type) { return this.type == type; } - /** - Define a new effect type. The type parameter indicates the type - of values that his effect holds. - */ - static define(spec = {}) { - return new StateEffectType(spec.map || (v => v)); - } - /** - Map an array of effects through a change set. - */ - static mapEffects(effects, mapping) { - if (!effects.length) - return effects; - let result = []; - for (let effect of effects) { - let mapped = effect.map(mapping); - if (mapped) - result.push(mapped); - } - return result; - } - } - /** - This effect can be used to reconfigure the root extensions of - the editor. Doing this will discard any extensions - [appended](https://codemirror.net/6/docs/ref/#state.StateEffect^appendConfig), but does not reset - the content of [reconfigured](https://codemirror.net/6/docs/ref/#state.Compartment.reconfigure) - compartments. - */ - StateEffect.reconfigure = /*@__PURE__*/StateEffect.define(); - /** - Append extensions to the top-level configuration of the editor. - */ - StateEffect.appendConfig = /*@__PURE__*/StateEffect.define(); - /** - Changes to the editor state are grouped into transactions. - Typically, a user action creates a single transaction, which may - contain any number of document changes, may change the selection, - or have other effects. Create a transaction by calling - [`EditorState.update`](https://codemirror.net/6/docs/ref/#state.EditorState.update). - */ - class Transaction { - /** - @internal - */ - constructor( - /** - The state from which the transaction starts. - */ - startState, - /** - The document changes made by this transaction. - */ - changes, - /** - The selection set by this transaction, or undefined if it - doesn't explicitly set a selection. - */ - selection, - /** - The effects added to the transaction. - */ - effects, - /** - @internal - */ - annotations, - /** - Whether the selection should be scrolled into view after this - transaction is dispatched. - */ - scrollIntoView) { - this.startState = startState; - this.changes = changes; - this.selection = selection; - this.effects = effects; - this.annotations = annotations; - this.scrollIntoView = scrollIntoView; - /** - @internal - */ - this._doc = null; - /** - @internal - */ - this._state = null; - if (selection) - checkSelection(selection, changes.newLength); - if (!annotations.some((a) => a.type == Transaction.time)) - this.annotations = annotations.concat(Transaction.time.of(Date.now())); - } - /** - The new document produced by the transaction. Contrary to - [`.state`](https://codemirror.net/6/docs/ref/#state.Transaction.state)`.doc`, accessing this won't - force the entire new state to be computed right away, so it is - recommended that [transaction - filters](https://codemirror.net/6/docs/ref/#state.EditorState^transactionFilter) use this getter - when they need to look at the new document. - */ - get newDoc() { - return this._doc || (this._doc = this.changes.apply(this.startState.doc)); - } - /** - The new selection produced by the transaction. If - [`this.selection`](https://codemirror.net/6/docs/ref/#state.Transaction.selection) is undefined, - this will [map](https://codemirror.net/6/docs/ref/#state.EditorSelection.map) the start state's - current selection through the changes made by the transaction. - */ - get newSelection() { - return this.selection || this.startState.selection.map(this.changes); - } - /** - The new state created by the transaction. Computed on demand - (but retained for subsequent access), so itis recommended not to - access it in [transaction - filters](https://codemirror.net/6/docs/ref/#state.EditorState^transactionFilter) when possible. - */ - get state() { - if (!this._state) - this.startState.applyTransaction(this); - return this._state; - } - /** - Get the value of the given annotation type, if any. - */ - annotation(type) { - for (let ann of this.annotations) - if (ann.type == type) - return ann.value; - return undefined; - } - /** - Indicates whether the transaction changed the document. - */ - get docChanged() { return !this.changes.empty; } - /** - Indicates whether this transaction reconfigures the state - (through a [configuration compartment](https://codemirror.net/6/docs/ref/#state.Compartment) or - with a top-level configuration - [effect](https://codemirror.net/6/docs/ref/#state.StateEffect^reconfigure). - */ - get reconfigured() { return this.startState.config != this.state.config; } - /** - Returns true if the transaction has a [user - event](https://codemirror.net/6/docs/ref/#state.Transaction^userEvent) annotation that is equal to - or more specific than `event`. For example, if the transaction - has `"select.pointer"` as user event, `"select"` and - `"select.pointer"` will match it. - */ - isUserEvent(event) { - let e = this.annotation(Transaction.userEvent); - return !!(e && (e == event || e.length > event.length && e.slice(0, event.length) == event && e[event.length] == ".")); - } - } - /** - Annotation used to store transaction timestamps. - */ - Transaction.time = /*@__PURE__*/Annotation.define(); - /** - Annotation used to associate a transaction with a user interface - event. Holds a string identifying the event, using a - dot-separated format to support attaching more specific - information. The events used by the core libraries are: + --- wait until (4) has finished --- - - `"input"` when content is entered - - `"input.type"` for typed input - - `"input.type.compose"` for composition - - `"input.paste"` for pasted input - - `"input.drop"` when adding content with drag-and-drop - - `"input.complete"` when autocompleting - - `"delete"` when the user deletes content - - `"delete.selection"` when deleting the selection - - `"delete.forward"` when deleting forward from the selection - - `"delete.backward"` when deleting backward from the selection - - `"delete.cut"` when cutting to the clipboard - - `"move"` when content is moved - - `"move.drop"` when content is moved within the editor through drag-and-drop - - `"select"` when explicitly changing the selection - - `"select.pointer"` when selecting with a mouse or other pointing device - - `"undo"` and `"redo"` for history actions + 5. now the pyodide src is available. Initialize the engine - Use [`isUserEvent`](https://codemirror.net/6/docs/ref/#state.Transaction.isUserEvent) to check - whether the annotation matches a given event. - */ - Transaction.userEvent = /*@__PURE__*/Annotation.define(); - /** - Annotation indicating whether a transaction should be added to - the undo history or not. - */ - Transaction.addToHistory = /*@__PURE__*/Annotation.define(); - /** - Annotation indicating (when present and true) that a transaction - represents a change made by some other actor, not the user. This - is used, for example, to tag other people's changes in - collaborative editing. - */ - Transaction.remote = /*@__PURE__*/Annotation.define(); - function joinRanges(a, b) { - let result = []; - for (let iA = 0, iB = 0;;) { - let from, to; - if (iA < a.length && (iB == b.length || b[iB] >= a[iA])) { - from = a[iA++]; - to = a[iA++]; - } - else if (iB < b.length) { - from = b[iB++]; - to = b[iB++]; - } - else - return result; - if (!result.length || result[result.length - 1] < from) - result.push(from, to); - else if (result[result.length - 1] < to) - result[result.length - 1] = to; - } - } - function mergeTransaction(a, b, sequential) { - var _a; - let mapForA, mapForB, changes; - if (sequential) { - mapForA = b.changes; - mapForB = ChangeSet.empty(b.changes.length); - changes = a.changes.compose(b.changes); - } - else { - mapForA = b.changes.map(a.changes); - mapForB = a.changes.mapDesc(b.changes, true); - changes = a.changes.compose(mapForA); - } - return { - changes, - selection: b.selection ? b.selection.map(mapForB) : (_a = a.selection) === null || _a === void 0 ? void 0 : _a.map(mapForA), - effects: StateEffect.mapEffects(a.effects, mapForA).concat(StateEffect.mapEffects(b.effects, mapForB)), - annotations: a.annotations.length ? a.annotations.concat(b.annotations) : b.annotations, - scrollIntoView: a.scrollIntoView || b.scrollIntoView - }; - } - function resolveTransactionInner(state, spec, docSize) { - let sel = spec.selection, annotations = asArray$1(spec.annotations); - if (spec.userEvent) - annotations = annotations.concat(Transaction.userEvent.of(spec.userEvent)); - return { - changes: spec.changes instanceof ChangeSet ? spec.changes - : ChangeSet.of(spec.changes || [], docSize, state.facet(lineSeparator)), - selection: sel && (sel instanceof EditorSelection ? sel : EditorSelection.single(sel.anchor, sel.head)), - effects: asArray$1(spec.effects), - annotations, - scrollIntoView: !!spec.scrollIntoView - }; - } - function resolveTransaction(state, specs, filter) { - let s = resolveTransactionInner(state, specs.length ? specs[0] : {}, state.doc.length); - if (specs.length && specs[0].filter === false) - filter = false; - for (let i = 1; i < specs.length; i++) { - if (specs[i].filter === false) - filter = false; - let seq = !!specs[i].sequential; - s = mergeTransaction(s, resolveTransactionInner(state, specs[i], seq ? s.changes.newLength : state.doc.length), seq); - } - let tr = new Transaction(state, s.changes, s.selection, s.effects, s.annotations, s.scrollIntoView); - return extendTransaction(filter ? filterTransaction(tr) : tr); - } - // Finish a transaction by applying filters if necessary. - function filterTransaction(tr) { - let state = tr.startState; - // Change filters - let result = true; - for (let filter of state.facet(changeFilter)) { - let value = filter(tr); - if (value === false) { - result = false; - break; - } - if (Array.isArray(value)) - result = result === true ? value : joinRanges(result, value); - } - if (result !== true) { - let changes, back; - if (result === false) { - back = tr.changes.invertedDesc; - changes = ChangeSet.empty(state.doc.length); - } - else { - let filtered = tr.changes.filter(result); - changes = filtered.changes; - back = filtered.filtered.invertedDesc; - } - tr = new Transaction(state, changes, tr.selection && tr.selection.map(back), StateEffect.mapEffects(tr.effects, back), tr.annotations, tr.scrollIntoView); - } - // Transaction filters - let filters = state.facet(transactionFilter); - for (let i = filters.length - 1; i >= 0; i--) { - let filtered = filters[i](tr); - if (filtered instanceof Transaction) - tr = filtered; - else if (Array.isArray(filtered) && filtered.length == 1 && filtered[0] instanceof Transaction) - tr = filtered[0]; - else - tr = resolveTransaction(state, asArray$1(filtered), false); - } - return tr; - } - function extendTransaction(tr) { - let state = tr.startState, extenders = state.facet(transactionExtender), spec = tr; - for (let i = extenders.length - 1; i >= 0; i--) { - let extension = extenders[i](tr); - if (extension && Object.keys(extension).length) - spec = mergeTransaction(tr, resolveTransactionInner(state, extension, tr.changes.newLength), true); - } - return spec == tr ? tr : new Transaction(state, tr.changes, tr.selection, spec.effects, spec.annotations, spec.scrollIntoView); - } - const none$3 = []; - function asArray$1(value) { - return value == null ? none$3 : Array.isArray(value) ? value : [value]; - } + 6. setup the environment, install packages - /** - The categories produced by a [character - categorizer](https://codemirror.net/6/docs/ref/#state.EditorState.charCategorizer). These are used - do things like selecting by word. - */ - var CharCategory = /*@__PURE__*/(function (CharCategory) { - /** - Word characters. - */ - CharCategory[CharCategory["Word"] = 0] = "Word"; - /** - Whitespace. - */ - CharCategory[CharCategory["Space"] = 1] = "Space"; - /** - Anything else. - */ - CharCategory[CharCategory["Other"] = 2] = "Other"; - return CharCategory})(CharCategory || (CharCategory = {})); - const nonASCIISingleCaseWordChar = /[\u00df\u0587\u0590-\u05f4\u0600-\u06ff\u3040-\u309f\u30a0-\u30ff\u3400-\u4db5\u4e00-\u9fcc\uac00-\ud7af]/; - let wordChar; - try { - wordChar = /*@__PURE__*/new RegExp("[\\p{Alphabetic}\\p{Number}_]", "u"); - } - catch (_) { } - function hasWordChar(str) { - if (wordChar) - return wordChar.test(str); - for (let i = 0; i < str.length; i++) { - let ch = str[i]; - if (/\w/.test(ch) || ch > "\x80" && (ch.toUpperCase() != ch.toLowerCase() || nonASCIISingleCaseWordChar.test(ch))) - return true; - } - return false; - } - function makeCategorizer(wordChars) { - return (char) => { - if (!/\S/.test(char)) - return CharCategory.Space; - if (hasWordChar(char)) - return CharCategory.Word; - for (let i = 0; i < wordChars.length; i++) - if (char.indexOf(wordChars[i]) > -1) - return CharCategory.Word; - return CharCategory.Other; - }; - } + 6.5: call the Plugin.afterSetup() hook - /** - The editor state class is a persistent (immutable) data structure. - To update a state, you [create](https://codemirror.net/6/docs/ref/#state.EditorState.update) a - [transaction](https://codemirror.net/6/docs/ref/#state.Transaction), which produces a _new_ state - instance, without modifying the original object. + 7. connect the py-script web component. This causes the execution of all the + user scripts - As such, _never_ mutate properties of a state directly. That'll - just break things. - */ - class EditorState { - /** - @internal - */ - constructor( - /** - @internal - */ - config, - /** - The current document. - */ - doc, - /** - The current selection. - */ - selection, - /** - @internal - */ - values, computeSlot, tr) { - this.config = config; - this.doc = doc; - this.selection = selection; - this.values = values; - this.status = config.statusTemplate.slice(); - this.computeSlot = computeSlot; - // Fill in the computed state immediately, so that further queries - // for it made during the update return this state - if (tr) - tr._state = this; - for (let i = 0; i < this.config.dynamicSlots.length; i++) - ensureAddr(this, i << 1); - this.computeSlot = null; - } - field(field, require = true) { - let addr = this.config.address[field.id]; - if (addr == null) { - if (require) - throw new RangeError("Field is not present in this state"); - return undefined; - } - ensureAddr(this, addr); - return getAddr(this, addr); - } - /** - Create a [transaction](https://codemirror.net/6/docs/ref/#state.Transaction) that updates this - state. Any number of [transaction specs](https://codemirror.net/6/docs/ref/#state.TransactionSpec) - can be passed. Unless - [`sequential`](https://codemirror.net/6/docs/ref/#state.TransactionSpec.sequential) is set, the - [changes](https://codemirror.net/6/docs/ref/#state.TransactionSpec.changes) (if any) of each spec - are assumed to start in the _current_ document (not the document - produced by previous specs), and its - [selection](https://codemirror.net/6/docs/ref/#state.TransactionSpec.selection) and - [effects](https://codemirror.net/6/docs/ref/#state.TransactionSpec.effects) are assumed to refer - to the document created by its _own_ changes. The resulting - transaction contains the combined effect of all the different - specs. For [selection](https://codemirror.net/6/docs/ref/#state.TransactionSpec.selection), later - specs take precedence over earlier ones. - */ - update(...specs) { - return resolveTransaction(this, specs, true); - } - /** - @internal - */ - applyTransaction(tr) { - let conf = this.config, { base, compartments } = conf; - for (let effect of tr.effects) { - if (effect.is(Compartment.reconfigure)) { - if (conf) { - compartments = new Map; - conf.compartments.forEach((val, key) => compartments.set(key, val)); - conf = null; - } - compartments.set(effect.value.compartment, effect.value.extension); - } - else if (effect.is(StateEffect.reconfigure)) { - conf = null; - base = effect.value; - } - else if (effect.is(StateEffect.appendConfig)) { - conf = null; - base = asArray$1(base).concat(effect.value); - } - } - let startValues; - if (!conf) { - conf = Configuration.resolve(base, compartments, this); - let intermediateState = new EditorState(conf, this.doc, this.selection, conf.dynamicSlots.map(() => null), (state, slot) => slot.reconfigure(state, this), null); - startValues = intermediateState.values; - } - else { - startValues = tr.startState.values.slice(); - } - new EditorState(conf, tr.newDoc, tr.newSelection, startValues, (state, slot) => slot.update(state, tr), tr); - } - /** - Create a [transaction spec](https://codemirror.net/6/docs/ref/#state.TransactionSpec) that - replaces every selection range with the given content. - */ - replaceSelection(text) { - if (typeof text == "string") - text = this.toText(text); - return this.changeByRange(range => ({ changes: { from: range.from, to: range.to, insert: text }, - range: EditorSelection.cursor(range.from + text.length) })); - } - /** - Create a set of changes and a new selection by running the given - function for each range in the active selection. The function - can return an optional set of changes (in the coordinate space - of the start document), plus an updated range (in the coordinate - space of the document produced by the call's own changes). This - method will merge all the changes and ranges into a single - changeset and selection, and return it as a [transaction - spec](https://codemirror.net/6/docs/ref/#state.TransactionSpec), which can be passed to - [`update`](https://codemirror.net/6/docs/ref/#state.EditorState.update). - */ - changeByRange(f) { - let sel = this.selection; - let result1 = f(sel.ranges[0]); - let changes = this.changes(result1.changes), ranges = [result1.range]; - let effects = asArray$1(result1.effects); - for (let i = 1; i < sel.ranges.length; i++) { - let result = f(sel.ranges[i]); - let newChanges = this.changes(result.changes), newMapped = newChanges.map(changes); - for (let j = 0; j < i; j++) - ranges[j] = ranges[j].map(newMapped); - let mapBy = changes.mapDesc(newChanges, true); - ranges.push(result.range.map(mapBy)); - changes = changes.compose(newMapped); - effects = StateEffect.mapEffects(effects, newMapped).concat(StateEffect.mapEffects(asArray$1(result.effects), mapBy)); - } - return { - changes, - selection: EditorSelection.create(ranges, sel.mainIndex), - effects - }; - } - /** - Create a [change set](https://codemirror.net/6/docs/ref/#state.ChangeSet) from the given change - description, taking the state's document length and line - separator into account. - */ - changes(spec = []) { - if (spec instanceof ChangeSet) - return spec; - return ChangeSet.of(spec, this.doc.length, this.facet(EditorState.lineSeparator)); - } - /** - Using the state's [line - separator](https://codemirror.net/6/docs/ref/#state.EditorState^lineSeparator), create a - [`Text`](https://codemirror.net/6/docs/ref/#text.Text) instance from the given string. - */ - toText(string) { - return Text.of(string.split(this.facet(EditorState.lineSeparator) || DefaultSplit)); - } - /** - Return the given range of the document as a string. - */ - sliceDoc(from = 0, to = this.doc.length) { - return this.doc.sliceString(from, to, this.lineBreak); - } - /** - Get the value of a state [facet](https://codemirror.net/6/docs/ref/#state.Facet). - */ - facet(facet) { - let addr = this.config.address[facet.id]; - if (addr == null) - return facet.default; - ensureAddr(this, addr); - return getAddr(this, addr); - } - /** - Convert this state to a JSON-serializable object. When custom - fields should be serialized, you can pass them in as an object - mapping property names (in the resulting object, which should - not use `doc` or `selection`) to fields. - */ - toJSON(fields) { - let result = { - doc: this.sliceDoc(), - selection: this.selection.toJSON() - }; - if (fields) - for (let prop in fields) { - let value = fields[prop]; - if (value instanceof StateField) - result[prop] = value.spec.toJSON(this.field(fields[prop]), this); - } - return result; - } - /** - Deserialize a state from its JSON representation. When custom - fields should be deserialized, pass the same object you passed - to [`toJSON`](https://codemirror.net/6/docs/ref/#state.EditorState.toJSON) when serializing as - third argument. - */ - static fromJSON(json, config = {}, fields) { - if (!json || typeof json.doc != "string") - throw new RangeError("Invalid JSON representation for EditorState"); - let fieldInit = []; - if (fields) - for (let prop in fields) { - let field = fields[prop], value = json[prop]; - fieldInit.push(field.init(state => field.spec.fromJSON(value, state))); - } - return EditorState.create({ - doc: json.doc, - selection: EditorSelection.fromJSON(json.selection), - extensions: config.extensions ? fieldInit.concat([config.extensions]) : fieldInit - }); - } - /** - Create a new state. You'll usually only need this when - initializing an editor—updated states are created by applying - transactions. - */ - static create(config = {}) { - let configuration = Configuration.resolve(config.extensions || [], new Map); - let doc = config.doc instanceof Text ? config.doc - : Text.of((config.doc || "").split(configuration.staticFacet(EditorState.lineSeparator) || DefaultSplit)); - let selection = !config.selection ? EditorSelection.single(0) - : config.selection instanceof EditorSelection ? config.selection - : EditorSelection.single(config.selection.anchor, config.selection.head); - checkSelection(selection, doc.length); - if (!configuration.staticFacet(allowMultipleSelections)) - selection = selection.asSingle(); - return new EditorState(configuration, doc, selection, configuration.dynamicSlots.map(() => null), (state, slot) => slot.create(state), null); - } - /** - The size (in columns) of a tab in the document, determined by - the [`tabSize`](https://codemirror.net/6/docs/ref/#state.EditorState^tabSize) facet. - */ - get tabSize() { return this.facet(EditorState.tabSize); } - /** - Get the proper [line-break](https://codemirror.net/6/docs/ref/#state.EditorState^lineSeparator) - string for this state. - */ - get lineBreak() { return this.facet(EditorState.lineSeparator) || "\n"; } - /** - Returns true when the editor is - [configured](https://codemirror.net/6/docs/ref/#state.EditorState^readOnly) to be read-only. - */ - get readOnly() { return this.facet(readOnly); } - /** - Look up a translation for the given phrase (via the - [`phrases`](https://codemirror.net/6/docs/ref/#state.EditorState^phrases) facet), or return the - original string if no translation is found. - */ - phrase(phrase) { - for (let map of this.facet(EditorState.phrases)) - if (Object.prototype.hasOwnProperty.call(map, phrase)) - return map[phrase]; - return phrase; - } - /** - Find the values for a given language data field, provided by the - the [`languageData`](https://codemirror.net/6/docs/ref/#state.EditorState^languageData) facet. - */ - languageDataAt(name, pos, side = -1) { - let values = []; - for (let provider of this.facet(languageData)) { - for (let result of provider(this, pos, side)) { - if (Object.prototype.hasOwnProperty.call(result, name)) - values.push(result[name]); - } - } - return values; - } - /** - Return a function that can categorize strings (expected to - represent a single [grapheme cluster](https://codemirror.net/6/docs/ref/#text.findClusterBreak)) - into one of: - - - Word (contains an alphanumeric character or a character - explicitly listed in the local language's `"wordChars"` - language data, which should be a string) - - Space (contains only whitespace) - - Other (anything else) - */ - charCategorizer(at) { - return makeCategorizer(this.languageDataAt("wordChars", at).join("")); - } - /** - Find the word at the given position, meaning the range - containing all [word](https://codemirror.net/6/docs/ref/#state.CharCategory.Word) characters - around it. If no word characters are adjacent to the position, - this returns null. - */ - wordAt(pos) { - let { text, from, length } = this.doc.lineAt(pos); - let cat = this.charCategorizer(pos); - let start = pos - from, end = pos - from; - while (start > 0) { - let prev = findClusterBreak(text, start, false); - if (cat(text.slice(prev, start)) != CharCategory.Word) - break; - start = prev; - } - while (end < length) { - let next = findClusterBreak(text, end); - if (cat(text.slice(end, next)) != CharCategory.Word) - break; - end = next; - } - return start == end ? null : EditorSelection.range(start + from, end + from); - } - } - /** - A facet that, when enabled, causes the editor to allow multiple - ranges to be selected. Be careful though, because by default the - editor relies on the native DOM selection, which cannot handle - multiple selections. An extension like - [`drawSelection`](https://codemirror.net/6/docs/ref/#view.drawSelection) can be used to make - secondary selections visible to the user. - */ - EditorState.allowMultipleSelections = allowMultipleSelections; - /** - Configures the tab size to use in this state. The first - (highest-precedence) value of the facet is used. If no value is - given, this defaults to 4. - */ - EditorState.tabSize = /*@__PURE__*/Facet.define({ - combine: values => values.length ? values[0] : 4 - }); - /** - The line separator to use. By default, any of `"\n"`, `"\r\n"` - and `"\r"` is treated as a separator when splitting lines, and - lines are joined with `"\n"`. + 8. initialize the rest of web components such as py-button, py-repl, etc. - When you configure a value here, only that precise separator - will be used, allowing you to round-trip documents through the - editor without normalizing line separators. - */ - EditorState.lineSeparator = lineSeparator; - /** - This facet controls the value of the - [`readOnly`](https://codemirror.net/6/docs/ref/#state.EditorState.readOnly) getter, which is - consulted by commands and extensions that implement editing - functionality to determine whether they should apply. It - defaults to false, but when its highest-precedence value is - `true`, such functionality disables itself. + More concretely: - Not to be confused with - [`EditorView.editable`](https://codemirror.net/6/docs/ref/#view.EditorView^editable), which - controls whether the editor's DOM is set to be editable (and - thus focusable). - */ - EditorState.readOnly = readOnly; - /** - Registers translation phrases. The - [`phrase`](https://codemirror.net/6/docs/ref/#state.EditorState.phrase) method will look through - all objects registered with this facet to find translations for - its argument. - */ - EditorState.phrases = /*@__PURE__*/Facet.define(); - /** - A facet used to register [language - data](https://codemirror.net/6/docs/ref/#state.EditorState.languageDataAt) providers. - */ - EditorState.languageData = languageData; - /** - Facet used to register change filters, which are called for each - transaction (unless explicitly - [disabled](https://codemirror.net/6/docs/ref/#state.TransactionSpec.filter)), and can suppress - part of the transaction's changes. + - Points 1-4 are implemented sequentially in PyScriptApp.main(). - Such a function can return `true` to indicate that it doesn't - want to do anything, `false` to completely stop the changes in - the transaction, or a set of ranges in which changes should be - suppressed. Such ranges are represented as an array of numbers, - with each pair of two number indicating the start and end of a - range. So for example `[10, 20, 100, 110]` suppresses changes - between 10 and 20, and between 100 and 110. - */ - EditorState.changeFilter = changeFilter; - /** - Facet used to register a hook that gets a chance to update or - replace transaction specs before they are applied. This will - only be applied for transactions that don't have - [`filter`](https://codemirror.net/6/docs/ref/#state.TransactionSpec.filter) set to `false`. You - can either return a single transaction spec (possibly the input - transaction), or an array of specs (which will be combined in - the same way as the arguments to - [`EditorState.update`](https://codemirror.net/6/docs/ref/#state.EditorState.update)). + - PyScriptApp.loadInterpreter adds a <script> tag to the document to initiate + the download, and then adds an event listener for the 'load' event, which + in turns calls PyScriptApp.afterInterpreterLoad(). - When possible, it is recommended to avoid accessing - [`Transaction.state`](https://codemirror.net/6/docs/ref/#state.Transaction.state) in a filter, - since it will force creation of a state that will then be - discarded again, if the transaction is actually filtered. - - (This functionality should be used with care. Indiscriminately - modifying transaction is likely to break something or degrade - the user experience.) - */ - EditorState.transactionFilter = transactionFilter; - /** - This is a more limited form of - [`transactionFilter`](https://codemirror.net/6/docs/ref/#state.EditorState^transactionFilter), - which can only add - [annotations](https://codemirror.net/6/docs/ref/#state.TransactionSpec.annotations) and - [effects](https://codemirror.net/6/docs/ref/#state.TransactionSpec.effects). _But_, this type - of filter runs even the transaction has disabled regular - [filtering](https://codemirror.net/6/docs/ref/#state.TransactionSpec.filter), making it suitable - for effects that don't need to touch the changes or selection, - but do want to process every transaction. - - Extenders run _after_ filters, when both are applied. - */ - EditorState.transactionExtender = transactionExtender; - Compartment.reconfigure = /*@__PURE__*/StateEffect.define(); - - /** - Utility function for combining behaviors to fill in a config - object from an array of provided configs. Will, by default, error - when a field gets two values that aren't `===`-equal, but you can - provide combine functions per field to do something else. - */ - function combineConfig(configs, defaults, // Should hold only the optional properties of Config, but I haven't managed to express that - combine = {}) { - let result = {}; - for (let config of configs) - for (let key of Object.keys(config)) { - let value = config[key], current = result[key]; - if (current === undefined) - result[key] = value; - else if (current === value || value === undefined) ; // No conflict - else if (Object.hasOwnProperty.call(combine, key)) - result[key] = combine[key](current, value); - else - throw new Error("Config merge conflict for field " + key); - } - for (let key in defaults) - if (result[key] === undefined) - result[key] = defaults[key]; - return result; - } - - const C = "\u037c"; - const COUNT = typeof Symbol == "undefined" ? "__" + C : Symbol.for(C); - const SET = typeof Symbol == "undefined" ? "__styleSet" + Math.floor(Math.random() * 1e8) : Symbol("styleSet"); - const top = typeof globalThis != "undefined" ? globalThis : typeof window != "undefined" ? window : {}; - - // :: - Style modules encapsulate a set of CSS rules defined from - // JavaScript. Their definitions are only available in a given DOM - // root after it has been _mounted_ there with `StyleModule.mount`. - // - // Style modules should be created once and stored somewhere, as - // opposed to re-creating them every time you need them. The amount of - // CSS rules generated for a given DOM root is bounded by the amount - // of style modules that were used. So to avoid leaking rules, don't - // create these dynamically, but treat them as one-time allocations. - class StyleModule { - // :: (Object<Style>, ?{finish: ?(string) → string}) - // Create a style module from the given spec. + - PyScriptApp.afterInterpreterLoad() implements all the points >= 5. + */ + class PyScriptApp { + constructor() { + // initialize the builtin plugins + this.plugins = new PluginManager(); + this.plugins.add(new SplashscreenPlugin(), new PyTerminalPlugin(this), new ImportmapPlugin()); + this._stdioMultiplexer = new StdioMultiplexer(); + this._stdioMultiplexer.addListener(DEFAULT_STDIO); + this.plugins.add(new StdioDirector(this._stdioMultiplexer)); + this.tagExecutionLock = createLock(); + } + // Error handling logic: if during the execution we encounter an error + // which is ultimate responsibility of the user (e.g.: syntax error in the + // config, file not found in fetch, etc.), we can throw UserError(). It is + // responsibility of main() to catch it and show it to the user in a + // proper way (e.g. by using a banner at the top of the page). + main() { + try { + this._realMain(); + } + catch (error) { + this._handleUserErrorMaybe(error); + } + } + _handleUserErrorMaybe(error) { + if (error instanceof UserError) { + _createAlertBanner(error.message, 'error', error.messageType); + this.plugins.onUserError(error); + } + else { + throw error; + } + } + // ============ lifecycle ============ + // lifecycle (1) + _realMain() { + this.loadConfig(); + this.plugins.configure(this.config); + this.plugins.beforeLaunch(this.config); + this.loadInterpreter(); + } + // lifecycle (2) + loadConfig() { + // find the <py-config> tag. If not found, we get null which means + // "use the default config" + // XXX: we should actively complain if there are multiple <py-config> + // and show a big error. PRs welcome :) + logger.info('searching for <py-config>'); + const elements = document.getElementsByTagName('py-config'); + let el = null; + if (elements.length > 0) + el = elements[0]; + if (elements.length >= 2) { + showWarning('Multiple <py-config> tags detected. Only the first is ' + + 'going to be parsed, all the others will be ignored'); + } + this.config = loadConfigFromElement(el); + logger.info('config loaded:\n' + JSON.stringify(this.config, null, 2)); + } + // lifecycle (4) + loadInterpreter() { + logger.info('Initializing interpreter'); + if (this.config.interpreters.length == 0) { + throw new UserError(ErrorCode.BAD_CONFIG, 'Fatal error: config.interpreter is empty'); + } + if (this.config.interpreters.length > 1) { + showWarning('Multiple interpreters are not supported yet.<br />Only the first will be used', 'html'); + } + const interpreter_cfg = this.config.interpreters[0]; + this.interpreter = new InterpreterClient(this.config, this._stdioMultiplexer); + this.logStatus(`Downloading ${interpreter_cfg.name}...`); + // download pyodide by using a <script> tag. Once it's ready, the + // "load" event will be fired and the exeuction logic will continue. + // Note that the load event is fired asynchronously and thus any + // exception which is throw inside the event handler is *NOT* caught + // by the try/catch inside main(): that's why we need to .catch() it + // explicitly and call _handleUserErrorMaybe also there. + const script = document.createElement('script'); // create a script DOM node + script.src = this.interpreter._remote.src; + script.addEventListener('load', () => { + this.afterInterpreterLoad(this.interpreter).catch(error => { + this._handleUserErrorMaybe(error); + }); + }); + document.head.appendChild(script); + } + // lifecycle (5) + // See the overview comment above for an explanation of how we jump from + // point (4) to point (5). // - // When `finish` is given, it is called on regular (non-`@`) - // selectors (after `&` expansion) to compute the final selector. - constructor(spec, options) { - this.rules = []; - let {finish} = options || {}; - - function splitSelector(selector) { - return /^@/.test(selector) ? [selector] : selector.split(/,\s*/) - } - - function render(selectors, spec, target, isKeyframes) { - let local = [], isAt = /^@(\w+)\b/.exec(selectors[0]), keyframes = isAt && isAt[1] == "keyframes"; - if (isAt && spec == null) return target.push(selectors[0] + ";") - for (let prop in spec) { - let value = spec[prop]; - if (/&/.test(prop)) { - render(prop.split(/,\s*/).map(part => selectors.map(sel => part.replace(/&/, sel))).reduce((a, b) => a.concat(b)), - value, target); - } else if (value && typeof value == "object") { - if (!isAt) throw new RangeError("The value of a property (" + prop + ") should be a primitive value.") - render(splitSelector(prop), value, local, keyframes); - } else if (value != null) { - local.push(prop.replace(/_.*/, "").replace(/[A-Z]/g, l => "-" + l.toLowerCase()) + ": " + value + ";"); - } + // Invariant: this.config is set and available. + async afterInterpreterLoad(interpreter) { + console.assert(this.config !== undefined); + this.logStatus('Python startup...'); + await this.interpreter.initializeRemote(); + this.logStatus('Python ready!'); + this.logStatus('Setting up virtual environment...'); + await this.setupVirtualEnv(interpreter); + await mountElements(interpreter); + // lifecycle (6.5) + this.plugins.afterSetup(interpreter); + //Refresh module cache in case plugins have modified the filesystem + interpreter._remote.invalidate_module_path_cache(); + this.logStatus('Executing <py-script> tags...'); + this.executeScripts(interpreter); + this.logStatus('Initializing web components...'); + // lifecycle (8) + createCustomElements(interpreter); + initHandlers(interpreter); + // NOTE: interpreter message is used by integration tests to know that + // pyscript initialization has complete. If you change it, you need to + // change it also in tests/integration/support.py + this.logStatus('Startup complete'); + this.plugins.afterStartup(interpreter); + logger.info('PyScript page fully initialized'); + } + // lifecycle (6) + async setupVirtualEnv(interpreter) { + // XXX: maybe the following calls could be parallelized, instead of + // await()ing immediately. For now I'm using await to be 100% + // compatible with the old behavior. + logger.info('importing pyscript'); + // Save and load pyscript.py from FS + interpreter._remote.interface.FS.mkdirTree('/home/pyodide/pyscript'); + interpreter._remote.interface.FS.writeFile('pyscript/__init__.py', pyscript); + //Refresh the module cache so Python consistently finds pyscript module + interpreter._remote.invalidate_module_path_cache(); + // inject `define_custom_element` and showWarning it into the PyScript + // module scope + const pyscript_module = interpreter._remote.interface.pyimport('pyscript'); + pyscript_module.define_custom_element = define_custom_element; + pyscript_module.showWarning = showWarning; + pyscript_module._set_version_info(version); + pyscript_module.destroy(); + // import some carefully selected names into the global namespace + await interpreter.run(` + import js + import pyscript + from pyscript import Element, display, HTML + pyscript._install_deprecated_globals_2022_12_1(globals()) + `); + if (this.config.packages) { + logger.info('Packages to install: ', this.config.packages); + await interpreter._remote.installPackage(this.config.packages); } - if (local.length || keyframes) { - target.push((finish && !isAt && !isKeyframes ? selectors.map(finish) : selectors).join(", ") + - " {" + local.join(" ") + "}"); + await this.fetchPaths(interpreter); + //This may be unnecessary - only useful if plugins try to import files fetch'd in fetchPaths() + interpreter._remote.invalidate_module_path_cache(); + // Finally load plugins + await this.fetchUserPlugins(interpreter); + } + async fetchPaths(interpreter) { + // XXX this can be VASTLY improved: for each path we need to fetch a + // URL and write to the virtual filesystem: pyodide.loadFromFile does + // it in Python, which means we need to have the interpreter + // initialized. But we could easily do it in JS in parallel with the + // download/startup of pyodide. + const [paths, fetchPaths] = calculatePaths(this.config.fetch); + logger.info('Paths to write: ', paths); + logger.info('Paths to fetch: ', fetchPaths); + for (let i = 0; i < paths.length; i++) { + logger.info(` fetching path: ${fetchPaths[i]}`); + // Exceptions raised from here will create an alert banner + await interpreter._remote.loadFromFile(paths[i], fetchPaths[i]); } - } - - for (let prop in spec) render(splitSelector(prop), spec[prop], this.rules); + logger.info('All paths fetched'); } - - // :: () → string - // Returns a string containing the module's CSS rules. - getRules() { return this.rules.join("\n") } - - // :: () → string - // Generate a new unique CSS class name. - static newName() { - let id = top[COUNT] || 1; - top[COUNT] = id + 1; - return C + id.toString(36) - } - - // :: (union<Document, ShadowRoot>, union<[StyleModule], StyleModule>) - // - // Mount the given set of modules in the given DOM root, which ensures - // that the CSS rules defined by the module are available in that - // context. - // - // Rules are only added to the document once per root. - // - // Rule order will follow the order of the modules, so that rules from - // modules later in the array take precedence of those from earlier - // modules. If you call this function multiple times for the same root - // in a way that changes the order of already mounted modules, the old - // order will be changed. - static mount(root, modules) { - (root[SET] || new StyleSet(root)).mount(Array.isArray(modules) ? modules : [modules]); - } - } - - let adoptedSet = null; - - class StyleSet { - constructor(root) { - if (!root.head && root.adoptedStyleSheets && typeof CSSStyleSheet != "undefined") { - if (adoptedSet) { - root.adoptedStyleSheets = [adoptedSet.sheet].concat(root.adoptedStyleSheets); - return root[SET] = adoptedSet + /** + * Fetch user plugins and adds them to `this.plugins` so they can + * be loaded by the PluginManager. Currently, we are just looking + * for .py and .js files and calling the appropriate methods. + * + * @param interpreter - the interpreter that will be used to execute the plugins that need it. + */ + async fetchUserPlugins(interpreter) { + const plugins = this.config.plugins; + logger.info('Plugins to fetch: ', plugins); + for (const singleFile of plugins) { + logger.info(` fetching plugins: ${singleFile}`); + if (singleFile.endsWith('.py')) { + await this.fetchPythonPlugin(interpreter, singleFile); + } + else if (singleFile.endsWith('.js')) { + await this.fetchJSPlugin(singleFile); + } + else { + throw new UserError(ErrorCode.BAD_PLUGIN_FILE_EXTENSION, `Unable to load plugin from '${singleFile}'. ` + + `Plugins need to contain a file extension and be ` + + `either a python or javascript file.`); + } + logger.info('All plugins fetched'); } - this.sheet = new CSSStyleSheet; - root.adoptedStyleSheets = [this.sheet].concat(root.adoptedStyleSheets); - adoptedSet = this; - } else { - this.styleTag = (root.ownerDocument || root).createElement("style"); - let target = root.head || root; - target.insertBefore(this.styleTag, target.firstChild); - } - this.modules = []; - root[SET] = this; } - - mount(modules) { - let sheet = this.sheet; - let pos = 0 /* Current rule offset */, j = 0; /* Index into this.modules */ - for (let i = 0; i < modules.length; i++) { - let mod = modules[i], index = this.modules.indexOf(mod); - if (index < j && index > -1) { // Ordering conflict - this.modules.splice(index, 1); - j--; - index = -1; + /** + * Fetch a javascript plugin from a filePath, it gets a blob from the + * fetch and creates a file from it, then we create a URL from the file + * so we can import it as a module. + * + * This allow us to instantiate the imported plugin with the default + * export in the module (the plugin class) and add it to the plugins + * list with `new importedPlugin()`. + * + * @param filePath - URL of the javascript file to fetch. + */ + async fetchJSPlugin(filePath) { + const pluginBlob = await (await robustFetch(filePath)).blob(); + const blobFile = new File([pluginBlob], 'plugin.js', { type: 'text/javascript' }); + const fileUrl = URL.createObjectURL(blobFile); + const module = await import(fileUrl); + // Note: We have to put module.default in a variable + // because we have seen weird behaviour when doing + // new module.default() directly. + const importedPlugin = module.default; + // If the imported plugin doesn't have a default export + // it will be undefined, so we throw a user error, so + // an alter banner will be created. + if (importedPlugin === undefined) { + throw new UserError(ErrorCode.NO_DEFAULT_EXPORT, `Unable to load plugin from '${filePath}'. ` + `Plugins need to contain a default export.`); } - if (index == -1) { - this.modules.splice(j++, 0, mod); - if (sheet) for (let k = 0; k < mod.rules.length; k++) - sheet.insertRule(mod.rules[k], pos++); - } else { - while (j < index) pos += this.modules[j++].rules.length; - pos += mod.rules.length; - j++; + else { + this.plugins.add(new importedPlugin()); } - } - - if (!sheet) { - let text = ""; - for (let i = 0; i < this.modules.length; i++) - text += this.modules[i].getRules() + "\n"; - this.styleTag.textContent = text; - } } - } - - // Style::Object<union<Style,string>> - // - // A style is an object that, in the simple case, maps CSS property - // names to strings holding their values, as in `{color: "red", - // fontWeight: "bold"}`. The property names can be given in - // camel-case—the library will insert a dash before capital letters - // when converting them to CSS. - // - // If you include an underscore in a property name, it and everything - // after it will be removed from the output, which can be useful when - // providing a property multiple times, for browser compatibility - // reasons. - // - // A property in a style object can also be a sub-selector, which - // extends the current context to add a pseudo-selector or a child - // selector. Such a property should contain a `&` character, which - // will be replaced by the current selector. For example `{"&:before": - // {content: '"hi"'}}`. Sub-selectors and regular properties can - // freely be mixed in a given object. Any property containing a `&` is - // assumed to be a sub-selector. - // - // Finally, a property can specify an @-block to be wrapped around the - // styles defined inside the object that's the property's value. For - // example to create a media query you can do `{"@media screen and - // (min-width: 400px)": {...}}`. - - /** - Each range is associated with a value, which must inherit from - this class. - */ - class RangeValue { - /** - Compare this value with another value. The default - implementation compares by identity. - */ - eq(other) { return this == other; } - /** - Create a [range](https://codemirror.net/6/docs/ref/#rangeset.Range) with this value. - */ - range(from, to = from) { return new Range$1(from, to, this); } - } - RangeValue.prototype.startSide = RangeValue.prototype.endSide = 0; - RangeValue.prototype.point = false; - RangeValue.prototype.mapMode = MapMode.TrackDel; - /** - A range associates a value with a range of positions. - */ - class Range$1 { - /** - @internal - */ - constructor( - /** - The range's start position. - */ - from, - /** - Its end position. - */ - to, - /** - The value associated with this range. - */ - value) { - this.from = from; - this.to = to; - this.value = value; - } - } - function cmpRange(a, b) { - return a.from - b.from || a.value.startSide - b.value.startSide; - } - class Chunk { - constructor(from, to, value, - // Chunks are marked with the largest point that occurs - // in them (or -1 for no points), so that scans that are - // only interested in points (such as the - // heightmap-related logic) can skip range-only chunks. - maxPoint) { - this.from = from; - this.to = to; - this.value = value; - this.maxPoint = maxPoint; - } - get length() { return this.to[this.to.length - 1]; } - // Find the index of the given position and side. Use the ranges' - // `from` pos when `end == false`, `to` when `end == true`. - findIndex(pos, side, end, startAt = 0) { - let arr = end ? this.to : this.from; - for (let lo = startAt, hi = arr.length;;) { - if (lo == hi) - return lo; - let mid = (lo + hi) >> 1; - let diff = arr[mid] - pos || (end ? this.value[mid].endSide : this.value[mid].startSide) - side; - if (mid == lo) - return diff >= 0 ? lo : hi; - if (diff >= 0) - hi = mid; - else - lo = mid + 1; - } - } - between(offset, from, to, f) { - for (let i = this.findIndex(from, -1000000000 /* Far */, true), e = this.findIndex(to, 1000000000 /* Far */, false, i); i < e; i++) - if (f(this.from[i] + offset, this.to[i] + offset, this.value[i]) === false) - return false; - } - map(offset, changes) { - let value = [], from = [], to = [], newPos = -1, maxPoint = -1; - for (let i = 0; i < this.value.length; i++) { - let val = this.value[i], curFrom = this.from[i] + offset, curTo = this.to[i] + offset, newFrom, newTo; - if (curFrom == curTo) { - let mapped = changes.mapPos(curFrom, val.startSide, val.mapMode); - if (mapped == null) - continue; - newFrom = newTo = mapped; - if (val.startSide != val.endSide) { - newTo = changes.mapPos(curFrom, val.endSide); - if (newTo < newFrom) - continue; - } - } - else { - newFrom = changes.mapPos(curFrom, val.startSide); - newTo = changes.mapPos(curTo, val.endSide); - if (newFrom > newTo || newFrom == newTo && val.startSide > 0 && val.endSide <= 0) - continue; - } - if ((newTo - newFrom || val.endSide - val.startSide) < 0) - continue; - if (newPos < 0) - newPos = newFrom; - if (val.point) - maxPoint = Math.max(maxPoint, newTo - newFrom); - value.push(val); - from.push(newFrom - newPos); - to.push(newTo - newPos); - } - return { mapped: value.length ? new Chunk(from, to, value, maxPoint) : null, pos: newPos }; - } - } - /** - A range set stores a collection of [ranges](https://codemirror.net/6/docs/ref/#rangeset.Range) in a - way that makes them efficient to [map](https://codemirror.net/6/docs/ref/#rangeset.RangeSet.map) and - [update](https://codemirror.net/6/docs/ref/#rangeset.RangeSet.update). This is an immutable data - structure. - */ - class RangeSet { - /** - @internal - */ - constructor( - /** - @internal - */ - chunkPos, - /** - @internal - */ - chunk, - /** - @internal - */ - nextLayer = RangeSet.empty, - /** - @internal - */ - maxPoint) { - this.chunkPos = chunkPos; - this.chunk = chunk; - this.nextLayer = nextLayer; - this.maxPoint = maxPoint; - } - /** - @internal - */ - get length() { - let last = this.chunk.length - 1; - return last < 0 ? 0 : Math.max(this.chunkEnd(last), this.nextLayer.length); - } - /** - The number of ranges in the set. - */ - get size() { - if (this.isEmpty) - return 0; - let size = this.nextLayer.size; - for (let chunk of this.chunk) - size += chunk.value.length; - return size; - } - /** - @internal - */ - chunkEnd(index) { - return this.chunkPos[index] + this.chunk[index].length; - } - /** - Update the range set, optionally adding new ranges or filtering - out existing ones. - - (The extra type parameter is just there as a kludge to work - around TypeScript variance issues that prevented `RangeSet<X>` - from being a subtype of `RangeSet<Y>` when `X` is a subtype of - `Y`.) - */ - update(updateSpec) { - let { add = [], sort = false, filterFrom = 0, filterTo = this.length } = updateSpec; - let filter = updateSpec.filter; - if (add.length == 0 && !filter) - return this; - if (sort) - add = add.slice().sort(cmpRange); - if (this.isEmpty) - return add.length ? RangeSet.of(add) : this; - let cur = new LayerCursor(this, null, -1).goto(0), i = 0, spill = []; - let builder = new RangeSetBuilder(); - while (cur.value || i < add.length) { - if (i < add.length && (cur.from - add[i].from || cur.startSide - add[i].value.startSide) >= 0) { - let range = add[i++]; - if (!builder.addInner(range.from, range.to, range.value)) - spill.push(range); - } - else if (cur.rangeIndex == 1 && cur.chunkIndex < this.chunk.length && - (i == add.length || this.chunkEnd(cur.chunkIndex) < add[i].from) && - (!filter || filterFrom > this.chunkEnd(cur.chunkIndex) || filterTo < this.chunkPos[cur.chunkIndex]) && - builder.addChunk(this.chunkPos[cur.chunkIndex], this.chunk[cur.chunkIndex])) { - cur.nextChunk(); - } - else { - if (!filter || filterFrom > cur.to || filterTo < cur.from || filter(cur.from, cur.to, cur.value)) { - if (!builder.addInner(cur.from, cur.to, cur.value)) - spill.push(new Range$1(cur.from, cur.to, cur.value)); - } - cur.next(); - } - } - return builder.finishInner(this.nextLayer.isEmpty && !spill.length ? RangeSet.empty - : this.nextLayer.update({ add: spill, filter, filterFrom, filterTo })); - } - /** - Map this range set through a set of changes, return the new set. - */ - map(changes) { - if (changes.empty || this.isEmpty) - return this; - let chunks = [], chunkPos = [], maxPoint = -1; - for (let i = 0; i < this.chunk.length; i++) { - let start = this.chunkPos[i], chunk = this.chunk[i]; - let touch = changes.touchesRange(start, start + chunk.length); - if (touch === false) { - maxPoint = Math.max(maxPoint, chunk.maxPoint); - chunks.push(chunk); - chunkPos.push(changes.mapPos(start)); - } - else if (touch === true) { - let { mapped, pos } = chunk.map(start, changes); - if (mapped) { - maxPoint = Math.max(maxPoint, mapped.maxPoint); - chunks.push(mapped); - chunkPos.push(pos); - } - } - } - let next = this.nextLayer.map(changes); - return chunks.length == 0 ? next : new RangeSet(chunkPos, chunks, next, maxPoint); - } - /** - Iterate over the ranges that touch the region `from` to `to`, - calling `f` for each. There is no guarantee that the ranges will - be reported in any specific order. When the callback returns - `false`, iteration stops. - */ - between(from, to, f) { - if (this.isEmpty) - return; - for (let i = 0; i < this.chunk.length; i++) { - let start = this.chunkPos[i], chunk = this.chunk[i]; - if (to >= start && from <= start + chunk.length && - chunk.between(start, from - start, to - start, f) === false) - return; - } - this.nextLayer.between(from, to, f); - } - /** - Iterate over the ranges in this set, in order, including all - ranges that end at or after `from`. - */ - iter(from = 0) { - return HeapCursor.from([this]).goto(from); - } - /** - @internal - */ - get isEmpty() { return this.nextLayer == this; } - /** - Iterate over the ranges in a collection of sets, in order, - starting from `from`. - */ - static iter(sets, from = 0) { - return HeapCursor.from(sets).goto(from); - } - /** - Iterate over two groups of sets, calling methods on `comparator` - to notify it of possible differences. - */ - static compare(oldSets, newSets, - /** - This indicates how the underlying data changed between these - ranges, and is needed to synchronize the iteration. `from` and - `to` are coordinates in the _new_ space, after these changes. - */ - textDiff, comparator, - /** - Can be used to ignore all non-point ranges, and points below - the given size. When -1, all ranges are compared. - */ - minPointSize = -1) { - let a = oldSets.filter(set => set.maxPoint > 0 || !set.isEmpty && set.maxPoint >= minPointSize); - let b = newSets.filter(set => set.maxPoint > 0 || !set.isEmpty && set.maxPoint >= minPointSize); - let sharedChunks = findSharedChunks(a, b, textDiff); - let sideA = new SpanCursor(a, sharedChunks, minPointSize); - let sideB = new SpanCursor(b, sharedChunks, minPointSize); - textDiff.iterGaps((fromA, fromB, length) => compare(sideA, fromA, sideB, fromB, length, comparator)); - if (textDiff.empty && textDiff.length == 0) - compare(sideA, 0, sideB, 0, 0, comparator); - } - /** - Compare the contents of two groups of range sets, returning true - if they are equivalent in the given range. - */ - static eq(oldSets, newSets, from = 0, to) { - if (to == null) - to = 1000000000 /* Far */; - let a = oldSets.filter(set => !set.isEmpty && newSets.indexOf(set) < 0); - let b = newSets.filter(set => !set.isEmpty && oldSets.indexOf(set) < 0); - if (a.length != b.length) - return false; - if (!a.length) - return true; - let sharedChunks = findSharedChunks(a, b); - let sideA = new SpanCursor(a, sharedChunks, 0).goto(from), sideB = new SpanCursor(b, sharedChunks, 0).goto(from); - for (;;) { - if (sideA.to != sideB.to || - !sameValues(sideA.active, sideB.active) || - sideA.point && (!sideB.point || !sideA.point.eq(sideB.point))) - return false; - if (sideA.to > to) - return true; - sideA.next(); - sideB.next(); - } - } - /** - Iterate over a group of range sets at the same time, notifying - the iterator about the ranges covering every given piece of - content. Returns the open count (see - [`SpanIterator.span`](https://codemirror.net/6/docs/ref/#rangeset.SpanIterator.span)) at the end - of the iteration. - */ - static spans(sets, from, to, iterator, - /** - When given and greater than -1, only points of at least this - size are taken into account. - */ - minPointSize = -1) { - var _a; - let cursor = new SpanCursor(sets, null, minPointSize, (_a = iterator.filterPoint) === null || _a === void 0 ? void 0 : _a.bind(iterator)).goto(from), pos = from; - let open = cursor.openStart; - for (;;) { - let curTo = Math.min(cursor.to, to); - if (cursor.point) { - iterator.point(pos, curTo, cursor.point, cursor.activeForPoint(cursor.to), open); - open = cursor.openEnd(curTo) + (cursor.to > curTo ? 1 : 0); - } - else if (curTo > pos) { - iterator.span(pos, curTo, cursor.active, open); - open = cursor.openEnd(curTo); - } - if (cursor.to > to) - break; - pos = cursor.to; - cursor.next(); - } - return open; - } - /** - Create a range set for the given range or array of ranges. By - default, this expects the ranges to be _sorted_ (by start - position and, if two start at the same position, - `value.startSide`). You can pass `true` as second argument to - cause the method to sort them. - */ - static of(ranges, sort = false) { - let build = new RangeSetBuilder(); - for (let range of ranges instanceof Range$1 ? [ranges] : sort ? lazySort(ranges) : ranges) - build.add(range.from, range.to, range.value); - return build.finish(); - } - } - /** - The empty set of ranges. - */ - RangeSet.empty = /*@__PURE__*/new RangeSet([], [], null, -1); - function lazySort(ranges) { - if (ranges.length > 1) - for (let prev = ranges[0], i = 1; i < ranges.length; i++) { - let cur = ranges[i]; - if (cmpRange(prev, cur) > 0) - return ranges.slice().sort(cmpRange); - prev = cur; - } - return ranges; - } - RangeSet.empty.nextLayer = RangeSet.empty; - /** - A range set builder is a data structure that helps build up a - [range set](https://codemirror.net/6/docs/ref/#rangeset.RangeSet) directly, without first allocating - an array of [`Range`](https://codemirror.net/6/docs/ref/#rangeset.Range) objects. - */ - class RangeSetBuilder { - /** - Create an empty builder. - */ - constructor() { - this.chunks = []; - this.chunkPos = []; - this.chunkStart = -1; - this.last = null; - this.lastFrom = -1000000000 /* Far */; - this.lastTo = -1000000000 /* Far */; - this.from = []; - this.to = []; - this.value = []; - this.maxPoint = -1; - this.setMaxPoint = -1; - this.nextLayer = null; - } - finishChunk(newArrays) { - this.chunks.push(new Chunk(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; - if (newArrays) { - this.from = []; - this.to = []; - this.value = []; - } - } - /** - Add a range. Ranges should be added in sorted (by `from` and - `value.startSide`) order. - */ - add(from, to, value) { - if (!this.addInner(from, to, value)) - (this.nextLayer || (this.nextLayer = new RangeSetBuilder)).add(from, to, value); - } - /** - @internal - */ - addInner(from, to, value) { - let diff = from - this.lastTo || value.startSide - this.last.endSide; - if (diff <= 0 && (from - this.lastFrom || value.startSide - this.last.startSide) < 0) - throw new Error("Ranges must be added sorted by `from` position and `startSide`"); - if (diff < 0) - return false; - if (this.from.length == 250 /* ChunkSize */) - this.finishChunk(true); - if (this.chunkStart < 0) - this.chunkStart = from; - this.from.push(from - this.chunkStart); - this.to.push(to - this.chunkStart); - this.last = value; - this.lastFrom = from; - this.lastTo = to; - this.value.push(value); - if (value.point) - this.maxPoint = Math.max(this.maxPoint, to - from); - return true; - } - /** - @internal - */ - addChunk(from, chunk) { - if ((from - this.lastTo || chunk.value[0].startSide - this.last.endSide) < 0) - return false; - if (this.from.length) - this.finishChunk(true); - this.setMaxPoint = Math.max(this.setMaxPoint, chunk.maxPoint); - this.chunks.push(chunk); - this.chunkPos.push(from); - let last = chunk.value.length - 1; - this.last = chunk.value[last]; - this.lastFrom = chunk.from[last] + from; - this.lastTo = chunk.to[last] + from; - return true; - } - /** - Finish the range set. Returns the new set. The builder can't be - used anymore after this has been called. - */ - finish() { return this.finishInner(RangeSet.empty); } - /** - @internal - */ - finishInner(next) { - if (this.from.length) - this.finishChunk(false); - if (this.chunks.length == 0) - return next; - let result = new RangeSet(this.chunkPos, this.chunks, this.nextLayer ? this.nextLayer.finishInner(next) : next, this.setMaxPoint); - this.from = null; // Make sure further `add` calls produce errors - return result; - } - } - function findSharedChunks(a, b, textDiff) { - let inA = new Map(); - for (let set of a) - for (let i = 0; i < set.chunk.length; i++) - if (set.chunk[i].maxPoint <= 0) - inA.set(set.chunk[i], set.chunkPos[i]); - let shared = new Set(); - for (let set of b) - for (let i = 0; i < set.chunk.length; i++) { - let known = inA.get(set.chunk[i]); - if (known != null && (textDiff ? textDiff.mapPos(known) : known) == set.chunkPos[i] && - !(textDiff === null || textDiff === void 0 ? void 0 : textDiff.touchesRange(known, known + set.chunk[i].length))) - shared.add(set.chunk[i]); - } - return shared; - } - class LayerCursor { - constructor(layer, skip, minPoint, rank = 0) { - this.layer = layer; - this.skip = skip; - this.minPoint = minPoint; - this.rank = rank; - } - get startSide() { return this.value ? this.value.startSide : 0; } - get endSide() { return this.value ? this.value.endSide : 0; } - goto(pos, side = -1000000000 /* Far */) { - this.chunkIndex = this.rangeIndex = 0; - this.gotoInner(pos, side, false); - return this; - } - gotoInner(pos, side, forward) { - while (this.chunkIndex < this.layer.chunk.length) { - let next = this.layer.chunk[this.chunkIndex]; - if (!(this.skip && this.skip.has(next) || - this.layer.chunkEnd(this.chunkIndex) < pos || - next.maxPoint < this.minPoint)) - break; - this.chunkIndex++; - forward = false; - } - if (this.chunkIndex < this.layer.chunk.length) { - let rangeIndex = this.layer.chunk[this.chunkIndex].findIndex(pos - this.layer.chunkPos[this.chunkIndex], side, true); - if (!forward || this.rangeIndex < rangeIndex) - this.setRangeIndex(rangeIndex); - } - this.next(); - } - forward(pos, side) { - if ((this.to - pos || this.endSide - side) < 0) - this.gotoInner(pos, side, true); - } - next() { - for (;;) { - if (this.chunkIndex == this.layer.chunk.length) { - this.from = this.to = 1000000000 /* Far */; - this.value = null; - break; - } - else { - let chunkPos = this.layer.chunkPos[this.chunkIndex], chunk = this.layer.chunk[this.chunkIndex]; - let from = chunkPos + chunk.from[this.rangeIndex]; - this.from = from; - this.to = chunkPos + chunk.to[this.rangeIndex]; - this.value = chunk.value[this.rangeIndex]; - this.setRangeIndex(this.rangeIndex + 1); - if (this.minPoint < 0 || this.value.point && this.to - this.from >= this.minPoint) - break; - } - } - } - setRangeIndex(index) { - if (index == this.layer.chunk[this.chunkIndex].value.length) { - this.chunkIndex++; - if (this.skip) { - while (this.chunkIndex < this.layer.chunk.length && this.skip.has(this.layer.chunk[this.chunkIndex])) - this.chunkIndex++; - } - this.rangeIndex = 0; - } - else { - this.rangeIndex = index; - } - } - nextChunk() { - this.chunkIndex++; - this.rangeIndex = 0; - this.next(); - } - compare(other) { - return this.from - other.from || this.startSide - other.startSide || this.rank - other.rank || - this.to - other.to || this.endSide - other.endSide; - } - } - class HeapCursor { - constructor(heap) { - this.heap = heap; - } - static from(sets, skip = null, minPoint = -1) { - let heap = []; - for (let i = 0; i < sets.length; i++) { - for (let cur = sets[i]; !cur.isEmpty; cur = cur.nextLayer) { - if (cur.maxPoint >= minPoint) - heap.push(new LayerCursor(cur, skip, minPoint, i)); - } - } - return heap.length == 1 ? heap[0] : new HeapCursor(heap); - } - get startSide() { return this.value ? this.value.startSide : 0; } - goto(pos, side = -1000000000 /* Far */) { - for (let cur of this.heap) - cur.goto(pos, side); - for (let i = this.heap.length >> 1; i >= 0; i--) - heapBubble(this.heap, i); - this.next(); - return this; - } - forward(pos, side) { - for (let cur of this.heap) - cur.forward(pos, side); - for (let i = this.heap.length >> 1; i >= 0; i--) - heapBubble(this.heap, i); - if ((this.to - pos || this.value.endSide - side) < 0) - this.next(); - } - next() { - if (this.heap.length == 0) { - this.from = this.to = 1000000000 /* Far */; - this.value = null; - this.rank = -1; - } - else { - let top = this.heap[0]; - this.from = top.from; - this.to = top.to; - this.value = top.value; - this.rank = top.rank; - if (top.value) - top.next(); - heapBubble(this.heap, 0); - } - } - } - function heapBubble(heap, index) { - for (let cur = heap[index];;) { - let childIndex = (index << 1) + 1; - if (childIndex >= heap.length) - break; - let child = heap[childIndex]; - if (childIndex + 1 < heap.length && child.compare(heap[childIndex + 1]) >= 0) { - child = heap[childIndex + 1]; - childIndex++; - } - if (cur.compare(child) < 0) - break; - heap[childIndex] = cur; - heap[index] = child; - index = childIndex; - } - } - class SpanCursor { - constructor(sets, skip, minPoint, filterPoint = () => true) { - this.minPoint = minPoint; - this.filterPoint = filterPoint; - this.active = []; - this.activeTo = []; - this.activeRank = []; - this.minActive = -1; - // A currently active point range, if any - this.point = null; - this.pointFrom = 0; - this.pointRank = 0; - this.to = -1000000000 /* Far */; - this.endSide = 0; - this.openStart = -1; - this.cursor = HeapCursor.from(sets, skip, minPoint); - } - goto(pos, side = -1000000000 /* Far */) { - this.cursor.goto(pos, side); - this.active.length = this.activeTo.length = this.activeRank.length = 0; - this.minActive = -1; - this.to = pos; - this.endSide = side; - this.openStart = -1; - this.next(); - return this; - } - forward(pos, side) { - while (this.minActive > -1 && (this.activeTo[this.minActive] - pos || this.active[this.minActive].endSide - side) < 0) - this.removeActive(this.minActive); - this.cursor.forward(pos, side); - } - removeActive(index) { - remove(this.active, index); - remove(this.activeTo, index); - remove(this.activeRank, index); - this.minActive = findMinIndex(this.active, this.activeTo); - } - addActive(trackOpen) { - let i = 0, { value, to, rank } = this.cursor; - while (i < this.activeRank.length && this.activeRank[i] <= rank) - i++; - insert(this.active, i, value); - insert(this.activeTo, i, to); - insert(this.activeRank, i, rank); - if (trackOpen) - insert(trackOpen, i, this.cursor.from); - this.minActive = findMinIndex(this.active, this.activeTo); - } - // After calling this, if `this.point` != null, the next range is a - // point. Otherwise, it's a regular range, covered by `this.active`. - next() { - let from = this.to, wasPoint = this.point; - this.point = null; - let trackOpen = this.openStart < 0 ? [] : null, trackExtra = 0; - for (;;) { - let a = this.minActive; - if (a > -1 && (this.activeTo[a] - this.cursor.from || this.active[a].endSide - this.cursor.startSide) < 0) { - if (this.activeTo[a] > from) { - this.to = this.activeTo[a]; - this.endSide = this.active[a].endSide; - break; - } - this.removeActive(a); - if (trackOpen) - remove(trackOpen, a); - } - else if (!this.cursor.value) { - this.to = this.endSide = 1000000000 /* Far */; - break; - } - else if (this.cursor.from > from) { - this.to = this.cursor.from; - this.endSide = this.cursor.startSide; - break; - } - else { - let nextVal = this.cursor.value; - if (!nextVal.point) { // Opening a range - this.addActive(trackOpen); - this.cursor.next(); - } - else if (wasPoint && this.cursor.to == this.to && this.cursor.from < this.cursor.to) { - // Ignore any non-empty points that end precisely at the end of the prev point - this.cursor.next(); - } - else if (!this.filterPoint(this.cursor.from, this.cursor.to, this.cursor.value, this.cursor.rank)) { - this.cursor.next(); - } - else { // New point - this.point = nextVal; - this.pointFrom = this.cursor.from; - this.pointRank = this.cursor.rank; - this.to = this.cursor.to; - this.endSide = nextVal.endSide; - if (this.cursor.from < from) - trackExtra = 1; - this.cursor.next(); - this.forward(this.to, this.endSide); - break; - } - } - } - if (trackOpen) { - let openStart = 0; - while (openStart < trackOpen.length && trackOpen[openStart] < from) - openStart++; - this.openStart = openStart + trackExtra; - } - } - activeForPoint(to) { - if (!this.active.length) - return this.active; - let active = []; - for (let i = this.active.length - 1; i >= 0; i--) { - if (this.activeRank[i] < this.pointRank) - break; - if (this.activeTo[i] > to || this.activeTo[i] == to && this.active[i].endSide >= this.point.endSide) - active.push(this.active[i]); - } - return active.reverse(); - } - openEnd(to) { - let open = 0; - for (let i = this.activeTo.length - 1; i >= 0 && this.activeTo[i] > to; i--) - open++; - return open; - } - } - function compare(a, startA, b, startB, length, comparator) { - a.goto(startA); - b.goto(startB); - let endB = startB + length; - let pos = startB, dPos = startB - startA; - for (;;) { - let diff = (a.to + dPos) - b.to || a.endSide - b.endSide; - let end = diff < 0 ? a.to + dPos : b.to, clipEnd = Math.min(end, endB); - if (a.point || b.point) { - if (!(a.point && b.point && (a.point == b.point || a.point.eq(b.point)) && - sameValues(a.activeForPoint(a.to + dPos), b.activeForPoint(b.to)))) - comparator.comparePoint(pos, clipEnd, a.point, b.point); - } - else { - if (clipEnd > pos && !sameValues(a.active, b.active)) - comparator.compareRange(pos, clipEnd, a.active, b.active); - } - if (end > endB) - break; - pos = end; - if (diff <= 0) - a.next(); - if (diff >= 0) - b.next(); - } - } - function sameValues(a, b) { - if (a.length != b.length) - return false; - for (let i = 0; i < a.length; i++) - if (a[i] != b[i] && !a[i].eq(b[i])) - return false; - return true; - } - function remove(array, index) { - for (let i = index, e = array.length - 1; i < e; i++) - array[i] = array[i + 1]; - array.pop(); - } - function insert(array, index, value) { - for (let i = array.length - 1; i >= index; i--) - array[i + 1] = array[i]; - array[index] = value; - } - function findMinIndex(value, array) { - let found = -1, foundPos = 1000000000 /* Far */; - for (let i = 0; i < array.length; i++) - if ((array[i] - foundPos || value[i].endSide - value[found].endSide) < 0) { - found = i; - foundPos = array[i]; - } - return found; - } - - var base = { - 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: "'" - }; - - var shift = { - 48: ")", - 49: "!", - 50: "@", - 51: "#", - 52: "$", - 53: "%", - 54: "^", - 55: "&", - 56: "*", - 57: "(", - 59: ":", - 61: "+", - 173: "_", - 186: ":", - 187: "+", - 188: "<", - 189: "_", - 190: ">", - 191: "?", - 192: "~", - 219: "{", - 220: "|", - 221: "}", - 222: "\"" - }; - - var chrome$1 = typeof navigator != "undefined" && /Chrome\/(\d+)/.exec(navigator.userAgent); - typeof navigator != "undefined" && /Gecko\/\d+/.test(navigator.userAgent); - var mac = typeof navigator != "undefined" && /Mac/.test(navigator.platform); - var ie$1 = typeof navigator != "undefined" && /MSIE \d|Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(navigator.userAgent); - var brokenModifierNames = mac || chrome$1 && +chrome$1[1] < 57; - - // Fill in the digit keys - for (var i = 0; i < 10; i++) base[48 + i] = base[96 + i] = String(i); - - // The function keys - for (var i = 1; i <= 24; i++) base[i + 111] = "F" + i; - - // And the alphabetic keys - for (var i = 65; i <= 90; i++) { - base[i] = String.fromCharCode(i + 32); - shift[i] = String.fromCharCode(i); - } - - // For each code that doesn't have a shift-equivalent, copy the base name - for (var code in base) if (!shift.hasOwnProperty(code)) shift[code] = base[code]; - - function keyName(event) { - var ignoreKey = brokenModifierNames && (event.ctrlKey || event.altKey || event.metaKey) || - ie$1 && event.shiftKey && event.key && event.key.length == 1 || - event.key == "Unidentified"; - var name = (!ignoreKey && event.key) || - (event.shiftKey ? shift : base)[event.keyCode] || - event.key || "Unidentified"; - // Edge sometimes produces wrong names (Issue #3) - if (name == "Esc") name = "Escape"; - if (name == "Del") name = "Delete"; - // https://developer.microsoft.com/en-us/microsoft-edge/platform/issues/8860571/ - if (name == "Left") name = "ArrowLeft"; - if (name == "Up") name = "ArrowUp"; - if (name == "Right") name = "ArrowRight"; - if (name == "Down") name = "ArrowDown"; - return name - } - - function getSelection(root) { - let target; - // Browsers differ on whether shadow roots have a getSelection - // method. If it exists, use that, otherwise, call it on the - // document. - if (root.nodeType == 11) { // Shadow root - target = root.getSelection ? root : root.ownerDocument; - } - else { - target = root; - } - return target.getSelection(); - } - function contains(dom, node) { - return node ? dom == node || dom.contains(node.nodeType != 1 ? node.parentNode : node) : false; - } - function deepActiveElement() { - let elt = document.activeElement; - while (elt && elt.shadowRoot) - elt = elt.shadowRoot.activeElement; - return elt; - } - function hasSelection(dom, selection) { - if (!selection.anchorNode) - return false; - try { - // Firefox will raise 'permission denied' errors when accessing - // properties of `sel.anchorNode` when it's in a generated CSS - // element. - return contains(dom, selection.anchorNode); - } - catch (_) { - return false; - } - } - function clientRectsFor(dom) { - if (dom.nodeType == 3) - return textRange(dom, 0, dom.nodeValue.length).getClientRects(); - else if (dom.nodeType == 1) - return dom.getClientRects(); - else - return []; - } - // Scans forward and backward through DOM positions equivalent to the - // given one to see if the two are in the same place (i.e. after a - // text node vs at the end of that text node) - function isEquivalentPosition(node, off, targetNode, targetOff) { - return targetNode ? (scanFor(node, off, targetNode, targetOff, -1) || - scanFor(node, off, targetNode, targetOff, 1)) : false; - } - function domIndex(node) { - for (var index = 0;; index++) { - node = node.previousSibling; - if (!node) - return index; - } - } - function scanFor(node, off, targetNode, targetOff, dir) { - for (;;) { - if (node == targetNode && off == targetOff) - return true; - if (off == (dir < 0 ? 0 : maxOffset(node))) { - if (node.nodeName == "DIV") - return false; - let parent = node.parentNode; - if (!parent || parent.nodeType != 1) - return false; - off = domIndex(node) + (dir < 0 ? 0 : 1); - node = parent; - } - else if (node.nodeType == 1) { - node = node.childNodes[off + (dir < 0 ? -1 : 0)]; - if (node.nodeType == 1 && node.contentEditable == "false") - return false; - off = dir < 0 ? maxOffset(node) : 0; - } - else { - return false; - } - } - } - function maxOffset(node) { - return node.nodeType == 3 ? node.nodeValue.length : node.childNodes.length; - } - const Rect0 = { left: 0, right: 0, top: 0, bottom: 0 }; - function flattenRect(rect, left) { - let x = left ? rect.left : rect.right; - return { left: x, right: x, top: rect.top, bottom: rect.bottom }; - } - function windowRect(win) { - return { left: 0, right: win.innerWidth, - top: 0, bottom: win.innerHeight }; - } - function scrollRectIntoView(dom, rect, side, x, y, xMargin, yMargin, ltr) { - let doc = dom.ownerDocument, win = doc.defaultView; - for (let cur = dom; cur;) { - if (cur.nodeType == 1) { // Element - let bounding, top = cur == doc.body; - if (top) { - bounding = windowRect(win); - } - else { - if (cur.scrollHeight <= cur.clientHeight && cur.scrollWidth <= cur.clientWidth) { - cur = cur.parentNode; - continue; - } - let rect = cur.getBoundingClientRect(); - // Make sure scrollbar width isn't included in the rectangle - bounding = { left: rect.left, right: rect.left + cur.clientWidth, - top: rect.top, bottom: rect.top + cur.clientHeight }; - } - let moveX = 0, moveY = 0; - if (y == "nearest") { - if (rect.top < bounding.top) { - moveY = -(bounding.top - rect.top + yMargin); - if (side > 0 && rect.bottom > bounding.bottom + moveY) - moveY = rect.bottom - bounding.bottom + moveY + yMargin; - } - else if (rect.bottom > bounding.bottom) { - moveY = rect.bottom - bounding.bottom + yMargin; - if (side < 0 && (rect.top - moveY) < bounding.top) - moveY = -(bounding.top + moveY - rect.top + yMargin); - } - } - else { - let rectHeight = rect.bottom - rect.top, boundingHeight = bounding.bottom - bounding.top; - let targetTop = y == "center" && rectHeight <= boundingHeight ? rect.top + rectHeight / 2 - boundingHeight / 2 : - y == "start" || y == "center" && side < 0 ? rect.top - yMargin : - rect.bottom - boundingHeight + yMargin; - moveY = targetTop - bounding.top; - } - if (x == "nearest") { - if (rect.left < bounding.left) { - moveX = -(bounding.left - rect.left + xMargin); - if (side > 0 && rect.right > bounding.right + moveX) - moveX = rect.right - bounding.right + moveX + xMargin; - } - else if (rect.right > bounding.right) { - moveX = rect.right - bounding.right + xMargin; - if (side < 0 && rect.left < bounding.left + moveX) - moveX = -(bounding.left + moveX - rect.left + xMargin); - } - } - else { - let targetLeft = x == "center" ? rect.left + (rect.right - rect.left) / 2 - (bounding.right - bounding.left) / 2 : - (x == "start") == ltr ? rect.left - xMargin : - rect.right - (bounding.right - bounding.left) + xMargin; - moveX = targetLeft - bounding.left; - } - if (moveX || moveY) { - if (top) { - win.scrollBy(moveX, moveY); - } - else { - if (moveY) { - let start = cur.scrollTop; - cur.scrollTop += moveY; - moveY = cur.scrollTop - start; - } - if (moveX) { - let start = cur.scrollLeft; - cur.scrollLeft += moveX; - moveX = cur.scrollLeft - start; - } - rect = { left: rect.left - moveX, top: rect.top - moveY, - right: rect.right - moveX, bottom: rect.bottom - moveY }; - } - } - if (top) - break; - cur = cur.assignedSlot || cur.parentNode; - x = y = "nearest"; - } - else if (cur.nodeType == 11) { // A shadow root - cur = cur.host; - } - else { - break; - } - } - } - class DOMSelectionState { - constructor() { - this.anchorNode = null; - this.anchorOffset = 0; - this.focusNode = null; - this.focusOffset = 0; - } - eq(domSel) { - return this.anchorNode == domSel.anchorNode && this.anchorOffset == domSel.anchorOffset && - this.focusNode == domSel.focusNode && this.focusOffset == domSel.focusOffset; - } - setRange(range) { - this.set(range.anchorNode, range.anchorOffset, range.focusNode, range.focusOffset); - } - set(anchorNode, anchorOffset, focusNode, focusOffset) { - this.anchorNode = anchorNode; - this.anchorOffset = anchorOffset; - this.focusNode = focusNode; - this.focusOffset = focusOffset; - } - } - let preventScrollSupported = null; - // Feature-detects support for .focus({preventScroll: true}), and uses - // a fallback kludge when not supported. - function focusPreventScroll(dom) { - if (dom.setActive) - return dom.setActive(); // in IE - if (preventScrollSupported) - return dom.focus(preventScrollSupported); - let stack = []; - for (let cur = dom; cur; cur = cur.parentNode) { - stack.push(cur, cur.scrollTop, cur.scrollLeft); - if (cur == cur.ownerDocument) - break; - } - dom.focus(preventScrollSupported == null ? { - get preventScroll() { - preventScrollSupported = { preventScroll: true }; - return true; - } - } : undefined); - if (!preventScrollSupported) { - preventScrollSupported = false; - for (let i = 0; i < stack.length;) { - let elt = stack[i++], top = stack[i++], left = stack[i++]; - if (elt.scrollTop != top) - elt.scrollTop = top; - if (elt.scrollLeft != left) - elt.scrollLeft = left; - } - } - } - let scratchRange; - function textRange(node, from, to = from) { - let range = scratchRange || (scratchRange = document.createRange()); - range.setEnd(node, to); - range.setStart(node, from); - return range; - } - function dispatchKey(elt, name, code) { - let options = { key: name, code: name, keyCode: code, which: code, cancelable: true }; - let down = new KeyboardEvent("keydown", options); - down.synthetic = true; - elt.dispatchEvent(down); - let up = new KeyboardEvent("keyup", options); - up.synthetic = true; - elt.dispatchEvent(up); - return down.defaultPrevented || up.defaultPrevented; - } - function getRoot(node) { - while (node) { - if (node && (node.nodeType == 9 || node.nodeType == 11 && node.host)) - return node; - node = node.assignedSlot || node.parentNode; - } - return null; - } - function clearAttributes(node) { - while (node.attributes.length) - node.removeAttributeNode(node.attributes[0]); - } - - class DOMPos { - constructor(node, offset, precise = true) { - this.node = node; - this.offset = offset; - this.precise = precise; - } - static before(dom, precise) { return new DOMPos(dom.parentNode, domIndex(dom), precise); } - static after(dom, precise) { return new DOMPos(dom.parentNode, domIndex(dom) + 1, precise); } - } - const noChildren = []; - class ContentView { - constructor() { - this.parent = null; - this.dom = null; - this.dirty = 2 /* Node */; - } - get editorView() { - if (!this.parent) - throw new Error("Accessing view in orphan content view"); - return this.parent.editorView; - } - get overrideDOMText() { return null; } - get posAtStart() { - return this.parent ? this.parent.posBefore(this) : 0; - } - get posAtEnd() { - return this.posAtStart + this.length; - } - posBefore(view) { - let pos = this.posAtStart; - for (let child of this.children) { - if (child == view) - return pos; - pos += child.length + child.breakAfter; - } - throw new RangeError("Invalid child in posBefore"); - } - posAfter(view) { - return this.posBefore(view) + view.length; - } - // Will return a rectangle directly before (when side < 0), after - // (side > 0) or directly on (when the browser supports it) the - // given position. - coordsAt(_pos, _side) { return null; } - sync(track) { - if (this.dirty & 2 /* Node */) { - let parent = this.dom; - let prev = null, next; - for (let child of this.children) { - if (child.dirty) { - if (!child.dom && (next = prev ? prev.nextSibling : parent.firstChild)) { - let contentView = ContentView.get(next); - if (!contentView || !contentView.parent && contentView.constructor == child.constructor) - child.reuseDOM(next); - } - child.sync(track); - child.dirty = 0 /* Not */; - } - next = prev ? prev.nextSibling : parent.firstChild; - if (track && !track.written && track.node == parent && next != child.dom) - track.written = true; - if (child.dom.parentNode == parent) { - while (next && next != child.dom) - next = rm$1(next); - } - else { - parent.insertBefore(child.dom, next); - } - prev = child.dom; - } - next = prev ? prev.nextSibling : parent.firstChild; - if (next && track && track.node == parent) - track.written = true; - while (next) - next = rm$1(next); - } - else if (this.dirty & 1 /* Child */) { - for (let child of this.children) - if (child.dirty) { - child.sync(track); - child.dirty = 0 /* Not */; - } - } - } - reuseDOM(_dom) { } - localPosFromDOM(node, offset) { - let after; - if (node == this.dom) { - after = this.dom.childNodes[offset]; - } - else { - let bias = maxOffset(node) == 0 ? 0 : offset == 0 ? -1 : 1; - for (;;) { - let parent = node.parentNode; - if (parent == this.dom) - break; - if (bias == 0 && parent.firstChild != parent.lastChild) { - if (node == parent.firstChild) - bias = -1; - else - bias = 1; - } - node = parent; - } - if (bias < 0) - after = node; - else - after = node.nextSibling; - } - if (after == this.dom.firstChild) - return 0; - while (after && !ContentView.get(after)) - after = after.nextSibling; - if (!after) - return this.length; - for (let i = 0, pos = 0;; i++) { - let child = this.children[i]; - if (child.dom == after) - return pos; - pos += child.length + child.breakAfter; - } - } - domBoundsAround(from, to, offset = 0) { - let fromI = -1, fromStart = -1, toI = -1, toEnd = -1; - for (let i = 0, pos = offset, prevEnd = offset; i < this.children.length; i++) { - let child = this.children[i], end = pos + child.length; - if (pos < from && end > to) - return child.domBoundsAround(from, to, pos); - if (end >= from && fromI == -1) { - fromI = i; - fromStart = pos; - } - if (pos > to && child.dom.parentNode == this.dom) { - toI = i; - toEnd = prevEnd; - break; - } - prevEnd = end; - pos = end + child.breakAfter; - } - return { from: fromStart, to: toEnd < 0 ? offset + this.length : toEnd, - startDOM: (fromI ? this.children[fromI - 1].dom.nextSibling : null) || this.dom.firstChild, - endDOM: toI < this.children.length && toI >= 0 ? this.children[toI].dom : null }; - } - markDirty(andParent = false) { - this.dirty |= 2 /* Node */; - this.markParentsDirty(andParent); - } - markParentsDirty(childList) { - for (let parent = this.parent; parent; parent = parent.parent) { - if (childList) - parent.dirty |= 2 /* Node */; - if (parent.dirty & 1 /* Child */) - return; - parent.dirty |= 1 /* Child */; - childList = false; - } - } - setParent(parent) { - if (this.parent != parent) { - this.parent = parent; - if (this.dirty) - this.markParentsDirty(true); - } - } - setDOM(dom) { - if (this.dom) - this.dom.cmView = null; - this.dom = dom; - dom.cmView = this; - } - get rootView() { - for (let v = this;;) { - let parent = v.parent; - if (!parent) - return v; - v = parent; - } - } - replaceChildren(from, to, children = noChildren) { - this.markDirty(); - for (let i = from; i < to; i++) { - let child = this.children[i]; - if (child.parent == this) - child.destroy(); - } - this.children.splice(from, to - from, ...children); - for (let i = 0; i < children.length; i++) - children[i].setParent(this); - } - ignoreMutation(_rec) { return false; } - ignoreEvent(_event) { return false; } - childCursor(pos = this.length) { - return new ChildCursor(this.children, pos, this.children.length); - } - childPos(pos, bias = 1) { - return this.childCursor().findPos(pos, bias); - } - toString() { - let name = this.constructor.name.replace("View", ""); - return name + (this.children.length ? "(" + this.children.join() + ")" : - this.length ? "[" + (name == "Text" ? this.text : this.length) + "]" : "") + - (this.breakAfter ? "#" : ""); - } - static get(node) { return node.cmView; } - get isEditable() { return true; } - merge(from, to, source, hasStart, openStart, openEnd) { - return false; - } - become(other) { return false; } - // When this is a zero-length view with a side, this should return a - // number <= 0 to indicate it is before its position, or a - // number > 0 when after its position. - getSide() { return 0; } - destroy() { - this.parent = null; - } - } - ContentView.prototype.breakAfter = 0; - // Remove a DOM node and return its next sibling. - function rm$1(dom) { - let next = dom.nextSibling; - dom.parentNode.removeChild(dom); - return next; - } - class ChildCursor { - constructor(children, pos, i) { - this.children = children; - this.pos = pos; - this.i = i; - this.off = 0; - } - findPos(pos, bias = 1) { - for (;;) { - if (pos > this.pos || pos == this.pos && - (bias > 0 || this.i == 0 || this.children[this.i - 1].breakAfter)) { - this.off = pos - this.pos; - return this; - } - let next = this.children[--this.i]; - this.pos -= next.length + next.breakAfter; - } - } - } - function replaceRange(parent, fromI, fromOff, toI, toOff, insert, breakAtStart, openStart, openEnd) { - let { children } = parent; - let before = children.length ? children[fromI] : null; - let last = insert.length ? insert[insert.length - 1] : null; - let breakAtEnd = last ? last.breakAfter : breakAtStart; - // Change within a single child - if (fromI == toI && before && !breakAtStart && !breakAtEnd && insert.length < 2 && - before.merge(fromOff, toOff, insert.length ? last : null, fromOff == 0, openStart, openEnd)) - return; - if (toI < children.length) { - let after = children[toI]; - // Make sure the end of the child after the update is preserved in `after` - if (after && toOff < after.length) { - // If we're splitting a child, separate part of it to avoid that - // being mangled when updating the child before the update. - if (fromI == toI) { - after = after.split(toOff); - toOff = 0; - } - // If the element after the replacement should be merged with - // the last replacing element, update `content` - if (!breakAtEnd && last && after.merge(0, toOff, last, true, 0, openEnd)) { - insert[insert.length - 1] = after; - } - else { - // Remove the start of the after element, if necessary, and - // add it to `content`. - if (toOff) - after.merge(0, toOff, null, false, 0, openEnd); - insert.push(after); - } - } - else if (after === null || after === void 0 ? void 0 : after.breakAfter) { - // The element at `toI` is entirely covered by this range. - // Preserve its line break, if any. - if (last) - last.breakAfter = 1; - else - breakAtStart = 1; - } - // Since we've handled the next element from the current elements - // now, make sure `toI` points after that. - toI++; - } - if (before) { - before.breakAfter = breakAtStart; - if (fromOff > 0) { - if (!breakAtStart && insert.length && before.merge(fromOff, before.length, insert[0], false, openStart, 0)) { - before.breakAfter = insert.shift().breakAfter; - } - else if (fromOff < before.length || before.children.length && before.children[before.children.length - 1].length == 0) { - before.merge(fromOff, before.length, null, false, openStart, 0); - } - fromI++; - } - } - // Try to merge widgets on the boundaries of the replacement - while (fromI < toI && insert.length) { - if (children[toI - 1].become(insert[insert.length - 1])) { - toI--; - insert.pop(); - openEnd = insert.length ? 0 : openStart; - } - else if (children[fromI].become(insert[0])) { - fromI++; - insert.shift(); - openStart = insert.length ? 0 : openEnd; - } - else { - break; - } - } - if (!insert.length && fromI && toI < children.length && !children[fromI - 1].breakAfter && - children[toI].merge(0, 0, children[fromI - 1], false, openStart, openEnd)) - fromI--; - if (fromI < toI || insert.length) - parent.replaceChildren(fromI, toI, insert); - } - function mergeChildrenInto(parent, from, to, insert, openStart, openEnd) { - let cur = parent.childCursor(); - let { i: toI, off: toOff } = cur.findPos(to, 1); - let { i: fromI, off: fromOff } = cur.findPos(from, -1); - let dLen = from - to; - for (let view of insert) - dLen += view.length; - parent.length += dLen; - replaceRange(parent, fromI, fromOff, toI, toOff, insert, 0, openStart, openEnd); - } - - let nav = typeof navigator != "undefined" ? navigator : { userAgent: "", vendor: "", platform: "" }; - let doc = typeof document != "undefined" ? document : { documentElement: { style: {} } }; - const ie_edge = /*@__PURE__*//Edge\/(\d+)/.exec(nav.userAgent); - const ie_upto10 = /*@__PURE__*//MSIE \d/.test(nav.userAgent); - const ie_11up = /*@__PURE__*//Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(nav.userAgent); - const ie = !!(ie_upto10 || ie_11up || ie_edge); - const gecko = !ie && /*@__PURE__*//gecko\/(\d+)/i.test(nav.userAgent); - const chrome = !ie && /*@__PURE__*//Chrome\/(\d+)/.exec(nav.userAgent); - const webkit = "webkitFontSmoothing" in doc.documentElement.style; - const safari = !ie && /*@__PURE__*//Apple Computer/.test(nav.vendor); - const ios$1 = safari && (/*@__PURE__*//Mobile\/\w+/.test(nav.userAgent) || nav.maxTouchPoints > 2); - var browser = { - mac: ios$1 || /*@__PURE__*//Mac/.test(nav.platform), - windows: /*@__PURE__*//Win/.test(nav.platform), - linux: /*@__PURE__*//Linux|X11/.test(nav.platform), - ie, - ie_version: ie_upto10 ? doc.documentMode || 6 : ie_11up ? +ie_11up[1] : ie_edge ? +ie_edge[1] : 0, - gecko, - gecko_version: gecko ? +(/*@__PURE__*//Firefox\/(\d+)/.exec(nav.userAgent) || [0, 0])[1] : 0, - chrome: !!chrome, - chrome_version: chrome ? +chrome[1] : 0, - ios: ios$1, - android: /*@__PURE__*//Android\b/.test(nav.userAgent), - webkit, - safari, - webkit_version: webkit ? +(/*@__PURE__*//\bAppleWebKit\/(\d+)/.exec(navigator.userAgent) || [0, 0])[1] : 0, - tabSize: doc.documentElement.style.tabSize != null ? "tab-size" : "-moz-tab-size" - }; - - const MaxJoinLen = 256; - class TextView extends ContentView { - constructor(text) { - super(); - this.text = text; - } - get length() { return this.text.length; } - createDOM(textDOM) { - this.setDOM(textDOM || document.createTextNode(this.text)); - } - sync(track) { - if (!this.dom) - this.createDOM(); - if (this.dom.nodeValue != this.text) { - if (track && track.node == this.dom) - track.written = true; - this.dom.nodeValue = this.text; - } - } - reuseDOM(dom) { - if (dom.nodeType == 3) - this.createDOM(dom); - } - merge(from, to, source) { - if (source && (!(source instanceof TextView) || this.length - (to - from) + source.length > MaxJoinLen)) - return false; - this.text = this.text.slice(0, from) + (source ? source.text : "") + this.text.slice(to); - this.markDirty(); - return true; - } - split(from) { - let result = new TextView(this.text.slice(from)); - this.text = this.text.slice(0, from); - this.markDirty(); - return result; - } - localPosFromDOM(node, offset) { - return node == this.dom ? offset : offset ? this.text.length : 0; - } - domAtPos(pos) { return new DOMPos(this.dom, pos); } - domBoundsAround(_from, _to, offset) { - return { from: offset, to: offset + this.length, startDOM: this.dom, endDOM: this.dom.nextSibling }; - } - coordsAt(pos, side) { - return textCoords(this.dom, pos, side); - } - } - class MarkView extends ContentView { - constructor(mark, children = [], length = 0) { - super(); - this.mark = mark; - this.children = children; - this.length = length; - for (let ch of children) - ch.setParent(this); - } - setAttrs(dom) { - clearAttributes(dom); - if (this.mark.class) - dom.className = this.mark.class; - if (this.mark.attrs) - for (let name in this.mark.attrs) - dom.setAttribute(name, this.mark.attrs[name]); - return dom; - } - reuseDOM(node) { - if (node.nodeName == this.mark.tagName.toUpperCase()) { - this.setDOM(node); - this.dirty |= 4 /* Attrs */ | 2 /* Node */; - } - } - sync(track) { - if (!this.dom) - this.setDOM(this.setAttrs(document.createElement(this.mark.tagName))); - else if (this.dirty & 4 /* Attrs */) - this.setAttrs(this.dom); - super.sync(track); - } - merge(from, to, source, _hasStart, openStart, openEnd) { - if (source && (!(source instanceof MarkView && source.mark.eq(this.mark)) || - (from && openStart <= 0) || (to < this.length && openEnd <= 0))) - return false; - mergeChildrenInto(this, from, to, source ? source.children : [], openStart - 1, openEnd - 1); - this.markDirty(); - return true; - } - split(from) { - let result = [], off = 0, detachFrom = -1, i = 0; - for (let elt of this.children) { - let end = off + elt.length; - if (end > from) - result.push(off < from ? elt.split(from - off) : elt); - if (detachFrom < 0 && off >= from) - detachFrom = i; - off = end; - i++; - } - let length = this.length - from; - this.length = from; - if (detachFrom > -1) { - this.children.length = detachFrom; - this.markDirty(); - } - return new MarkView(this.mark, result, length); - } - domAtPos(pos) { - return inlineDOMAtPos(this.dom, this.children, pos); - } - coordsAt(pos, side) { - return coordsInChildren(this, pos, side); - } - } - function textCoords(text, pos, side) { - let length = text.nodeValue.length; - if (pos > length) - pos = length; - let from = pos, to = pos, flatten = 0; - if (pos == 0 && side < 0 || pos == length && side >= 0) { - if (!(browser.chrome || browser.gecko)) { // These browsers reliably return valid rectangles for empty ranges - if (pos) { - from--; - flatten = 1; - } // FIXME this is wrong in RTL text - else { - to++; - flatten = -1; - } - } - } - else { - if (side < 0) - from--; - else - to++; - } - let rects = textRange(text, from, to).getClientRects(); - if (!rects.length) - return Rect0; - let rect = rects[(flatten ? flatten < 0 : side >= 0) ? 0 : rects.length - 1]; - if (browser.safari && !flatten && rect.width == 0) - rect = Array.prototype.find.call(rects, r => r.width) || rect; - return flatten ? flattenRect(rect, flatten < 0) : rect || null; - } - // Also used for collapsed ranges that don't have a placeholder widget! - class WidgetView extends ContentView { - constructor(widget, length, side) { - super(); - this.widget = widget; - this.length = length; - this.side = side; - this.prevWidget = null; - } - static create(widget, length, side) { - return new (widget.customView || WidgetView)(widget, length, side); - } - split(from) { - let result = WidgetView.create(this.widget, this.length - from, this.side); - this.length -= from; - return result; - } - sync() { - if (!this.dom || !this.widget.updateDOM(this.dom)) { - if (this.dom && this.prevWidget) - this.prevWidget.destroy(this.dom); - this.prevWidget = null; - this.setDOM(this.widget.toDOM(this.editorView)); - this.dom.contentEditable = "false"; - } - } - getSide() { return this.side; } - merge(from, to, source, hasStart, openStart, openEnd) { - if (source && (!(source instanceof WidgetView) || !this.widget.compare(source.widget) || - from > 0 && openStart <= 0 || to < this.length && openEnd <= 0)) - return false; - this.length = from + (source ? source.length : 0) + (this.length - to); - return true; - } - become(other) { - if (other.length == this.length && other instanceof WidgetView && other.side == this.side) { - if (this.widget.constructor == other.widget.constructor) { - if (!this.widget.eq(other.widget)) - this.markDirty(true); - if (this.dom && !this.prevWidget) - this.prevWidget = this.widget; - this.widget = other.widget; - return true; - } - } - return false; - } - ignoreMutation() { return true; } - ignoreEvent(event) { return this.widget.ignoreEvent(event); } - get overrideDOMText() { - if (this.length == 0) - return Text.empty; - let top = this; - while (top.parent) - top = top.parent; - let view = top.editorView, text = view && view.state.doc, start = this.posAtStart; - return text ? text.slice(start, start + this.length) : Text.empty; - } - domAtPos(pos) { - return pos == 0 ? DOMPos.before(this.dom) : DOMPos.after(this.dom, pos == this.length); - } - domBoundsAround() { return null; } - coordsAt(pos, side) { - let rects = this.dom.getClientRects(), rect = null; - if (!rects.length) - return Rect0; - for (let i = pos > 0 ? rects.length - 1 : 0;; i += (pos > 0 ? -1 : 1)) { - rect = rects[i]; - if (pos > 0 ? i == 0 : i == rects.length - 1 || rect.top < rect.bottom) - break; - } - return (pos == 0 && side > 0 || pos == this.length && side <= 0) ? rect : flattenRect(rect, pos == 0); - } - get isEditable() { return false; } - destroy() { - super.destroy(); - if (this.dom) - this.widget.destroy(this.dom); - } - } - class CompositionView extends WidgetView { - domAtPos(pos) { - let { topView, text } = this.widget; - if (!topView) - return new DOMPos(text, Math.min(pos, text.nodeValue.length)); - return scanCompositionTree(pos, 0, topView, text, (v, p) => v.domAtPos(p), p => new DOMPos(text, Math.min(p, text.nodeValue.length))); - } - sync() { this.setDOM(this.widget.toDOM()); } - localPosFromDOM(node, offset) { - let { topView, text } = this.widget; - if (!topView) - return Math.min(offset, this.length); - return posFromDOMInCompositionTree(node, offset, topView, text); - } - ignoreMutation() { return false; } - get overrideDOMText() { return null; } - coordsAt(pos, side) { - let { topView, text } = this.widget; - if (!topView) - return textCoords(text, pos, side); - return scanCompositionTree(pos, side, topView, text, (v, pos, side) => v.coordsAt(pos, side), (pos, side) => textCoords(text, pos, side)); - } - destroy() { - var _a; - super.destroy(); - (_a = this.widget.topView) === null || _a === void 0 ? void 0 : _a.destroy(); - } - get isEditable() { return true; } - } - // Uses the old structure of a chunk of content view frozen for - // composition to try and find a reasonable DOM location for the given - // offset. - function scanCompositionTree(pos, side, view, text, enterView, fromText) { - if (view instanceof MarkView) { - for (let child of view.children) { - let hasComp = contains(child.dom, text); - let len = hasComp ? text.nodeValue.length : child.length; - if (pos < len || pos == len && child.getSide() <= 0) - return hasComp ? scanCompositionTree(pos, side, child, text, enterView, fromText) : enterView(child, pos, side); - pos -= len; - } - return enterView(view, view.length, -1); - } - else if (view.dom == text) { - return fromText(pos, side); - } - else { - return enterView(view, pos, side); - } - } - function posFromDOMInCompositionTree(node, offset, view, text) { - if (view instanceof MarkView) { - for (let child of view.children) { - let pos = 0, hasComp = contains(child.dom, text); - if (contains(child.dom, node)) - return pos + (hasComp ? posFromDOMInCompositionTree(node, offset, child, text) : child.localPosFromDOM(node, offset)); - pos += hasComp ? text.nodeValue.length : child.length; - } - } - else if (view.dom == text) { - return Math.min(offset, text.nodeValue.length); - } - return view.localPosFromDOM(node, offset); - } - // These are drawn around uneditable widgets to avoid a number of - // browser bugs that show up when the cursor is directly next to - // uneditable inline content. - class WidgetBufferView extends ContentView { - constructor(side) { - super(); - this.side = side; - } - get length() { return 0; } - merge() { return false; } - become(other) { - return other instanceof WidgetBufferView && other.side == this.side; - } - split() { return new WidgetBufferView(this.side); } - sync() { - if (!this.dom) { - let dom = document.createElement("img"); - dom.className = "cm-widgetBuffer"; - dom.setAttribute("aria-hidden", "true"); - this.setDOM(dom); - } - } - getSide() { return this.side; } - domAtPos(pos) { return DOMPos.before(this.dom); } - localPosFromDOM() { return 0; } - domBoundsAround() { return null; } - coordsAt(pos) { - let imgRect = this.dom.getBoundingClientRect(); - // Since the <img> height doesn't correspond to text height, try - // to borrow the height from some sibling node. - let siblingRect = inlineSiblingRect(this, this.side > 0 ? -1 : 1); - return siblingRect && siblingRect.top < imgRect.bottom && siblingRect.bottom > imgRect.top - ? { left: imgRect.left, right: imgRect.right, top: siblingRect.top, bottom: siblingRect.bottom } : imgRect; - } - get overrideDOMText() { - return Text.empty; - } - } - TextView.prototype.children = WidgetView.prototype.children = WidgetBufferView.prototype.children = noChildren; - function inlineSiblingRect(view, side) { - let parent = view.parent, index = parent ? parent.children.indexOf(view) : -1; - while (parent && index >= 0) { - if (side < 0 ? index > 0 : index < parent.children.length) { - let next = parent.children[index + side]; - if (next instanceof TextView) { - let nextRect = next.coordsAt(side < 0 ? next.length : 0, side); - if (nextRect) - return nextRect; - } - index += side; - } - else if (parent instanceof MarkView && parent.parent) { - index = parent.parent.children.indexOf(parent) + (side < 0 ? 0 : 1); - parent = parent.parent; - } - else { - let last = parent.dom.lastChild; - if (last && last.nodeName == "BR") - return last.getClientRects()[0]; - break; - } - } - return undefined; - } - function inlineDOMAtPos(dom, children, pos) { - let i = 0; - for (let off = 0; i < children.length; i++) { - let child = children[i], end = off + child.length; - if (end == off && child.getSide() <= 0) - continue; - if (pos > off && pos < end && child.dom.parentNode == dom) - return child.domAtPos(pos - off); - if (pos <= off) - break; - off = end; - } - for (; i > 0; i--) { - let before = children[i - 1].dom; - if (before.parentNode == dom) - return DOMPos.after(before); - } - return new DOMPos(dom, 0); - } - // Assumes `view`, if a mark view, has precisely 1 child. - function joinInlineInto(parent, view, open) { - let last, { children } = parent; - if (open > 0 && view instanceof MarkView && children.length && - (last = children[children.length - 1]) instanceof MarkView && last.mark.eq(view.mark)) { - joinInlineInto(last, view.children[0], open - 1); - } - else { - children.push(view); - view.setParent(parent); - } - parent.length += view.length; - } - function coordsInChildren(view, pos, side) { - for (let off = 0, i = 0; i < view.children.length; i++) { - let child = view.children[i], end = off + child.length, next; - if ((side <= 0 || end == view.length || child.getSide() > 0 ? end >= pos : end > pos) && - (pos < end || i + 1 == view.children.length || (next = view.children[i + 1]).length || next.getSide() > 0)) { - let flatten = 0; - if (end == off) { - if (child.getSide() <= 0) - continue; - flatten = side = -child.getSide(); - } - let rect = child.coordsAt(Math.max(0, pos - off), side); - return flatten && rect ? flattenRect(rect, side < 0) : rect; - } - off = end; - } - let last = view.dom.lastChild; - if (!last) - return view.dom.getBoundingClientRect(); - let rects = clientRectsFor(last); - return rects[rects.length - 1] || null; - } - - function combineAttrs(source, target) { - for (let name in source) { - if (name == "class" && target.class) - target.class += " " + source.class; - else if (name == "style" && target.style) - target.style += ";" + source.style; - else - target[name] = source[name]; - } - return target; - } - function attrsEq(a, b) { - if (a == b) - return true; - if (!a || !b) - return false; - let keysA = Object.keys(a), keysB = Object.keys(b); - if (keysA.length != keysB.length) - return false; - for (let key of keysA) { - if (keysB.indexOf(key) == -1 || a[key] !== b[key]) - return false; - } - return true; - } - function updateAttrs(dom, prev, attrs) { - if (prev) - for (let name in prev) - if (!(attrs && name in attrs)) - dom.removeAttribute(name); - if (attrs) - for (let name in attrs) - if (!(prev && prev[name] == attrs[name])) - dom.setAttribute(name, attrs[name]); - } - - /** - Widgets added to the content are described by subclasses of this - class. Using a description object like that makes it possible to - delay creating of the DOM structure for a widget until it is - needed, and to avoid redrawing widgets even when the decorations - that define them are recreated. - */ - class WidgetType { - /** - Compare this instance to another instance of the same type. - (TypeScript can't express this, but only instances of the same - specific class will be passed to this method.) This is used to - avoid redrawing widgets when they are replaced by a new - decoration of the same type. The default implementation just - returns `false`, which will cause new instances of the widget to - always be redrawn. - */ - eq(_widget) { return false; } - /** - Update a DOM element created by a widget of the same type (but - different, non-`eq` content) to reflect this widget. May return - true to indicate that it could update, false to indicate it - couldn't (in which case the widget will be redrawn). The default - implementation just returns false. - */ - updateDOM(_dom) { return false; } - /** - @internal - */ - compare(other) { - return this == other || this.constructor == other.constructor && this.eq(other); - } - /** - The estimated height this widget will have, to be used when - estimating the height of content that hasn't been drawn. May - return -1 to indicate you don't know. The default implementation - returns -1. - */ - get estimatedHeight() { return -1; } - /** - Can be used to configure which kinds of events inside the widget - should be ignored by the editor. The default is to ignore all - events. - */ - ignoreEvent(_event) { return true; } - /** - @internal - */ - get customView() { return null; } - /** - This is called when the an instance of the widget is removed - from the editor view. - */ - destroy(_dom) { } - } - /** - The different types of blocks that can occur in an editor view. - */ - var BlockType = /*@__PURE__*/(function (BlockType) { - /** - A line of text. - */ - BlockType[BlockType["Text"] = 0] = "Text"; - /** - A block widget associated with the position after it. - */ - BlockType[BlockType["WidgetBefore"] = 1] = "WidgetBefore"; - /** - A block widget associated with the position before it. - */ - BlockType[BlockType["WidgetAfter"] = 2] = "WidgetAfter"; - /** - A block widget [replacing](https://codemirror.net/6/docs/ref/#view.Decoration^replace) a range of content. - */ - BlockType[BlockType["WidgetRange"] = 3] = "WidgetRange"; - return BlockType})(BlockType || (BlockType = {})); - /** - A decoration provides information on how to draw or style a piece - of content. You'll usually use it wrapped in a - [`Range`](https://codemirror.net/6/docs/ref/#rangeset.Range), which adds a start and end position. - */ - class Decoration extends RangeValue { - /** - @internal - */ - constructor( - /** - @internal - */ - startSide, - /** - @internal - */ - endSide, - /** - @internal - */ - widget, - /** - The config object used to create this decoration. You can - include additional properties in there to store metadata about - your decoration. - */ - spec) { - super(); - this.startSide = startSide; - this.endSide = endSide; - this.widget = widget; - this.spec = spec; - } - /** - @internal - */ - get heightRelevant() { return false; } - /** - Create a mark decoration, which influences the styling of the - content in its range. Nested mark decorations will cause nested - DOM elements to be created. Nesting order is determined by - precedence of the [facet](https://codemirror.net/6/docs/ref/#view.EditorView^decorations) or - (below the facet-provided decorations) [view - plugin](https://codemirror.net/6/docs/ref/#view.PluginSpec.decorations). Such elements are split - on line boundaries and on the boundaries of higher-precedence - decorations. - */ - static mark(spec) { - return new MarkDecoration(spec); - } - /** - Create a widget decoration, which adds an element at the given - position. - */ - static widget(spec) { - let side = spec.side || 0, block = !!spec.block; - side += block ? (side > 0 ? 300000000 /* BlockAfter */ : -400000000 /* BlockBefore */) : (side > 0 ? 100000000 /* InlineAfter */ : -100000000 /* InlineBefore */); - return new PointDecoration(spec, side, side, block, spec.widget || null, false); - } - /** - Create a replace decoration which replaces the given range with - a widget, or simply hides it. - */ - static replace(spec) { - let block = !!spec.block, startSide, endSide; - if (spec.isBlockGap) { - startSide = -500000000 /* GapStart */; - endSide = 400000000 /* GapEnd */; - } - else { - let { start, end } = getInclusive(spec, block); - startSide = (start ? (block ? -300000000 /* BlockIncStart */ : -1 /* InlineIncStart */) : 500000000 /* NonIncStart */) - 1; - endSide = (end ? (block ? 200000000 /* BlockIncEnd */ : 1 /* InlineIncEnd */) : -600000000 /* NonIncEnd */) + 1; - } - return new PointDecoration(spec, startSide, endSide, block, spec.widget || null, true); - } - /** - Create a line decoration, which can add DOM attributes to the - line starting at the given position. - */ - static line(spec) { - return new LineDecoration(spec); - } - /** - Build a [`DecorationSet`](https://codemirror.net/6/docs/ref/#view.DecorationSet) from the given - decorated range or ranges. If the ranges aren't already sorted, - pass `true` for `sort` to make the library sort them for you. - */ - static set(of, sort = false) { - return RangeSet.of(of, sort); - } - /** - @internal - */ - hasHeight() { return this.widget ? this.widget.estimatedHeight > -1 : false; } - } - /** - The empty set of decorations. - */ - Decoration.none = RangeSet.empty; - class MarkDecoration extends Decoration { - constructor(spec) { - let { start, end } = getInclusive(spec); - super(start ? -1 /* InlineIncStart */ : 500000000 /* NonIncStart */, end ? 1 /* InlineIncEnd */ : -600000000 /* NonIncEnd */, null, spec); - this.tagName = spec.tagName || "span"; - this.class = spec.class || ""; - this.attrs = spec.attributes || null; - } - eq(other) { - return this == other || - other instanceof MarkDecoration && - this.tagName == other.tagName && - this.class == other.class && - attrsEq(this.attrs, other.attrs); - } - range(from, to = from) { - if (from >= to) - throw new RangeError("Mark decorations may not be empty"); - return super.range(from, to); - } - } - MarkDecoration.prototype.point = false; - class LineDecoration extends Decoration { - constructor(spec) { - super(-200000000 /* Line */, -200000000 /* Line */, null, spec); - } - eq(other) { - return other instanceof LineDecoration && attrsEq(this.spec.attributes, other.spec.attributes); - } - range(from, to = from) { - if (to != from) - throw new RangeError("Line decoration ranges must be zero-length"); - return super.range(from, to); - } - } - LineDecoration.prototype.mapMode = MapMode.TrackBefore; - LineDecoration.prototype.point = true; - class PointDecoration extends Decoration { - constructor(spec, startSide, endSide, block, widget, isReplace) { - super(startSide, endSide, widget, spec); - this.block = block; - this.isReplace = isReplace; - this.mapMode = !block ? MapMode.TrackDel : startSide <= 0 ? MapMode.TrackBefore : MapMode.TrackAfter; - } - // Only relevant when this.block == true - get type() { - return this.startSide < this.endSide ? BlockType.WidgetRange - : this.startSide <= 0 ? BlockType.WidgetBefore : BlockType.WidgetAfter; - } - get heightRelevant() { return this.block || !!this.widget && this.widget.estimatedHeight >= 5; } - eq(other) { - return other instanceof PointDecoration && - widgetsEq(this.widget, other.widget) && - this.block == other.block && - this.startSide == other.startSide && this.endSide == other.endSide; - } - range(from, to = from) { - if (this.isReplace && (from > to || (from == to && this.startSide > 0 && this.endSide <= 0))) - throw new RangeError("Invalid range for replacement decoration"); - if (!this.isReplace && to != from) - throw new RangeError("Widget decorations can only have zero-length ranges"); - return super.range(from, to); - } - } - PointDecoration.prototype.point = true; - function getInclusive(spec, block = false) { - let { inclusiveStart: start, inclusiveEnd: end } = spec; - if (start == null) - start = spec.inclusive; - if (end == null) - end = spec.inclusive; - return { start: start !== null && start !== void 0 ? start : block, end: end !== null && end !== void 0 ? end : block }; - } - function widgetsEq(a, b) { - return a == b || !!(a && b && a.compare(b)); - } - function addRange(from, to, ranges, margin = 0) { - let last = ranges.length - 1; - if (last >= 0 && ranges[last] + margin >= from) - ranges[last] = Math.max(ranges[last], to); - else - ranges.push(from, to); - } - - class LineView extends ContentView { - constructor() { - super(...arguments); - this.children = []; - this.length = 0; - this.prevAttrs = undefined; - this.attrs = null; - this.breakAfter = 0; - } - // Consumes source - merge(from, to, source, hasStart, openStart, openEnd) { - if (source) { - if (!(source instanceof LineView)) - return false; - if (!this.dom) - source.transferDOM(this); // Reuse source.dom when appropriate - } - if (hasStart) - this.setDeco(source ? source.attrs : null); - mergeChildrenInto(this, from, to, source ? source.children : [], openStart, openEnd); - return true; - } - split(at) { - let end = new LineView; - end.breakAfter = this.breakAfter; - if (this.length == 0) - return end; - let { i, off } = this.childPos(at); - if (off) { - end.append(this.children[i].split(off), 0); - this.children[i].merge(off, this.children[i].length, null, false, 0, 0); - i++; - } - for (let j = i; j < this.children.length; j++) - end.append(this.children[j], 0); - while (i > 0 && this.children[i - 1].length == 0) - this.children[--i].destroy(); - this.children.length = i; - this.markDirty(); - this.length = at; - return end; - } - transferDOM(other) { - if (!this.dom) - return; - other.setDOM(this.dom); - other.prevAttrs = this.prevAttrs === undefined ? this.attrs : this.prevAttrs; - this.prevAttrs = undefined; - this.dom = null; - } - setDeco(attrs) { - if (!attrsEq(this.attrs, attrs)) { - if (this.dom) { - this.prevAttrs = this.attrs; - this.markDirty(); - } - this.attrs = attrs; - } - } - append(child, openStart) { - joinInlineInto(this, child, openStart); - } - // Only called when building a line view in ContentBuilder - addLineDeco(deco) { - let attrs = deco.spec.attributes, cls = deco.spec.class; - if (attrs) - this.attrs = combineAttrs(attrs, this.attrs || {}); - if (cls) - this.attrs = combineAttrs({ class: cls }, this.attrs || {}); - } - domAtPos(pos) { - return inlineDOMAtPos(this.dom, this.children, pos); - } - reuseDOM(node) { - if (node.nodeName == "DIV") { - this.setDOM(node); - this.dirty |= 4 /* Attrs */ | 2 /* Node */; - } - } - sync(track) { - var _a; - if (!this.dom) { - this.setDOM(document.createElement("div")); - this.dom.className = "cm-line"; - this.prevAttrs = this.attrs ? null : undefined; - } - else if (this.dirty & 4 /* Attrs */) { - clearAttributes(this.dom); - this.dom.className = "cm-line"; - this.prevAttrs = this.attrs ? null : undefined; - } - if (this.prevAttrs !== undefined) { - updateAttrs(this.dom, this.prevAttrs, this.attrs); - this.dom.classList.add("cm-line"); - this.prevAttrs = undefined; - } - super.sync(track); - let last = this.dom.lastChild; - while (last && ContentView.get(last) instanceof MarkView) - last = last.lastChild; - if (!last || !this.length || - last.nodeName != "BR" && ((_a = ContentView.get(last)) === null || _a === void 0 ? void 0 : _a.isEditable) == false && - (!browser.ios || !this.children.some(ch => ch instanceof TextView))) { - let hack = document.createElement("BR"); - hack.cmIgnore = true; - this.dom.appendChild(hack); - } - } - measureTextSize() { - if (this.children.length == 0 || this.length > 20) - return null; - let totalWidth = 0; - for (let child of this.children) { - if (!(child instanceof TextView)) - return null; - let rects = clientRectsFor(child.dom); - if (rects.length != 1) - return null; - totalWidth += rects[0].width; - } - return { lineHeight: this.dom.getBoundingClientRect().height, - charWidth: totalWidth / this.length }; - } - coordsAt(pos, side) { - return coordsInChildren(this, pos, side); - } - become(_other) { return false; } - get type() { return BlockType.Text; } - static find(docView, pos) { - for (let i = 0, off = 0; i < docView.children.length; i++) { - let block = docView.children[i], end = off + block.length; - if (end >= pos) { - if (block instanceof LineView) - return block; - if (end > pos) - break; - } - off = end + block.breakAfter; - } - return null; - } - } - class BlockWidgetView extends ContentView { - constructor(widget, length, type) { - super(); - this.widget = widget; - this.length = length; - this.type = type; - this.breakAfter = 0; - this.prevWidget = null; - } - merge(from, to, source, _takeDeco, openStart, openEnd) { - if (source && (!(source instanceof BlockWidgetView) || !this.widget.compare(source.widget) || - from > 0 && openStart <= 0 || to < this.length && openEnd <= 0)) - return false; - this.length = from + (source ? source.length : 0) + (this.length - to); - return true; - } - domAtPos(pos) { - return pos == 0 ? DOMPos.before(this.dom) : DOMPos.after(this.dom, pos == this.length); - } - split(at) { - let len = this.length - at; - this.length = at; - let end = new BlockWidgetView(this.widget, len, this.type); - end.breakAfter = this.breakAfter; - return end; - } - get children() { return noChildren; } - sync() { - if (!this.dom || !this.widget.updateDOM(this.dom)) { - if (this.dom && this.prevWidget) - this.prevWidget.destroy(this.dom); - this.prevWidget = null; - this.setDOM(this.widget.toDOM(this.editorView)); - this.dom.contentEditable = "false"; - } - } - get overrideDOMText() { - return this.parent ? this.parent.view.state.doc.slice(this.posAtStart, this.posAtEnd) : Text.empty; - } - domBoundsAround() { return null; } - become(other) { - if (other instanceof BlockWidgetView && other.type == this.type && - other.widget.constructor == this.widget.constructor) { - if (!other.widget.eq(this.widget)) - this.markDirty(true); - if (this.dom && !this.prevWidget) - this.prevWidget = this.widget; - this.widget = other.widget; - this.length = other.length; - this.breakAfter = other.breakAfter; - return true; - } - return false; - } - ignoreMutation() { return true; } - ignoreEvent(event) { return this.widget.ignoreEvent(event); } - destroy() { - super.destroy(); - if (this.dom) - this.widget.destroy(this.dom); - } - } - - class ContentBuilder { - constructor(doc, pos, end, disallowBlockEffectsBelow) { - this.doc = doc; - this.pos = pos; - this.end = end; - this.disallowBlockEffectsBelow = disallowBlockEffectsBelow; - this.content = []; - this.curLine = null; - this.breakAtStart = 0; - this.pendingBuffer = 0 /* No */; - // Set to false directly after a widget that covers the position after it - this.atCursorPos = true; - this.openStart = -1; - this.openEnd = -1; - this.text = ""; - this.textOff = 0; - this.cursor = doc.iter(); - this.skip = pos; - } - posCovered() { - if (this.content.length == 0) - return !this.breakAtStart && this.doc.lineAt(this.pos).from != this.pos; - let last = this.content[this.content.length - 1]; - return !last.breakAfter && !(last instanceof BlockWidgetView && last.type == BlockType.WidgetBefore); - } - getLine() { - if (!this.curLine) { - this.content.push(this.curLine = new LineView); - this.atCursorPos = true; - } - return this.curLine; - } - flushBuffer(active) { - if (this.pendingBuffer) { - this.curLine.append(wrapMarks(new WidgetBufferView(-1), active), active.length); - this.pendingBuffer = 0 /* No */; - } - } - addBlockWidget(view) { - this.flushBuffer([]); - this.curLine = null; - this.content.push(view); - } - finish(openEnd) { - if (!openEnd) - this.flushBuffer([]); - else - this.pendingBuffer = 0 /* No */; - if (!this.posCovered()) - this.getLine(); - } - buildText(length, active, openStart) { - while (length > 0) { - if (this.textOff == this.text.length) { - let { value, lineBreak, done } = this.cursor.next(this.skip); - this.skip = 0; - if (done) - throw new Error("Ran out of text content when drawing inline views"); - if (lineBreak) { - if (!this.posCovered()) - this.getLine(); - if (this.content.length) - this.content[this.content.length - 1].breakAfter = 1; - else - this.breakAtStart = 1; - this.flushBuffer([]); - this.curLine = null; - length--; - continue; - } - else { - this.text = value; - this.textOff = 0; - } - } - let take = Math.min(this.text.length - this.textOff, length, 512 /* Chunk */); - this.flushBuffer(active.slice(0, openStart)); - this.getLine().append(wrapMarks(new TextView(this.text.slice(this.textOff, this.textOff + take)), active), openStart); - this.atCursorPos = true; - this.textOff += take; - length -= take; - openStart = 0; - } - } - span(from, to, active, openStart) { - this.buildText(to - from, active, openStart); - this.pos = to; - if (this.openStart < 0) - this.openStart = openStart; - } - point(from, to, deco, active, openStart) { - let len = to - from; - if (deco instanceof PointDecoration) { - if (deco.block) { - let { type } = deco; - if (type == BlockType.WidgetAfter && !this.posCovered()) - this.getLine(); - this.addBlockWidget(new BlockWidgetView(deco.widget || new NullWidget("div"), len, type)); - } - else { - let view = WidgetView.create(deco.widget || new NullWidget("span"), len, deco.startSide); - let cursorBefore = this.atCursorPos && !view.isEditable && openStart <= active.length && (from < to || deco.startSide > 0); - let cursorAfter = !view.isEditable && (from < to || deco.startSide <= 0); - let line = this.getLine(); - if (this.pendingBuffer == 2 /* IfCursor */ && !cursorBefore) - this.pendingBuffer = 0 /* No */; - this.flushBuffer(active); - if (cursorBefore) { - line.append(wrapMarks(new WidgetBufferView(1), active), openStart); - openStart = active.length + Math.max(0, openStart - active.length); - } - line.append(wrapMarks(view, active), openStart); - this.atCursorPos = cursorAfter; - this.pendingBuffer = !cursorAfter ? 0 /* No */ : from < to ? 1 /* Yes */ : 2 /* IfCursor */; - } - } - else if (this.doc.lineAt(this.pos).from == this.pos) { // Line decoration - this.getLine().addLineDeco(deco); - } - if (len) { - // Advance the iterator past the replaced content - if (this.textOff + len <= this.text.length) { - this.textOff += len; - } - else { - this.skip += len - (this.text.length - this.textOff); - this.text = ""; - this.textOff = 0; - } - this.pos = to; - } - if (this.openStart < 0) - this.openStart = openStart; - } - filterPoint(from, to, value, index) { - if (index < this.disallowBlockEffectsBelow && value instanceof PointDecoration) { - if (value.block) - throw new RangeError("Block decorations may not be specified via plugins"); - if (to > this.doc.lineAt(this.pos).to) - throw new RangeError("Decorations that replace line breaks may not be specified via plugins"); - } - return true; - } - static build(text, from, to, decorations, pluginDecorationLength) { - let builder = new ContentBuilder(text, from, to, pluginDecorationLength); - builder.openEnd = RangeSet.spans(decorations, from, to, builder); - if (builder.openStart < 0) - builder.openStart = builder.openEnd; - builder.finish(builder.openEnd); - return builder; - } - } - function wrapMarks(view, active) { - for (let mark of active) - view = new MarkView(mark, [view], view.length); - return view; - } - class NullWidget extends WidgetType { - constructor(tag) { - super(); - this.tag = tag; - } - eq(other) { return other.tag == this.tag; } - toDOM() { return document.createElement(this.tag); } - updateDOM(elt) { return elt.nodeName.toLowerCase() == this.tag; } - } - - const none$2 = []; - const clickAddsSelectionRange = /*@__PURE__*/Facet.define(); - const dragMovesSelection$1 = /*@__PURE__*/Facet.define(); - const mouseSelectionStyle = /*@__PURE__*/Facet.define(); - const exceptionSink = /*@__PURE__*/Facet.define(); - const updateListener = /*@__PURE__*/Facet.define(); - const inputHandler$1 = /*@__PURE__*/Facet.define(); - // FIXME remove - const scrollTo = /*@__PURE__*/StateEffect.define({ - map: (range, changes) => range.map(changes) - }); - // FIXME remove - const centerOn = /*@__PURE__*/StateEffect.define({ - map: (range, changes) => range.map(changes) - }); - class ScrollTarget { - constructor(range, y = "nearest", x = "nearest", yMargin = 5, xMargin = 5) { - this.range = range; - this.y = y; - this.x = x; - this.yMargin = yMargin; - this.xMargin = xMargin; - } - map(changes) { - return changes.empty ? this : new ScrollTarget(this.range.map(changes), this.y, this.x, this.yMargin, this.xMargin); - } - } - const scrollIntoView$1 = /*@__PURE__*/StateEffect.define({ map: (t, ch) => t.map(ch) }); - /** - Log or report an unhandled exception in client code. Should - probably only be used by extension code that allows client code to - provide functions, and calls those functions in a context where an - exception can't be propagated to calling code in a reasonable way - (for example when in an event handler). - - Either calls a handler registered with - [`EditorView.exceptionSink`](https://codemirror.net/6/docs/ref/#view.EditorView^exceptionSink), - `window.onerror`, if defined, or `console.error` (in which case - it'll pass `context`, when given, as first argument). - */ - function logException(state, exception, context) { - let handler = state.facet(exceptionSink); - if (handler.length) - handler[0](exception); - else if (window.onerror) - window.onerror(String(exception), context, undefined, undefined, exception); - else if (context) - console.error(context + ":", exception); - else - console.error(exception); - } - const editable = /*@__PURE__*/Facet.define({ combine: values => values.length ? values[0] : true }); - /** - Used to [declare](https://codemirror.net/6/docs/ref/#view.PluginSpec.provide) which - [fields](https://codemirror.net/6/docs/ref/#view.PluginValue) a [view plugin](https://codemirror.net/6/docs/ref/#view.ViewPlugin) - provides. - */ - class PluginFieldProvider { - /** - @internal - */ - constructor( - /** - @internal - */ - field, - /** - @internal - */ - get) { - this.field = field; - this.get = get; - } - } - /** - Plugin fields are a mechanism for allowing plugins to provide - values that can be retrieved through the - [`pluginField`](https://codemirror.net/6/docs/ref/#view.EditorView.pluginField) view method. - */ - class PluginField { - /** - Create a [provider](https://codemirror.net/6/docs/ref/#view.PluginFieldProvider) for this field, - to use with a plugin's [provide](https://codemirror.net/6/docs/ref/#view.PluginSpec.provide) - option. - */ - from(get) { - return new PluginFieldProvider(this, get); - } - /** - Define a new plugin field. - */ - static define() { return new PluginField(); } - } - /** - This field can be used by plugins to provide - [decorations](https://codemirror.net/6/docs/ref/#view.Decoration). - - **Note**: For reasons of data flow (plugins are only updated - after the viewport is computed), decorations produced by plugins - are _not_ taken into account when predicting the vertical layout - structure of the editor. They **must not** introduce block - widgets (that will raise an error) or replacing decorations that - cover line breaks (these will be ignored if they occur). Such - decorations, or others that cause a large amount of vertical - size shift compared to the undecorated content, should be - provided through the state-level [`decorations` - facet](https://codemirror.net/6/docs/ref/#view.EditorView^decorations) instead. - */ - PluginField.decorations = /*@__PURE__*/PluginField.define(); - /** - Used to provide ranges that should be treated as atoms as far as - cursor motion is concerned. This causes methods like - [`moveByChar`](https://codemirror.net/6/docs/ref/#view.EditorView.moveByChar) and - [`moveVertically`](https://codemirror.net/6/docs/ref/#view.EditorView.moveVertically) (and the - commands built on top of them) to skip across such regions when - a selection endpoint would enter them. This does _not_ prevent - direct programmatic [selection - updates](https://codemirror.net/6/docs/ref/#state.TransactionSpec.selection) from moving into such - regions. - */ - PluginField.atomicRanges = /*@__PURE__*/PluginField.define(); - /** - Plugins can provide additional scroll margins (space around the - sides of the scrolling element that should be considered - invisible) through this field. This can be useful when the - plugin introduces elements that cover part of that element (for - example a horizontally fixed gutter). - */ - PluginField.scrollMargins = /*@__PURE__*/PluginField.define(); - let nextPluginID = 0; - const viewPlugin = /*@__PURE__*/Facet.define(); - /** - View plugins associate stateful values with a view. They can - influence the way the content is drawn, and are notified of things - that happen in the view. - */ - class ViewPlugin { - constructor( - /** - @internal - */ - id, - /** - @internal - */ - create, - /** - @internal - */ - fields) { - this.id = id; - this.create = create; - this.fields = fields; - this.extension = viewPlugin.of(this); - } - /** - Define a plugin from a constructor function that creates the - plugin's value, given an editor view. - */ - static define(create, spec) { - let { eventHandlers, provide, decorations } = spec || {}; - let fields = []; - if (provide) - for (let provider of Array.isArray(provide) ? provide : [provide]) - fields.push(provider); - if (eventHandlers) - fields.push(domEventHandlers.from((value) => ({ plugin: value, handlers: eventHandlers }))); - if (decorations) - fields.push(PluginField.decorations.from(decorations)); - return new ViewPlugin(nextPluginID++, create, fields); - } - /** - Create a plugin for a class whose constructor takes a single - editor view as argument. - */ - static fromClass(cls, spec) { - return ViewPlugin.define(view => new cls(view), spec); - } - } - const domEventHandlers = /*@__PURE__*/PluginField.define(); - class PluginInstance { - constructor(spec) { - this.spec = spec; - // When starting an update, all plugins have this field set to the - // update object, indicating they need to be updated. When finished - // updating, it is set to `false`. Retrieving a plugin that needs to - // be updated with `view.plugin` forces an eager update. - this.mustUpdate = null; - // This is null when the plugin is initially created, but - // initialized on the first update. - this.value = null; - } - takeField(type, target) { - if (this.spec) - for (let { field, get } of this.spec.fields) - if (field == type) - target.push(get(this.value)); - } - update(view) { - if (!this.value) { - if (this.spec) { - try { - this.value = this.spec.create(view); - } - catch (e) { - logException(view.state, e, "CodeMirror plugin crashed"); - this.deactivate(); - } - } - } - else if (this.mustUpdate) { - let update = this.mustUpdate; - this.mustUpdate = null; - if (this.value.update) { - try { - this.value.update(update); - } - catch (e) { - logException(update.state, e, "CodeMirror plugin crashed"); - if (this.value.destroy) - try { - this.value.destroy(); - } - catch (_) { } - this.deactivate(); - } - } - } - return this; - } - destroy(view) { - var _a; - if ((_a = this.value) === null || _a === void 0 ? void 0 : _a.destroy) { - try { - this.value.destroy(); - } - catch (e) { - logException(view.state, e, "CodeMirror plugin crashed"); - } - } - } - deactivate() { - this.spec = this.value = null; - } - } - const editorAttributes = /*@__PURE__*/Facet.define(); - const contentAttributes = /*@__PURE__*/Facet.define(); - // Provide decorations - const decorations = /*@__PURE__*/Facet.define(); - const styleModule = /*@__PURE__*/Facet.define(); - class ChangedRange { - constructor(fromA, toA, fromB, toB) { - this.fromA = fromA; - this.toA = toA; - this.fromB = fromB; - this.toB = toB; - } - join(other) { - return new ChangedRange(Math.min(this.fromA, other.fromA), Math.max(this.toA, other.toA), Math.min(this.fromB, other.fromB), Math.max(this.toB, other.toB)); - } - addToSet(set) { - let i = set.length, me = this; - for (; i > 0; i--) { - let range = set[i - 1]; - if (range.fromA > me.toA) - continue; - if (range.toA < me.fromA) - break; - me = me.join(range); - set.splice(i - 1, 1); - } - set.splice(i, 0, me); - return set; - } - static extendWithRanges(diff, ranges) { - if (ranges.length == 0) - return diff; - let result = []; - for (let dI = 0, rI = 0, posA = 0, posB = 0;; dI++) { - let next = dI == diff.length ? null : diff[dI], off = posA - posB; - let end = next ? next.fromB : 1e9; - while (rI < ranges.length && ranges[rI] < end) { - let from = ranges[rI], to = ranges[rI + 1]; - let fromB = Math.max(posB, from), toB = Math.min(end, to); - if (fromB <= toB) - new ChangedRange(fromB + off, toB + off, fromB, toB).addToSet(result); - if (to > end) - break; - else - rI += 2; - } - if (!next) - return result; - new ChangedRange(next.fromA, next.toA, next.fromB, next.toB).addToSet(result); - posA = next.toA; - posB = next.toB; - } - } - } - /** - View [plugins](https://codemirror.net/6/docs/ref/#view.ViewPlugin) are given instances of this - class, which describe what happened, whenever the view is updated. - */ - class ViewUpdate { - /** - @internal - */ - constructor( - /** - The editor view that the update is associated with. - */ - view, - /** - The new editor state. - */ - state, - /** - The transactions involved in the update. May be empty. - */ - transactions = none$2) { - this.view = view; - this.state = state; - this.transactions = transactions; - /** - @internal - */ - this.flags = 0; - this.startState = view.state; - this.changes = ChangeSet.empty(this.startState.doc.length); - for (let tr of transactions) - this.changes = this.changes.compose(tr.changes); - let changedRanges = []; - this.changes.iterChangedRanges((fromA, toA, fromB, toB) => changedRanges.push(new ChangedRange(fromA, toA, fromB, toB))); - this.changedRanges = changedRanges; - let focus = view.hasFocus; - if (focus != view.inputState.notifiedFocused) { - view.inputState.notifiedFocused = focus; - this.flags |= 1 /* Focus */; - } - } - /** - Tells you whether the [viewport](https://codemirror.net/6/docs/ref/#view.EditorView.viewport) or - [visible ranges](https://codemirror.net/6/docs/ref/#view.EditorView.visibleRanges) changed in this - update. - */ - get viewportChanged() { - return (this.flags & 4 /* Viewport */) > 0; - } - /** - Indicates whether the height of an element in the editor changed - in this update. - */ - get heightChanged() { - return (this.flags & 2 /* Height */) > 0; - } - /** - Returns true when the document was modified or the size of the - editor, or elements within the editor, changed. - */ - get geometryChanged() { - return this.docChanged || (this.flags & (8 /* Geometry */ | 2 /* Height */)) > 0; - } - /** - True when this update indicates a focus change. - */ - get focusChanged() { - return (this.flags & 1 /* Focus */) > 0; - } - /** - Whether the document changed in this update. - */ - get docChanged() { - return !this.changes.empty; - } - /** - Whether the selection was explicitly set in this update. - */ - get selectionSet() { - return this.transactions.some(tr => tr.selection); - } - /** - @internal - */ - get empty() { return this.flags == 0 && this.transactions.length == 0; } - } - - /** - Used to indicate [text direction](https://codemirror.net/6/docs/ref/#view.EditorView.textDirection). - */ - var Direction = /*@__PURE__*/(function (Direction) { - // (These are chosen to match the base levels, in bidi algorithm - // terms, of spans in that direction.) - /** - Left-to-right. - */ - Direction[Direction["LTR"] = 0] = "LTR"; - /** - Right-to-left. - */ - Direction[Direction["RTL"] = 1] = "RTL"; - return Direction})(Direction || (Direction = {})); - const LTR = Direction.LTR, RTL = Direction.RTL; - // Decode a string with each type encoded as log2(type) - function dec(str) { - let result = []; - for (let i = 0; i < str.length; i++) - result.push(1 << +str[i]); - return result; - } - // Character types for codepoints 0 to 0xf8 - const LowTypes = /*@__PURE__*/dec("88888888888888888888888888888888888666888888787833333333337888888000000000000000000000000008888880000000000000000000000000088888888888888888888888888888888888887866668888088888663380888308888800000000000000000000000800000000000000000000000000000008"); - // Character types for codepoints 0x600 to 0x6f9 - const ArabicTypes = /*@__PURE__*/dec("4444448826627288999999999992222222222222222222222222222222222222222222222229999999999999999999994444444444644222822222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222999999949999999229989999223333333333"); - const Brackets = /*@__PURE__*/Object.create(null), BracketStack = []; - // There's a lot more in - // https://www.unicode.org/Public/UCD/latest/ucd/BidiBrackets.txt, - // which are left out to keep code size down. - for (let p of ["()", "[]", "{}"]) { - let l = /*@__PURE__*/p.charCodeAt(0), r = /*@__PURE__*/p.charCodeAt(1); - Brackets[l] = r; - Brackets[r] = -l; - } - function charType(ch) { - return ch <= 0xf7 ? LowTypes[ch] : - 0x590 <= ch && ch <= 0x5f4 ? 2 /* R */ : - 0x600 <= ch && ch <= 0x6f9 ? ArabicTypes[ch - 0x600] : - 0x6ee <= ch && ch <= 0x8ac ? 4 /* AL */ : - 0x2000 <= ch && ch <= 0x200b ? 256 /* NI */ : - ch == 0x200c ? 256 /* NI */ : 1 /* L */; - } - const BidiRE = /[\u0590-\u05f4\u0600-\u06ff\u0700-\u08ac]/; - /** - Represents a contiguous range of text that has a single direction - (as in left-to-right or right-to-left). - */ - class BidiSpan { - /** - @internal - */ - constructor( - /** - The start of the span (relative to the start of the line). - */ - from, - /** - The end of the span. - */ - to, - /** - The ["bidi - level"](https://unicode.org/reports/tr9/#Basic_Display_Algorithm) - of the span (in this context, 0 means - left-to-right, 1 means right-to-left, 2 means left-to-right - number inside right-to-left text). - */ - level) { - this.from = from; - this.to = to; - this.level = level; - } - /** - The direction of this span. - */ - get dir() { return this.level % 2 ? RTL : LTR; } - /** - @internal - */ - side(end, dir) { return (this.dir == dir) == end ? this.to : this.from; } - /** - @internal - */ - static find(order, index, level, assoc) { - let maybe = -1; - for (let i = 0; i < order.length; i++) { - let span = order[i]; - if (span.from <= index && span.to >= index) { - if (span.level == level) - return i; - // When multiple spans match, if assoc != 0, take the one that - // covers that side, otherwise take the one with the minimum - // level. - if (maybe < 0 || (assoc != 0 ? (assoc < 0 ? span.from < index : span.to > index) : order[maybe].level > span.level)) - maybe = i; - } - } - if (maybe < 0) - throw new RangeError("Index out of range"); - return maybe; - } - } - // Reused array of character types - const types = []; - function computeOrder(line, direction) { - let len = line.length, outerType = direction == LTR ? 1 /* L */ : 2 /* R */, oppositeType = direction == LTR ? 2 /* R */ : 1 /* L */; - if (!line || outerType == 1 /* L */ && !BidiRE.test(line)) - return trivialOrder(len); - // 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. - // 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. - // (Left after this: L, R, EN, AN, ET, CS, NI) - for (let i = 0, prev = outerType, prevStrong = outerType; i < len; i++) { - let type = charType(line.charCodeAt(i)); - if (type == 512 /* NSM */) - type = prev; - else if (type == 8 /* EN */ && prevStrong == 4 /* AL */) - type = 16 /* AN */; - types[i] = type == 4 /* AL */ ? 2 /* R */ : type; - if (type & 7 /* Strong */) - prevStrong = type; - prev = type; - } - // W5. A sequence of European terminators adjacent to European - // numbers changes to all European numbers. - // W6. Otherwise, separators and terminators change to Other - // Neutral. - // 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. - // (Left after this: L, R, EN+AN, NI) - for (let i = 0, prev = outerType, prevStrong = outerType; i < len; i++) { - let type = types[i]; - if (type == 128 /* CS */) { - if (i < len - 1 && prev == types[i + 1] && (prev & 24 /* Num */)) - type = types[i] = prev; - else - types[i] = 256 /* NI */; - } - else if (type == 64 /* ET */) { - let end = i + 1; - while (end < len && types[end] == 64 /* ET */) - end++; - let replace = (i && prev == 8 /* EN */) || (end < len && types[end] == 8 /* EN */) ? (prevStrong == 1 /* L */ ? 1 /* L */ : 8 /* EN */) : 256 /* NI */; - for (let j = i; j < end; j++) - types[j] = replace; - i = end - 1; - } - else if (type == 8 /* EN */ && prevStrong == 1 /* L */) { - types[i] = 1 /* L */; - } - prev = type; - if (type & 7 /* Strong */) - prevStrong = type; - } - // N0. Process bracket pairs in an isolating run sequence - // sequentially in the logical order of the text positions of the - // opening paired brackets using the logic given below. Within this - // scope, bidirectional types EN and AN are treated as R. - for (let i = 0, sI = 0, context = 0, ch, br, type; i < len; i++) { - // Keeps [startIndex, type, strongSeen] triples for each open - // bracket on BracketStack. - if (br = Brackets[ch = line.charCodeAt(i)]) { - if (br < 0) { // Closing bracket - for (let sJ = sI - 3; sJ >= 0; sJ -= 3) { - if (BracketStack[sJ + 1] == -br) { - let flags = BracketStack[sJ + 2]; - let type = (flags & 2 /* EmbedInside */) ? outerType : - !(flags & 4 /* OppositeInside */) ? 0 : - (flags & 1 /* OppositeBefore */) ? oppositeType : outerType; - if (type) - types[i] = types[BracketStack[sJ]] = type; - sI = sJ; - break; - } - } - } - else if (BracketStack.length == 189 /* MaxDepth */) { - break; - } - else { - BracketStack[sI++] = i; - BracketStack[sI++] = ch; - BracketStack[sI++] = context; - } - } - else if ((type = types[i]) == 2 /* R */ || type == 1 /* L */) { - let embed = type == outerType; - context = embed ? 0 : 1 /* OppositeBefore */; - for (let sJ = sI - 3; sJ >= 0; sJ -= 3) { - let cur = BracketStack[sJ + 2]; - if (cur & 2 /* EmbedInside */) - break; - if (embed) { - BracketStack[sJ + 2] |= 2 /* EmbedInside */; - } - else { - if (cur & 4 /* OppositeInside */) - break; - BracketStack[sJ + 2] |= 4 /* OppositeInside */; - } - } - } - } - // 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. - // (Left after this: L, R, EN+AN) - for (let i = 0; i < len; i++) { - if (types[i] == 256 /* NI */) { - let end = i + 1; - while (end < len && types[end] == 256 /* NI */) - end++; - let beforeL = (i ? types[i - 1] : outerType) == 1 /* L */; - let afterL = (end < len ? types[end] : outerType) == 1 /* L */; - let replace = beforeL == afterL ? (beforeL ? 1 /* L */ : 2 /* R */) : outerType; - for (let j = i; j < end; j++) - types[j] = replace; - i = end - 1; - } - } - // Here we depart from the documented algorithm, in order to avoid - // building up an actual levels array. Since there are only three - // levels (0, 1, 2) in an implementation that doesn't take - // explicit embedding into account, we can build up the order on - // the fly, without following the level-based algorithm. - let order = []; - if (outerType == 1 /* L */) { - for (let i = 0; i < len;) { - let start = i, rtl = types[i++] != 1 /* L */; - while (i < len && rtl == (types[i] != 1 /* L */)) - i++; - if (rtl) { - for (let j = i; j > start;) { - let end = j, l = types[--j] != 2 /* R */; - while (j > start && l == (types[j - 1] != 2 /* R */)) - j--; - order.push(new BidiSpan(j, end, l ? 2 : 1)); - } - } - else { - order.push(new BidiSpan(start, i, 0)); - } - } - } - else { - for (let i = 0; i < len;) { - let start = i, rtl = types[i++] == 2 /* R */; - while (i < len && rtl == (types[i] == 2 /* R */)) - i++; - order.push(new BidiSpan(start, i, rtl ? 1 : 2)); - } - } - return order; - } - function trivialOrder(length) { - return [new BidiSpan(0, length, 0)]; - } - let movedOver = ""; - function moveVisually(line, order, dir, start, forward) { - var _a; - let startIndex = start.head - line.from, spanI = -1; - if (startIndex == 0) { - if (!forward || !line.length) - return null; - if (order[0].level != dir) { - startIndex = order[0].side(false, dir); - spanI = 0; - } - } - else if (startIndex == line.length) { - if (forward) - return null; - let last = order[order.length - 1]; - if (last.level != dir) { - startIndex = last.side(true, dir); - spanI = order.length - 1; - } - } - if (spanI < 0) - spanI = BidiSpan.find(order, startIndex, (_a = start.bidiLevel) !== null && _a !== void 0 ? _a : -1, start.assoc); - let span = order[spanI]; - // End of span. (But not end of line--that was checked for above.) - if (startIndex == span.side(forward, dir)) { - span = order[spanI += forward ? 1 : -1]; - startIndex = span.side(!forward, dir); - } - let indexForward = forward == (span.dir == dir); - let nextIndex = findClusterBreak(line.text, startIndex, indexForward); - movedOver = line.text.slice(Math.min(startIndex, nextIndex), Math.max(startIndex, nextIndex)); - if (nextIndex != span.side(forward, dir)) - return EditorSelection.cursor(nextIndex + line.from, indexForward ? -1 : 1, span.level); - let nextSpan = spanI == (forward ? order.length - 1 : 0) ? null : order[spanI + (forward ? 1 : -1)]; - if (!nextSpan && span.level != dir) - return EditorSelection.cursor(forward ? line.to : line.from, forward ? -1 : 1, dir); - if (nextSpan && nextSpan.level < span.level) - return EditorSelection.cursor(nextSpan.side(!forward, dir) + line.from, forward ? 1 : -1, nextSpan.level); - return EditorSelection.cursor(nextIndex + line.from, forward ? -1 : 1, span.level); - } - - const LineBreakPlaceholder = "\uffff"; - class DOMReader { - constructor(points, state) { - this.points = points; - this.text = ""; - this.lineSeparator = state.facet(EditorState.lineSeparator); - } - append(text) { - this.text += text; - } - lineBreak() { - this.text += LineBreakPlaceholder; - } - readRange(start, end) { - if (!start) - return this; - let parent = start.parentNode; - for (let cur = start;;) { - this.findPointBefore(parent, cur); - this.readNode(cur); - let next = cur.nextSibling; - if (next == end) - break; - let view = ContentView.get(cur), nextView = ContentView.get(next); - if (view && nextView ? view.breakAfter : - (view ? view.breakAfter : isBlockElement(cur)) || - (isBlockElement(next) && (cur.nodeName != "BR" || cur.cmIgnore))) - this.lineBreak(); - cur = next; - } - this.findPointBefore(parent, end); - return this; - } - readTextNode(node) { - let text = node.nodeValue; - for (let point of this.points) - if (point.node == node) - point.pos = this.text.length + Math.min(point.offset, text.length); - for (let off = 0, re = this.lineSeparator ? null : /\r\n?|\n/g;;) { - let nextBreak = -1, breakSize = 1, m; - if (this.lineSeparator) { - nextBreak = text.indexOf(this.lineSeparator, off); - breakSize = this.lineSeparator.length; - } - else if (m = re.exec(text)) { - nextBreak = m.index; - breakSize = m[0].length; - } - this.append(text.slice(off, nextBreak < 0 ? text.length : nextBreak)); - if (nextBreak < 0) - break; - this.lineBreak(); - if (breakSize > 1) - for (let point of this.points) - if (point.node == node && point.pos > this.text.length) - point.pos -= breakSize - 1; - off = nextBreak + breakSize; - } - } - readNode(node) { - if (node.cmIgnore) - return; - let view = ContentView.get(node); - let fromView = view && view.overrideDOMText; - if (fromView != null) { - this.findPointInside(node, fromView.length); - for (let i = fromView.iter(); !i.next().done;) { - if (i.lineBreak) - this.lineBreak(); - else - this.append(i.value); - } - } - else if (node.nodeType == 3) { - this.readTextNode(node); - } - else if (node.nodeName == "BR") { - if (node.nextSibling) - this.lineBreak(); - } - else if (node.nodeType == 1) { - this.readRange(node.firstChild, null); - } - } - findPointBefore(node, next) { - for (let point of this.points) - if (point.node == node && node.childNodes[point.offset] == next) - point.pos = this.text.length; - } - findPointInside(node, maxLen) { - for (let point of this.points) - if (node.nodeType == 3 ? point.node == node : node.contains(point.node)) - point.pos = this.text.length + Math.min(maxLen, point.offset); - } - } - function isBlockElement(node) { - return node.nodeType == 1 && /^(DIV|P|LI|UL|OL|BLOCKQUOTE|DD|DT|H\d|SECTION|PRE)$/.test(node.nodeName); - } - class DOMPoint { - constructor(node, offset) { - this.node = node; - this.offset = offset; - this.pos = -1; - } - } - - class DocView extends ContentView { - constructor(view) { - super(); - this.view = view; - this.compositionDeco = Decoration.none; - this.decorations = []; - this.pluginDecorationLength = 0; - // Track a minimum width for the editor. When measuring sizes in - // measureVisibleLineHeights, this is updated to point at the width - // of a given element and its extent in the document. When a change - // happens in that range, these are reset. That way, once we've seen - // a line/element of a given length, we keep the editor wide enough - // to fit at least that element, until it is changed, at which point - // we forget it again. - this.minWidth = 0; - this.minWidthFrom = 0; - this.minWidthTo = 0; - // Track whether the DOM selection was set in a lossy way, so that - // we don't mess it up when reading it back it - this.impreciseAnchor = null; - this.impreciseHead = null; - this.forceSelection = false; - // Used by the resize observer to ignore resizes that we caused - // ourselves - this.lastUpdate = Date.now(); - this.setDOM(view.contentDOM); - this.children = [new LineView]; - this.children[0].setParent(this); - this.updateDeco(); - this.updateInner([new ChangedRange(0, 0, 0, view.state.doc.length)], 0); - } - get root() { return this.view.root; } - get editorView() { return this.view; } - get length() { return this.view.state.doc.length; } - // Update the document view to a given state. scrollIntoView can be - // used as a hint to compute a new viewport that includes that - // position, if we know the editor is going to scroll that position - // into view. - update(update) { - let changedRanges = update.changedRanges; - if (this.minWidth > 0 && changedRanges.length) { - if (!changedRanges.every(({ fromA, toA }) => toA < this.minWidthFrom || fromA > this.minWidthTo)) { - this.minWidth = this.minWidthFrom = this.minWidthTo = 0; - } - else { - this.minWidthFrom = update.changes.mapPos(this.minWidthFrom, 1); - this.minWidthTo = update.changes.mapPos(this.minWidthTo, 1); - } - } - if (this.view.inputState.composing < 0) - this.compositionDeco = Decoration.none; - else if (update.transactions.length || this.dirty) - this.compositionDeco = computeCompositionDeco(this.view, update.changes); - // When the DOM nodes around the selection are moved to another - // parent, Chrome sometimes reports a different selection through - // getSelection than the one that it actually shows to the user. - // This forces a selection update when lines are joined to work - // around that. Issue #54 - if ((browser.ie || browser.chrome) && !this.compositionDeco.size && update && - update.state.doc.lines != update.startState.doc.lines) - this.forceSelection = true; - let prevDeco = this.decorations, deco = this.updateDeco(); - let decoDiff = findChangedDeco(prevDeco, deco, update.changes); - changedRanges = ChangedRange.extendWithRanges(changedRanges, decoDiff); - if (this.dirty == 0 /* Not */ && changedRanges.length == 0) { - return false; - } - else { - this.updateInner(changedRanges, update.startState.doc.length); - if (update.transactions.length) - this.lastUpdate = Date.now(); - return true; - } - } - // Used by update and the constructor do perform the actual DOM - // update - updateInner(changes, oldLength) { - this.view.viewState.mustMeasureContent = true; - this.updateChildren(changes, oldLength); - let { observer } = this.view; - observer.ignore(() => { - // Lock the height during redrawing, since Chrome sometimes - // messes with the scroll position during DOM mutation (though - // no relayout is triggered and I cannot imagine how it can - // recompute the scroll position without a layout) - this.dom.style.height = this.view.viewState.contentHeight + "px"; - this.dom.style.minWidth = this.minWidth ? this.minWidth + "px" : ""; - // Chrome will sometimes, when DOM mutations occur directly - // around the selection, get confused and report a different - // selection from the one it displays (issue #218). This tries - // to detect that situation. - let track = browser.chrome || browser.ios ? { node: observer.selectionRange.focusNode, written: false } : undefined; - this.sync(track); - this.dirty = 0 /* Not */; - if (track && (track.written || observer.selectionRange.focusNode != track.node)) - this.forceSelection = true; - this.dom.style.height = ""; - }); - let gaps = []; - if (this.view.viewport.from || this.view.viewport.to < this.view.state.doc.length) - for (let child of this.children) - if (child instanceof BlockWidgetView && child.widget instanceof BlockGapWidget) - gaps.push(child.dom); - observer.updateGaps(gaps); - } - updateChildren(changes, oldLength) { - let cursor = this.childCursor(oldLength); - for (let i = changes.length - 1;; i--) { - let next = i >= 0 ? changes[i] : null; - if (!next) - break; - let { fromA, toA, fromB, toB } = next; - let { content, breakAtStart, openStart, openEnd } = ContentBuilder.build(this.view.state.doc, fromB, toB, this.decorations, this.pluginDecorationLength); - let { i: toI, off: toOff } = cursor.findPos(toA, 1); - let { i: fromI, off: fromOff } = cursor.findPos(fromA, -1); - replaceRange(this, fromI, fromOff, toI, toOff, content, breakAtStart, openStart, openEnd); - } - } - // Sync the DOM selection to this.state.selection - updateSelection(mustRead = false, fromPointer = false) { - if (mustRead) - this.view.observer.readSelectionRange(); - if (!(fromPointer || this.mayControlSelection()) || - browser.ios && this.view.inputState.rapidCompositionStart) - return; - let force = this.forceSelection; - this.forceSelection = false; - let main = this.view.state.selection.main; - // FIXME need to handle the case where the selection falls inside a block range - let anchor = this.domAtPos(main.anchor); - let head = main.empty ? anchor : this.domAtPos(main.head); - // Always reset on Firefox when next to an uneditable node to - // avoid invisible cursor bugs (#111) - if (browser.gecko && main.empty && betweenUneditable(anchor)) { - let dummy = document.createTextNode(""); - this.view.observer.ignore(() => anchor.node.insertBefore(dummy, anchor.node.childNodes[anchor.offset] || null)); - anchor = head = new DOMPos(dummy, 0); - force = true; - } - let domSel = this.view.observer.selectionRange; - // If the selection is already here, or in an equivalent position, don't touch it - if (force || !domSel.focusNode || - !isEquivalentPosition(anchor.node, anchor.offset, domSel.anchorNode, domSel.anchorOffset) || - !isEquivalentPosition(head.node, head.offset, domSel.focusNode, domSel.focusOffset)) { - this.view.observer.ignore(() => { - // Chrome Android will hide the virtual keyboard when tapping - // inside an uneditable node, and not bring it back when we - // move the cursor to its proper position. This tries to - // restore the keyboard by cycling focus. - if (browser.android && browser.chrome && this.dom.contains(domSel.focusNode) && - inUneditable(domSel.focusNode, this.dom)) { - this.dom.blur(); - this.dom.focus({ preventScroll: true }); - } - let rawSel = getSelection(this.root); - if (main.empty) { - // Work around https://bugzilla.mozilla.org/show_bug.cgi?id=1612076 - if (browser.gecko) { - let nextTo = nextToUneditable(anchor.node, anchor.offset); - if (nextTo && nextTo != (1 /* Before */ | 2 /* After */)) { - let text = nearbyTextNode(anchor.node, anchor.offset, nextTo == 1 /* Before */ ? 1 : -1); - if (text) - anchor = new DOMPos(text, nextTo == 1 /* Before */ ? 0 : text.nodeValue.length); - } - } - rawSel.collapse(anchor.node, anchor.offset); - if (main.bidiLevel != null && domSel.cursorBidiLevel != null) - domSel.cursorBidiLevel = main.bidiLevel; - } - else if (rawSel.extend) { - // Selection.extend can be used to create an 'inverted' selection - // (one where the focus is before the anchor), but not all - // browsers support it yet. - rawSel.collapse(anchor.node, anchor.offset); - rawSel.extend(head.node, head.offset); - } - else { - // Primitive (IE) way - let range = document.createRange(); - if (main.anchor > main.head) - [anchor, head] = [head, anchor]; - range.setEnd(head.node, head.offset); - range.setStart(anchor.node, anchor.offset); - rawSel.removeAllRanges(); - rawSel.addRange(range); - } - }); - this.view.observer.setSelectionRange(anchor, head); - } - this.impreciseAnchor = anchor.precise ? null : new DOMPos(domSel.anchorNode, domSel.anchorOffset); - this.impreciseHead = head.precise ? null : new DOMPos(domSel.focusNode, domSel.focusOffset); - } - enforceCursorAssoc() { - if (this.compositionDeco.size) - return; - let cursor = this.view.state.selection.main; - let sel = getSelection(this.root); - if (!cursor.empty || !cursor.assoc || !sel.modify) - return; - let line = LineView.find(this, cursor.head); - if (!line) - return; - let lineStart = line.posAtStart; - if (cursor.head == lineStart || cursor.head == lineStart + line.length) - return; - let before = this.coordsAt(cursor.head, -1), after = this.coordsAt(cursor.head, 1); - if (!before || !after || before.bottom > after.top) - return; - let dom = this.domAtPos(cursor.head + cursor.assoc); - sel.collapse(dom.node, dom.offset); - sel.modify("move", cursor.assoc < 0 ? "forward" : "backward", "lineboundary"); - } - mayControlSelection() { - return this.view.state.facet(editable) ? this.root.activeElement == this.dom - : hasSelection(this.dom, this.view.observer.selectionRange); - } - nearest(dom) { - for (let cur = dom; cur;) { - let domView = ContentView.get(cur); - if (domView && domView.rootView == this) - return domView; - cur = cur.parentNode; - } - return null; - } - posFromDOM(node, offset) { - let view = this.nearest(node); - if (!view) - throw new RangeError("Trying to find position for a DOM position outside of the document"); - return view.localPosFromDOM(node, offset) + view.posAtStart; - } - domAtPos(pos) { - let { i, off } = this.childCursor().findPos(pos, -1); - for (; i < this.children.length - 1;) { - let child = this.children[i]; - if (off < child.length || child instanceof LineView) - break; - i++; - off = 0; - } - return this.children[i].domAtPos(off); - } - coordsAt(pos, side) { - for (let off = this.length, i = this.children.length - 1;; i--) { - let child = this.children[i], start = off - child.breakAfter - child.length; - if (pos > start || - (pos == start && child.type != BlockType.WidgetBefore && child.type != BlockType.WidgetAfter && - (!i || side == 2 || this.children[i - 1].breakAfter || - (this.children[i - 1].type == BlockType.WidgetBefore && side > -2)))) - return child.coordsAt(pos - start, side); - off = start; - } - } - measureVisibleLineHeights() { - let result = [], { from, to } = this.view.viewState.viewport; - let contentWidth = this.view.contentDOM.clientWidth; - let isWider = contentWidth > Math.max(this.view.scrollDOM.clientWidth, this.minWidth) + 1; - let widest = -1; - for (let pos = 0, i = 0; i < this.children.length; i++) { - let child = this.children[i], end = pos + child.length; - if (end > to) - break; - if (pos >= from) { - let childRect = child.dom.getBoundingClientRect(); - result.push(childRect.height); - if (isWider) { - let last = child.dom.lastChild; - let rects = last ? clientRectsFor(last) : []; - if (rects.length) { - let rect = rects[rects.length - 1]; - let width = this.view.textDirection == Direction.LTR ? rect.right - childRect.left - : childRect.right - rect.left; - if (width > widest) { - widest = width; - this.minWidth = contentWidth; - this.minWidthFrom = pos; - this.minWidthTo = end; - } - } - } - } - pos = end + child.breakAfter; - } - return result; - } - measureTextSize() { - for (let child of this.children) { - if (child instanceof LineView) { - let measure = child.measureTextSize(); - if (measure) - return measure; - } - } - // If no workable line exists, force a layout of a measurable element - let dummy = document.createElement("div"), lineHeight, charWidth; - dummy.className = "cm-line"; - dummy.textContent = "abc def ghi jkl mno pqr stu"; - this.view.observer.ignore(() => { - this.dom.appendChild(dummy); - let rect = clientRectsFor(dummy.firstChild)[0]; - lineHeight = dummy.getBoundingClientRect().height; - charWidth = rect ? rect.width / 27 : 7; - dummy.remove(); - }); - return { lineHeight, charWidth }; - } - childCursor(pos = this.length) { - // Move back to start of last element when possible, so that - // `ChildCursor.findPos` doesn't have to deal with the edge case - // of being after the last element. - let i = this.children.length; - if (i) - pos -= this.children[--i].length; - return new ChildCursor(this.children, pos, i); - } - computeBlockGapDeco() { - let deco = [], vs = this.view.viewState; - for (let pos = 0, i = 0;; i++) { - let next = i == vs.viewports.length ? null : vs.viewports[i]; - let end = next ? next.from - 1 : this.length; - if (end > pos) { - let height = vs.lineBlockAt(end).bottom - vs.lineBlockAt(pos).top; - deco.push(Decoration.replace({ - widget: new BlockGapWidget(height), - block: true, - inclusive: true, - isBlockGap: true, - }).range(pos, end)); - } - if (!next) - break; - pos = next.to + 1; - } - return Decoration.set(deco); - } - updateDeco() { - let pluginDecorations = this.view.pluginField(PluginField.decorations); - this.pluginDecorationLength = pluginDecorations.length; - return this.decorations = [ - ...pluginDecorations, - ...this.view.state.facet(decorations), - this.compositionDeco, - this.computeBlockGapDeco(), - this.view.viewState.lineGapDeco - ]; - } - scrollIntoView(target) { - let { range } = target; - let rect = this.coordsAt(range.head, range.empty ? range.assoc : range.head > range.anchor ? -1 : 1), other; - if (!rect) - return; - if (!range.empty && (other = this.coordsAt(range.anchor, range.anchor > range.head ? -1 : 1))) - rect = { left: Math.min(rect.left, other.left), top: Math.min(rect.top, other.top), - right: Math.max(rect.right, other.right), bottom: Math.max(rect.bottom, other.bottom) }; - let mLeft = 0, mRight = 0, mTop = 0, mBottom = 0; - for (let margins of this.view.pluginField(PluginField.scrollMargins)) - if (margins) { - let { left, right, top, bottom } = margins; - if (left != null) - mLeft = Math.max(mLeft, left); - if (right != null) - mRight = Math.max(mRight, right); - if (top != null) - mTop = Math.max(mTop, top); - if (bottom != null) - mBottom = Math.max(mBottom, bottom); - } - let targetRect = { - left: rect.left - mLeft, top: rect.top - mTop, - right: rect.right + mRight, bottom: rect.bottom + mBottom - }; - scrollRectIntoView(this.view.scrollDOM, targetRect, range.head < range.anchor ? -1 : 1, target.x, target.y, target.xMargin, target.yMargin, this.view.textDirection == Direction.LTR); - } - } - function betweenUneditable(pos) { - return pos.node.nodeType == 1 && pos.node.firstChild && - (pos.offset == 0 || pos.node.childNodes[pos.offset - 1].contentEditable == "false") && - (pos.offset == pos.node.childNodes.length || pos.node.childNodes[pos.offset].contentEditable == "false"); - } - class BlockGapWidget extends WidgetType { - constructor(height) { - super(); - this.height = height; - } - toDOM() { - let elt = document.createElement("div"); - this.updateDOM(elt); - return elt; - } - eq(other) { return other.height == this.height; } - updateDOM(elt) { - elt.style.height = this.height + "px"; - return true; - } - get estimatedHeight() { return this.height; } - } - function compositionSurroundingNode(view) { - let sel = view.observer.selectionRange; - let textNode = sel.focusNode && nearbyTextNode(sel.focusNode, sel.focusOffset, 0); - if (!textNode) - return null; - let cView = view.docView.nearest(textNode); - if (!cView) - return null; - if (cView instanceof LineView) { - let topNode = textNode; - while (topNode.parentNode != cView.dom) - topNode = topNode.parentNode; - let prev = topNode.previousSibling; - while (prev && !ContentView.get(prev)) - prev = prev.previousSibling; - let pos = prev ? ContentView.get(prev).posAtEnd : cView.posAtStart; - return { from: pos, to: pos, node: topNode, text: textNode }; - } - else { - for (;;) { - let { parent } = cView; - if (!parent) - return null; - if (parent instanceof LineView) - break; - cView = parent; - } - let from = cView.posAtStart; - return { from, to: from + cView.length, node: cView.dom, text: textNode }; - } - } - function computeCompositionDeco(view, changes) { - let surrounding = compositionSurroundingNode(view); - if (!surrounding) - return Decoration.none; - let { from, to, node, text: textNode } = surrounding; - let newFrom = changes.mapPos(from, 1), newTo = Math.max(newFrom, changes.mapPos(to, -1)); - let { state } = view, text = node.nodeType == 3 ? node.nodeValue : - new DOMReader([], state).readRange(node.firstChild, null).text; - if (newTo - newFrom < text.length) { - if (state.doc.sliceString(newFrom, Math.min(state.doc.length, newFrom + text.length), LineBreakPlaceholder) == text) - newTo = newFrom + text.length; - else if (state.doc.sliceString(Math.max(0, newTo - text.length), newTo, LineBreakPlaceholder) == text) - newFrom = newTo - text.length; - else - return Decoration.none; - } - else if (state.doc.sliceString(newFrom, newTo, LineBreakPlaceholder) != text) { - return Decoration.none; - } - let topView = ContentView.get(node); - if (topView instanceof CompositionView) - topView = topView.widget.topView; - else if (topView) - topView.parent = null; - return Decoration.set(Decoration.replace({ widget: new CompositionWidget(node, textNode, topView) }).range(newFrom, newTo)); - } - class CompositionWidget extends WidgetType { - constructor(top, text, topView) { - super(); - this.top = top; - this.text = text; - this.topView = topView; - } - eq(other) { return this.top == other.top && this.text == other.text; } - toDOM() { return this.top; } - ignoreEvent() { return false; } - get customView() { return CompositionView; } - } - function nearbyTextNode(node, offset, side) { - for (;;) { - if (node.nodeType == 3) - return node; - if (node.nodeType == 1 && offset > 0 && side <= 0) { - node = node.childNodes[offset - 1]; - offset = maxOffset(node); - } - else if (node.nodeType == 1 && offset < node.childNodes.length && side >= 0) { - node = node.childNodes[offset]; - offset = 0; - } - else { - return null; - } - } - } - function nextToUneditable(node, offset) { - if (node.nodeType != 1) - return 0; - return (offset && node.childNodes[offset - 1].contentEditable == "false" ? 1 /* Before */ : 0) | - (offset < node.childNodes.length && node.childNodes[offset].contentEditable == "false" ? 2 /* After */ : 0); - } - class DecorationComparator$1 { - constructor() { - this.changes = []; - } - compareRange(from, to) { addRange(from, to, this.changes); } - comparePoint(from, to) { addRange(from, to, this.changes); } - } - function findChangedDeco(a, b, diff) { - let comp = new DecorationComparator$1; - RangeSet.compare(a, b, diff, comp); - return comp.changes; - } - function inUneditable(node, inside) { - for (let cur = node; cur && cur != inside; cur = cur.assignedSlot || cur.parentNode) { - if (cur.nodeType == 1 && cur.contentEditable == 'false') { - return true; - } - } - return false; - } - - function groupAt(state, pos, bias = 1) { - let categorize = state.charCategorizer(pos); - let line = state.doc.lineAt(pos), linePos = pos - line.from; - if (line.length == 0) - return EditorSelection.cursor(pos); - if (linePos == 0) - bias = 1; - else if (linePos == line.length) - bias = -1; - let from = linePos, to = linePos; - if (bias < 0) - from = findClusterBreak(line.text, linePos, false); - else - to = findClusterBreak(line.text, linePos); - let cat = categorize(line.text.slice(from, to)); - while (from > 0) { - let prev = findClusterBreak(line.text, from, false); - if (categorize(line.text.slice(prev, from)) != cat) - break; - from = prev; - } - while (to < line.length) { - let next = findClusterBreak(line.text, to); - if (categorize(line.text.slice(to, next)) != cat) - break; - to = next; - } - return EditorSelection.range(from + line.from, to + line.from); - } - // Search the DOM for the {node, offset} position closest to the given - // coordinates. Very inefficient and crude, but can usually be avoided - // by calling caret(Position|Range)FromPoint instead. - function getdx(x, rect) { - return rect.left > x ? rect.left - x : Math.max(0, x - rect.right); - } - function getdy(y, rect) { - return rect.top > y ? rect.top - y : Math.max(0, y - rect.bottom); - } - function yOverlap(a, b) { - return a.top < b.bottom - 1 && a.bottom > b.top + 1; - } - function upTop(rect, top) { - return top < rect.top ? { top, left: rect.left, right: rect.right, bottom: rect.bottom } : rect; - } - function upBot(rect, bottom) { - return bottom > rect.bottom ? { top: rect.top, left: rect.left, right: rect.right, bottom } : rect; - } - function domPosAtCoords(parent, x, y) { - let closest, closestRect, closestX, closestY; - let above, below, aboveRect, belowRect; - for (let child = parent.firstChild; child; child = child.nextSibling) { - let rects = clientRectsFor(child); - for (let i = 0; i < rects.length; i++) { - let rect = rects[i]; - if (closestRect && yOverlap(closestRect, rect)) - rect = upTop(upBot(rect, closestRect.bottom), closestRect.top); - let dx = getdx(x, rect), dy = getdy(y, rect); - if (dx == 0 && dy == 0) - return child.nodeType == 3 ? domPosInText(child, x, y) : domPosAtCoords(child, x, y); - if (!closest || closestY > dy || closestY == dy && closestX > dx) { - closest = child; - closestRect = rect; - closestX = dx; - closestY = dy; - } - if (dx == 0) { - if (y > rect.bottom && (!aboveRect || aboveRect.bottom < rect.bottom)) { - above = child; - aboveRect = rect; - } - else if (y < rect.top && (!belowRect || belowRect.top > rect.top)) { - below = child; - belowRect = rect; - } - } - else if (aboveRect && yOverlap(aboveRect, rect)) { - aboveRect = upBot(aboveRect, rect.bottom); - } - else if (belowRect && yOverlap(belowRect, rect)) { - belowRect = upTop(belowRect, rect.top); - } - } - } - if (aboveRect && aboveRect.bottom >= y) { - closest = above; - closestRect = aboveRect; - } - else if (belowRect && belowRect.top <= y) { - closest = below; - closestRect = belowRect; - } - if (!closest) - return { node: parent, offset: 0 }; - let clipX = Math.max(closestRect.left, Math.min(closestRect.right, x)); - if (closest.nodeType == 3) - return domPosInText(closest, clipX, y); - if (!closestX && closest.contentEditable == "true") - return domPosAtCoords(closest, clipX, y); - let offset = Array.prototype.indexOf.call(parent.childNodes, closest) + - (x >= (closestRect.left + closestRect.right) / 2 ? 1 : 0); - return { node: parent, offset }; - } - function domPosInText(node, x, y) { - let len = node.nodeValue.length; - let closestOffset = -1, closestDY = 1e9, generalSide = 0; - for (let i = 0; i < len; i++) { - let rects = textRange(node, i, i + 1).getClientRects(); - for (let j = 0; j < rects.length; j++) { - let rect = rects[j]; - if (rect.top == rect.bottom) - continue; - if (!generalSide) - generalSide = x - rect.left; - let dy = (rect.top > y ? rect.top - y : y - rect.bottom) - 1; - if (rect.left - 1 <= x && rect.right + 1 >= x && dy < closestDY) { - let right = x >= (rect.left + rect.right) / 2, after = right; - if (browser.chrome || browser.gecko) { - // Check for RTL on browsers that support getting client - // rects for empty ranges. - let rectBefore = textRange(node, i).getBoundingClientRect(); - if (rectBefore.left == rect.right) - after = !right; - } - if (dy <= 0) - return { node, offset: i + (after ? 1 : 0) }; - closestOffset = i + (after ? 1 : 0); - closestDY = dy; - } - } - } - return { node, offset: closestOffset > -1 ? closestOffset : generalSide > 0 ? node.nodeValue.length : 0 }; - } - function posAtCoords(view, { x, y }, precise, bias = -1) { - var _a; - let content = view.contentDOM.getBoundingClientRect(), docTop = content.top + view.viewState.paddingTop; - let block, { docHeight } = view.viewState; - let yOffset = y - docTop; - if (yOffset < 0) - return 0; - if (yOffset > docHeight) - return view.state.doc.length; - // Scan for a text block near the queried y position - for (let halfLine = view.defaultLineHeight / 2, bounced = false;;) { - block = view.elementAtHeight(yOffset); - if (block.type == BlockType.Text) - break; - for (;;) { - // Move the y position out of this block - yOffset = bias > 0 ? block.bottom + halfLine : block.top - halfLine; - if (yOffset >= 0 && yOffset <= docHeight) - break; - // If the document consists entirely of replaced widgets, we - // won't find a text block, so return 0 - if (bounced) - return precise ? null : 0; - bounced = true; - bias = -bias; - } - } - y = docTop + yOffset; - let lineStart = block.from; - // If this is outside of the rendered viewport, we can't determine a position - if (lineStart < view.viewport.from) - return view.viewport.from == 0 ? 0 : precise ? null : posAtCoordsImprecise(view, content, block, x, y); - if (lineStart > view.viewport.to) - return view.viewport.to == view.state.doc.length ? view.state.doc.length : - precise ? null : posAtCoordsImprecise(view, content, block, x, y); - // Prefer ShadowRootOrDocument.elementFromPoint if present, fall back to document if not - let doc = view.dom.ownerDocument; - let root = view.root.elementFromPoint ? view.root : doc; - let element = root.elementFromPoint(x, y); - if (element && !view.contentDOM.contains(element)) - element = null; - // If the element is unexpected, clip x at the sides of the content area and try again - if (!element) { - x = Math.max(content.left + 1, Math.min(content.right - 1, x)); - element = root.elementFromPoint(x, y); - if (element && !view.contentDOM.contains(element)) - element = null; - } - // There's visible editor content under the point, so we can try - // using caret(Position|Range)FromPoint as a shortcut - let node, offset = -1; - if (element && ((_a = view.docView.nearest(element)) === null || _a === void 0 ? void 0 : _a.isEditable) != false) { - if (doc.caretPositionFromPoint) { - let pos = doc.caretPositionFromPoint(x, y); - if (pos) - ({ offsetNode: node, offset } = pos); - } - else if (doc.caretRangeFromPoint) { - let range = doc.caretRangeFromPoint(x, y); - if (range) { - ({ startContainer: node, startOffset: offset } = range); - if (browser.safari && isSuspiciousCaretResult(node, offset, x)) - node = undefined; - } - } - } - // No luck, do our own (potentially expensive) search - if (!node || !view.docView.dom.contains(node)) { - let line = LineView.find(view.docView, lineStart); - if (!line) - return yOffset > block.top + block.height / 2 ? block.to : block.from; - ({ node, offset } = domPosAtCoords(line.dom, x, y)); - } - return view.docView.posFromDOM(node, offset); - } - function posAtCoordsImprecise(view, contentRect, block, x, y) { - let into = Math.round((x - contentRect.left) * view.defaultCharacterWidth); - if (view.lineWrapping && block.height > view.defaultLineHeight * 1.5) { - let line = Math.floor((y - block.top) / view.defaultLineHeight); - into += line * view.viewState.heightOracle.lineLength; - } - let content = view.state.sliceDoc(block.from, block.to); - return block.from + findColumn(content, into, view.state.tabSize); - } - // In case of a high line height, Safari's caretRangeFromPoint treats - // the space between lines as belonging to the last character of the - // line before. This is used to detect such a result so that it can be - // ignored (issue #401). - function isSuspiciousCaretResult(node, offset, x) { - let len; - if (node.nodeType != 3 || offset != (len = node.nodeValue.length)) - return false; - for (let next = node.nextSibling; next; next = next.nextSibling) - if (next.nodeType != 1 || next.nodeName != "BR") - return false; - return textRange(node, len - 1, len).getBoundingClientRect().left > x; - } - function moveToLineBoundary(view, start, forward, includeWrap) { - let line = view.state.doc.lineAt(start.head); - let coords = !includeWrap || !view.lineWrapping ? null - : view.coordsAtPos(start.assoc < 0 && start.head > line.from ? start.head - 1 : start.head); - if (coords) { - let editorRect = view.dom.getBoundingClientRect(); - let pos = view.posAtCoords({ x: forward == (view.textDirection == Direction.LTR) ? editorRect.right - 1 : editorRect.left + 1, - y: (coords.top + coords.bottom) / 2 }); - if (pos != null) - return EditorSelection.cursor(pos, forward ? -1 : 1); - } - let lineView = LineView.find(view.docView, start.head); - let end = lineView ? (forward ? lineView.posAtEnd : lineView.posAtStart) : (forward ? line.to : line.from); - return EditorSelection.cursor(end, forward ? -1 : 1); - } - function moveByChar(view, start, forward, by) { - let line = view.state.doc.lineAt(start.head), spans = view.bidiSpans(line); - for (let cur = start, check = null;;) { - let next = moveVisually(line, spans, view.textDirection, cur, forward), char = movedOver; - if (!next) { - if (line.number == (forward ? view.state.doc.lines : 1)) - return cur; - char = "\n"; - line = view.state.doc.line(line.number + (forward ? 1 : -1)); - spans = view.bidiSpans(line); - next = EditorSelection.cursor(forward ? line.from : line.to); - } - if (!check) { - if (!by) - return next; - check = by(char); - } - else if (!check(char)) { - return cur; - } - cur = next; - } - } - function byGroup(view, pos, start) { - let categorize = view.state.charCategorizer(pos); - let cat = categorize(start); - return (next) => { - let nextCat = categorize(next); - if (cat == CharCategory.Space) - cat = nextCat; - return cat == nextCat; - }; - } - function moveVertically(view, start, forward, distance) { - let startPos = start.head, dir = forward ? 1 : -1; - if (startPos == (forward ? view.state.doc.length : 0)) - return EditorSelection.cursor(startPos, start.assoc); - let goal = start.goalColumn, startY; - let rect = view.contentDOM.getBoundingClientRect(); - let startCoords = view.coordsAtPos(startPos), docTop = view.documentTop; - if (startCoords) { - if (goal == null) - goal = startCoords.left - rect.left; - startY = dir < 0 ? startCoords.top : startCoords.bottom; - } - else { - let line = view.viewState.lineBlockAt(startPos - docTop); - if (goal == null) - goal = Math.min(rect.right - rect.left, view.defaultCharacterWidth * (startPos - line.from)); - startY = (dir < 0 ? line.top : line.bottom) + docTop; - } - let resolvedGoal = rect.left + goal; - let dist = distance !== null && distance !== void 0 ? distance : (view.defaultLineHeight >> 1); - for (let extra = 0;; extra += 10) { - let curY = startY + (dist + extra) * dir; - let pos = posAtCoords(view, { x: resolvedGoal, y: curY }, false, dir); - if (curY < rect.top || curY > rect.bottom || (dir < 0 ? pos < startPos : pos > startPos)) - return EditorSelection.cursor(pos, start.assoc, undefined, goal); - } - } - function skipAtoms(view, oldPos, pos) { - let atoms = view.pluginField(PluginField.atomicRanges); - for (;;) { - let moved = false; - for (let set of atoms) { - set.between(pos.from - 1, pos.from + 1, (from, to, value) => { - if (pos.from > from && pos.from < to) { - pos = oldPos.from > pos.from ? EditorSelection.cursor(from, 1) : EditorSelection.cursor(to, -1); - moved = true; - } - }); - } - if (!moved) - return pos; - } - } - - // This will also be where dragging info and such goes - class InputState { - constructor(view) { - this.lastKeyCode = 0; - this.lastKeyTime = 0; - // On iOS, some keys need to have their default behavior happen - // (after which we retroactively handle them and reset the DOM) to - // avoid messing up the virtual keyboard state. - this.pendingIOSKey = undefined; - this.lastSelectionOrigin = null; - this.lastSelectionTime = 0; - this.lastEscPress = 0; - this.lastContextMenu = 0; - this.scrollHandlers = []; - this.registeredEvents = []; - this.customHandlers = []; - // -1 means not in a composition. Otherwise, this counts the number - // of changes made during the composition. The count is used to - // avoid treating the start state of the composition, before any - // changes have been made, as part of the composition. - this.composing = -1; - // Tracks whether the next change should be marked as starting the - // composition (null means no composition, true means next is the - // first, false means first has already been marked for this - // composition) - this.compositionFirstChange = null; - this.compositionEndedAt = 0; - this.rapidCompositionStart = false; - this.mouseSelection = null; - for (let type in handlers) { - let handler = handlers[type]; - view.contentDOM.addEventListener(type, (event) => { - if (!eventBelongsToEditor(view, event) || this.ignoreDuringComposition(event)) - return; - if (type == "keydown" && this.keydown(view, event)) - return; - if (this.mustFlushObserver(event)) - view.observer.forceFlush(); - if (this.runCustomHandlers(type, view, event)) - event.preventDefault(); - else - handler(view, event); - }); - this.registeredEvents.push(type); - } - this.notifiedFocused = view.hasFocus; - this.ensureHandlers(view); - // On Safari adding an input event handler somehow prevents an - // issue where the composition vanishes when you press enter. - if (browser.safari) - view.contentDOM.addEventListener("input", () => null); - } - setSelectionOrigin(origin) { - this.lastSelectionOrigin = origin; - this.lastSelectionTime = Date.now(); - } - ensureHandlers(view) { - let handlers = this.customHandlers = view.pluginField(domEventHandlers); - for (let set of handlers) { - for (let type in set.handlers) - if (this.registeredEvents.indexOf(type) < 0 && type != "scroll") { - this.registeredEvents.push(type); - view.contentDOM.addEventListener(type, (event) => { - if (!eventBelongsToEditor(view, event)) - return; - if (this.runCustomHandlers(type, view, event)) - event.preventDefault(); - }); - } - } - } - runCustomHandlers(type, view, event) { - for (let set of this.customHandlers) { - let handler = set.handlers[type]; - if (handler) { - try { - if (handler.call(set.plugin, event, view) || event.defaultPrevented) - return true; - } - catch (e) { - logException(view.state, e); - } - } - } - return false; - } - runScrollHandlers(view, event) { - for (let set of this.customHandlers) { - let handler = set.handlers.scroll; - if (handler) { - try { - handler.call(set.plugin, event, view); - } - catch (e) { - logException(view.state, e); - } - } - } - } - keydown(view, event) { - // Must always run, even if a custom handler handled the event - this.lastKeyCode = event.keyCode; - this.lastKeyTime = Date.now(); - if (event.keyCode == 9 && Date.now() < this.lastEscPress + 2000) - return true; - // Chrome for Android usually doesn't fire proper key events, but - // occasionally does, usually surrounded by a bunch of complicated - // composition changes. When an enter or backspace key event is - // seen, hold off on handling DOM events for a bit, and then - // dispatch it. - if (browser.android && browser.chrome && !event.synthetic && - (event.keyCode == 13 || event.keyCode == 8)) { - view.observer.delayAndroidKey(event.key, event.keyCode); - return true; - } - // Prevent the default behavior of Enter on iOS makes the - // virtual keyboard get stuck in the wrong (lowercase) - // state. So we let it go through, and then, in - // applyDOMChange, notify key handlers of it and reset to - // the state they produce. - let pending; - if (browser.ios && (pending = PendingKeys.find(key => key.keyCode == event.keyCode)) && - !(event.ctrlKey || event.altKey || event.metaKey) && !event.synthetic) { - this.pendingIOSKey = pending; - setTimeout(() => this.flushIOSKey(view), 250); - return true; - } - return false; - } - flushIOSKey(view) { - let key = this.pendingIOSKey; - if (!key) - return false; - this.pendingIOSKey = undefined; - return dispatchKey(view.contentDOM, key.key, key.keyCode); - } - ignoreDuringComposition(event) { - if (!/^key/.test(event.type)) - return false; - if (this.composing > 0) - return true; - // See https://www.stum.de/2016/06/24/handling-ime-events-in-javascript/. - // On some input method editors (IMEs), the Enter key is used to - // confirm character selection. On Safari, when Enter is pressed, - // compositionend and keydown events are sometimes emitted in the - // wrong order. The key event should still be ignored, even when - // it happens after the compositionend event. - if (browser.safari && Date.now() - this.compositionEndedAt < 500) { - this.compositionEndedAt = 0; - return true; - } - return false; - } - mustFlushObserver(event) { - return (event.type == "keydown" && event.keyCode != 229) || - event.type == "compositionend" && !browser.ios; - } - startMouseSelection(mouseSelection) { - if (this.mouseSelection) - this.mouseSelection.destroy(); - this.mouseSelection = mouseSelection; - } - update(update) { - if (this.mouseSelection) - this.mouseSelection.update(update); - if (update.transactions.length) - this.lastKeyCode = this.lastSelectionTime = 0; - } - destroy() { - if (this.mouseSelection) - this.mouseSelection.destroy(); - } - } - const PendingKeys = [ - { key: "Backspace", keyCode: 8, inputType: "deleteContentBackward" }, - { key: "Enter", keyCode: 13, inputType: "insertParagraph" }, - { key: "Delete", keyCode: 46, inputType: "deleteContentForward" } - ]; - // Key codes for modifier keys - const modifierCodes = [16, 17, 18, 20, 91, 92, 224, 225]; - class MouseSelection { - constructor(view, startEvent, style, mustSelect) { - this.view = view; - this.style = style; - this.mustSelect = mustSelect; - this.lastEvent = startEvent; - let doc = view.contentDOM.ownerDocument; - doc.addEventListener("mousemove", this.move = this.move.bind(this)); - doc.addEventListener("mouseup", this.up = this.up.bind(this)); - this.extend = startEvent.shiftKey; - this.multiple = view.state.facet(EditorState.allowMultipleSelections) && addsSelectionRange(view, startEvent); - this.dragMove = dragMovesSelection(view, startEvent); - this.dragging = isInPrimarySelection(view, startEvent) && getClickType(startEvent) == 1 ? null : false; - // When clicking outside of the selection, immediately apply the - // effect of starting the selection - if (this.dragging === false) { - startEvent.preventDefault(); - this.select(startEvent); - } - } - move(event) { - if (event.buttons == 0) - return this.destroy(); - if (this.dragging !== false) - return; - this.select(this.lastEvent = event); - } - up(event) { - if (this.dragging == null) - this.select(this.lastEvent); - if (!this.dragging) - event.preventDefault(); - this.destroy(); - } - destroy() { - let doc = this.view.contentDOM.ownerDocument; - doc.removeEventListener("mousemove", this.move); - doc.removeEventListener("mouseup", this.up); - this.view.inputState.mouseSelection = null; - } - select(event) { - let selection = this.style.get(event, this.extend, this.multiple); - if (this.mustSelect || !selection.eq(this.view.state.selection) || - selection.main.assoc != this.view.state.selection.main.assoc) - this.view.dispatch({ - selection, - userEvent: "select.pointer", - scrollIntoView: true - }); - this.mustSelect = false; - } - update(update) { - if (update.docChanged && this.dragging) - this.dragging = this.dragging.map(update.changes); - if (this.style.update(update)) - setTimeout(() => this.select(this.lastEvent), 20); - } - } - function addsSelectionRange(view, event) { - let facet = view.state.facet(clickAddsSelectionRange); - return facet.length ? facet[0](event) : browser.mac ? event.metaKey : event.ctrlKey; - } - function dragMovesSelection(view, event) { - let facet = view.state.facet(dragMovesSelection$1); - return facet.length ? facet[0](event) : browser.mac ? !event.altKey : !event.ctrlKey; - } - function isInPrimarySelection(view, event) { - let { main } = view.state.selection; - if (main.empty) - return false; - // On boundary clicks, check whether the coordinates are inside the - // selection's client rectangles - let sel = getSelection(view.root); - if (sel.rangeCount == 0) - return true; - let rects = sel.getRangeAt(0).getClientRects(); - for (let i = 0; i < rects.length; i++) { - let rect = rects[i]; - if (rect.left <= event.clientX && rect.right >= event.clientX && - rect.top <= event.clientY && rect.bottom >= event.clientY) - return true; - } - return false; - } - function eventBelongsToEditor(view, event) { - if (!event.bubbles) - return true; - if (event.defaultPrevented) - return false; - for (let node = event.target, cView; node != view.contentDOM; node = node.parentNode) - if (!node || node.nodeType == 11 || ((cView = ContentView.get(node)) && cView.ignoreEvent(event))) - return false; - return true; - } - const handlers = /*@__PURE__*/Object.create(null); - // This is very crude, but unfortunately both these browsers _pretend_ - // that they have a clipboard API—all the objects and methods are - // there, they just don't work, and they are hard to test. - const brokenClipboardAPI = (browser.ie && browser.ie_version < 15) || - (browser.ios && browser.webkit_version < 604); - function capturePaste(view) { - let parent = view.dom.parentNode; - if (!parent) - return; - let target = parent.appendChild(document.createElement("textarea")); - target.style.cssText = "position: fixed; left: -10000px; top: 10px"; - target.focus(); - setTimeout(() => { - view.focus(); - target.remove(); - doPaste(view, target.value); - }, 50); - } - function doPaste(view, input) { - let { state } = view, changes, i = 1, text = state.toText(input); - let byLine = text.lines == state.selection.ranges.length; - let linewise = lastLinewiseCopy != null && state.selection.ranges.every(r => r.empty) && lastLinewiseCopy == text.toString(); - if (linewise) { - let lastLine = -1; - changes = state.changeByRange(range => { - let line = state.doc.lineAt(range.from); - if (line.from == lastLine) - return { range }; - lastLine = line.from; - let insert = state.toText((byLine ? text.line(i++).text : input) + state.lineBreak); - return { changes: { from: line.from, insert }, - range: EditorSelection.cursor(range.from + insert.length) }; - }); - } - else if (byLine) { - changes = state.changeByRange(range => { - let line = text.line(i++); - return { changes: { from: range.from, to: range.to, insert: line.text }, - range: EditorSelection.cursor(range.from + line.length) }; - }); - } - else { - changes = state.replaceSelection(text); - } - view.dispatch(changes, { - userEvent: "input.paste", - scrollIntoView: true - }); - } - handlers.keydown = (view, event) => { - view.inputState.setSelectionOrigin("select"); - if (event.keyCode == 27) - view.inputState.lastEscPress = Date.now(); - else if (modifierCodes.indexOf(event.keyCode) < 0) - view.inputState.lastEscPress = 0; - }; - let lastTouch = 0; - handlers.touchstart = (view, e) => { - lastTouch = Date.now(); - view.inputState.setSelectionOrigin("select.pointer"); - }; - handlers.touchmove = view => { - view.inputState.setSelectionOrigin("select.pointer"); - }; - handlers.mousedown = (view, event) => { - view.observer.flush(); - if (lastTouch > Date.now() - 2000 && getClickType(event) == 1) - return; // Ignore touch interaction - let style = null; - for (let makeStyle of view.state.facet(mouseSelectionStyle)) { - style = makeStyle(view, event); - if (style) - break; - } - if (!style && event.button == 0) - style = basicMouseSelection(view, event); - if (style) { - let mustFocus = view.root.activeElement != view.contentDOM; - if (mustFocus) - view.observer.ignore(() => focusPreventScroll(view.contentDOM)); - view.inputState.startMouseSelection(new MouseSelection(view, event, style, mustFocus)); - } - }; - function rangeForClick(view, pos, bias, type) { - if (type == 1) { // Single click - return EditorSelection.cursor(pos, bias); - } - else if (type == 2) { // Double click - return groupAt(view.state, pos, bias); - } - else { // Triple click - let visual = LineView.find(view.docView, pos), line = view.state.doc.lineAt(visual ? visual.posAtEnd : pos); - let from = visual ? visual.posAtStart : line.from, to = visual ? visual.posAtEnd : line.to; - if (to < view.state.doc.length && to == line.to) - to++; - return EditorSelection.range(from, to); - } - } - let insideY = (y, rect) => y >= rect.top && y <= rect.bottom; - let inside = (x, y, rect) => insideY(y, rect) && x >= rect.left && x <= rect.right; - // Try to determine, for the given coordinates, associated with the - // given position, whether they are related to the element before or - // the element after the position. - function findPositionSide(view, pos, x, y) { - let line = LineView.find(view.docView, pos); - if (!line) - return 1; - let off = pos - line.posAtStart; - // Line boundaries point into the line - if (off == 0) - return 1; - if (off == line.length) - return -1; - // Positions on top of an element point at that element - let before = line.coordsAt(off, -1); - if (before && inside(x, y, before)) - return -1; - let after = line.coordsAt(off, 1); - if (after && inside(x, y, after)) - return 1; - // This is probably a line wrap point. Pick before if the point is - // beside it. - return before && insideY(y, before) ? -1 : 1; - } - function queryPos(view, event) { - let pos = view.posAtCoords({ x: event.clientX, y: event.clientY }, false); - return { pos, bias: findPositionSide(view, pos, event.clientX, event.clientY) }; - } - const BadMouseDetail = browser.ie && browser.ie_version <= 11; - let lastMouseDown = null, lastMouseDownCount = 0, lastMouseDownTime = 0; - function getClickType(event) { - if (!BadMouseDetail) - return event.detail; - let last = lastMouseDown, lastTime = lastMouseDownTime; - lastMouseDown = event; - lastMouseDownTime = Date.now(); - return lastMouseDownCount = !last || (lastTime > Date.now() - 400 && Math.abs(last.clientX - event.clientX) < 2 && - Math.abs(last.clientY - event.clientY) < 2) ? (lastMouseDownCount + 1) % 3 : 1; - } - function basicMouseSelection(view, event) { - let start = queryPos(view, event), type = getClickType(event); - let startSel = view.state.selection; - let last = start, lastEvent = event; - return { - update(update) { - if (update.docChanged) { - if (start) - start.pos = update.changes.mapPos(start.pos); - startSel = startSel.map(update.changes); - lastEvent = null; - } - }, - get(event, extend, multiple) { - let cur; - if (lastEvent && event.clientX == lastEvent.clientX && event.clientY == lastEvent.clientY) - cur = last; - else { - cur = last = queryPos(view, event); - lastEvent = event; - } - if (!cur || !start) - return startSel; - let range = rangeForClick(view, cur.pos, cur.bias, type); - if (start.pos != cur.pos && !extend) { - let startRange = rangeForClick(view, start.pos, start.bias, type); - let from = Math.min(startRange.from, range.from), to = Math.max(startRange.to, range.to); - range = from < range.from ? EditorSelection.range(from, to) : EditorSelection.range(to, from); - } - if (extend) - return startSel.replaceRange(startSel.main.extend(range.from, range.to)); - else if (multiple) - return startSel.addRange(range); - else - return EditorSelection.create([range]); - } - }; - } - handlers.dragstart = (view, event) => { - let { selection: { main } } = view.state; - let { mouseSelection } = view.inputState; - if (mouseSelection) - mouseSelection.dragging = main; - if (event.dataTransfer) { - event.dataTransfer.setData("Text", view.state.sliceDoc(main.from, main.to)); - event.dataTransfer.effectAllowed = "copyMove"; - } - }; - function dropText(view, event, text, direct) { - if (!text) - return; - let dropPos = view.posAtCoords({ x: event.clientX, y: event.clientY }, false); - event.preventDefault(); - let { mouseSelection } = view.inputState; - let del = direct && mouseSelection && mouseSelection.dragging && mouseSelection.dragMove ? - { from: mouseSelection.dragging.from, to: mouseSelection.dragging.to } : null; - let ins = { from: dropPos, insert: text }; - let changes = view.state.changes(del ? [del, ins] : ins); - view.focus(); - view.dispatch({ - changes, - selection: { anchor: changes.mapPos(dropPos, -1), head: changes.mapPos(dropPos, 1) }, - userEvent: del ? "move.drop" : "input.drop" - }); - } - handlers.drop = (view, event) => { - if (!event.dataTransfer) - return; - if (view.state.readOnly) - return event.preventDefault(); - let files = event.dataTransfer.files; - if (files && files.length) { // For a file drop, read the file's text. - event.preventDefault(); - let text = Array(files.length), read = 0; - let finishFile = () => { - if (++read == files.length) - dropText(view, event, text.filter(s => s != null).join(view.state.lineBreak), false); - }; - for (let i = 0; i < files.length; i++) { - let reader = new FileReader; - reader.onerror = finishFile; - reader.onload = () => { - if (!/[\x00-\x08\x0e-\x1f]{2}/.test(reader.result)) - text[i] = reader.result; - finishFile(); - }; - reader.readAsText(files[i]); - } - } - else { - dropText(view, event, event.dataTransfer.getData("Text"), true); - } - }; - handlers.paste = (view, event) => { - if (view.state.readOnly) - return event.preventDefault(); - view.observer.flush(); - let data = brokenClipboardAPI ? null : event.clipboardData; - if (data) { - doPaste(view, data.getData("text/plain")); - event.preventDefault(); - } - else { - capturePaste(view); - } - }; - function captureCopy(view, text) { - // The extra wrapper is somehow necessary on IE/Edge to prevent the - // content from being mangled when it is put onto the clipboard - let parent = view.dom.parentNode; - if (!parent) - return; - let target = parent.appendChild(document.createElement("textarea")); - target.style.cssText = "position: fixed; left: -10000px; top: 10px"; - target.value = text; - target.focus(); - target.selectionEnd = text.length; - target.selectionStart = 0; - setTimeout(() => { - target.remove(); - view.focus(); - }, 50); - } - function copiedRange(state) { - let content = [], ranges = [], linewise = false; - for (let range of state.selection.ranges) - if (!range.empty) { - content.push(state.sliceDoc(range.from, range.to)); - ranges.push(range); - } - if (!content.length) { - // Nothing selected, do a line-wise copy - let upto = -1; - for (let { from } of state.selection.ranges) { - let line = state.doc.lineAt(from); - if (line.number > upto) { - content.push(line.text); - ranges.push({ from: line.from, to: Math.min(state.doc.length, line.to + 1) }); - } - upto = line.number; - } - linewise = true; - } - return { text: content.join(state.lineBreak), ranges, linewise }; - } - let lastLinewiseCopy = null; - handlers.copy = handlers.cut = (view, event) => { - let { text, ranges, linewise } = copiedRange(view.state); - if (!text && !linewise) - return; - lastLinewiseCopy = linewise ? text : null; - let data = brokenClipboardAPI ? null : event.clipboardData; - if (data) { - event.preventDefault(); - data.clearData(); - data.setData("text/plain", text); - } - else { - captureCopy(view, text); - } - if (event.type == "cut" && !view.state.readOnly) - view.dispatch({ - changes: ranges, - scrollIntoView: true, - userEvent: "delete.cut" - }); - }; - handlers.focus = handlers.blur = view => { - setTimeout(() => { - if (view.hasFocus != view.inputState.notifiedFocused) - view.update([]); - }, 10); - }; - function forceClearComposition(view, rapid) { - if (view.docView.compositionDeco.size) { - view.inputState.rapidCompositionStart = rapid; - try { - view.update([]); - } - finally { - view.inputState.rapidCompositionStart = false; - } - } - } - handlers.compositionstart = handlers.compositionupdate = view => { - if (view.inputState.compositionFirstChange == null) - view.inputState.compositionFirstChange = true; - if (view.inputState.composing < 0) { - // FIXME possibly set a timeout to clear it again on Android - view.inputState.composing = 0; - if (view.docView.compositionDeco.size) { - view.observer.flush(); - forceClearComposition(view, true); - } - } - }; - handlers.compositionend = view => { - view.inputState.composing = -1; - view.inputState.compositionEndedAt = Date.now(); - view.inputState.compositionFirstChange = null; - setTimeout(() => { - if (view.inputState.composing < 0) - forceClearComposition(view, false); - }, 50); - }; - handlers.contextmenu = view => { - view.inputState.lastContextMenu = Date.now(); - }; - handlers.beforeinput = (view, event) => { - var _a; - // Because Chrome Android doesn't fire useful key events, use - // beforeinput to detect backspace (and possibly enter and delete, - // but those usually don't even seem to fire beforeinput events at - // the moment) and fake a key event for it. - // - // (preventDefault on beforeinput, though supported in the spec, - // seems to do nothing at all on Chrome). - let pending; - if (browser.chrome && browser.android && (pending = PendingKeys.find(key => key.inputType == event.inputType))) { - view.observer.delayAndroidKey(pending.key, pending.keyCode); - if (pending.key == "Backspace" || pending.key == "Delete") { - let startViewHeight = ((_a = window.visualViewport) === null || _a === void 0 ? void 0 : _a.height) || 0; - setTimeout(() => { - var _a; - // Backspacing near uneditable nodes on Chrome Android sometimes - // closes the virtual keyboard. This tries to crudely detect - // that and refocus to get it back. - if ((((_a = window.visualViewport) === null || _a === void 0 ? void 0 : _a.height) || 0) > startViewHeight + 10 && view.hasFocus) { - view.contentDOM.blur(); - view.focus(); - } - }, 100); - } - } - }; - - const wrappingWhiteSpace = ["pre-wrap", "normal", "pre-line", "break-spaces"]; - class HeightOracle { - constructor() { - this.doc = Text.empty; - this.lineWrapping = false; - this.direction = Direction.LTR; - this.heightSamples = {}; - this.lineHeight = 14; - this.charWidth = 7; - this.lineLength = 30; - // Used to track, during updateHeight, if any actual heights changed - this.heightChanged = false; - } - heightForGap(from, to) { - let lines = this.doc.lineAt(to).number - this.doc.lineAt(from).number + 1; - if (this.lineWrapping) - lines += Math.ceil(((to - from) - (lines * this.lineLength * 0.5)) / this.lineLength); - return this.lineHeight * lines; - } - heightForLine(length) { - if (!this.lineWrapping) - return this.lineHeight; - let lines = 1 + Math.max(0, Math.ceil((length - this.lineLength) / (this.lineLength - 5))); - return lines * this.lineHeight; - } - setDoc(doc) { this.doc = doc; return this; } - mustRefreshForStyle(whiteSpace, direction) { - return (wrappingWhiteSpace.indexOf(whiteSpace) > -1) != this.lineWrapping || this.direction != direction; - } - mustRefreshForHeights(lineHeights) { - let newHeight = false; - for (let i = 0; i < lineHeights.length; i++) { - let h = lineHeights[i]; - if (h < 0) { - i++; - } - else if (!this.heightSamples[Math.floor(h * 10)]) { // Round to .1 pixels - newHeight = true; - this.heightSamples[Math.floor(h * 10)] = true; - } - } - return newHeight; - } - refresh(whiteSpace, direction, lineHeight, charWidth, lineLength, knownHeights) { - let lineWrapping = wrappingWhiteSpace.indexOf(whiteSpace) > -1; - let changed = Math.round(lineHeight) != Math.round(this.lineHeight) || - this.lineWrapping != lineWrapping || - this.direction != direction; - this.lineWrapping = lineWrapping; - this.direction = direction; - this.lineHeight = lineHeight; - this.charWidth = charWidth; - this.lineLength = lineLength; - if (changed) { - this.heightSamples = {}; - for (let i = 0; i < knownHeights.length; i++) { - let h = knownHeights[i]; - if (h < 0) - i++; - else - this.heightSamples[Math.floor(h * 10)] = true; - } - } - return changed; - } - } - // This object is used by `updateHeight` to make DOM measurements - // arrive at the right nides. The `heights` array is a sequence of - // block heights, starting from position `from`. - class MeasuredHeights { - constructor(from, heights) { - this.from = from; - this.heights = heights; - this.index = 0; - } - get more() { return this.index < this.heights.length; } - } - /** - Record used to represent information about a block-level element - in the editor view. - */ - class BlockInfo { - /** - @internal - */ - constructor( - /** - The start of the element in the document. - */ - from, - /** - The length of the element. - */ - length, - /** - The top position of the element (relative to the top of the - document). - */ - top, - /** - Its height. - */ - height, - /** - The type of element this is. When querying lines, this may be - an array of all the blocks that make up the line. - */ - type) { - this.from = from; - this.length = length; - this.top = top; - this.height = height; - this.type = type; - } - /** - The end of the element as a document position. - */ - get to() { return this.from + this.length; } - /** - The bottom position of the element. - */ - get bottom() { return this.top + this.height; } - /** - @internal - */ - join(other) { - let detail = (Array.isArray(this.type) ? this.type : [this]) - .concat(Array.isArray(other.type) ? other.type : [other]); - return new BlockInfo(this.from, this.length + other.length, this.top, this.height + other.height, detail); - } - /** - FIXME remove on next breaking release @internal - */ - moveY(offset) { - return !offset ? this : new BlockInfo(this.from, this.length, this.top + offset, this.height, Array.isArray(this.type) ? this.type.map(b => b.moveY(offset)) : this.type); - } - } - var QueryType$1 = /*@__PURE__*/(function (QueryType) { - QueryType[QueryType["ByPos"] = 0] = "ByPos"; - QueryType[QueryType["ByHeight"] = 1] = "ByHeight"; - QueryType[QueryType["ByPosNoHeight"] = 2] = "ByPosNoHeight"; - return QueryType})(QueryType$1 || (QueryType$1 = {})); - const Epsilon = 1e-3; - class HeightMap { - constructor(length, // The number of characters covered - height, // Height of this part of the document - flags = 2 /* Outdated */) { - this.length = length; - this.height = height; - this.flags = flags; - } - get outdated() { return (this.flags & 2 /* Outdated */) > 0; } - set outdated(value) { this.flags = (value ? 2 /* Outdated */ : 0) | (this.flags & ~2 /* Outdated */); } - setHeight(oracle, height) { - if (this.height != height) { - if (Math.abs(this.height - height) > Epsilon) - oracle.heightChanged = true; - this.height = height; - } - } - // Base case is to replace a leaf node, which simply builds a tree - // from the new nodes and returns that (HeightMapBranch and - // HeightMapGap override this to actually use from/to) - replace(_from, _to, nodes) { - return HeightMap.of(nodes); - } - // Again, these are base cases, and are overridden for branch and gap nodes. - decomposeLeft(_to, result) { result.push(this); } - decomposeRight(_from, result) { result.push(this); } - applyChanges(decorations, oldDoc, oracle, changes) { - let me = this; - for (let i = changes.length - 1; i >= 0; i--) { - let { fromA, toA, fromB, toB } = changes[i]; - let start = me.lineAt(fromA, QueryType$1.ByPosNoHeight, oldDoc, 0, 0); - let end = start.to >= toA ? start : me.lineAt(toA, QueryType$1.ByPosNoHeight, oldDoc, 0, 0); - toB += end.to - toA; - toA = end.to; - while (i > 0 && start.from <= changes[i - 1].toA) { - fromA = changes[i - 1].fromA; - fromB = changes[i - 1].fromB; - i--; - if (fromA < start.from) - start = me.lineAt(fromA, QueryType$1.ByPosNoHeight, oldDoc, 0, 0); - } - fromB += start.from - fromA; - fromA = start.from; - let nodes = NodeBuilder.build(oracle, decorations, fromB, toB); - me = me.replace(fromA, toA, nodes); - } - return me.updateHeight(oracle, 0); - } - static empty() { return new HeightMapText(0, 0); } - // nodes uses null values to indicate the position of line breaks. - // There are never line breaks at the start or end of the array, or - // two line breaks next to each other, and the array isn't allowed - // to be empty (same restrictions as return value from the builder). - static of(nodes) { - if (nodes.length == 1) - return nodes[0]; - let i = 0, j = nodes.length, before = 0, after = 0; - for (;;) { - if (i == j) { - if (before > after * 2) { - let split = nodes[i - 1]; - if (split.break) - nodes.splice(--i, 1, split.left, null, split.right); - else - nodes.splice(--i, 1, split.left, split.right); - j += 1 + split.break; - before -= split.size; - } - else if (after > before * 2) { - let split = nodes[j]; - if (split.break) - nodes.splice(j, 1, split.left, null, split.right); - else - nodes.splice(j, 1, split.left, split.right); - j += 2 + split.break; - after -= split.size; - } - else { - break; - } - } - else if (before < after) { - let next = nodes[i++]; - if (next) - before += next.size; - } - else { - let next = nodes[--j]; - if (next) - after += next.size; - } - } - let brk = 0; - if (nodes[i - 1] == null) { - brk = 1; - i--; - } - else if (nodes[i] == null) { - brk = 1; - j++; - } - return new HeightMapBranch(HeightMap.of(nodes.slice(0, i)), brk, HeightMap.of(nodes.slice(j))); - } - } - HeightMap.prototype.size = 1; - class HeightMapBlock extends HeightMap { - constructor(length, height, type) { - super(length, height); - this.type = type; - } - blockAt(_height, _doc, top, offset) { - return new BlockInfo(offset, this.length, top, this.height, this.type); - } - lineAt(_value, _type, doc, top, offset) { - return this.blockAt(0, doc, top, offset); - } - forEachLine(_from, _to, doc, top, offset, f) { - f(this.blockAt(0, doc, top, offset)); - } - updateHeight(oracle, offset = 0, _force = false, measured) { - if (measured && measured.from <= offset && measured.more) - this.setHeight(oracle, measured.heights[measured.index++]); - this.outdated = false; - return this; - } - toString() { return `block(${this.length})`; } - } - class HeightMapText extends HeightMapBlock { - constructor(length, height) { - super(length, height, BlockType.Text); - this.collapsed = 0; // Amount of collapsed content in the line - this.widgetHeight = 0; // Maximum inline widget height - } - replace(_from, _to, nodes) { - let node = nodes[0]; - if (nodes.length == 1 && (node instanceof HeightMapText || node instanceof HeightMapGap && (node.flags & 4 /* SingleLine */)) && - Math.abs(this.length - node.length) < 10) { - if (node instanceof HeightMapGap) - node = new HeightMapText(node.length, this.height); - else - node.height = this.height; - if (!this.outdated) - node.outdated = false; - return node; - } - else { - return HeightMap.of(nodes); - } - } - updateHeight(oracle, offset = 0, force = false, measured) { - if (measured && measured.from <= offset && measured.more) - this.setHeight(oracle, measured.heights[measured.index++]); - else if (force || this.outdated) - this.setHeight(oracle, Math.max(this.widgetHeight, oracle.heightForLine(this.length - this.collapsed))); - this.outdated = false; - return this; - } - toString() { - return `line(${this.length}${this.collapsed ? -this.collapsed : ""}${this.widgetHeight ? ":" + this.widgetHeight : ""})`; - } - } - class HeightMapGap extends HeightMap { - constructor(length) { super(length, 0); } - lines(doc, offset) { - let firstLine = doc.lineAt(offset).number, lastLine = doc.lineAt(offset + this.length).number; - return { firstLine, lastLine, lineHeight: this.height / (lastLine - firstLine + 1) }; - } - blockAt(height, doc, top, offset) { - let { firstLine, lastLine, lineHeight } = this.lines(doc, offset); - let line = Math.max(0, Math.min(lastLine - firstLine, Math.floor((height - top) / lineHeight))); - let { from, length } = doc.line(firstLine + line); - return new BlockInfo(from, length, top + lineHeight * line, lineHeight, BlockType.Text); - } - lineAt(value, type, doc, top, offset) { - if (type == QueryType$1.ByHeight) - return this.blockAt(value, doc, top, offset); - if (type == QueryType$1.ByPosNoHeight) { - let { from, to } = doc.lineAt(value); - return new BlockInfo(from, to - from, 0, 0, BlockType.Text); - } - let { firstLine, lineHeight } = this.lines(doc, offset); - let { from, length, number } = doc.lineAt(value); - return new BlockInfo(from, length, top + lineHeight * (number - firstLine), lineHeight, BlockType.Text); - } - forEachLine(from, to, doc, top, offset, f) { - let { firstLine, lineHeight } = this.lines(doc, offset); - for (let pos = Math.max(from, offset), end = Math.min(offset + this.length, to); pos <= end;) { - let line = doc.lineAt(pos); - if (pos == from) - top += lineHeight * (line.number - firstLine); - f(new BlockInfo(line.from, line.length, top, lineHeight, BlockType.Text)); - top += lineHeight; - pos = line.to + 1; - } - } - replace(from, to, nodes) { - let after = this.length - to; - if (after > 0) { - let last = nodes[nodes.length - 1]; - if (last instanceof HeightMapGap) - nodes[nodes.length - 1] = new HeightMapGap(last.length + after); - else - nodes.push(null, new HeightMapGap(after - 1)); - } - if (from > 0) { - let first = nodes[0]; - if (first instanceof HeightMapGap) - nodes[0] = new HeightMapGap(from + first.length); - else - nodes.unshift(new HeightMapGap(from - 1), null); - } - return HeightMap.of(nodes); - } - decomposeLeft(to, result) { - result.push(new HeightMapGap(to - 1), null); - } - decomposeRight(from, result) { - result.push(null, new HeightMapGap(this.length - from - 1)); - } - updateHeight(oracle, offset = 0, force = false, measured) { - let end = offset + this.length; - if (measured && measured.from <= offset + this.length && measured.more) { - // Fill in part of this gap with measured lines. We know there - // can't be widgets or collapsed ranges in those lines, because - // they would already have been added to the heightmap (gaps - // only contain plain text). - let nodes = [], pos = Math.max(offset, measured.from), singleHeight = -1; - let wasChanged = oracle.heightChanged; - if (measured.from > offset) - nodes.push(new HeightMapGap(measured.from - offset - 1).updateHeight(oracle, offset)); - while (pos <= end && measured.more) { - let len = oracle.doc.lineAt(pos).length; - if (nodes.length) - nodes.push(null); - let height = measured.heights[measured.index++]; - if (singleHeight == -1) - singleHeight = height; - else if (Math.abs(height - singleHeight) >= Epsilon) - singleHeight = -2; - let line = new HeightMapText(len, height); - line.outdated = false; - nodes.push(line); - pos += len + 1; - } - if (pos <= end) - nodes.push(null, new HeightMapGap(end - pos).updateHeight(oracle, pos)); - let result = HeightMap.of(nodes); - oracle.heightChanged = wasChanged || singleHeight < 0 || Math.abs(result.height - this.height) >= Epsilon || - Math.abs(singleHeight - this.lines(oracle.doc, offset).lineHeight) >= Epsilon; - return result; - } - else if (force || this.outdated) { - this.setHeight(oracle, oracle.heightForGap(offset, offset + this.length)); - this.outdated = false; - } - return this; - } - toString() { return `gap(${this.length})`; } - } - class HeightMapBranch extends HeightMap { - constructor(left, brk, right) { - super(left.length + brk + right.length, left.height + right.height, brk | (left.outdated || right.outdated ? 2 /* Outdated */ : 0)); - this.left = left; - this.right = right; - this.size = left.size + right.size; - } - get break() { return this.flags & 1 /* Break */; } - blockAt(height, doc, top, offset) { - let mid = top + this.left.height; - return height < mid ? this.left.blockAt(height, doc, top, offset) - : this.right.blockAt(height, doc, mid, offset + this.left.length + this.break); - } - lineAt(value, type, doc, top, offset) { - let rightTop = top + this.left.height, rightOffset = offset + this.left.length + this.break; - let left = type == QueryType$1.ByHeight ? value < rightTop : value < rightOffset; - let base = left ? this.left.lineAt(value, type, doc, top, offset) - : this.right.lineAt(value, type, doc, rightTop, rightOffset); - if (this.break || (left ? base.to < rightOffset : base.from > rightOffset)) - return base; - let subQuery = type == QueryType$1.ByPosNoHeight ? QueryType$1.ByPosNoHeight : QueryType$1.ByPos; - if (left) - return base.join(this.right.lineAt(rightOffset, subQuery, doc, rightTop, rightOffset)); - else - return this.left.lineAt(rightOffset, subQuery, doc, top, offset).join(base); - } - forEachLine(from, to, doc, top, offset, f) { - let rightTop = top + this.left.height, rightOffset = offset + this.left.length + this.break; - if (this.break) { - if (from < rightOffset) - this.left.forEachLine(from, to, doc, top, offset, f); - if (to >= rightOffset) - this.right.forEachLine(from, to, doc, rightTop, rightOffset, f); - } - else { - let mid = this.lineAt(rightOffset, QueryType$1.ByPos, doc, top, offset); - if (from < mid.from) - this.left.forEachLine(from, mid.from - 1, doc, top, offset, f); - if (mid.to >= from && mid.from <= to) - f(mid); - if (to > mid.to) - this.right.forEachLine(mid.to + 1, to, doc, rightTop, rightOffset, f); - } - } - replace(from, to, nodes) { - let rightStart = this.left.length + this.break; - if (to < rightStart) - return this.balanced(this.left.replace(from, to, nodes), this.right); - if (from > this.left.length) - return this.balanced(this.left, this.right.replace(from - rightStart, to - rightStart, nodes)); - let result = []; - if (from > 0) - this.decomposeLeft(from, result); - let left = result.length; - for (let node of nodes) - result.push(node); - if (from > 0) - mergeGaps(result, left - 1); - if (to < this.length) { - let right = result.length; - this.decomposeRight(to, result); - mergeGaps(result, right); - } - return HeightMap.of(result); - } - decomposeLeft(to, result) { - let left = this.left.length; - if (to <= left) - return this.left.decomposeLeft(to, result); - result.push(this.left); - if (this.break) { - left++; - if (to >= left) - result.push(null); - } - if (to > left) - this.right.decomposeLeft(to - left, result); - } - decomposeRight(from, result) { - let left = this.left.length, right = left + this.break; - if (from >= right) - return this.right.decomposeRight(from - right, result); - if (from < left) - this.left.decomposeRight(from, result); - if (this.break && from < right) - result.push(null); - result.push(this.right); - } - balanced(left, right) { - if (left.size > 2 * right.size || right.size > 2 * left.size) - return HeightMap.of(this.break ? [left, null, right] : [left, right]); - this.left = left; - this.right = right; - this.height = left.height + right.height; - this.outdated = left.outdated || right.outdated; - this.size = left.size + right.size; - this.length = left.length + this.break + right.length; - return this; - } - updateHeight(oracle, offset = 0, force = false, measured) { - let { left, right } = this, rightStart = offset + left.length + this.break, rebalance = null; - if (measured && measured.from <= offset + left.length && measured.more) - rebalance = left = left.updateHeight(oracle, offset, force, measured); - else - left.updateHeight(oracle, offset, force); - if (measured && measured.from <= rightStart + right.length && measured.more) - rebalance = right = right.updateHeight(oracle, rightStart, force, measured); - else - right.updateHeight(oracle, rightStart, force); - if (rebalance) - return this.balanced(left, right); - this.height = this.left.height + this.right.height; - this.outdated = false; - return this; - } - toString() { return this.left + (this.break ? " " : "-") + this.right; } - } - function mergeGaps(nodes, around) { - let before, after; - if (nodes[around] == null && - (before = nodes[around - 1]) instanceof HeightMapGap && - (after = nodes[around + 1]) instanceof HeightMapGap) - nodes.splice(around - 1, 3, new HeightMapGap(before.length + 1 + after.length)); - } - const relevantWidgetHeight = 5; - class NodeBuilder { - constructor(pos, oracle) { - this.pos = pos; - this.oracle = oracle; - this.nodes = []; - this.lineStart = -1; - this.lineEnd = -1; - this.covering = null; - this.writtenTo = pos; - } - get isCovered() { - return this.covering && this.nodes[this.nodes.length - 1] == this.covering; - } - span(_from, to) { - if (this.lineStart > -1) { - let end = Math.min(to, this.lineEnd), last = this.nodes[this.nodes.length - 1]; - if (last instanceof HeightMapText) - last.length += end - this.pos; - else if (end > this.pos || !this.isCovered) - this.nodes.push(new HeightMapText(end - this.pos, -1)); - this.writtenTo = end; - if (to > end) { - this.nodes.push(null); - this.writtenTo++; - this.lineStart = -1; - } - } - this.pos = to; - } - point(from, to, deco) { - if (from < to || deco.heightRelevant) { - let height = deco.widget ? deco.widget.estimatedHeight : 0; - if (height < 0) - height = this.oracle.lineHeight; - let len = to - from; - if (deco.block) { - this.addBlock(new HeightMapBlock(len, height, deco.type)); - } - else if (len || height >= relevantWidgetHeight) { - this.addLineDeco(height, len); - } - } - else if (to > from) { - this.span(from, to); - } - if (this.lineEnd > -1 && this.lineEnd < this.pos) - this.lineEnd = this.oracle.doc.lineAt(this.pos).to; - } - enterLine() { - if (this.lineStart > -1) - return; - let { from, to } = this.oracle.doc.lineAt(this.pos); - this.lineStart = from; - this.lineEnd = to; - if (this.writtenTo < from) { - if (this.writtenTo < from - 1 || this.nodes[this.nodes.length - 1] == null) - this.nodes.push(this.blankContent(this.writtenTo, from - 1)); - this.nodes.push(null); - } - if (this.pos > from) - this.nodes.push(new HeightMapText(this.pos - from, -1)); - this.writtenTo = this.pos; - } - blankContent(from, to) { - let gap = new HeightMapGap(to - from); - if (this.oracle.doc.lineAt(from).to == to) - gap.flags |= 4 /* SingleLine */; - return gap; - } - ensureLine() { - this.enterLine(); - let last = this.nodes.length ? this.nodes[this.nodes.length - 1] : null; - if (last instanceof HeightMapText) - return last; - let line = new HeightMapText(0, -1); - this.nodes.push(line); - return line; - } - addBlock(block) { - this.enterLine(); - if (block.type == BlockType.WidgetAfter && !this.isCovered) - this.ensureLine(); - this.nodes.push(block); - this.writtenTo = this.pos = this.pos + block.length; - if (block.type != BlockType.WidgetBefore) - this.covering = block; - } - addLineDeco(height, length) { - let line = this.ensureLine(); - line.length += length; - line.collapsed += length; - line.widgetHeight = Math.max(line.widgetHeight, height); - this.writtenTo = this.pos = this.pos + length; - } - finish(from) { - let last = this.nodes.length == 0 ? null : this.nodes[this.nodes.length - 1]; - if (this.lineStart > -1 && !(last instanceof HeightMapText) && !this.isCovered) - this.nodes.push(new HeightMapText(0, -1)); - else if (this.writtenTo < this.pos || last == null) - this.nodes.push(this.blankContent(this.writtenTo, this.pos)); - let pos = from; - for (let node of this.nodes) { - if (node instanceof HeightMapText) - node.updateHeight(this.oracle, pos); - pos += node ? node.length : 1; - } - return this.nodes; - } - // Always called with a region that on both sides either stretches - // to a line break or the end of the document. - // The returned array uses null to indicate line breaks, but never - // starts or ends in a line break, or has multiple line breaks next - // to each other. - static build(oracle, decorations, from, to) { - let builder = new NodeBuilder(from, oracle); - RangeSet.spans(decorations, from, to, builder, 0); - return builder.finish(from); - } - } - function heightRelevantDecoChanges(a, b, diff) { - let comp = new DecorationComparator; - RangeSet.compare(a, b, diff, comp, 0); - return comp.changes; - } - class DecorationComparator { - constructor() { - this.changes = []; - } - compareRange() { } - comparePoint(from, to, a, b) { - if (from < to || a && a.heightRelevant || b && b.heightRelevant) - addRange(from, to, this.changes, 5); - } - } - - function visiblePixelRange(dom, paddingTop) { - let rect = dom.getBoundingClientRect(); - let left = Math.max(0, rect.left), right = Math.min(innerWidth, rect.right); - let top = Math.max(0, rect.top), bottom = Math.min(innerHeight, rect.bottom); - let body = dom.ownerDocument.body; - for (let parent = dom.parentNode; parent && parent != body;) { - if (parent.nodeType == 1) { - let elt = parent; - let style = window.getComputedStyle(elt); - if ((elt.scrollHeight > elt.clientHeight || elt.scrollWidth > elt.clientWidth) && - style.overflow != "visible") { - let parentRect = elt.getBoundingClientRect(); - left = Math.max(left, parentRect.left); - right = Math.min(right, parentRect.right); - top = Math.max(top, parentRect.top); - bottom = Math.min(bottom, parentRect.bottom); - } - parent = style.position == "absolute" || style.position == "fixed" ? elt.offsetParent : elt.parentNode; - } - else if (parent.nodeType == 11) { // Shadow root - parent = parent.host; - } - else { - break; - } - } - return { left: left - rect.left, right: Math.max(left, right) - rect.left, - top: top - (rect.top + paddingTop), bottom: Math.max(top, bottom) - (rect.top + paddingTop) }; - } - function fullPixelRange(dom, paddingTop) { - let rect = dom.getBoundingClientRect(); - return { left: 0, right: rect.right - rect.left, - top: paddingTop, bottom: rect.bottom - (rect.top + paddingTop) }; - } - // Line gaps are placeholder widgets used to hide pieces of overlong - // lines within the viewport, as a kludge to keep the editor - // responsive when a ridiculously long line is loaded into it. - class LineGap { - constructor(from, to, size) { - this.from = from; - this.to = to; - this.size = size; - } - static same(a, b) { - if (a.length != b.length) - return false; - for (let i = 0; i < a.length; i++) { - let gA = a[i], gB = b[i]; - if (gA.from != gB.from || gA.to != gB.to || gA.size != gB.size) - return false; - } - return true; - } - draw(wrapping) { - return Decoration.replace({ widget: new LineGapWidget(this.size, wrapping) }).range(this.from, this.to); - } - } - class LineGapWidget extends WidgetType { - constructor(size, vertical) { - super(); - this.size = size; - this.vertical = vertical; - } - eq(other) { return other.size == this.size && other.vertical == this.vertical; } - toDOM() { - let elt = document.createElement("div"); - if (this.vertical) { - elt.style.height = this.size + "px"; - } - else { - elt.style.width = this.size + "px"; - elt.style.height = "2px"; - elt.style.display = "inline-block"; - } - return elt; - } - get estimatedHeight() { return this.vertical ? this.size : -1; } - } - class ViewState { - constructor(state) { - this.state = state; - // These are contentDOM-local coordinates - this.pixelViewport = { left: 0, right: window.innerWidth, top: 0, bottom: 0 }; - this.inView = true; - this.paddingTop = 0; - this.paddingBottom = 0; - this.contentDOMWidth = 0; - this.contentDOMHeight = 0; - this.editorHeight = 0; - this.editorWidth = 0; - this.heightOracle = new HeightOracle; - // See VP.MaxDOMHeight - this.scaler = IdScaler; - this.scrollTarget = null; - // Briefly set to true when printing, to disable viewport limiting - this.printing = false; - // Flag set when editor content was redrawn, so that the next - // measure stage knows it must read DOM layout - this.mustMeasureContent = true; - this.visibleRanges = []; - // Cursor 'assoc' is only significant when the cursor is on a line - // wrap point, where it must stick to the character that it is - // associated with. Since browsers don't provide a reasonable - // interface to set or query this, when a selection is set that - // might cause this to be significant, this flag is set. The next - // measure phase will check whether the cursor is on a line-wrapping - // boundary and, if so, reset it to make sure it is positioned in - // the right place. - this.mustEnforceCursorAssoc = false; - this.heightMap = HeightMap.empty().applyChanges(state.facet(decorations), Text.empty, this.heightOracle.setDoc(state.doc), [new ChangedRange(0, 0, 0, state.doc.length)]); - this.viewport = this.getViewport(0, null); - this.updateViewportLines(); - this.updateForViewport(); - this.lineGaps = this.ensureLineGaps([]); - this.lineGapDeco = Decoration.set(this.lineGaps.map(gap => gap.draw(false))); - this.computeVisibleRanges(); - } - updateForViewport() { - let viewports = [this.viewport], { main } = this.state.selection; - for (let i = 0; i <= 1; i++) { - let pos = i ? main.head : main.anchor; - if (!viewports.some(({ from, to }) => pos >= from && pos <= to)) { - let { from, to } = this.lineBlockAt(pos); - viewports.push(new Viewport(from, to)); - } - } - this.viewports = viewports.sort((a, b) => a.from - b.from); - this.scaler = this.heightMap.height <= 7000000 /* MaxDOMHeight */ ? IdScaler : - new BigScaler(this.heightOracle.doc, this.heightMap, this.viewports); - } - updateViewportLines() { - this.viewportLines = []; - this.heightMap.forEachLine(this.viewport.from, this.viewport.to, this.state.doc, 0, 0, block => { - this.viewportLines.push(this.scaler.scale == 1 ? block : scaleBlock(block, this.scaler)); - }); - } - update(update, scrollTarget = null) { - let prev = this.state; - this.state = update.state; - let newDeco = this.state.facet(decorations); - let contentChanges = update.changedRanges; - let heightChanges = ChangedRange.extendWithRanges(contentChanges, heightRelevantDecoChanges(update.startState.facet(decorations), newDeco, update ? update.changes : ChangeSet.empty(this.state.doc.length))); - let prevHeight = this.heightMap.height; - this.heightMap = this.heightMap.applyChanges(newDeco, prev.doc, this.heightOracle.setDoc(this.state.doc), heightChanges); - if (this.heightMap.height != prevHeight) - update.flags |= 2 /* Height */; - let viewport = heightChanges.length ? this.mapViewport(this.viewport, update.changes) : this.viewport; - if (scrollTarget && (scrollTarget.range.head < viewport.from || scrollTarget.range.head > viewport.to) || - !this.viewportIsAppropriate(viewport)) - viewport = this.getViewport(0, scrollTarget); - let updateLines = !update.changes.empty || (update.flags & 2 /* Height */) || - viewport.from != this.viewport.from || viewport.to != this.viewport.to; - this.viewport = viewport; - this.updateForViewport(); - if (updateLines) - this.updateViewportLines(); - if (this.lineGaps.length || this.viewport.to - this.viewport.from > 4000 /* DoubleMargin */) - this.updateLineGaps(this.ensureLineGaps(this.mapLineGaps(this.lineGaps, update.changes))); - update.flags |= this.computeVisibleRanges(); - if (scrollTarget) - this.scrollTarget = scrollTarget; - if (!this.mustEnforceCursorAssoc && update.selectionSet && update.view.lineWrapping && - update.state.selection.main.empty && update.state.selection.main.assoc) - this.mustEnforceCursorAssoc = true; - } - measure(view) { - let dom = view.contentDOM, style = window.getComputedStyle(dom); - let oracle = this.heightOracle; - let whiteSpace = style.whiteSpace, direction = style.direction == "rtl" ? Direction.RTL : Direction.LTR; - let refresh = this.heightOracle.mustRefreshForStyle(whiteSpace, direction); - let measureContent = refresh || this.mustMeasureContent || this.contentDOMHeight != dom.clientHeight; - let result = 0, bias = 0; - if (this.editorWidth != view.scrollDOM.clientWidth) { - if (oracle.lineWrapping) - measureContent = true; - this.editorWidth = view.scrollDOM.clientWidth; - result |= 8 /* Geometry */; - } - if (measureContent) { - this.mustMeasureContent = false; - this.contentDOMHeight = dom.clientHeight; - // Vertical padding - let paddingTop = parseInt(style.paddingTop) || 0, paddingBottom = parseInt(style.paddingBottom) || 0; - if (this.paddingTop != paddingTop || this.paddingBottom != paddingBottom) { - result |= 8 /* Geometry */; - this.paddingTop = paddingTop; - this.paddingBottom = paddingBottom; - } - } - // Pixel viewport - let pixelViewport = (this.printing ? fullPixelRange : visiblePixelRange)(dom, this.paddingTop); - let dTop = pixelViewport.top - this.pixelViewport.top, dBottom = pixelViewport.bottom - this.pixelViewport.bottom; - this.pixelViewport = pixelViewport; - let inView = this.pixelViewport.bottom > this.pixelViewport.top && this.pixelViewport.right > this.pixelViewport.left; - if (inView != this.inView) { - this.inView = inView; - if (inView) - measureContent = true; - } - if (!this.inView) - return 0; - let contentWidth = dom.clientWidth; - if (this.contentDOMWidth != contentWidth || this.editorHeight != view.scrollDOM.clientHeight) { - this.contentDOMWidth = contentWidth; - this.editorHeight = view.scrollDOM.clientHeight; - result |= 8 /* Geometry */; - } - if (measureContent) { - let lineHeights = view.docView.measureVisibleLineHeights(); - if (oracle.mustRefreshForHeights(lineHeights)) - refresh = true; - if (refresh || oracle.lineWrapping && Math.abs(contentWidth - this.contentDOMWidth) > oracle.charWidth) { - let { lineHeight, charWidth } = view.docView.measureTextSize(); - refresh = oracle.refresh(whiteSpace, direction, lineHeight, charWidth, contentWidth / charWidth, lineHeights); - if (refresh) { - view.docView.minWidth = 0; - result |= 8 /* Geometry */; - } - } - if (dTop > 0 && dBottom > 0) - bias = Math.max(dTop, dBottom); - else if (dTop < 0 && dBottom < 0) - bias = Math.min(dTop, dBottom); - oracle.heightChanged = false; - this.heightMap = this.heightMap.updateHeight(oracle, 0, refresh, new MeasuredHeights(this.viewport.from, lineHeights)); - if (oracle.heightChanged) - result |= 2 /* Height */; - } - let viewportChange = !this.viewportIsAppropriate(this.viewport, bias) || - this.scrollTarget && (this.scrollTarget.range.head < this.viewport.from || this.scrollTarget.range.head > this.viewport.to); - if (viewportChange) - this.viewport = this.getViewport(bias, this.scrollTarget); - this.updateForViewport(); - if ((result & 2 /* Height */) || viewportChange) - this.updateViewportLines(); - if (this.lineGaps.length || this.viewport.to - this.viewport.from > 4000 /* DoubleMargin */) - this.updateLineGaps(this.ensureLineGaps(refresh ? [] : this.lineGaps)); - result |= this.computeVisibleRanges(); - if (this.mustEnforceCursorAssoc) { - this.mustEnforceCursorAssoc = false; - // This is done in the read stage, because moving the selection - // to a line end is going to trigger a layout anyway, so it - // can't be a pure write. It should be rare that it does any - // writing. - view.docView.enforceCursorAssoc(); - } - return result; - } - get visibleTop() { return this.scaler.fromDOM(this.pixelViewport.top); } - get visibleBottom() { return this.scaler.fromDOM(this.pixelViewport.bottom); } - getViewport(bias, scrollTarget) { - // This will divide VP.Margin between the top and the - // bottom, depending on the bias (the change in viewport position - // since the last update). It'll hold a number between 0 and 1 - let marginTop = 0.5 - Math.max(-0.5, Math.min(0.5, bias / 1000 /* Margin */ / 2)); - let map = this.heightMap, doc = this.state.doc, { visibleTop, visibleBottom } = this; - let viewport = new Viewport(map.lineAt(visibleTop - marginTop * 1000 /* Margin */, QueryType$1.ByHeight, doc, 0, 0).from, map.lineAt(visibleBottom + (1 - marginTop) * 1000 /* Margin */, QueryType$1.ByHeight, doc, 0, 0).to); - // If scrollTarget is given, make sure the viewport includes that position - if (scrollTarget) { - let { head } = scrollTarget.range; - if (head < viewport.from || head > viewport.to) { - let viewHeight = Math.min(this.editorHeight, this.pixelViewport.bottom - this.pixelViewport.top); - let block = map.lineAt(head, QueryType$1.ByPos, doc, 0, 0), topPos; - if (scrollTarget.y == "center") - topPos = (block.top + block.bottom) / 2 - viewHeight / 2; - else if (scrollTarget.y == "start" || scrollTarget.y == "nearest" && head < viewport.from) - topPos = block.top; - else - topPos = block.bottom - viewHeight; - viewport = new Viewport(map.lineAt(topPos - 1000 /* Margin */ / 2, QueryType$1.ByHeight, doc, 0, 0).from, map.lineAt(topPos + viewHeight + 1000 /* Margin */ / 2, QueryType$1.ByHeight, doc, 0, 0).to); - } - } - return viewport; - } - mapViewport(viewport, changes) { - let from = changes.mapPos(viewport.from, -1), to = changes.mapPos(viewport.to, 1); - return new Viewport(this.heightMap.lineAt(from, QueryType$1.ByPos, this.state.doc, 0, 0).from, this.heightMap.lineAt(to, QueryType$1.ByPos, this.state.doc, 0, 0).to); - } - // Checks if a given viewport covers the visible part of the - // document and not too much beyond that. - viewportIsAppropriate({ from, to }, bias = 0) { - if (!this.inView) - return true; - let { top } = this.heightMap.lineAt(from, QueryType$1.ByPos, this.state.doc, 0, 0); - let { bottom } = this.heightMap.lineAt(to, QueryType$1.ByPos, this.state.doc, 0, 0); - let { visibleTop, visibleBottom } = this; - return (from == 0 || top <= visibleTop - Math.max(10 /* MinCoverMargin */, Math.min(-bias, 250 /* MaxCoverMargin */))) && - (to == this.state.doc.length || - bottom >= visibleBottom + Math.max(10 /* MinCoverMargin */, Math.min(bias, 250 /* MaxCoverMargin */))) && - (top > visibleTop - 2 * 1000 /* Margin */ && bottom < visibleBottom + 2 * 1000 /* Margin */); - } - mapLineGaps(gaps, changes) { - if (!gaps.length || changes.empty) - return gaps; - let mapped = []; - for (let gap of gaps) - if (!changes.touchesRange(gap.from, gap.to)) - mapped.push(new LineGap(changes.mapPos(gap.from), changes.mapPos(gap.to), gap.size)); - return mapped; - } - // Computes positions in the viewport where the start or end of a - // line should be hidden, trying to reuse existing line gaps when - // appropriate to avoid unneccesary redraws. - // Uses crude character-counting for the positioning and sizing, - // since actual DOM coordinates aren't always available and - // predictable. Relies on generous margins (see LG.Margin) to hide - // the artifacts this might produce from the user. - ensureLineGaps(current) { - let gaps = []; - // This won't work at all in predominantly right-to-left text. - if (this.heightOracle.direction != Direction.LTR) - return gaps; - for (let line of this.viewportLines) { - if (line.length < 4000 /* DoubleMargin */) - continue; - let structure = lineStructure(line.from, line.to, this.state); - if (structure.total < 4000 /* DoubleMargin */) - continue; - let viewFrom, viewTo; - if (this.heightOracle.lineWrapping) { - let marginHeight = (2000 /* Margin */ / this.heightOracle.lineLength) * this.heightOracle.lineHeight; - viewFrom = findPosition(structure, (this.visibleTop - line.top - marginHeight) / line.height); - viewTo = findPosition(structure, (this.visibleBottom - line.top + marginHeight) / line.height); - } - else { - let totalWidth = structure.total * this.heightOracle.charWidth; - let marginWidth = 2000 /* Margin */ * this.heightOracle.charWidth; - viewFrom = findPosition(structure, (this.pixelViewport.left - marginWidth) / totalWidth); - viewTo = findPosition(structure, (this.pixelViewport.right + marginWidth) / totalWidth); - } - let outside = []; - if (viewFrom > line.from) - outside.push({ from: line.from, to: viewFrom }); - if (viewTo < line.to) - outside.push({ from: viewTo, to: line.to }); - let sel = this.state.selection.main; - // Make sure the gaps don't cover a selection end - if (sel.from >= line.from && sel.from <= line.to) - cutRange(outside, sel.from - 10 /* SelectionMargin */, sel.from + 10 /* SelectionMargin */); - if (!sel.empty && sel.to >= line.from && sel.to <= line.to) - cutRange(outside, sel.to - 10 /* SelectionMargin */, sel.to + 10 /* SelectionMargin */); - for (let { from, to } of outside) - if (to - from > 1000 /* HalfMargin */) { - gaps.push(find(current, gap => gap.from >= line.from && gap.to <= line.to && - Math.abs(gap.from - from) < 1000 /* HalfMargin */ && Math.abs(gap.to - to) < 1000 /* HalfMargin */) || - new LineGap(from, to, this.gapSize(line, from, to, structure))); - } - } - return gaps; - } - gapSize(line, from, to, structure) { - let fraction = findFraction(structure, to) - findFraction(structure, from); - if (this.heightOracle.lineWrapping) { - return line.height * fraction; - } - else { - return structure.total * this.heightOracle.charWidth * fraction; - } - } - updateLineGaps(gaps) { - if (!LineGap.same(gaps, this.lineGaps)) { - this.lineGaps = gaps; - this.lineGapDeco = Decoration.set(gaps.map(gap => gap.draw(this.heightOracle.lineWrapping))); - } - } - computeVisibleRanges() { - let deco = this.state.facet(decorations); - if (this.lineGaps.length) - deco = deco.concat(this.lineGapDeco); - let ranges = []; - RangeSet.spans(deco, this.viewport.from, this.viewport.to, { - span(from, to) { ranges.push({ from, to }); }, - point() { } - }, 20); - let changed = ranges.length != this.visibleRanges.length || - this.visibleRanges.some((r, i) => r.from != ranges[i].from || r.to != ranges[i].to); - this.visibleRanges = ranges; - return changed ? 4 /* Viewport */ : 0; - } - lineBlockAt(pos) { - return (pos >= this.viewport.from && pos <= this.viewport.to && this.viewportLines.find(b => b.from <= pos && b.to >= pos)) || - scaleBlock(this.heightMap.lineAt(pos, QueryType$1.ByPos, this.state.doc, 0, 0), this.scaler); - } - lineBlockAtHeight(height) { - return scaleBlock(this.heightMap.lineAt(this.scaler.fromDOM(height), QueryType$1.ByHeight, this.state.doc, 0, 0), this.scaler); - } - elementAtHeight(height) { - return scaleBlock(this.heightMap.blockAt(this.scaler.fromDOM(height), this.state.doc, 0, 0), this.scaler); - } - get docHeight() { - return this.scaler.toDOM(this.heightMap.height); - } - get contentHeight() { - return this.docHeight + this.paddingTop + this.paddingBottom; - } - } - class Viewport { - constructor(from, to) { - this.from = from; - this.to = to; - } - } - function lineStructure(from, to, state) { - let ranges = [], pos = from, total = 0; - RangeSet.spans(state.facet(decorations), from, to, { - span() { }, - point(from, to) { - if (from > pos) { - ranges.push({ from: pos, to: from }); - total += from - pos; - } - pos = to; - } - }, 20); // We're only interested in collapsed ranges of a significant size - if (pos < to) { - ranges.push({ from: pos, to }); - total += to - pos; - } - return { total, ranges }; - } - function findPosition({ total, ranges }, ratio) { - if (ratio <= 0) - return ranges[0].from; - if (ratio >= 1) - return ranges[ranges.length - 1].to; - let dist = Math.floor(total * ratio); - for (let i = 0;; i++) { - let { from, to } = ranges[i], size = to - from; - if (dist <= size) - return from + dist; - dist -= size; - } - } - function findFraction(structure, pos) { - let counted = 0; - for (let { from, to } of structure.ranges) { - if (pos <= to) { - counted += pos - from; - break; - } - counted += to - from; - } - return counted / structure.total; - } - function cutRange(ranges, from, to) { - for (let i = 0; i < ranges.length; i++) { - let r = ranges[i]; - if (r.from < to && r.to > from) { - let pieces = []; - if (r.from < from) - pieces.push({ from: r.from, to: from }); - if (r.to > to) - pieces.push({ from: to, to: r.to }); - ranges.splice(i, 1, ...pieces); - i += pieces.length - 1; - } - } - } - function find(array, f) { - for (let val of array) - if (f(val)) - return val; - return undefined; - } - // Don't scale when the document height is within the range of what - // the DOM can handle. - const IdScaler = { - toDOM(n) { return n; }, - fromDOM(n) { return n; }, - scale: 1 - }; - // When the height is too big (> VP.MaxDOMHeight), scale down the - // regions outside the viewports so that the total height is - // VP.MaxDOMHeight. - class BigScaler { - constructor(doc, heightMap, viewports) { - let vpHeight = 0, base = 0, domBase = 0; - this.viewports = viewports.map(({ from, to }) => { - let top = heightMap.lineAt(from, QueryType$1.ByPos, doc, 0, 0).top; - let bottom = heightMap.lineAt(to, QueryType$1.ByPos, doc, 0, 0).bottom; - vpHeight += bottom - top; - return { from, to, top, bottom, domTop: 0, domBottom: 0 }; - }); - this.scale = (7000000 /* MaxDOMHeight */ - vpHeight) / (heightMap.height - vpHeight); - for (let obj of this.viewports) { - obj.domTop = domBase + (obj.top - base) * this.scale; - domBase = obj.domBottom = obj.domTop + (obj.bottom - obj.top); - base = obj.bottom; - } - } - toDOM(n) { - for (let i = 0, base = 0, domBase = 0;; i++) { - let vp = i < this.viewports.length ? this.viewports[i] : null; - if (!vp || n < vp.top) - return domBase + (n - base) * this.scale; - if (n <= vp.bottom) - return vp.domTop + (n - vp.top); - base = vp.bottom; - domBase = vp.domBottom; - } - } - fromDOM(n) { - for (let i = 0, base = 0, domBase = 0;; i++) { - let vp = i < this.viewports.length ? this.viewports[i] : null; - if (!vp || n < vp.domTop) - return base + (n - domBase) / this.scale; - if (n <= vp.domBottom) - return vp.top + (n - vp.domTop); - base = vp.bottom; - domBase = vp.domBottom; - } - } - } - function scaleBlock(block, scaler) { - if (scaler.scale == 1) - return block; - let bTop = scaler.toDOM(block.top), bBottom = scaler.toDOM(block.bottom); - return new BlockInfo(block.from, block.length, bTop, bBottom - bTop, Array.isArray(block.type) ? block.type.map(b => scaleBlock(b, scaler)) : block.type); - } - - const theme = /*@__PURE__*/Facet.define({ combine: strs => strs.join(" ") }); - const darkTheme = /*@__PURE__*/Facet.define({ combine: values => values.indexOf(true) > -1 }); - const baseThemeID = /*@__PURE__*/StyleModule.newName(), baseLightID = /*@__PURE__*/StyleModule.newName(), baseDarkID = /*@__PURE__*/StyleModule.newName(); - const lightDarkIDs = { "&light": "." + baseLightID, "&dark": "." + baseDarkID }; - function buildTheme(main, spec, scopes) { - return new StyleModule(spec, { - finish(sel) { - return /&/.test(sel) ? sel.replace(/&\w*/, m => { - if (m == "&") - return main; - if (!scopes || !scopes[m]) - throw new RangeError(`Unsupported selector: ${m}`); - return scopes[m]; - }) : main + " " + sel; - } - }); - } - const baseTheme$8 = /*@__PURE__*/buildTheme("." + baseThemeID, { - "&.cm-editor": { - position: "relative !important", - boxSizing: "border-box", - "&.cm-focused": { - // Provide a simple default outline to make sure a focused - // editor is visually distinct. Can't leave the default behavior - // because that will apply to the content element, which is - // inside the scrollable container and doesn't include the - // gutters. We also can't use an 'auto' outline, since those - // are, for some reason, drawn behind the element content, which - // will cause things like the active line background to cover - // the outline (#297). - 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, - minHeight: "100%", - display: "block", - whiteSpace: "pre", - wordWrap: "normal", - boxSizing: "border-box", - 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" - }, - "&light .cm-content": { caretColor: "black" }, - "&dark .cm-content": { caretColor: "white" }, - ".cm-line": { - display: "block", - padding: "0 2px 0 4px" - }, - ".cm-selectionLayer": { - zIndex: -1, - contain: "size style" - }, - ".cm-selectionBackground": { - position: "absolute", - }, - "&light .cm-selectionBackground": { - background: "#d9d9d9" - }, - "&dark .cm-selectionBackground": { - background: "#222" - }, - "&light.cm-focused .cm-selectionBackground": { - background: "#d7d4f0" - }, - "&dark.cm-focused .cm-selectionBackground": { - background: "#233" - }, - ".cm-cursorLayer": { - zIndex: 100, - contain: "size style", - pointerEvents: "none" - }, - "&.cm-focused .cm-cursorLayer": { - animation: "steps(1) cm-blink 1.2s infinite" - }, - // Two animations defined so that we can switch between them to - // restart the animation without forcing another style - // recomputation. - "@keyframes cm-blink": { "0%": {}, "50%": { visibility: "hidden" }, "100%": {} }, - "@keyframes cm-blink2": { "0%": {}, "50%": { visibility: "hidden" }, "100%": {} }, - ".cm-cursor, .cm-dropCursor": { - position: "absolute", - borderLeft: "1.2px solid black", - marginLeft: "-0.6px", - pointerEvents: "none", - }, - ".cm-cursor": { - display: "none" - }, - "&dark .cm-cursor": { - borderLeftColor: "#444" - }, - "&.cm-focused .cm-cursor": { - display: "block" - }, - "&light .cm-activeLine": { backgroundColor: "#f3f9ff" }, - "&dark .cm-activeLine": { backgroundColor: "#223039" }, - "&light .cm-specialChar": { color: "red" }, - "&dark .cm-specialChar": { color: "#f78" }, - ".cm-tab": { - display: "inline-block", - overflow: "hidden", - verticalAlign: "bottom" - }, - ".cm-widgetBuffer": { - verticalAlign: "text-top", - height: "1em", - display: "inline" - }, - ".cm-placeholder": { - color: "#888", - display: "inline-block", - verticalAlign: "top", - }, - ".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" - } - }, lightDarkIDs); - - const observeOptions = { - childList: true, - characterData: true, - subtree: true, - attributes: true, - characterDataOldValue: true - }; - // IE11 has very broken mutation observers, so we also listen to - // DOMCharacterDataModified there - const useCharData = browser.ie && browser.ie_version <= 11; - class DOMObserver { - constructor(view, onChange, onScrollChanged) { - this.view = view; - this.onChange = onChange; - this.onScrollChanged = onScrollChanged; - this.active = false; - // The known selection. Kept in our own object, as opposed to just - // directly accessing the selection because: - // - Safari doesn't report the right selection in shadow DOM - // - Reading from the selection forces a DOM layout - // - This way, we can ignore selectionchange events if we have - // already seen the 'new' selection - this.selectionRange = new DOMSelectionState; - // Set when a selection change is detected, cleared on flush - this.selectionChanged = false; - this.delayedFlush = -1; - this.resizeTimeout = -1; - this.queue = []; - this.delayedAndroidKey = null; - this.scrollTargets = []; - this.intersection = null; - this.resize = null; - this.intersecting = false; - this.gapIntersection = null; - this.gaps = []; - // Timeout for scheduling check of the parents that need scroll handlers - this.parentCheck = -1; - this.dom = view.contentDOM; - this.observer = new MutationObserver(mutations => { - for (let mut of mutations) - this.queue.push(mut); - // IE11 will sometimes (on typing over a selection or - // backspacing out a single character text node) call the - // observer callback before actually updating the DOM. - // - // Unrelatedly, iOS Safari will, when ending a composition, - // sometimes first clear it, deliver the mutations, and then - // reinsert the finished text. CodeMirror's handling of the - // deletion will prevent the reinsertion from happening, - // breaking composition. - if ((browser.ie && browser.ie_version <= 11 || browser.ios && view.composing) && - mutations.some(m => m.type == "childList" && m.removedNodes.length || - m.type == "characterData" && m.oldValue.length > m.target.nodeValue.length)) - this.flushSoon(); - else - this.flush(); - }); - if (useCharData) - this.onCharData = (event) => { - this.queue.push({ target: event.target, - type: "characterData", - oldValue: event.prevValue }); - this.flushSoon(); - }; - this.onSelectionChange = this.onSelectionChange.bind(this); - window.addEventListener("resize", this.onResize = this.onResize.bind(this)); - if (typeof ResizeObserver == "function") { - this.resize = new ResizeObserver(() => { - if (this.view.docView.lastUpdate < Date.now() - 75) - this.onResize(); - }); - this.resize.observe(view.scrollDOM); - } - window.addEventListener("beforeprint", this.onPrint = this.onPrint.bind(this)); - this.start(); - window.addEventListener("scroll", this.onScroll = this.onScroll.bind(this)); - if (typeof IntersectionObserver == "function") { - this.intersection = new IntersectionObserver(entries => { - if (this.parentCheck < 0) - this.parentCheck = setTimeout(this.listenForScroll.bind(this), 1000); - if (entries.length > 0 && (entries[entries.length - 1].intersectionRatio > 0) != this.intersecting) { - this.intersecting = !this.intersecting; - if (this.intersecting != this.view.inView) - this.onScrollChanged(document.createEvent("Event")); - } - }, {}); - this.intersection.observe(this.dom); - this.gapIntersection = new IntersectionObserver(entries => { - if (entries.length > 0 && entries[entries.length - 1].intersectionRatio > 0) - this.onScrollChanged(document.createEvent("Event")); - }, {}); - } - this.listenForScroll(); - this.readSelectionRange(); - this.dom.ownerDocument.addEventListener("selectionchange", this.onSelectionChange); - } - onScroll(e) { - if (this.intersecting) - this.flush(false); - this.onScrollChanged(e); - } - onResize() { - if (this.resizeTimeout < 0) - this.resizeTimeout = setTimeout(() => { - this.resizeTimeout = -1; - this.view.requestMeasure(); - }, 50); - } - onPrint() { - this.view.viewState.printing = true; - this.view.measure(); - setTimeout(() => { - this.view.viewState.printing = false; - this.view.requestMeasure(); - }, 500); - } - updateGaps(gaps) { - if (this.gapIntersection && (gaps.length != this.gaps.length || this.gaps.some((g, i) => g != gaps[i]))) { - this.gapIntersection.disconnect(); - for (let gap of gaps) - this.gapIntersection.observe(gap); - this.gaps = gaps; - } - } - onSelectionChange(event) { - if (!this.readSelectionRange() || this.delayedAndroidKey) - return; - let { view } = this, sel = this.selectionRange; - if (view.state.facet(editable) ? view.root.activeElement != this.dom : !hasSelection(view.dom, sel)) - return; - let context = sel.anchorNode && view.docView.nearest(sel.anchorNode); - if (context && context.ignoreEvent(event)) - return; - // Deletions on IE11 fire their events in the wrong order, giving - // us a selection change event before the DOM changes are - // reported. - // Chrome Android has a similar issue when backspacing out a - // selection (#645). - if ((browser.ie && browser.ie_version <= 11 || browser.android && browser.chrome) && !view.state.selection.main.empty && - // (Selection.isCollapsed isn't reliable on IE) - sel.focusNode && isEquivalentPosition(sel.focusNode, sel.focusOffset, sel.anchorNode, sel.anchorOffset)) - this.flushSoon(); - else - this.flush(false); - } - readSelectionRange() { - let { root } = this.view, domSel = getSelection(root); - // The Selection object is broken in shadow roots in Safari. See - // https://github.com/codemirror/codemirror.next/issues/414 - let range = browser.safari && root.nodeType == 11 && deepActiveElement() == this.view.contentDOM && - safariSelectionRangeHack(this.view) || domSel; - if (this.selectionRange.eq(range)) - return false; - this.selectionRange.setRange(range); - return this.selectionChanged = true; - } - setSelectionRange(anchor, head) { - this.selectionRange.set(anchor.node, anchor.offset, head.node, head.offset); - this.selectionChanged = false; - } - listenForScroll() { - this.parentCheck = -1; - let i = 0, changed = null; - for (let dom = this.dom; dom;) { - if (dom.nodeType == 1) { - if (!changed && i < this.scrollTargets.length && this.scrollTargets[i] == dom) - i++; - else if (!changed) - changed = this.scrollTargets.slice(0, i); - if (changed) - changed.push(dom); - dom = dom.assignedSlot || dom.parentNode; - } - else if (dom.nodeType == 11) { // Shadow root - dom = dom.host; - } - else { - break; - } - } - if (i < this.scrollTargets.length && !changed) - changed = this.scrollTargets.slice(0, i); - if (changed) { - for (let dom of this.scrollTargets) - dom.removeEventListener("scroll", this.onScroll); - for (let dom of this.scrollTargets = changed) - dom.addEventListener("scroll", this.onScroll); - } - } - ignore(f) { - if (!this.active) - return f(); - try { - this.stop(); - return f(); - } - finally { - this.start(); - this.clear(); - } - } - start() { - if (this.active) - return; - this.observer.observe(this.dom, observeOptions); - if (useCharData) - this.dom.addEventListener("DOMCharacterDataModified", this.onCharData); - this.active = true; - } - stop() { - if (!this.active) - return; - this.active = false; - this.observer.disconnect(); - if (useCharData) - this.dom.removeEventListener("DOMCharacterDataModified", this.onCharData); - } - // Throw away any pending changes - clear() { - this.processRecords(); - this.queue.length = 0; - this.selectionChanged = false; - } - // Chrome Android, especially in combination with GBoard, not only - // doesn't reliably fire regular key events, but also often - // surrounds the effect of enter or backspace with a bunch of - // composition events that, when interrupted, cause text duplication - // or other kinds of corruption. This hack makes the editor back off - // from handling DOM changes for a moment when such a key is - // detected (via beforeinput or keydown), and then dispatches the - // key event, throwing away the DOM changes if it gets handled. - delayAndroidKey(key, keyCode) { - if (!this.delayedAndroidKey) - requestAnimationFrame(() => { - let key = this.delayedAndroidKey; - this.delayedAndroidKey = null; - let startState = this.view.state; - if (dispatchKey(this.view.contentDOM, key.key, key.keyCode)) - this.processRecords(); - else - this.flush(); - if (this.view.state == startState) - this.view.update([]); - }); - // Since backspace beforeinput is sometimes signalled spuriously, - // Enter always takes precedence. - if (!this.delayedAndroidKey || key == "Enter") - this.delayedAndroidKey = { key, keyCode }; - } - flushSoon() { - if (this.delayedFlush < 0) - this.delayedFlush = window.setTimeout(() => { this.delayedFlush = -1; this.flush(); }, 20); - } - forceFlush() { - if (this.delayedFlush >= 0) { - window.clearTimeout(this.delayedFlush); - this.delayedFlush = -1; - this.flush(); - } - } - processRecords() { - let records = this.queue; - for (let mut of this.observer.takeRecords()) - records.push(mut); - if (records.length) - this.queue = []; - let from = -1, to = -1, typeOver = false; - for (let record of records) { - let range = this.readMutation(record); - if (!range) - continue; - if (range.typeOver) - typeOver = true; - if (from == -1) { - ({ from, to } = range); - } - else { - from = Math.min(range.from, from); - to = Math.max(range.to, to); - } - } - return { from, to, typeOver }; - } - // Apply pending changes, if any - flush(readSelection = true) { - // Completely hold off flushing when pending keys are set—the code - // managing those will make sure processRecords is called and the - // view is resynchronized after - if (this.delayedFlush >= 0 || this.delayedAndroidKey) - return; - if (readSelection) - this.readSelectionRange(); - let { from, to, typeOver } = this.processRecords(); - let newSel = this.selectionChanged && hasSelection(this.dom, this.selectionRange); - if (from < 0 && !newSel) - return; - this.selectionChanged = false; - let startState = this.view.state; - this.onChange(from, to, typeOver); - // The view wasn't updated - if (this.view.state == startState) - this.view.update([]); - } - readMutation(rec) { - let cView = this.view.docView.nearest(rec.target); - if (!cView || cView.ignoreMutation(rec)) - return null; - cView.markDirty(rec.type == "attributes"); - if (rec.type == "attributes") - cView.dirty |= 4 /* Attrs */; - if (rec.type == "childList") { - let childBefore = findChild(cView, rec.previousSibling || rec.target.previousSibling, -1); - let childAfter = findChild(cView, rec.nextSibling || rec.target.nextSibling, 1); - return { from: childBefore ? cView.posAfter(childBefore) : cView.posAtStart, - to: childAfter ? cView.posBefore(childAfter) : cView.posAtEnd, typeOver: false }; - } - else if (rec.type == "characterData") { - return { from: cView.posAtStart, to: cView.posAtEnd, typeOver: rec.target.nodeValue == rec.oldValue }; - } - else { - return null; - } - } - destroy() { - var _a, _b, _c; - this.stop(); - (_a = this.intersection) === null || _a === void 0 ? void 0 : _a.disconnect(); - (_b = this.gapIntersection) === null || _b === void 0 ? void 0 : _b.disconnect(); - (_c = this.resize) === null || _c === void 0 ? void 0 : _c.disconnect(); - for (let dom of this.scrollTargets) - dom.removeEventListener("scroll", this.onScroll); - window.removeEventListener("scroll", this.onScroll); - window.removeEventListener("resize", this.onResize); - window.removeEventListener("beforeprint", this.onPrint); - this.dom.ownerDocument.removeEventListener("selectionchange", this.onSelectionChange); - clearTimeout(this.parentCheck); - clearTimeout(this.resizeTimeout); - } - } - function findChild(cView, dom, dir) { - while (dom) { - let curView = ContentView.get(dom); - if (curView && curView.parent == cView) - return curView; - let parent = dom.parentNode; - dom = parent != cView.dom ? parent : dir > 0 ? dom.nextSibling : dom.previousSibling; - } - return null; - } - // Used to work around a Safari Selection/shadow DOM bug (#414) - function safariSelectionRangeHack(view) { - let found = null; - // Because Safari (at least in 2018-2021) doesn't provide regular - // access to the selection inside a shadowroot, we have to perform a - // ridiculous hack to get at it—using `execCommand` to trigger a - // `beforeInput` event so that we can read the target range from the - // event. - function read(event) { - event.preventDefault(); - event.stopImmediatePropagation(); - found = event.getTargetRanges()[0]; - } - view.contentDOM.addEventListener("beforeinput", read, true); - document.execCommand("indent"); - view.contentDOM.removeEventListener("beforeinput", read, true); - if (!found) - return null; - let anchorNode = found.startContainer, anchorOffset = found.startOffset; - let focusNode = found.endContainer, focusOffset = found.endOffset; - let curAnchor = view.docView.domAtPos(view.state.selection.main.anchor); - // Since such a range doesn't distinguish between anchor and head, - // use a heuristic that flips it around if its end matches the - // current anchor. - if (isEquivalentPosition(curAnchor.node, curAnchor.offset, focusNode, focusOffset)) - [anchorNode, anchorOffset, focusNode, focusOffset] = [focusNode, focusOffset, anchorNode, anchorOffset]; - return { anchorNode, anchorOffset, focusNode, focusOffset }; - } - - function applyDOMChange(view, start, end, typeOver) { - let change, newSel; - let sel = view.state.selection.main; - if (start > -1) { - let bounds = view.docView.domBoundsAround(start, end, 0); - if (!bounds || view.state.readOnly) - return; - let { from, to } = bounds; - let selPoints = view.docView.impreciseHead || view.docView.impreciseAnchor ? [] : selectionPoints(view); - let reader = new DOMReader(selPoints, view.state); - reader.readRange(bounds.startDOM, bounds.endDOM); - let preferredPos = sel.from, preferredSide = null; - // Prefer anchoring to end when Backspace is pressed (or, on - // Android, when something was deleted) - if (view.inputState.lastKeyCode === 8 && view.inputState.lastKeyTime > Date.now() - 100 || - browser.android && reader.text.length < to - from) { - preferredPos = sel.to; - preferredSide = "end"; - } - let diff = findDiff(view.state.doc.sliceString(from, to, LineBreakPlaceholder), reader.text, preferredPos - from, preferredSide); - if (diff) { - // Chrome inserts two newlines when pressing shift-enter at the - // end of a line. This drops one of those. - if (browser.chrome && view.inputState.lastKeyCode == 13 && - diff.toB == diff.from + 2 && reader.text.slice(diff.from, diff.toB) == LineBreakPlaceholder + LineBreakPlaceholder) - diff.toB--; - change = { from: from + diff.from, to: from + diff.toA, - insert: Text.of(reader.text.slice(diff.from, diff.toB).split(LineBreakPlaceholder)) }; - } - newSel = selectionFromPoints(selPoints, from); - } - else if (view.hasFocus || !view.state.facet(editable)) { - let domSel = view.observer.selectionRange; - let { impreciseHead: iHead, impreciseAnchor: iAnchor } = view.docView; - let head = iHead && iHead.node == domSel.focusNode && iHead.offset == domSel.focusOffset || - !contains(view.contentDOM, domSel.focusNode) - ? view.state.selection.main.head - : view.docView.posFromDOM(domSel.focusNode, domSel.focusOffset); - let anchor = iAnchor && iAnchor.node == domSel.anchorNode && iAnchor.offset == domSel.anchorOffset || - !contains(view.contentDOM, domSel.anchorNode) - ? view.state.selection.main.anchor - : view.docView.posFromDOM(domSel.anchorNode, domSel.anchorOffset); - if (head != sel.head || anchor != sel.anchor) - newSel = EditorSelection.single(anchor, head); - } - if (!change && !newSel) - return; - // Heuristic to notice typing over a selected character - if (!change && typeOver && !sel.empty && newSel && newSel.main.empty) - change = { from: sel.from, to: sel.to, insert: view.state.doc.slice(sel.from, sel.to) }; - // If the change is inside the selection and covers most of it, - // assume it is a selection replace (with identical characters at - // the start/end not included in the diff) - else if (change && change.from >= sel.from && change.to <= sel.to && - (change.from != sel.from || change.to != sel.to) && - (sel.to - sel.from) - (change.to - change.from) <= 4) - change = { - from: sel.from, to: sel.to, - insert: view.state.doc.slice(sel.from, change.from).append(change.insert).append(view.state.doc.slice(change.to, sel.to)) - }; - if (change) { - let startState = view.state; - if (browser.ios && view.inputState.flushIOSKey(view)) - return; - // Android browsers don't fire reasonable key events for enter, - // backspace, or delete. So this detects changes that look like - // they're caused by those keys, and reinterprets them as key - // events. (Some of these keys are also handled by beforeinput - // events and the pendingAndroidKey mechanism, but that's not - // reliable in all situations.) - if (browser.android && - ((change.from == sel.from && change.to == sel.to && - change.insert.length == 1 && change.insert.lines == 2 && - dispatchKey(view.contentDOM, "Enter", 13)) || - (change.from == sel.from - 1 && change.to == sel.to && change.insert.length == 0 && - dispatchKey(view.contentDOM, "Backspace", 8)) || - (change.from == sel.from && change.to == sel.to + 1 && change.insert.length == 0 && - dispatchKey(view.contentDOM, "Delete", 46)))) - return; - let text = change.insert.toString(); - if (view.state.facet(inputHandler$1).some(h => h(view, change.from, change.to, text))) - return; - if (view.inputState.composing >= 0) - view.inputState.composing++; - let tr; - if (change.from >= sel.from && change.to <= sel.to && change.to - change.from >= (sel.to - sel.from) / 3 && - (!newSel || newSel.main.empty && newSel.main.from == change.from + change.insert.length) && - view.inputState.composing < 0) { - let before = sel.from < change.from ? startState.sliceDoc(sel.from, change.from) : ""; - let after = sel.to > change.to ? startState.sliceDoc(change.to, sel.to) : ""; - tr = startState.replaceSelection(view.state.toText(before + change.insert.sliceString(0, undefined, view.state.lineBreak) + after)); - } - else { - let changes = startState.changes(change); - let mainSel = newSel && !startState.selection.main.eq(newSel.main) && newSel.main.to <= changes.newLength - ? newSel.main : undefined; - // Try to apply a composition change to all cursors - if (startState.selection.ranges.length > 1 && view.inputState.composing >= 0 && - change.to <= sel.to && change.to >= sel.to - 10) { - let replaced = view.state.sliceDoc(change.from, change.to); - let compositionRange = compositionSurroundingNode(view) || view.state.doc.lineAt(sel.head); - let offset = sel.to - change.to, size = sel.to - sel.from; - tr = startState.changeByRange(range => { - if (range.from == sel.from && range.to == sel.to) - return { changes, range: mainSel || range.map(changes) }; - let to = range.to - offset, from = to - replaced.length; - if (range.to - range.from != size || view.state.sliceDoc(from, to) != replaced || - // Unfortunately, there's no way to make multiple - // changes in the same node work without aborting - // composition, so cursors in the composition range are - // ignored. - compositionRange && range.to >= compositionRange.from && range.from <= compositionRange.to) - return { range }; - let rangeChanges = startState.changes({ from, to, insert: change.insert }), selOff = range.to - sel.to; - return { - changes: rangeChanges, - range: !mainSel ? range.map(rangeChanges) : - EditorSelection.range(Math.max(0, mainSel.anchor + selOff), Math.max(0, mainSel.head + selOff)) - }; - }); - } - else { - tr = { - changes, - selection: mainSel && startState.selection.replaceRange(mainSel) - }; - } - } - let userEvent = "input.type"; - if (view.composing) { - userEvent += ".compose"; - if (view.inputState.compositionFirstChange) { - userEvent += ".start"; - view.inputState.compositionFirstChange = false; - } - } - view.dispatch(tr, { scrollIntoView: true, userEvent }); - } - else if (newSel && !newSel.main.eq(sel)) { - let scrollIntoView = false, userEvent = "select"; - if (view.inputState.lastSelectionTime > Date.now() - 50) { - if (view.inputState.lastSelectionOrigin == "select") - scrollIntoView = true; - userEvent = view.inputState.lastSelectionOrigin; - } - view.dispatch({ selection: newSel, scrollIntoView, userEvent }); - } - } - function findDiff(a, b, preferredPos, preferredSide) { - let minLen = Math.min(a.length, b.length); - let from = 0; - while (from < minLen && a.charCodeAt(from) == b.charCodeAt(from)) - from++; - if (from == minLen && a.length == b.length) - return null; - let toA = a.length, toB = b.length; - while (toA > 0 && toB > 0 && a.charCodeAt(toA - 1) == b.charCodeAt(toB - 1)) { - toA--; - toB--; - } - if (preferredSide == "end") { - let adjust = Math.max(0, from - Math.min(toA, toB)); - preferredPos -= toA + adjust - from; - } - if (toA < from && a.length < b.length) { - let move = preferredPos <= from && preferredPos >= toA ? from - preferredPos : 0; - from -= move; - toB = from + (toB - toA); - toA = from; - } - else if (toB < from) { - let move = preferredPos <= from && preferredPos >= toB ? from - preferredPos : 0; - from -= move; - toA = from + (toA - toB); - toB = from; - } - return { from, toA, toB }; - } - function selectionPoints(view) { - let result = []; - if (view.root.activeElement != view.contentDOM) - return result; - let { anchorNode, anchorOffset, focusNode, focusOffset } = view.observer.selectionRange; - if (anchorNode) { - result.push(new DOMPoint(anchorNode, anchorOffset)); - if (focusNode != anchorNode || focusOffset != anchorOffset) - result.push(new DOMPoint(focusNode, focusOffset)); - } - return result; - } - function selectionFromPoints(points, base) { - if (points.length == 0) - return null; - let anchor = points[0].pos, head = points.length == 2 ? points[1].pos : anchor; - return anchor > -1 && head > -1 ? EditorSelection.single(anchor + base, head + base) : null; - } - - // The editor's update state machine looks something like this: - // - // Idle → Updating ⇆ Idle (unchecked) → Measuring → Idle - // ↑ ↓ - // Updating (measure) - // - // The difference between 'Idle' and 'Idle (unchecked)' lies in - // whether a layout check has been scheduled. A regular update through - // the `update` method updates the DOM in a write-only fashion, and - // relies on a check (scheduled with `requestAnimationFrame`) to make - // sure everything is where it should be and the viewport covers the - // visible code. That check continues to measure and then optionally - // update until it reaches a coherent state. - /** - An editor view represents the editor's user interface. It holds - the editable DOM surface, and possibly other elements such as the - line number gutter. It handles events and dispatches state - transactions for editing actions. - */ - class EditorView { - /** - Construct a new view. You'll usually want to put `view.dom` into - your document after creating a view, so that the user can see - it. - */ - constructor( - /** - Initialization options. - */ - config = {}) { - this.plugins = []; - this.pluginMap = new Map; - this.editorAttrs = {}; - this.contentAttrs = {}; - this.bidiCache = []; - this.destroyed = false; - /** - @internal - */ - this.updateState = 2 /* Updating */; - /** - @internal - */ - this.measureScheduled = -1; - /** - @internal - */ - 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.style.cssText = "position: absolute; top: -10000px"; - this.announceDOM.setAttribute("aria-live", "polite"); - this.dom = document.createElement("div"); - this.dom.appendChild(this.announceDOM); - this.dom.appendChild(this.scrollDOM); - this._dispatch = config.dispatch || ((tr) => this.update([tr])); - this.dispatch = this.dispatch.bind(this); - this.root = (config.root || getRoot(config.parent) || document); - this.viewState = new ViewState(config.state || EditorState.create()); - this.plugins = this.state.facet(viewPlugin).map(spec => new PluginInstance(spec)); - for (let plugin of this.plugins) - plugin.update(this); - this.observer = new DOMObserver(this, (from, to, typeOver) => { - applyDOMChange(this, from, to, typeOver); - }, event => { - this.inputState.runScrollHandlers(this, event); - if (this.observer.intersecting) - this.measure(); - }); - this.inputState = new InputState(this); - this.docView = new DocView(this); - this.mountStyles(); - this.updateAttrs(); - this.updateState = 0 /* Idle */; - this.requestMeasure(); - if (config.parent) - config.parent.appendChild(this.dom); - } - /** - The current editor state. - */ - get state() { return this.viewState.state; } - /** - To be able to display large documents without consuming too much - memory or overloading the browser, CodeMirror only draws the - code that is visible (plus a margin around it) to the DOM. This - property tells you the extent of the current drawn viewport, in - document positions. - */ - get viewport() { return this.viewState.viewport; } - /** - When there are, for example, large collapsed ranges in the - viewport, its size can be a lot bigger than the actual visible - content. Thus, if you are doing something like styling the - content in the viewport, it is preferable to only do so for - these ranges, which are the subset of the viewport that is - actually drawn. - */ - get visibleRanges() { return this.viewState.visibleRanges; } - /** - Returns false when the editor is entirely scrolled out of view - or otherwise hidden. - */ - get inView() { return this.viewState.inView; } - /** - Indicates whether the user is currently composing text via - [IME](https://en.wikipedia.org/wiki/Input_method), and at least - one change has been made in the current composition. - */ - get composing() { return this.inputState.composing > 0; } - /** - Indicates whether the user is currently in composing state. Note - that on some platforms, like Android, this will be the case a - lot, since just putting the cursor on a word starts a - composition there. - */ - get compositionStarted() { return this.inputState.composing >= 0; } - dispatch(...input) { - this._dispatch(input.length == 1 && input[0] instanceof Transaction ? input[0] - : this.state.update(...input)); - } - /** - Update the view for the given array of transactions. This will - update the visible document and selection to match the state - produced by the transactions, and notify view plugins of the - change. You should usually call - [`dispatch`](https://codemirror.net/6/docs/ref/#view.EditorView.dispatch) instead, which uses this - as a primitive. - */ - update(transactions) { - if (this.updateState != 0 /* Idle */) - throw new Error("Calls to EditorView.update are not allowed while an update is in progress"); - let redrawn = false, update; - let state = this.state; - for (let tr of transactions) { - if (tr.startState != state) - throw new RangeError("Trying to update state with a transaction that doesn't start from the previous state."); - state = tr.state; - } - if (this.destroyed) { - this.viewState.state = state; - return; - } - // When the phrases change, redraw the editor - if (state.facet(EditorState.phrases) != this.state.facet(EditorState.phrases)) - return this.setState(state); - update = new ViewUpdate(this, state, transactions); - let scrollTarget = this.viewState.scrollTarget; - try { - this.updateState = 2 /* Updating */; - for (let tr of transactions) { - if (scrollTarget) - scrollTarget = scrollTarget.map(tr.changes); - if (tr.scrollIntoView) { - let { main } = tr.state.selection; - scrollTarget = new ScrollTarget(main.empty ? main : EditorSelection.cursor(main.head, main.head > main.anchor ? -1 : 1)); - } - for (let e of tr.effects) { - if (e.is(scrollTo)) - scrollTarget = new ScrollTarget(e.value); - else if (e.is(centerOn)) - scrollTarget = new ScrollTarget(e.value, "center"); - else if (e.is(scrollIntoView$1)) - scrollTarget = e.value; - } - } - this.viewState.update(update, scrollTarget); - this.bidiCache = CachedOrder.update(this.bidiCache, update.changes); - if (!update.empty) { - this.updatePlugins(update); - this.inputState.update(update); - } - redrawn = this.docView.update(update); - if (this.state.facet(styleModule) != this.styleModules) - this.mountStyles(); - this.updateAttrs(); - this.showAnnouncements(transactions); - this.docView.updateSelection(redrawn, transactions.some(tr => tr.isUserEvent("select.pointer"))); - } - finally { - this.updateState = 0 /* Idle */; - } - if (update.startState.facet(theme) != update.state.facet(theme)) - this.viewState.mustMeasureContent = true; - if (redrawn || scrollTarget || this.viewState.mustEnforceCursorAssoc || this.viewState.mustMeasureContent) - this.requestMeasure(); - if (!update.empty) - for (let listener of this.state.facet(updateListener)) - listener(update); - } - /** - Reset the view to the given state. (This will cause the entire - document to be redrawn and all view plugins to be reinitialized, - so you should probably only use it when the new state isn't - derived from the old state. Otherwise, use - [`dispatch`](https://codemirror.net/6/docs/ref/#view.EditorView.dispatch) instead.) - */ - setState(newState) { - if (this.updateState != 0 /* Idle */) - throw new Error("Calls to EditorView.setState are not allowed while an update is in progress"); - if (this.destroyed) { - this.viewState.state = newState; - return; - } - this.updateState = 2 /* Updating */; - let hadFocus = this.hasFocus; - try { - for (let plugin of this.plugins) - plugin.destroy(this); - this.viewState = new ViewState(newState); - this.plugins = newState.facet(viewPlugin).map(spec => new PluginInstance(spec)); - this.pluginMap.clear(); - for (let plugin of this.plugins) - plugin.update(this); - this.docView = new DocView(this); - this.inputState.ensureHandlers(this); - this.mountStyles(); - this.updateAttrs(); - this.bidiCache = []; - } - finally { - this.updateState = 0 /* Idle */; - } - if (hadFocus) - this.focus(); - this.requestMeasure(); - } - updatePlugins(update) { - let prevSpecs = update.startState.facet(viewPlugin), specs = update.state.facet(viewPlugin); - if (prevSpecs != specs) { - let newPlugins = []; - for (let spec of specs) { - let found = prevSpecs.indexOf(spec); - if (found < 0) { - newPlugins.push(new PluginInstance(spec)); - } - else { - let plugin = this.plugins[found]; - plugin.mustUpdate = update; - newPlugins.push(plugin); - } - } - for (let plugin of this.plugins) - if (plugin.mustUpdate != update) - plugin.destroy(this); - this.plugins = newPlugins; - this.pluginMap.clear(); - this.inputState.ensureHandlers(this); - } - else { - for (let p of this.plugins) - p.mustUpdate = update; - } - for (let i = 0; i < this.plugins.length; i++) - this.plugins[i].update(this); - } - /** - @internal - */ - measure(flush = true) { - if (this.destroyed) - return; - if (this.measureScheduled > -1) - cancelAnimationFrame(this.measureScheduled); - this.measureScheduled = 0; // Prevent requestMeasure calls from scheduling another animation frame - if (flush) - this.observer.flush(); - let updated = null; - try { - for (let i = 0;; i++) { - this.updateState = 1 /* Measuring */; - let oldViewport = this.viewport; - let changed = this.viewState.measure(this); - if (!changed && !this.measureRequests.length && this.viewState.scrollTarget == null) - break; - if (i > 5) { - console.warn(this.measureRequests.length - ? "Measure loop restarted more than 5 times" - : "Viewport failed to stabilize"); - break; - } - let measuring = []; - // Only run measure requests in this cycle when the viewport didn't change - if (!(changed & 4 /* Viewport */)) - [this.measureRequests, measuring] = [measuring, this.measureRequests]; - let measured = measuring.map(m => { - try { - return m.read(this); - } - catch (e) { - logException(this.state, e); - return BadMeasure; - } - }); - let update = new ViewUpdate(this, this.state), redrawn = false, scrolled = false; - update.flags |= changed; - if (!updated) - updated = update; - else - updated.flags |= changed; - this.updateState = 2 /* Updating */; - if (!update.empty) { - this.updatePlugins(update); - this.inputState.update(update); - this.updateAttrs(); - redrawn = this.docView.update(update); - } - for (let i = 0; i < measuring.length; i++) - if (measured[i] != BadMeasure) { - try { - let m = measuring[i]; - if (m.write) - m.write(measured[i], this); - } - catch (e) { - logException(this.state, e); - } - } - if (this.viewState.scrollTarget) { - this.docView.scrollIntoView(this.viewState.scrollTarget); - this.viewState.scrollTarget = null; - scrolled = true; - } - if (redrawn) - this.docView.updateSelection(true); - if (this.viewport.from == oldViewport.from && this.viewport.to == oldViewport.to && - !scrolled && this.measureRequests.length == 0) - break; - } - } - finally { - this.updateState = 0 /* Idle */; - this.measureScheduled = -1; - } - if (updated && !updated.empty) - for (let listener of this.state.facet(updateListener)) - listener(updated); - } - /** - Get the CSS classes for the currently active editor themes. - */ - get themeClasses() { - return baseThemeID + " " + - (this.state.facet(darkTheme) ? baseDarkID : baseLightID) + " " + - this.state.facet(theme); - } - updateAttrs() { - let editorAttrs = attrsFromFacet(this, editorAttributes, { - class: "cm-editor" + (this.hasFocus ? " cm-focused " : " ") + this.themeClasses - }); - let contentAttrs = { - spellcheck: "false", - autocorrect: "off", - autocapitalize: "off", - translate: "no", - contenteditable: !this.state.facet(editable) ? "false" : "true", - class: "cm-content", - style: `${browser.tabSize}: ${this.state.tabSize}`, - role: "textbox", - "aria-multiline": "true" - }; - if (this.state.readOnly) - contentAttrs["aria-readonly"] = "true"; - attrsFromFacet(this, contentAttributes, contentAttrs); - this.observer.ignore(() => { - updateAttrs(this.contentDOM, this.contentAttrs, contentAttrs); - updateAttrs(this.dom, this.editorAttrs, editorAttrs); - }); - this.editorAttrs = editorAttrs; - this.contentAttrs = contentAttrs; - } - showAnnouncements(trs) { - let first = true; - for (let tr of trs) - for (let effect of tr.effects) - if (effect.is(EditorView.announce)) { - if (first) - this.announceDOM.textContent = ""; - first = false; - let div = this.announceDOM.appendChild(document.createElement("div")); - div.textContent = effect.value; - } - } - mountStyles() { - this.styleModules = this.state.facet(styleModule); - StyleModule.mount(this.root, this.styleModules.concat(baseTheme$8).reverse()); - } - readMeasured() { - if (this.updateState == 2 /* Updating */) - throw new Error("Reading the editor layout isn't allowed during an update"); - if (this.updateState == 0 /* Idle */ && this.measureScheduled > -1) - this.measure(false); - } - /** - Schedule a layout measurement, optionally providing callbacks to - do custom DOM measuring followed by a DOM write phase. Using - this is preferable reading DOM layout directly from, for - example, an event handler, because it'll make sure measuring and - drawing done by other components is synchronized, avoiding - unnecessary DOM layout computations. - */ - requestMeasure(request) { - if (this.measureScheduled < 0) - this.measureScheduled = requestAnimationFrame(() => this.measure()); - if (request) { - if (request.key != null) - for (let i = 0; i < this.measureRequests.length; i++) { - if (this.measureRequests[i].key === request.key) { - this.measureRequests[i] = request; - return; - } - } - this.measureRequests.push(request); - } - } - /** - Collect all values provided by the active plugins for a given - field. - */ - pluginField(field) { - let result = []; - for (let plugin of this.plugins) - plugin.update(this).takeField(field, result); - return result; - } - /** - Get the value of a specific plugin, if present. Note that - plugins that crash can be dropped from a view, so even when you - know you registered a given plugin, it is recommended to check - the return value of this method. - */ - plugin(plugin) { - let known = this.pluginMap.get(plugin); - if (known === undefined || known && known.spec != plugin) - this.pluginMap.set(plugin, known = this.plugins.find(p => p.spec == plugin) || null); - return known && known.update(this).value; - } - /** - The top position of the document, in screen coordinates. This - may be negative when the editor is scrolled down. Points - directly to the top of the first line, not above the padding. - */ - get documentTop() { - return this.contentDOM.getBoundingClientRect().top + this.viewState.paddingTop; - } - /** - Reports the padding above and below the document. - */ - get documentPadding() { - return { top: this.viewState.paddingTop, bottom: this.viewState.paddingBottom }; - } - /** - Find the line or block widget at the given vertical position. - - By default, this position is interpreted as a screen position, - meaning `docTop` is set to the DOM top position of the editor - content (forcing a layout). You can pass a different `docTop` - value—for example 0 to interpret `height` as a document-relative - position, or a precomputed document top - (`view.contentDOM.getBoundingClientRect().top`) to limit layout - queries. - - *Deprecated: use `elementAtHeight` instead.* - */ - blockAtHeight(height, docTop) { - let top = ensureTop(docTop, this); - return this.elementAtHeight(height - top).moveY(top); - } - /** - Find the text line or block widget at the given vertical - position (which is interpreted as relative to the [top of the - document](https://codemirror.net/6/docs/ref/#view.EditorView.documentTop) - */ - elementAtHeight(height) { - this.readMeasured(); - return this.viewState.elementAtHeight(height); - } - /** - Find information for the visual line (see - [`visualLineAt`](https://codemirror.net/6/docs/ref/#view.EditorView.visualLineAt)) at the given - vertical position. The resulting block info might hold another - array of block info structs in its `type` field if this line - consists of more than one block. - - Defaults to treating `height` as a screen position. See - [`blockAtHeight`](https://codemirror.net/6/docs/ref/#view.EditorView.blockAtHeight) for the - interpretation of the `docTop` parameter. - - *Deprecated: use `lineBlockAtHeight` instead.* - */ - visualLineAtHeight(height, docTop) { - let top = ensureTop(docTop, this); - return this.lineBlockAtHeight(height - top).moveY(top); - } - /** - Find the line block (see - [`lineBlockAt`](https://codemirror.net/6/docs/ref/#view.EditorView.lineBlockAt) at the given - height. - */ - lineBlockAtHeight(height) { - this.readMeasured(); - return this.viewState.lineBlockAtHeight(height); - } - /** - Iterate over the height information of the visual lines in the - viewport. The heights of lines are reported relative to the - given document top, which defaults to the screen position of the - document (forcing a layout). - - *Deprecated: use `viewportLineBlocks` instead.* - */ - viewportLines(f, docTop) { - let top = ensureTop(docTop, this); - for (let line of this.viewportLineBlocks) - f(line.moveY(top)); - } - /** - Get the extent and vertical position of all [line - blocks](https://codemirror.net/6/docs/ref/#view.EditorView.lineBlockAt) in the viewport. Positions - are relative to the [top of the - document](https://codemirror.net/6/docs/ref/#view.EditorView.documentTop); - */ - get viewportLineBlocks() { - return this.viewState.viewportLines; - } - /** - Find the extent and height of the visual line (a range delimited - on both sides by either non-[hidden](https://codemirror.net/6/docs/ref/#view.Decoration^range) - line breaks, or the start/end of the document) at the given position. - - Vertical positions are computed relative to the `docTop` - argument, which defaults to 0 for this method. You can pass - `view.contentDOM.getBoundingClientRect().top` here to get screen - coordinates. - - *Deprecated: use `lineBlockAt` instead.* - */ - visualLineAt(pos, docTop = 0) { - return this.lineBlockAt(pos).moveY(docTop + this.viewState.paddingTop); - } - /** - Find the line block around the given document position. A line - block is a range delimited on both sides by either a - non-[hidden](https://codemirror.net/6/docs/ref/#view.Decoration^range) line breaks, or the - start/end of the document. It will usually just hold a line of - text, but may be broken into multiple textblocks by block - widgets. - */ - lineBlockAt(pos) { - return this.viewState.lineBlockAt(pos); - } - /** - The editor's total content height. - */ - get contentHeight() { - return this.viewState.contentHeight; - } - /** - Move a cursor position by [grapheme - cluster](https://codemirror.net/6/docs/ref/#text.findClusterBreak). `forward` determines whether - the motion is away from the line start, or towards it. Motion in - bidirectional text is in visual order, in the editor's [text - direction](https://codemirror.net/6/docs/ref/#view.EditorView.textDirection). When the start - position was the last one on the line, the returned position - will be across the line break. If there is no further line, the - original position is returned. - - By default, this method moves over a single cluster. The - optional `by` argument can be used to move across more. It will - be called with the first cluster as argument, and should return - a predicate that determines, for each subsequent cluster, - whether it should also be moved over. - */ - moveByChar(start, forward, by) { - return skipAtoms(this, start, moveByChar(this, start, forward, by)); - } - /** - Move a cursor position across the next group of either - [letters](https://codemirror.net/6/docs/ref/#state.EditorState.charCategorizer) or non-letter - non-whitespace characters. - */ - moveByGroup(start, forward) { - return skipAtoms(this, start, moveByChar(this, start, forward, initial => byGroup(this, start.head, initial))); - } - /** - Move to the next line boundary in the given direction. If - `includeWrap` is true, line wrapping is on, and there is a - further wrap point on the current line, the wrap point will be - returned. Otherwise this function will return the start or end - of the line. - */ - moveToLineBoundary(start, forward, includeWrap = true) { - return moveToLineBoundary(this, start, forward, includeWrap); - } - /** - Move a cursor position vertically. When `distance` isn't given, - it defaults to moving to the next line (including wrapped - lines). Otherwise, `distance` should provide a positive distance - in pixels. - - When `start` has a - [`goalColumn`](https://codemirror.net/6/docs/ref/#state.SelectionRange.goalColumn), the vertical - motion will use that as a target horizontal position. Otherwise, - the cursor's own horizontal position is used. The returned - cursor will have its goal column set to whichever column was - used. - */ - moveVertically(start, forward, distance) { - return skipAtoms(this, start, moveVertically(this, start, forward, distance)); - } - // FIXME remove on next major version - scrollPosIntoView(pos) { - this.dispatch({ effects: scrollTo.of(EditorSelection.cursor(pos)) }); - } - /** - Find the DOM parent node and offset (child offset if `node` is - an element, character offset when it is a text node) at the - given document position. - - Note that for positions that aren't currently in - `visibleRanges`, the resulting DOM position isn't necessarily - meaningful (it may just point before or after a placeholder - element). - */ - domAtPos(pos) { - return this.docView.domAtPos(pos); - } - /** - Find the document position at the given DOM node. Can be useful - for associating positions with DOM events. Will raise an error - when `node` isn't part of the editor content. - */ - posAtDOM(node, offset = 0) { - return this.docView.posFromDOM(node, offset); - } - posAtCoords(coords, precise = true) { - this.readMeasured(); - return posAtCoords(this, coords, precise); - } - /** - Get the screen coordinates at the given document position. - `side` determines whether the coordinates are based on the - element before (-1) or after (1) the position (if no element is - available on the given side, the method will transparently use - another strategy to get reasonable coordinates). - */ - coordsAtPos(pos, side = 1) { - this.readMeasured(); - let rect = this.docView.coordsAt(pos, side); - if (!rect || rect.left == rect.right) - return rect; - let line = this.state.doc.lineAt(pos), order = this.bidiSpans(line); - let span = order[BidiSpan.find(order, pos - line.from, -1, side)]; - return flattenRect(rect, (span.dir == Direction.LTR) == (side > 0)); - } - /** - The default width of a character in the editor. May not - accurately reflect the width of all characters (given variable - width fonts or styling of invididual ranges). - */ - get defaultCharacterWidth() { return this.viewState.heightOracle.charWidth; } - /** - The default height of a line in the editor. May not be accurate - for all lines. - */ - get defaultLineHeight() { return this.viewState.heightOracle.lineHeight; } - /** - The text direction - ([`direction`](https://developer.mozilla.org/en-US/docs/Web/CSS/direction) - CSS property) of the editor. - */ - get textDirection() { return this.viewState.heightOracle.direction; } - /** - Whether this editor [wraps lines](https://codemirror.net/6/docs/ref/#view.EditorView.lineWrapping) - (as determined by the - [`white-space`](https://developer.mozilla.org/en-US/docs/Web/CSS/white-space) - CSS property of its content element). - */ - get lineWrapping() { return this.viewState.heightOracle.lineWrapping; } - /** - Returns the bidirectional text structure of the given line - (which should be in the current document) as an array of span - objects. The order of these spans matches the [text - direction](https://codemirror.net/6/docs/ref/#view.EditorView.textDirection)—if that is - left-to-right, the leftmost spans come first, otherwise the - rightmost spans come first. - */ - bidiSpans(line) { - if (line.length > MaxBidiLine) - return trivialOrder(line.length); - let dir = this.textDirection; - for (let entry of this.bidiCache) - if (entry.from == line.from && entry.dir == dir) - return entry.order; - let order = computeOrder(line.text, this.textDirection); - this.bidiCache.push(new CachedOrder(line.from, line.to, dir, order)); - return order; - } - /** - Check whether the editor has focus. - */ - get hasFocus() { - var _a; - // Safari return false for hasFocus when the context menu is open - // or closing, which leads us to ignore selection changes from the - // context menu because it looks like the editor isn't focused. - // This kludges around that. - return (document.hasFocus() || browser.safari && ((_a = this.inputState) === null || _a === void 0 ? void 0 : _a.lastContextMenu) > Date.now() - 3e4) && - this.root.activeElement == this.contentDOM; - } - /** - Put focus on the editor. - */ - focus() { - this.observer.ignore(() => { - focusPreventScroll(this.contentDOM); - this.docView.updateSelection(); - }); - } - /** - Clean up this editor view, removing its element from the - document, unregistering event handlers, and notifying - plugins. The view instance can no longer be used after - calling this. - */ - destroy() { - for (let plugin of this.plugins) - plugin.destroy(this); - this.plugins = []; - this.inputState.destroy(); - this.dom.remove(); - this.observer.destroy(); - if (this.measureScheduled > -1) - cancelAnimationFrame(this.measureScheduled); - this.destroyed = true; - } - /** - Returns an effect that can be - [added](https://codemirror.net/6/docs/ref/#state.TransactionSpec.effects) to a transaction to - cause it to scroll the given position or range into view. - */ - static scrollIntoView(pos, options = {}) { - return scrollIntoView$1.of(new ScrollTarget(typeof pos == "number" ? EditorSelection.cursor(pos) : pos, options.y, options.x, options.yMargin, options.xMargin)); - } - /** - Facet that can be used to add DOM event handlers. The value - should be an object mapping event names to handler functions. The - first such function to return true will be assumed to have handled - that event, and no other handlers or built-in behavior will be - activated for it. - These are registered on the [content - element](https://codemirror.net/6/docs/ref/#view.EditorView.contentDOM), except for `scroll` - handlers, which will be called any time the editor's [scroll - element](https://codemirror.net/6/docs/ref/#view.EditorView.scrollDOM) or one of its parent nodes - is scrolled. - */ - static domEventHandlers(handlers) { - return ViewPlugin.define(() => ({}), { eventHandlers: handlers }); - } - /** - Create a theme extension. The first argument can be a - [`style-mod`](https://github.com/marijnh/style-mod#documentation) - style spec providing the styles for the theme. These will be - prefixed with a generated class for the style. - - Because the selectors will be prefixed with a scope class, rule - that directly match the editor's [wrapper - element](https://codemirror.net/6/docs/ref/#view.EditorView.dom)—to which the scope class will be - added—need to be explicitly differentiated by adding an `&` to - the selector for that element—for example - `&.cm-focused`. - - When `dark` is set to true, the theme will be marked as dark, - which will cause the `&dark` rules from [base - themes](https://codemirror.net/6/docs/ref/#view.EditorView^baseTheme) to be used (as opposed to - `&light` when a light theme is active). - */ - static theme(spec, options) { - let prefix = StyleModule.newName(); - let result = [theme.of(prefix), styleModule.of(buildTheme(`.${prefix}`, spec))]; - if (options && options.dark) - result.push(darkTheme.of(true)); - return result; - } - /** - Create an extension that adds styles to the base theme. Like - with [`theme`](https://codemirror.net/6/docs/ref/#view.EditorView^theme), use `&` to indicate the - place of the editor wrapper element when directly targeting - that. You can also use `&dark` or `&light` instead to only - target editors with a dark or light theme. - */ - static baseTheme(spec) { - return Prec.lowest(styleModule.of(buildTheme("." + baseThemeID, spec, lightDarkIDs))); - } - } - /** - Effect that can be [added](https://codemirror.net/6/docs/ref/#state.TransactionSpec.effects) to a - transaction to make it scroll the given range into view. - - *Deprecated*. Use [`scrollIntoView`](https://codemirror.net/6/docs/ref/#view.EditorView^scrollIntoView) instead. - */ - EditorView.scrollTo = scrollTo; - /** - Effect that makes the editor scroll the given range to the - center of the visible view. - - *Deprecated*. Use [`scrollIntoView`](https://codemirror.net/6/docs/ref/#view.EditorView^scrollIntoView) instead. - */ - EditorView.centerOn = centerOn; - /** - Facet to add a [style - module](https://github.com/marijnh/style-mod#documentation) to - an editor view. The view will ensure that the module is - mounted in its [document - root](https://codemirror.net/6/docs/ref/#view.EditorView.constructor^config.root). - */ - EditorView.styleModule = styleModule; - /** - An input handler can override the way changes to the editable - DOM content are handled. Handlers are passed the document - positions between which the change was found, and the new - content. When one returns true, no further input handlers are - called and the default behavior is prevented. - */ - EditorView.inputHandler = inputHandler$1; - /** - Allows you to provide a function that should be called when the - library catches an exception from an extension (mostly from view - plugins, but may be used by other extensions to route exceptions - from user-code-provided callbacks). This is mostly useful for - debugging and logging. See [`logException`](https://codemirror.net/6/docs/ref/#view.logException). - */ - EditorView.exceptionSink = exceptionSink; - /** - A facet that can be used to register a function to be called - every time the view updates. - */ - EditorView.updateListener = updateListener; - /** - Facet that controls whether the editor content DOM is editable. - When its highest-precedence value is `false`, the element will - not longer have its `contenteditable` attribute set. (Note that - this doesn't affect API calls that change the editor content, - even when those are bound to keys or buttons. See the - [`readOnly`](https://codemirror.net/6/docs/ref/#state.EditorState.readOnly) facet for that.) - */ - EditorView.editable = editable; - /** - Allows you to influence the way mouse selection happens. The - functions in this facet will be called for a `mousedown` event - on the editor, and can return an object that overrides the way a - selection is computed from that mouse click or drag. - */ - EditorView.mouseSelectionStyle = mouseSelectionStyle; - /** - Facet used to configure whether a given selection drag event - should move or copy the selection. The given predicate will be - called with the `mousedown` event, and can return `true` when - the drag should move the content. - */ - EditorView.dragMovesSelection = dragMovesSelection$1; - /** - Facet used to configure whether a given selecting click adds - a new range to the existing selection or replaces it entirely. - */ - EditorView.clickAddsSelectionRange = clickAddsSelectionRange; - /** - A facet that determines which [decorations](https://codemirror.net/6/docs/ref/#view.Decoration) - are shown in the view. See also [view - plugins](https://codemirror.net/6/docs/ref/#view.EditorView^decorations), which have a separate - mechanism for providing decorations. - */ - EditorView.decorations = decorations; - /** - This facet records whether a dark theme is active. The extension - returned by [`theme`](https://codemirror.net/6/docs/ref/#view.EditorView^theme) automatically - includes an instance of this when the `dark` option is set to - true. - */ - EditorView.darkTheme = darkTheme; - /** - Facet that provides additional DOM attributes for the editor's - editable DOM element. - */ - EditorView.contentAttributes = contentAttributes; - /** - Facet that provides DOM attributes for the editor's outer - element. - */ - EditorView.editorAttributes = editorAttributes; - /** - An extension that enables line wrapping in the editor (by - setting CSS `white-space` to `pre-wrap` in the content). - */ - EditorView.lineWrapping = /*@__PURE__*/EditorView.contentAttributes.of({ "class": "cm-lineWrapping" }); - /** - State effect used to include screen reader announcements in a - transaction. These will be added to the DOM in a visually hidden - element with `aria-live="polite"` set, and should be used to - describe effects that are visually obvious but may not be - noticed by screen reader users (such as moving to the next - search match). - */ - EditorView.announce = /*@__PURE__*/StateEffect.define(); - // Maximum line length for which we compute accurate bidi info - const MaxBidiLine = 4096; - // FIXME remove this and its callers on next breaking release - function ensureTop(given, view) { - return (given == null ? view.contentDOM.getBoundingClientRect().top : given) + view.viewState.paddingTop; - } - const BadMeasure = {}; - class CachedOrder { - constructor(from, to, dir, order) { - this.from = from; - this.to = to; - this.dir = dir; - this.order = order; - } - static update(cache, changes) { - if (changes.empty) - return cache; - let result = [], lastDir = cache.length ? cache[cache.length - 1].dir : Direction.LTR; - for (let i = Math.max(0, cache.length - 10); i < cache.length; i++) { - let entry = cache[i]; - if (entry.dir == lastDir && !changes.touchesRange(entry.from, entry.to)) - result.push(new CachedOrder(changes.mapPos(entry.from, 1), changes.mapPos(entry.to, -1), entry.dir, entry.order)); - } - return result; - } - } - function attrsFromFacet(view, facet, base) { - for (let sources = view.state.facet(facet), i = sources.length - 1; i >= 0; i--) { - let source = sources[i], value = typeof source == "function" ? source(view) : source; - if (value) - combineAttrs(value, base); - } - return base; - } - - const currentPlatform = browser.mac ? "mac" : browser.windows ? "win" : browser.linux ? "linux" : "key"; - function normalizeKeyName(name, platform) { - const parts = name.split(/-(?!$)/); - let result = parts[parts.length - 1]; - if (result == "Space") - result = " "; - let alt, ctrl, shift, meta; - for (let i = 0; i < parts.length - 1; ++i) { - const mod = parts[i]; - if (/^(cmd|meta|m)$/i.test(mod)) - meta = 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 if (/^mod$/i.test(mod)) { - if (platform == "mac") - meta = true; - else - ctrl = true; - } - else - throw new Error("Unrecognized modifier name: " + mod); - } - if (alt) - result = "Alt-" + result; - if (ctrl) - result = "Ctrl-" + result; - if (meta) - result = "Meta-" + result; - if (shift) - result = "Shift-" + result; - return result; - } - function modifiers(name, event, shift) { - if (event.altKey) - name = "Alt-" + name; - if (event.ctrlKey) - name = "Ctrl-" + name; - if (event.metaKey) - name = "Meta-" + name; - if (shift !== false && event.shiftKey) - name = "Shift-" + name; - return name; - } - const handleKeyEvents = /*@__PURE__*/EditorView.domEventHandlers({ - keydown(event, view) { - return runHandlers(getKeymap(view.state), event, view, "editor"); - } - }); - /** - Facet used for registering keymaps. - - You can add multiple keymaps to an editor. Their priorities - determine their precedence (the ones specified early or with high - priority get checked first). When a handler has returned `true` - for a given key, no further handlers are called. - */ - const keymap = /*@__PURE__*/Facet.define({ enables: handleKeyEvents }); - const Keymaps = /*@__PURE__*/new WeakMap(); - // This is hidden behind an indirection, rather than directly computed - // by the facet, to keep internal types out of the facet's type. - function getKeymap(state) { - let bindings = state.facet(keymap); - let map = Keymaps.get(bindings); - if (!map) - Keymaps.set(bindings, map = buildKeymap(bindings.reduce((a, b) => a.concat(b), []))); - return map; - } - /** - Run the key handlers registered for a given scope. The event - object should be `"keydown"` event. Returns true if any of the - handlers handled it. - */ - function runScopeHandlers(view, event, scope) { - return runHandlers(getKeymap(view.state), event, view, scope); - } - let storedPrefix = null; - const PrefixTimeout = 4000; - function buildKeymap(bindings, platform = currentPlatform) { - let bound = Object.create(null); - let isPrefix = Object.create(null); - let checkPrefix = (name, is) => { - let current = isPrefix[name]; - if (current == null) - isPrefix[name] = is; - else if (current != is) - throw new Error("Key binding " + name + " is used both as a regular binding and as a multi-stroke prefix"); - }; - let add = (scope, key, command, preventDefault) => { - let scopeObj = bound[scope] || (bound[scope] = Object.create(null)); - let parts = key.split(/ (?!$)/).map(k => normalizeKeyName(k, platform)); - for (let i = 1; i < parts.length; i++) { - let prefix = parts.slice(0, i).join(" "); - checkPrefix(prefix, true); - if (!scopeObj[prefix]) - scopeObj[prefix] = { - preventDefault: true, - commands: [(view) => { - let ourObj = storedPrefix = { view, prefix, scope }; - setTimeout(() => { if (storedPrefix == ourObj) - storedPrefix = null; }, PrefixTimeout); - return true; - }] - }; - } - let full = parts.join(" "); - checkPrefix(full, false); - let binding = scopeObj[full] || (scopeObj[full] = { preventDefault: false, commands: [] }); - binding.commands.push(command); - if (preventDefault) - binding.preventDefault = true; - }; - for (let b of bindings) { - let name = b[platform] || b.key; - if (!name) - continue; - for (let scope of b.scope ? b.scope.split(" ") : ["editor"]) { - add(scope, name, b.run, b.preventDefault); - if (b.shift) - add(scope, "Shift-" + name, b.shift, b.preventDefault); - } - } - return bound; - } - function runHandlers(map, event, view, scope) { - let name = keyName(event), isChar = name.length == 1 && name != " "; - let prefix = "", fallthrough = false; - if (storedPrefix && storedPrefix.view == view && storedPrefix.scope == scope) { - prefix = storedPrefix.prefix + " "; - if (fallthrough = modifierCodes.indexOf(event.keyCode) < 0) - storedPrefix = null; - } - let runFor = (binding) => { - if (binding) { - for (let cmd of binding.commands) - if (cmd(view)) - return true; - if (binding.preventDefault) - fallthrough = true; - } - return false; - }; - let scopeObj = map[scope], baseName; - if (scopeObj) { - if (runFor(scopeObj[prefix + modifiers(name, event, !isChar)])) - return true; - if (isChar && (event.shiftKey || event.altKey || event.metaKey) && - (baseName = base[event.keyCode]) && baseName != name) { - if (runFor(scopeObj[prefix + modifiers(baseName, event, true)])) - return true; - } - else if (isChar && event.shiftKey) { - if (runFor(scopeObj[prefix + modifiers(name, event, true)])) - return true; - } - } - return fallthrough; - } - - const CanHidePrimary = !browser.ios; // FIXME test IE - const selectionConfig = /*@__PURE__*/Facet.define({ - combine(configs) { - return combineConfig(configs, { - cursorBlinkRate: 1200, - drawRangeCursor: true - }, { - cursorBlinkRate: (a, b) => Math.min(a, b), - drawRangeCursor: (a, b) => a || b - }); - } - }); - /** - Returns an extension that hides the browser's native selection and - cursor, replacing the selection with a background behind the text - (with the `cm-selectionBackground` class), and the - cursors with elements overlaid over the code (using - `cm-cursor-primary` and `cm-cursor-secondary`). - - This allows the editor to display secondary selection ranges, and - tends to produce a type of selection more in line with that users - expect in a text editor (the native selection styling will often - leave gaps between lines and won't fill the horizontal space after - a line when the selection continues past it). - - It does have a performance cost, in that it requires an extra DOM - layout cycle for many updates (the selection is drawn based on DOM - layout information that's only available after laying out the - content). - */ - function drawSelection(config = {}) { - return [ - selectionConfig.of(config), - drawSelectionPlugin, - hideNativeSelection - ]; - } - class Piece { - constructor(left, top, width, height, className) { - this.left = left; - this.top = top; - this.width = width; - this.height = height; - this.className = className; - } - draw() { - let elt = document.createElement("div"); - elt.className = this.className; - this.adjust(elt); - return elt; - } - adjust(elt) { - elt.style.left = this.left + "px"; - elt.style.top = this.top + "px"; - if (this.width >= 0) - elt.style.width = this.width + "px"; - elt.style.height = this.height + "px"; - } - eq(p) { - return this.left == p.left && this.top == p.top && this.width == p.width && this.height == p.height && - this.className == p.className; - } - } - const drawSelectionPlugin = /*@__PURE__*/ViewPlugin.fromClass(class { - constructor(view) { - this.view = view; - this.rangePieces = []; - this.cursors = []; - this.measureReq = { read: this.readPos.bind(this), write: this.drawSel.bind(this) }; - this.selectionLayer = view.scrollDOM.appendChild(document.createElement("div")); - this.selectionLayer.className = "cm-selectionLayer"; - this.selectionLayer.setAttribute("aria-hidden", "true"); - this.cursorLayer = view.scrollDOM.appendChild(document.createElement("div")); - this.cursorLayer.className = "cm-cursorLayer"; - this.cursorLayer.setAttribute("aria-hidden", "true"); - view.requestMeasure(this.measureReq); - this.setBlinkRate(); - } - setBlinkRate() { - this.cursorLayer.style.animationDuration = this.view.state.facet(selectionConfig).cursorBlinkRate + "ms"; - } - update(update) { - let confChanged = update.startState.facet(selectionConfig) != update.state.facet(selectionConfig); - if (confChanged || update.selectionSet || update.geometryChanged || update.viewportChanged) - this.view.requestMeasure(this.measureReq); - if (update.transactions.some(tr => tr.scrollIntoView)) - this.cursorLayer.style.animationName = this.cursorLayer.style.animationName == "cm-blink" ? "cm-blink2" : "cm-blink"; - if (confChanged) - this.setBlinkRate(); - } - readPos() { - let { state } = this.view, conf = state.facet(selectionConfig); - let rangePieces = state.selection.ranges.map(r => r.empty ? [] : measureRange(this.view, r)).reduce((a, b) => a.concat(b)); - let cursors = []; - for (let r of state.selection.ranges) { - let prim = r == state.selection.main; - if (r.empty ? !prim || CanHidePrimary : conf.drawRangeCursor) { - let piece = measureCursor(this.view, r, prim); - if (piece) - cursors.push(piece); - } - } - return { rangePieces, cursors }; - } - drawSel({ rangePieces, cursors }) { - if (rangePieces.length != this.rangePieces.length || rangePieces.some((p, i) => !p.eq(this.rangePieces[i]))) { - this.selectionLayer.textContent = ""; - for (let p of rangePieces) - this.selectionLayer.appendChild(p.draw()); - this.rangePieces = rangePieces; - } - if (cursors.length != this.cursors.length || cursors.some((c, i) => !c.eq(this.cursors[i]))) { - let oldCursors = this.cursorLayer.children; - if (oldCursors.length !== cursors.length) { - this.cursorLayer.textContent = ""; - for (const c of cursors) - this.cursorLayer.appendChild(c.draw()); - } - else { - cursors.forEach((c, idx) => c.adjust(oldCursors[idx])); - } - this.cursors = cursors; - } - } - destroy() { - this.selectionLayer.remove(); - this.cursorLayer.remove(); - } - }); - const themeSpec = { - ".cm-line": { - "& ::selection": { backgroundColor: "transparent !important" }, - "&::selection": { backgroundColor: "transparent !important" } - } - }; - if (CanHidePrimary) - themeSpec[".cm-line"].caretColor = "transparent !important"; - const hideNativeSelection = /*@__PURE__*/Prec.highest(/*@__PURE__*/EditorView.theme(themeSpec)); - function getBase(view) { - let rect = view.scrollDOM.getBoundingClientRect(); - let left = view.textDirection == Direction.LTR ? rect.left : rect.right - view.scrollDOM.clientWidth; - return { left: left - view.scrollDOM.scrollLeft, top: rect.top - view.scrollDOM.scrollTop }; - } - function wrappedLine(view, pos, inside) { - let range = EditorSelection.cursor(pos); - return { from: Math.max(inside.from, view.moveToLineBoundary(range, false, true).from), - to: Math.min(inside.to, view.moveToLineBoundary(range, true, true).from), - type: BlockType.Text }; - } - function blockAt(view, pos) { - let line = view.lineBlockAt(pos); - if (Array.isArray(line.type)) - for (let l of line.type) { - if (l.to > pos || l.to == pos && (l.to == line.to || l.type == BlockType.Text)) - return l; - } - return line; - } - function measureRange(view, range) { - if (range.to <= view.viewport.from || range.from >= view.viewport.to) - return []; - let from = Math.max(range.from, view.viewport.from), to = Math.min(range.to, view.viewport.to); - let ltr = view.textDirection == Direction.LTR; - let content = view.contentDOM, contentRect = content.getBoundingClientRect(), base = getBase(view); - let lineStyle = window.getComputedStyle(content.firstChild); - let leftSide = contentRect.left + parseInt(lineStyle.paddingLeft) + Math.min(0, parseInt(lineStyle.textIndent)); - let rightSide = contentRect.right - parseInt(lineStyle.paddingRight); - let startBlock = blockAt(view, from), endBlock = blockAt(view, to); - let visualStart = startBlock.type == BlockType.Text ? startBlock : null; - let visualEnd = endBlock.type == BlockType.Text ? endBlock : null; - if (view.lineWrapping) { - if (visualStart) - visualStart = wrappedLine(view, from, visualStart); - if (visualEnd) - visualEnd = wrappedLine(view, to, visualEnd); - } - if (visualStart && visualEnd && visualStart.from == visualEnd.from) { - return pieces(drawForLine(range.from, range.to, visualStart)); - } - else { - let top = visualStart ? drawForLine(range.from, null, visualStart) : drawForWidget(startBlock, false); - let bottom = visualEnd ? drawForLine(null, range.to, visualEnd) : drawForWidget(endBlock, true); - let between = []; - if ((visualStart || startBlock).to < (visualEnd || endBlock).from - 1) - between.push(piece(leftSide, top.bottom, rightSide, bottom.top)); - else if (top.bottom < bottom.top && view.elementAtHeight((top.bottom + bottom.top) / 2).type == BlockType.Text) - top.bottom = bottom.top = (top.bottom + bottom.top) / 2; - return pieces(top).concat(between).concat(pieces(bottom)); - } - function piece(left, top, right, bottom) { - return new Piece(left - base.left, top - base.top - 0.01 /* Epsilon */, right - left, bottom - top + 0.01 /* Epsilon */, "cm-selectionBackground"); - } - function pieces({ top, bottom, horizontal }) { - let pieces = []; - for (let i = 0; i < horizontal.length; i += 2) - pieces.push(piece(horizontal[i], top, horizontal[i + 1], bottom)); - return pieces; - } - // Gets passed from/to in line-local positions - function drawForLine(from, to, line) { - let top = 1e9, bottom = -1e9, horizontal = []; - function addSpan(from, fromOpen, to, toOpen, dir) { - // Passing 2/-2 is a kludge to force the view to return - // coordinates on the proper side of block widgets, since - // normalizing the side there, though appropriate for most - // coordsAtPos queries, would break selection drawing. - let fromCoords = view.coordsAtPos(from, (from == line.to ? -2 : 2)); - let toCoords = view.coordsAtPos(to, (to == line.from ? 2 : -2)); - top = Math.min(fromCoords.top, toCoords.top, top); - bottom = Math.max(fromCoords.bottom, toCoords.bottom, bottom); - if (dir == Direction.LTR) - horizontal.push(ltr && fromOpen ? leftSide : fromCoords.left, ltr && toOpen ? rightSide : toCoords.right); - else - horizontal.push(!ltr && toOpen ? leftSide : toCoords.left, !ltr && fromOpen ? rightSide : fromCoords.right); - } - let start = from !== null && from !== void 0 ? from : line.from, end = to !== null && to !== void 0 ? to : line.to; - // Split the range by visible range and document line - for (let r of view.visibleRanges) - if (r.to > start && r.from < end) { - for (let pos = Math.max(r.from, start), endPos = Math.min(r.to, end);;) { - let docLine = view.state.doc.lineAt(pos); - for (let span of view.bidiSpans(docLine)) { - let spanFrom = span.from + docLine.from, spanTo = span.to + docLine.from; - if (spanFrom >= endPos) - break; - if (spanTo > pos) - addSpan(Math.max(spanFrom, pos), from == null && spanFrom <= start, Math.min(spanTo, endPos), to == null && spanTo >= end, span.dir); - } - pos = docLine.to + 1; - if (pos >= endPos) - break; - } - } - if (horizontal.length == 0) - addSpan(start, from == null, end, to == null, view.textDirection); - return { top, bottom, horizontal }; - } - function drawForWidget(block, top) { - let y = contentRect.top + (top ? block.top : block.bottom); - return { top: y, bottom: y, horizontal: [] }; - } - } - function measureCursor(view, cursor, primary) { - let pos = view.coordsAtPos(cursor.head, cursor.assoc || 1); - if (!pos) - return null; - let base = getBase(view); - return new Piece(pos.left - base.left, pos.top - base.top, -1, pos.bottom - pos.top, primary ? "cm-cursor cm-cursor-primary" : "cm-cursor cm-cursor-secondary"); - } - - const setDropCursorPos = /*@__PURE__*/StateEffect.define({ - map(pos, mapping) { return pos == null ? null : mapping.mapPos(pos); } - }); - const dropCursorPos = /*@__PURE__*/StateField.define({ - create() { return null; }, - update(pos, tr) { - if (pos != null) - pos = tr.changes.mapPos(pos); - return tr.effects.reduce((pos, e) => e.is(setDropCursorPos) ? e.value : pos, pos); - } - }); - const drawDropCursor = /*@__PURE__*/ViewPlugin.fromClass(class { - constructor(view) { - this.view = view; - this.cursor = null; - this.measureReq = { read: this.readPos.bind(this), write: this.drawCursor.bind(this) }; - } - update(update) { - var _a; - let cursorPos = update.state.field(dropCursorPos); - if (cursorPos == null) { - if (this.cursor != null) { - (_a = this.cursor) === null || _a === void 0 ? void 0 : _a.remove(); - this.cursor = null; - } - } - else { - if (!this.cursor) { - this.cursor = this.view.scrollDOM.appendChild(document.createElement("div")); - this.cursor.className = "cm-dropCursor"; - } - if (update.startState.field(dropCursorPos) != cursorPos || update.docChanged || update.geometryChanged) - this.view.requestMeasure(this.measureReq); - } - } - readPos() { - let pos = this.view.state.field(dropCursorPos); - let rect = pos != null && this.view.coordsAtPos(pos); - if (!rect) - return null; - let outer = this.view.scrollDOM.getBoundingClientRect(); - return { - left: rect.left - outer.left + this.view.scrollDOM.scrollLeft, - top: rect.top - outer.top + this.view.scrollDOM.scrollTop, - height: rect.bottom - rect.top - }; - } - drawCursor(pos) { - if (this.cursor) { - if (pos) { - this.cursor.style.left = pos.left + "px"; - this.cursor.style.top = pos.top + "px"; - this.cursor.style.height = pos.height + "px"; - } - else { - this.cursor.style.left = "-100000px"; - } - } - } - destroy() { - if (this.cursor) - this.cursor.remove(); - } - setDropPos(pos) { - if (this.view.state.field(dropCursorPos) != pos) - this.view.dispatch({ effects: setDropCursorPos.of(pos) }); - } - }, { - eventHandlers: { - dragover(event) { - this.setDropPos(this.view.posAtCoords({ x: event.clientX, y: event.clientY })); - }, - dragleave(event) { - if (event.target == this.view.contentDOM || !this.view.contentDOM.contains(event.relatedTarget)) - this.setDropPos(null); - }, - dragend() { - this.setDropPos(null); - }, - drop() { - this.setDropPos(null); - } - } - }); - /** - Draws a cursor at the current drop position when something is - dragged over the editor. - */ - function dropCursor() { - return [dropCursorPos, drawDropCursor]; - } - - function iterMatches(doc, re, from, to, f) { - re.lastIndex = 0; - for (let cursor = doc.iterRange(from, to), pos = from, m; !cursor.next().done; pos += cursor.value.length) { - if (!cursor.lineBreak) - while (m = re.exec(cursor.value)) - f(pos + m.index, pos + m.index + m[0].length, m); - } - } - function matchRanges(view, maxLength) { - let visible = view.visibleRanges; - if (visible.length == 1 && visible[0].from == view.viewport.from && - visible[0].to == view.viewport.to) - return visible; - let result = []; - for (let { from, to } of visible) { - from = Math.max(view.state.doc.lineAt(from).from, from - maxLength); - to = Math.min(view.state.doc.lineAt(to).to, to + maxLength); - if (result.length && result[result.length - 1].to >= from) - result[result.length - 1].to = to; - else - result.push({ from, to }); - } - return result; - } - /** - Helper class used to make it easier to maintain decorations on - visible code that matches a given regular expression. To be used - in a [view plugin](https://codemirror.net/6/docs/ref/#view.ViewPlugin). Instances of this object - represent a matching configuration. - */ - class MatchDecorator { - /** - Create a decorator. - */ - constructor(config) { - let { regexp, decoration, boundary, maxLength = 1000 } = config; - if (!regexp.global) - throw new RangeError("The regular expression given to MatchDecorator should have its 'g' flag set"); - this.regexp = regexp; - this.getDeco = typeof decoration == "function" ? decoration : () => decoration; - this.boundary = boundary; - this.maxLength = maxLength; - } - /** - Compute the full set of decorations for matches in the given - view's viewport. You'll want to call this when initializing your - plugin. - */ - createDeco(view) { - let build = new RangeSetBuilder(); - for (let { from, to } of matchRanges(view, this.maxLength)) - iterMatches(view.state.doc, this.regexp, from, to, (a, b, m) => build.add(a, b, this.getDeco(m, view, a))); - return build.finish(); - } - /** - Update a set of decorations for a view update. `deco` _must_ be - the set of decorations produced by _this_ `MatchDecorator` for - the view state before the update. - */ - updateDeco(update, deco) { - let changeFrom = 1e9, changeTo = -1; - if (update.docChanged) - update.changes.iterChanges((_f, _t, from, to) => { - if (to > update.view.viewport.from && from < update.view.viewport.to) { - changeFrom = Math.min(from, changeFrom); - changeTo = Math.max(to, changeTo); - } - }); - if (update.viewportChanged || changeTo - changeFrom > 1000) - return this.createDeco(update.view); - if (changeTo > -1) - return this.updateRange(update.view, deco.map(update.changes), changeFrom, changeTo); - return deco; - } - updateRange(view, deco, updateFrom, updateTo) { - for (let r of view.visibleRanges) { - let from = Math.max(r.from, updateFrom), to = Math.min(r.to, updateTo); - if (to > from) { - let fromLine = view.state.doc.lineAt(from), toLine = fromLine.to < to ? view.state.doc.lineAt(to) : fromLine; - let start = Math.max(r.from, fromLine.from), end = Math.min(r.to, toLine.to); - if (this.boundary) { - for (; from > fromLine.from; from--) - if (this.boundary.test(fromLine.text[from - 1 - fromLine.from])) { - start = from; - break; - } - for (; to < toLine.to; to++) - if (this.boundary.test(toLine.text[to - toLine.from])) { - end = to; - break; - } - } - let ranges = [], m; - if (fromLine == toLine) { - this.regexp.lastIndex = start - fromLine.from; - while ((m = this.regexp.exec(fromLine.text)) && m.index < end - fromLine.from) { - let pos = m.index + fromLine.from; - ranges.push(this.getDeco(m, view, pos).range(pos, pos + m[0].length)); - } - } - else { - iterMatches(view.state.doc, this.regexp, start, end, (from, to, m) => ranges.push(this.getDeco(m, view, from).range(from, to))); - } - deco = deco.update({ filterFrom: start, filterTo: end, filter: (from, to) => from < start || to > end, add: ranges }); - } - } - return deco; - } - } - - const UnicodeRegexpSupport = /x/.unicode != null ? "gu" : "g"; - const Specials = /*@__PURE__*/new RegExp("[\u0000-\u0008\u000a-\u001f\u007f-\u009f\u00ad\u061c\u200b\u200e\u200f\u2028\u2029\u202d\u202e\ufeff\ufff9-\ufffc]", UnicodeRegexpSupport); - const Names = { - 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", - 8233: "paragraph separator", - 65279: "zero width no-break space", - 65532: "object replacement" - }; - let _supportsTabSize = null; - function supportsTabSize() { - var _a; - if (_supportsTabSize == null && typeof document != "undefined" && document.body) { - let styles = document.body.style; - _supportsTabSize = ((_a = styles.tabSize) !== null && _a !== void 0 ? _a : styles.MozTabSize) != null; - } - return _supportsTabSize || false; - } - const specialCharConfig = /*@__PURE__*/Facet.define({ - combine(configs) { - let config = combineConfig(configs, { - render: null, - specialChars: Specials, - addSpecialChars: null - }); - if (config.replaceTabs = !supportsTabSize()) - config.specialChars = new RegExp("\t|" + config.specialChars.source, UnicodeRegexpSupport); - if (config.addSpecialChars) - config.specialChars = new RegExp(config.specialChars.source + "|" + config.addSpecialChars.source, UnicodeRegexpSupport); - return config; - } - }); - /** - Returns an extension that installs highlighting of special - characters. - */ - function highlightSpecialChars( - /** - Configuration options. - */ - config = {}) { - return [specialCharConfig.of(config), specialCharPlugin()]; - } - let _plugin = null; - function specialCharPlugin() { - return _plugin || (_plugin = ViewPlugin.fromClass(class { - constructor(view) { - this.view = view; - this.decorations = Decoration.none; - this.decorationCache = Object.create(null); - this.decorator = this.makeDecorator(view.state.facet(specialCharConfig)); - this.decorations = this.decorator.createDeco(view); - } - makeDecorator(conf) { - return new MatchDecorator({ - regexp: conf.specialChars, - decoration: (m, view, pos) => { - let { doc } = view.state; - let code = codePointAt(m[0], 0); - if (code == 9) { - let line = doc.lineAt(pos); - let size = view.state.tabSize, col = countColumn(line.text, size, pos - line.from); - return Decoration.replace({ widget: new TabWidget((size - (col % size)) * this.view.defaultCharacterWidth) }); - } - return this.decorationCache[code] || - (this.decorationCache[code] = Decoration.replace({ widget: new SpecialCharWidget(conf, code) })); - }, - boundary: conf.replaceTabs ? undefined : /[^]/ - }); - } - update(update) { - let conf = update.state.facet(specialCharConfig); - if (update.startState.facet(specialCharConfig) != conf) { - this.decorator = this.makeDecorator(conf); - this.decorations = this.decorator.createDeco(update.view); - } - else { - this.decorations = this.decorator.updateDeco(update, this.decorations); - } - } - }, { - decorations: v => v.decorations - })); - } - const DefaultPlaceholder = "\u2022"; - // Assigns placeholder characters from the Control Pictures block to - // ASCII control characters - function placeholder$1(code) { - if (code >= 32) - return DefaultPlaceholder; - if (code == 10) - return "\u2424"; - return String.fromCharCode(9216 + code); - } - class SpecialCharWidget extends WidgetType { - constructor(options, code) { - super(); - this.options = options; - this.code = code; - } - eq(other) { return other.code == this.code; } - toDOM(view) { - let ph = placeholder$1(this.code); - let desc = view.state.phrase("Control character") + " " + (Names[this.code] || "0x" + this.code.toString(16)); - let custom = this.options.render && this.options.render(this.code, desc, ph); - if (custom) - return custom; - let span = document.createElement("span"); - span.textContent = ph; - span.title = desc; - span.setAttribute("aria-label", desc); - span.className = "cm-specialChar"; - return span; - } - ignoreEvent() { return false; } - } - class TabWidget extends WidgetType { - constructor(width) { - super(); - this.width = width; - } - eq(other) { return other.width == this.width; } - toDOM() { - let span = document.createElement("span"); - span.textContent = "\t"; - span.className = "cm-tab"; - span.style.width = this.width + "px"; - return span; - } - ignoreEvent() { return false; } - } - - /** - Mark lines that have a cursor on them with the `"cm-activeLine"` - DOM class. - */ - function highlightActiveLine() { - return activeLineHighlighter; - } - const lineDeco = /*@__PURE__*/Decoration.line({ class: "cm-activeLine" }); - const activeLineHighlighter = /*@__PURE__*/ViewPlugin.fromClass(class { - constructor(view) { - this.decorations = this.getDeco(view); - } - update(update) { - if (update.docChanged || update.selectionSet) - this.decorations = this.getDeco(update.view); - } - getDeco(view) { - let lastLineStart = -1, deco = []; - for (let r of view.state.selection.ranges) { - if (!r.empty) - return Decoration.none; - let line = view.lineBlockAt(r.head); - if (line.from > lastLineStart) { - deco.push(lineDeco.range(line.from)); - lastLineStart = line.from; - } - } - return Decoration.set(deco); - } - }, { - decorations: v => v.decorations - }); - - const fromHistory = /*@__PURE__*/Annotation.define(); - /** - Transaction annotation that will prevent that transaction from - being combined with other transactions in the undo history. Given - `"before"`, it'll prevent merging with previous transactions. With - `"after"`, subsequent transactions won't be combined with this - one. With `"full"`, the transaction is isolated on both sides. - */ - const isolateHistory = /*@__PURE__*/Annotation.define(); - /** - This facet provides a way to register functions that, given a - transaction, provide a set of effects that the history should - store when inverting the transaction. This can be used to - integrate some kinds of effects in the history, so that they can - be undone (and redone again). - */ - const invertedEffects = /*@__PURE__*/Facet.define(); - const historyConfig = /*@__PURE__*/Facet.define({ - combine(configs) { - return combineConfig(configs, { - minDepth: 100, - newGroupDelay: 500 - }, { minDepth: Math.max, newGroupDelay: Math.min }); - } - }); - function changeEnd(changes) { - let end = 0; - changes.iterChangedRanges((_, to) => end = to); - return end; - } - const historyField_ = /*@__PURE__*/StateField.define({ - create() { - return HistoryState.empty; - }, - update(state, tr) { - let config = tr.state.facet(historyConfig); - let fromHist = tr.annotation(fromHistory); - if (fromHist) { - let selection = tr.docChanged ? EditorSelection.single(changeEnd(tr.changes)) : undefined; - let item = HistEvent.fromTransaction(tr, selection), from = fromHist.side; - let other = from == 0 /* Done */ ? state.undone : state.done; - if (item) - other = updateBranch(other, other.length, config.minDepth, item); - else - other = addSelection(other, tr.startState.selection); - return new HistoryState(from == 0 /* Done */ ? fromHist.rest : other, from == 0 /* Done */ ? other : fromHist.rest); - } - let isolate = tr.annotation(isolateHistory); - if (isolate == "full" || isolate == "before") - state = state.isolate(); - if (tr.annotation(Transaction.addToHistory) === false) - return !tr.changes.empty ? state.addMapping(tr.changes.desc) : state; - let event = HistEvent.fromTransaction(tr); - let time = tr.annotation(Transaction.time), userEvent = tr.annotation(Transaction.userEvent); - if (event) - state = state.addChanges(event, time, userEvent, config.newGroupDelay, config.minDepth); - else if (tr.selection) - state = state.addSelection(tr.startState.selection, time, userEvent, config.newGroupDelay); - if (isolate == "full" || isolate == "after") - state = state.isolate(); - return state; - }, - toJSON(value) { - return { done: value.done.map(e => e.toJSON()), undone: value.undone.map(e => e.toJSON()) }; - }, - fromJSON(json) { - return new HistoryState(json.done.map(HistEvent.fromJSON), json.undone.map(HistEvent.fromJSON)); - } - }); - /** - Create a history extension with the given configuration. - */ - function history(config = {}) { - return [ - historyField_, - historyConfig.of(config), - EditorView.domEventHandlers({ - beforeinput(e, view) { - let command = e.inputType == "historyUndo" ? undo : e.inputType == "historyRedo" ? redo : null; - if (!command) - return false; - e.preventDefault(); - return command(view); - } - }) - ]; - } - function cmd(side, selection) { - return function ({ state, dispatch }) { - if (!selection && state.readOnly) - return false; - let historyState = state.field(historyField_, false); - if (!historyState) - return false; - let tr = historyState.pop(side, state, selection); - if (!tr) - return false; - dispatch(tr); - return true; - }; - } - /** - Undo a single group of history events. Returns false if no group - was available. - */ - const undo = /*@__PURE__*/cmd(0 /* Done */, false); - /** - Redo a group of history events. Returns false if no group was - available. - */ - const redo = /*@__PURE__*/cmd(1 /* Undone */, false); - /** - Undo a selection change. - */ - const undoSelection = /*@__PURE__*/cmd(0 /* Done */, true); - /** - Redo a selection change. - */ - const redoSelection = /*@__PURE__*/cmd(1 /* Undone */, true); - // History events store groups of changes or effects that need to be - // undone/redone together. - class HistEvent { - constructor( - // The changes in this event. Normal events hold at least one - // change or effect. But it may be necessary to store selection - // events before the first change, in which case a special type of - // instance is created which doesn't hold any changes, with - // changes == startSelection == undefined - changes, - // The effects associated with this event - effects, mapped, - // The selection before this event - startSelection, - // Stores selection changes after this event, to be used for - // selection undo/redo. - selectionsAfter) { - this.changes = changes; - this.effects = effects; - this.mapped = mapped; - this.startSelection = startSelection; - this.selectionsAfter = selectionsAfter; - } - setSelAfter(after) { - return new HistEvent(this.changes, this.effects, this.mapped, this.startSelection, after); - } - toJSON() { - var _a, _b, _c; - return { - changes: (_a = this.changes) === null || _a === void 0 ? void 0 : _a.toJSON(), - mapped: (_b = this.mapped) === null || _b === void 0 ? void 0 : _b.toJSON(), - startSelection: (_c = this.startSelection) === null || _c === void 0 ? void 0 : _c.toJSON(), - selectionsAfter: this.selectionsAfter.map(s => s.toJSON()) - }; - } - static fromJSON(json) { - return new HistEvent(json.changes && ChangeSet.fromJSON(json.changes), [], json.mapped && ChangeDesc.fromJSON(json.mapped), json.startSelection && EditorSelection.fromJSON(json.startSelection), json.selectionsAfter.map(EditorSelection.fromJSON)); - } - // This does not check `addToHistory` and such, it assumes the - // transaction needs to be converted to an item. Returns null when - // there are no changes or effects in the transaction. - static fromTransaction(tr, selection) { - let effects = none$1; - for (let invert of tr.startState.facet(invertedEffects)) { - let result = invert(tr); - if (result.length) - effects = effects.concat(result); - } - if (!effects.length && tr.changes.empty) - return null; - return new HistEvent(tr.changes.invert(tr.startState.doc), effects, undefined, selection || tr.startState.selection, none$1); - } - static selection(selections) { - return new HistEvent(undefined, none$1, undefined, undefined, selections); - } - } - function updateBranch(branch, to, maxLen, newEvent) { - let start = to + 1 > maxLen + 20 ? to - maxLen - 1 : 0; - let newBranch = branch.slice(start, to); - newBranch.push(newEvent); - return newBranch; - } - function isAdjacent(a, b) { - let ranges = [], isAdjacent = false; - a.iterChangedRanges((f, t) => ranges.push(f, t)); - b.iterChangedRanges((_f, _t, f, t) => { - for (let i = 0; i < ranges.length;) { - let from = ranges[i++], to = ranges[i++]; - if (t >= from && f <= to) - isAdjacent = true; - } - }); - return isAdjacent; - } - function eqSelectionShape(a, b) { - return a.ranges.length == b.ranges.length && - a.ranges.filter((r, i) => r.empty != b.ranges[i].empty).length === 0; - } - function conc(a, b) { - return !a.length ? b : !b.length ? a : a.concat(b); - } - const none$1 = []; - const MaxSelectionsPerEvent = 200; - function addSelection(branch, selection) { - if (!branch.length) { - return [HistEvent.selection([selection])]; - } - else { - let lastEvent = branch[branch.length - 1]; - let sels = lastEvent.selectionsAfter.slice(Math.max(0, lastEvent.selectionsAfter.length - MaxSelectionsPerEvent)); - if (sels.length && sels[sels.length - 1].eq(selection)) - return branch; - sels.push(selection); - return updateBranch(branch, branch.length - 1, 1e9, lastEvent.setSelAfter(sels)); - } - } - // Assumes the top item has one or more selectionAfter values - function popSelection(branch) { - let last = branch[branch.length - 1]; - let newBranch = branch.slice(); - newBranch[branch.length - 1] = last.setSelAfter(last.selectionsAfter.slice(0, last.selectionsAfter.length - 1)); - return newBranch; - } - // Add a mapping to the top event in the given branch. If this maps - // away all the changes and effects in that item, drop it and - // propagate the mapping to the next item. - function addMappingToBranch(branch, mapping) { - if (!branch.length) - return branch; - let length = branch.length, selections = none$1; - while (length) { - let event = mapEvent(branch[length - 1], mapping, selections); - if (event.changes && !event.changes.empty || event.effects.length) { // Event survived mapping - let result = branch.slice(0, length); - result[length - 1] = event; - return result; - } - else { // Drop this event, since there's no changes or effects left - mapping = event.mapped; - length--; - selections = event.selectionsAfter; - } - } - return selections.length ? [HistEvent.selection(selections)] : none$1; - } - function mapEvent(event, mapping, extraSelections) { - let selections = conc(event.selectionsAfter.length ? event.selectionsAfter.map(s => s.map(mapping)) : none$1, extraSelections); - // Change-less events don't store mappings (they are always the last event in a branch) - if (!event.changes) - return HistEvent.selection(selections); - let mappedChanges = event.changes.map(mapping), before = mapping.mapDesc(event.changes, true); - let fullMapping = event.mapped ? event.mapped.composeDesc(before) : before; - return new HistEvent(mappedChanges, StateEffect.mapEffects(event.effects, mapping), fullMapping, event.startSelection.map(before), selections); - } - const joinableUserEvent = /^(input\.type|delete)($|\.)/; - class HistoryState { - constructor(done, undone, prevTime = 0, prevUserEvent = undefined) { - this.done = done; - this.undone = undone; - this.prevTime = prevTime; - this.prevUserEvent = prevUserEvent; - } - isolate() { - return this.prevTime ? new HistoryState(this.done, this.undone) : this; - } - addChanges(event, time, userEvent, newGroupDelay, maxLen) { - let done = this.done, lastEvent = done[done.length - 1]; - if (lastEvent && lastEvent.changes && !lastEvent.changes.empty && event.changes && - (!userEvent || joinableUserEvent.test(userEvent)) && - ((!lastEvent.selectionsAfter.length && - time - this.prevTime < newGroupDelay && - isAdjacent(lastEvent.changes, event.changes)) || - // For compose (but not compose.start) events, always join with previous event - userEvent == "input.type.compose")) { - done = updateBranch(done, done.length - 1, maxLen, new HistEvent(event.changes.compose(lastEvent.changes), conc(event.effects, lastEvent.effects), lastEvent.mapped, lastEvent.startSelection, none$1)); - } - else { - done = updateBranch(done, done.length, maxLen, event); - } - return new HistoryState(done, none$1, time, userEvent); - } - addSelection(selection, time, userEvent, newGroupDelay) { - let last = this.done.length ? this.done[this.done.length - 1].selectionsAfter : none$1; - if (last.length > 0 && - time - this.prevTime < newGroupDelay && - userEvent == this.prevUserEvent && userEvent && /^select($|\.)/.test(userEvent) && - eqSelectionShape(last[last.length - 1], selection)) - return this; - return new HistoryState(addSelection(this.done, selection), this.undone, time, userEvent); - } - addMapping(mapping) { - return new HistoryState(addMappingToBranch(this.done, mapping), addMappingToBranch(this.undone, mapping), this.prevTime, this.prevUserEvent); - } - pop(side, state, selection) { - let branch = side == 0 /* Done */ ? this.done : this.undone; - if (branch.length == 0) - return null; - let event = branch[branch.length - 1]; - if (selection && event.selectionsAfter.length) { - return state.update({ - selection: event.selectionsAfter[event.selectionsAfter.length - 1], - annotations: fromHistory.of({ side, rest: popSelection(branch) }), - userEvent: side == 0 /* Done */ ? "select.undo" : "select.redo", - scrollIntoView: true - }); - } - else if (!event.changes) { - return null; - } - else { - let rest = branch.length == 1 ? none$1 : branch.slice(0, branch.length - 1); - if (event.mapped) - rest = addMappingToBranch(rest, event.mapped); - return state.update({ - changes: event.changes, - selection: event.startSelection, - effects: event.effects, - annotations: fromHistory.of({ side, rest }), - filter: false, - userEvent: side == 0 /* Done */ ? "undo" : "redo", - scrollIntoView: true - }); - } - } - } - HistoryState.empty = /*@__PURE__*/new HistoryState(none$1, none$1); - /** - Default key bindings for the undo history. - - - Mod-z: [`undo`](https://codemirror.net/6/docs/ref/#history.undo). - - Mod-y (Mod-Shift-z on macOS): [`redo`](https://codemirror.net/6/docs/ref/#history.redo). - - Mod-u: [`undoSelection`](https://codemirror.net/6/docs/ref/#history.undoSelection). - - Alt-u (Mod-Shift-u on macOS): [`redoSelection`](https://codemirror.net/6/docs/ref/#history.redoSelection). - */ - const historyKeymap = [ - { key: "Mod-z", run: undo, preventDefault: true }, - { key: "Mod-y", mac: "Mod-Shift-z", run: redo, preventDefault: true }, - { key: "Mod-u", run: undoSelection, preventDefault: true }, - { key: "Alt-u", mac: "Mod-Shift-u", run: redoSelection, preventDefault: true } - ]; - - // FIXME profile adding a per-Tree TreeNode cache, validating it by - // parent pointer - /// The default maximum length of a `TreeBuffer` node (1024). - const DefaultBufferLength = 1024; - let nextPropID = 0; - class Range { - constructor(from, to) { - this.from = from; - this.to = to; - } - } - /// Each [node type](#common.NodeType) or [individual tree](#common.Tree) - /// can have metadata associated with it in props. Instances of this - /// class represent prop names. - class NodeProp { - /// Create a new node prop type. - constructor(config = {}) { - this.id = nextPropID++; - this.perNode = !!config.perNode; - this.deserialize = config.deserialize || (() => { - throw new Error("This node type doesn't define a deserialize function"); - }); - } - /// This is meant to be used with - /// [`NodeSet.extend`](#common.NodeSet.extend) or - /// [`LRParser.configure`](#lr.ParserConfig.props) to compute - /// prop values for each node type in the set. Takes a [match - /// object](#common.NodeType^match) or function that returns undefined - /// if the node type doesn't get this prop, and the prop's value if - /// it does. - add(match) { - if (this.perNode) - throw new RangeError("Can't add per-node props to node types"); - if (typeof match != "function") - match = NodeType.match(match); - return (type) => { - let result = match(type); - return result === undefined ? null : [this, result]; - }; - } - } - /// Prop that is used to describe matching delimiters. For opening - /// delimiters, this holds an array of node names (written as a - /// space-separated string when declaring this prop in a grammar) - /// for the node types of closing delimiters that match it. - NodeProp.closedBy = new NodeProp({ deserialize: str => str.split(" ") }); - /// The inverse of [`closedBy`](#common.NodeProp^closedBy). This is - /// attached to closing delimiters, holding an array of node names - /// of types of matching opening delimiters. - NodeProp.openedBy = new NodeProp({ deserialize: str => str.split(" ") }); - /// Used to assign node types to groups (for example, all node - /// types that represent an expression could be tagged with an - /// `"Expression"` group). - NodeProp.group = new NodeProp({ deserialize: str => str.split(" ") }); - /// The hash of the [context](#lr.ContextTracker.constructor) - /// that the node was parsed in, if any. Used to limit reuse of - /// contextual nodes. - NodeProp.contextHash = new NodeProp({ perNode: true }); - /// The distance beyond the end of the node that the tokenizer - /// looked ahead for any of the tokens inside the node. (The LR - /// parser only stores this when it is larger than 25, for - /// efficiency reasons.) - NodeProp.lookAhead = new NodeProp({ perNode: true }); - /// This per-node prop is used to replace a given node, or part of a - /// node, with another tree. This is useful to include trees from - /// different languages. - NodeProp.mounted = new NodeProp({ perNode: true }); - const noProps = Object.create(null); - /// Each node in a syntax tree has a node type associated with it. - class NodeType { - /// @internal - constructor( - /// The name of the node type. Not necessarily unique, but if the - /// grammar was written properly, different node types with the - /// same name within a node set should play the same semantic - /// role. - name, - /// @internal - props, - /// The id of this node in its set. Corresponds to the term ids - /// used in the parser. - id, - /// @internal - flags = 0) { - this.name = name; - this.props = props; - this.id = id; - this.flags = flags; - } - static define(spec) { - let props = spec.props && spec.props.length ? Object.create(null) : noProps; - let flags = (spec.top ? 1 /* Top */ : 0) | (spec.skipped ? 2 /* Skipped */ : 0) | - (spec.error ? 4 /* Error */ : 0) | (spec.name == null ? 8 /* Anonymous */ : 0); - let type = new NodeType(spec.name || "", props, spec.id, flags); - if (spec.props) - for (let src of spec.props) { - if (!Array.isArray(src)) - src = src(type); - if (src) { - if (src[0].perNode) - throw new RangeError("Can't store a per-node prop on a node type"); - props[src[0].id] = src[1]; - } - } - return type; - } - /// Retrieves a node prop for this type. Will return `undefined` if - /// the prop isn't present on this node. - prop(prop) { return this.props[prop.id]; } - /// True when this is the top node of a grammar. - get isTop() { return (this.flags & 1 /* Top */) > 0; } - /// True when this node is produced by a skip rule. - get isSkipped() { return (this.flags & 2 /* Skipped */) > 0; } - /// Indicates whether this is an error node. - get isError() { return (this.flags & 4 /* Error */) > 0; } - /// When true, this node type doesn't correspond to a user-declared - /// named node, for example because it is used to cache repetition. - get isAnonymous() { return (this.flags & 8 /* Anonymous */) > 0; } - /// Returns true when this node's name or one of its - /// [groups](#common.NodeProp^group) matches the given string. - is(name) { - if (typeof name == 'string') { - if (this.name == name) - return true; - let group = this.prop(NodeProp.group); - return group ? group.indexOf(name) > -1 : false; - } - return this.id == name; - } - /// Create a function from node types to arbitrary values by - /// specifying an object whose property names are node or - /// [group](#common.NodeProp^group) names. Often useful with - /// [`NodeProp.add`](#common.NodeProp.add). You can put multiple - /// names, separated by spaces, in a single property name to map - /// multiple node names to a single value. - static match(map) { - let direct = Object.create(null); - for (let prop in map) - for (let name of prop.split(" ")) - direct[name] = map[prop]; - return (node) => { - for (let groups = node.prop(NodeProp.group), i = -1; i < (groups ? groups.length : 0); i++) { - let found = direct[i < 0 ? node.name : groups[i]]; - if (found) - return found; - } - }; - } - } - /// An empty dummy node type to use when no actual type is available. - NodeType.none = new NodeType("", Object.create(null), 0, 8 /* Anonymous */); - /// A node set holds a collection of node types. It is used to - /// compactly represent trees by storing their type ids, rather than a - /// full pointer to the type object, in a numeric array. Each parser - /// [has](#lr.LRParser.nodeSet) a node set, and [tree - /// buffers](#common.TreeBuffer) can only store collections of nodes - /// from the same set. A set can have a maximum of 2**16 (65536) node - /// types in it, so that the ids fit into 16-bit typed array slots. - class NodeSet { - /// Create a set with the given types. The `id` property of each - /// type should correspond to its position within the array. - constructor( - /// The node types in this set, by id. - types) { - this.types = types; - for (let i = 0; i < types.length; i++) - if (types[i].id != i) - throw new RangeError("Node type ids should correspond to array positions when creating a node set"); - } - /// Create a copy of this set with some node properties added. The - /// arguments to this method should be created with - /// [`NodeProp.add`](#common.NodeProp.add). - extend(...props) { - let newTypes = []; - for (let type of this.types) { - let newProps = null; - for (let source of props) { - let add = source(type); - if (add) { - if (!newProps) - newProps = Object.assign({}, type.props); - newProps[add[0].id] = add[1]; - } - } - newTypes.push(newProps ? new NodeType(type.name, newProps, type.id, type.flags) : type); - } - return new NodeSet(newTypes); - } - } - const CachedNode = new WeakMap(), CachedInnerNode = new WeakMap(); - /// A piece of syntax tree. There are two ways to approach these - /// trees: the way they are actually stored in memory, and the - /// convenient way. - /// - /// Syntax trees are stored as a tree of `Tree` and `TreeBuffer` - /// objects. By packing detail information into `TreeBuffer` leaf - /// nodes, the representation is made a lot more memory-efficient. - /// - /// However, when you want to actually work with tree nodes, this - /// representation is very awkward, so most client code will want to - /// use the [`TreeCursor`](#common.TreeCursor) or - /// [`SyntaxNode`](#common.SyntaxNode) interface instead, which provides - /// a view on some part of this data structure, and can be used to - /// move around to adjacent nodes. - class Tree { - /// Construct a new tree. See also [`Tree.build`](#common.Tree^build). - constructor( - /// The type of the top node. - type, - /// This node's child nodes. - children, - /// The positions (offsets relative to the start of this tree) of - /// the children. - positions, - /// The total length of this tree - length, - /// Per-node [node props](#common.NodeProp) to associate with this node. - props) { - this.type = type; - this.children = children; - this.positions = positions; - this.length = length; - /// @internal - this.props = null; - if (props && props.length) { - this.props = Object.create(null); - for (let [prop, value] of props) - this.props[typeof prop == "number" ? prop : prop.id] = value; - } - } - /// @internal - toString() { - let mounted = this.prop(NodeProp.mounted); - if (mounted && !mounted.overlay) - return mounted.tree.toString(); - let children = ""; - for (let ch of this.children) { - let str = ch.toString(); - if (str) { - if (children) - children += ","; - children += str; - } - } - return !this.type.name ? children : - (/\W/.test(this.type.name) && !this.type.isError ? JSON.stringify(this.type.name) : this.type.name) + - (children.length ? "(" + children + ")" : ""); - } - /// Get a [tree cursor](#common.TreeCursor) rooted at this tree. When - /// `pos` is given, the cursor is [moved](#common.TreeCursor.moveTo) - /// to the given position and side. - cursor(pos, side = 0) { - let scope = (pos != null && CachedNode.get(this)) || this.topNode; - let cursor = new TreeCursor(scope); - if (pos != null) { - cursor.moveTo(pos, side); - CachedNode.set(this, cursor._tree); - } - return cursor; - } - /// Get a [tree cursor](#common.TreeCursor) that, unlike regular - /// cursors, doesn't skip through - /// [anonymous](#common.NodeType.isAnonymous) nodes and doesn't - /// automatically enter mounted nodes. - fullCursor() { - return new TreeCursor(this.topNode, 1 /* Full */); - } - /// Get a [syntax node](#common.SyntaxNode) object for the top of the - /// tree. - get topNode() { - return new TreeNode(this, 0, 0, null); - } - /// Get the [syntax node](#common.SyntaxNode) at the given position. - /// If `side` is -1, this will move into nodes that end at the - /// position. If 1, it'll move into nodes that start at the - /// position. With 0, it'll only enter nodes that cover the position - /// from both sides. - resolve(pos, side = 0) { - let node = resolveNode(CachedNode.get(this) || this.topNode, pos, side, false); - CachedNode.set(this, node); - return node; - } - /// Like [`resolve`](#common.Tree.resolve), but will enter - /// [overlaid](#common.MountedTree.overlay) nodes, producing a syntax node - /// pointing into the innermost overlaid tree at the given position - /// (with parent links going through all parent structure, including - /// the host trees). - resolveInner(pos, side = 0) { - let node = resolveNode(CachedInnerNode.get(this) || this.topNode, pos, side, true); - CachedInnerNode.set(this, node); - return node; - } - /// Iterate over the tree and its children, calling `enter` for any - /// node that touches the `from`/`to` region (if given) before - /// running over such a node's children, and `leave` (if given) when - /// leaving the node. When `enter` returns `false`, that node will - /// not have its children iterated over (or `leave` called). - iterate(spec) { - let { enter, leave, from = 0, to = this.length } = spec; - for (let c = this.cursor(), get = () => c.node;;) { - let mustLeave = false; - if (c.from <= to && c.to >= from && (c.type.isAnonymous || enter(c.type, c.from, c.to, get) !== false)) { - if (c.firstChild()) - continue; - if (!c.type.isAnonymous) - mustLeave = true; - } - for (;;) { - if (mustLeave && leave) - leave(c.type, c.from, c.to, get); - mustLeave = c.type.isAnonymous; - if (c.nextSibling()) - break; - if (!c.parent()) - return; - mustLeave = true; - } - } - } - /// Get the value of the given [node prop](#common.NodeProp) for this - /// node. Works with both per-node and per-type props. - prop(prop) { - return !prop.perNode ? this.type.prop(prop) : this.props ? this.props[prop.id] : undefined; - } - /// Returns the node's [per-node props](#common.NodeProp.perNode) in a - /// format that can be passed to the [`Tree`](#common.Tree) - /// constructor. - get propValues() { - let result = []; - if (this.props) - for (let id in this.props) - result.push([+id, this.props[id]]); - return result; - } - /// Balance the direct children of this tree, producing a copy of - /// which may have children grouped into subtrees with type - /// [`NodeType.none`](#common.NodeType^none). - balance(config = {}) { - return this.children.length <= 8 /* BranchFactor */ ? this : - balanceRange(NodeType.none, this.children, this.positions, 0, this.children.length, 0, this.length, (children, positions, length) => new Tree(this.type, children, positions, length, this.propValues), config.makeTree || ((children, positions, length) => new Tree(NodeType.none, children, positions, length))); - } - /// Build a tree from a postfix-ordered buffer of node information, - /// or a cursor over such a buffer. - static build(data) { return buildTree(data); } - } - /// The empty tree - Tree.empty = new Tree(NodeType.none, [], [], 0); - class FlatBufferCursor { - constructor(buffer, index) { - this.buffer = buffer; - this.index = index; - } - 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 FlatBufferCursor(this.buffer, this.index); } - } - /// Tree buffers contain (type, start, end, endIndex) quads for each - /// node. In such a buffer, nodes are stored in prefix order (parents - /// before children, with the endIndex of the parent indicating which - /// children belong to it) - class TreeBuffer { - /// Create a tree buffer. - constructor( - /// The buffer's content. - buffer, - /// The total length of the group of nodes in the buffer. - length, - /// The node set used in this buffer. - set) { - this.buffer = buffer; - this.length = length; - this.set = set; - } - /// @internal - get type() { return NodeType.none; } - /// @internal - toString() { - let result = []; - for (let index = 0; index < this.buffer.length;) { - result.push(this.childString(index)); - index = this.buffer[index + 3]; - } - return result.join(","); - } - /// @internal - childString(index) { - let id = this.buffer[index], endIndex = this.buffer[index + 3]; - let type = this.set.types[id], result = type.name; - if (/\W/.test(result) && !type.isError) - result = JSON.stringify(result); - index += 4; - if (endIndex == index) - return result; - let children = []; - while (index < endIndex) { - children.push(this.childString(index)); - index = this.buffer[index + 3]; - } - return result + "(" + children.join(",") + ")"; - } - /// @internal - findChild(startIndex, endIndex, dir, pos, side) { - let { buffer } = this, pick = -1; - for (let i = startIndex; i != endIndex; i = buffer[i + 3]) { - if (checkSide(side, pos, buffer[i + 1], buffer[i + 2])) { - pick = i; - if (dir > 0) - break; - } - } - return pick; - } - /// @internal - slice(startI, endI, from, to) { - let b = this.buffer; - let copy = new Uint16Array(endI - startI); - for (let i = startI, j = 0; i < endI;) { - copy[j++] = b[i++]; - copy[j++] = b[i++] - from; - copy[j++] = b[i++] - from; - copy[j++] = b[i++] - startI; - } - return new TreeBuffer(copy, to - from, this.set); - } - } - function checkSide(side, pos, from, to) { - switch (side) { - case -2 /* Before */: return from < pos; - case -1 /* AtOrBefore */: return to >= pos && from < pos; - case 0 /* Around */: return from < pos && to > pos; - case 1 /* AtOrAfter */: return from <= pos && to > pos; - case 2 /* After */: return to > pos; - case 4 /* DontCare */: return true; - } - } - function enterUnfinishedNodesBefore(node, pos) { - let scan = node.childBefore(pos); - while (scan) { - let last = scan.lastChild; - if (!last || last.to != scan.to) - break; - if (last.type.isError && last.from == last.to) { - node = scan; - scan = last.prevSibling; - } - else { - scan = last; - } - } - return node; - } - function resolveNode(node, pos, side, overlays) { - var _a; - // Move up to a node that actually holds the position, if possible - while (node.from == node.to || - (side < 1 ? node.from >= pos : node.from > pos) || - (side > -1 ? node.to <= pos : node.to < pos)) { - let parent = !overlays && node instanceof TreeNode && node.index < 0 ? null : node.parent; - if (!parent) - return node; - node = parent; - } - // Must go up out of overlays when those do not overlap with pos - if (overlays) - for (let scan = node, parent = scan.parent; parent; scan = parent, parent = scan.parent) { - if (scan instanceof TreeNode && scan.index < 0 && ((_a = parent.enter(pos, side, true)) === null || _a === void 0 ? void 0 : _a.from) != scan.from) - node = parent; - } - for (;;) { - let inner = node.enter(pos, side, overlays); - if (!inner) - return node; - node = inner; - } - } - class TreeNode { - constructor(node, _from, - // Index in parent node, set to -1 if the node is not a direct child of _parent.node (overlay) - index, _parent) { - this.node = node; - this._from = _from; - this.index = index; - this._parent = _parent; - } - get type() { return this.node.type; } - get name() { return this.node.type.name; } - get from() { return this._from; } - get to() { return this._from + this.node.length; } - nextChild(i, dir, pos, side, mode = 0) { - for (let parent = this;;) { - for (let { children, positions } = parent.node, e = dir > 0 ? children.length : -1; i != e; i += dir) { - let next = children[i], start = positions[i] + parent._from; - if (!checkSide(side, pos, start, start + next.length)) - continue; - if (next instanceof TreeBuffer) { - if (mode & 2 /* NoEnterBuffer */) - continue; - let index = next.findChild(0, next.buffer.length, dir, pos - start, side); - if (index > -1) - return new BufferNode(new BufferContext(parent, next, i, start), null, index); - } - else if ((mode & 1 /* Full */) || (!next.type.isAnonymous || hasChild(next))) { - let mounted; - if (!(mode & 1 /* Full */) && next.props && (mounted = next.prop(NodeProp.mounted)) && !mounted.overlay) - return new TreeNode(mounted.tree, start, i, parent); - let inner = new TreeNode(next, start, i, parent); - return (mode & 1 /* Full */) || !inner.type.isAnonymous ? inner - : inner.nextChild(dir < 0 ? next.children.length - 1 : 0, dir, pos, side); - } - } - if ((mode & 1 /* Full */) || !parent.type.isAnonymous) - return null; - if (parent.index >= 0) - i = parent.index + dir; - else - i = dir < 0 ? -1 : parent._parent.node.children.length; - parent = parent._parent; - if (!parent) - return null; - } - } - get firstChild() { return this.nextChild(0, 1, 0, 4 /* DontCare */); } - get lastChild() { return this.nextChild(this.node.children.length - 1, -1, 0, 4 /* DontCare */); } - childAfter(pos) { return this.nextChild(0, 1, pos, 2 /* After */); } - childBefore(pos) { return this.nextChild(this.node.children.length - 1, -1, pos, -2 /* Before */); } - enter(pos, side, overlays = true, buffers = true) { - let mounted; - if (overlays && (mounted = this.node.prop(NodeProp.mounted)) && mounted.overlay) { - let rPos = pos - this.from; - for (let { from, to } of mounted.overlay) { - if ((side > 0 ? from <= rPos : from < rPos) && - (side < 0 ? to >= rPos : to > rPos)) - return new TreeNode(mounted.tree, mounted.overlay[0].from + this.from, -1, this); - } - } - return this.nextChild(0, 1, pos, side, buffers ? 0 : 2 /* NoEnterBuffer */); - } - nextSignificantParent() { - let val = this; - while (val.type.isAnonymous && val._parent) - val = val._parent; - return val; - } - 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 /* DontCare */) : null; - } - get prevSibling() { - return this._parent && this.index >= 0 ? this._parent.nextChild(this.index - 1, -1, 0, 4 /* DontCare */) : null; - } - get cursor() { return new TreeCursor(this); } - get tree() { return this.node; } - toTree() { return this.node; } - resolve(pos, side = 0) { - return resolveNode(this, pos, side, false); - } - resolveInner(pos, side = 0) { - return resolveNode(this, pos, side, true); - } - enterUnfinishedNodesBefore(pos) { return enterUnfinishedNodesBefore(this, pos); } - getChild(type, before = null, after = null) { - let r = getChildren(this, type, before, after); - return r.length ? r[0] : null; - } - getChildren(type, before = null, after = null) { - return getChildren(this, type, before, after); - } - /// @internal - toString() { return this.node.toString(); } - } - function getChildren(node, type, before, after) { - let cur = node.cursor, result = []; - if (!cur.firstChild()) - return result; - if (before != null) - while (!cur.type.is(before)) - if (!cur.nextSibling()) - return result; - for (;;) { - if (after != null && cur.type.is(after)) - return result; - if (cur.type.is(type)) - result.push(cur.node); - if (!cur.nextSibling()) - return after == null ? result : []; - } - } - class BufferContext { - constructor(parent, buffer, index, start) { - this.parent = parent; - this.buffer = buffer; - this.index = index; - this.start = start; - } - } - class BufferNode { - constructor(context, _parent, index) { - this.context = context; - this._parent = _parent; - this.index = index; - this.type = context.buffer.set.types[context.buffer.buffer[index]]; - } - 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]; } - child(dir, pos, side) { - let { buffer } = this.context; - let index = buffer.findChild(this.index + 4, buffer.buffer[this.index + 3], dir, pos - this.context.start, side); - return index < 0 ? null : new BufferNode(this.context, this, index); - } - get firstChild() { return this.child(1, 0, 4 /* DontCare */); } - get lastChild() { return this.child(-1, 0, 4 /* DontCare */); } - childAfter(pos) { return this.child(1, pos, 2 /* After */); } - childBefore(pos) { return this.child(-1, pos, -2 /* Before */); } - enter(pos, side, overlays, buffers = true) { - if (!buffers) - return null; - let { buffer } = this.context; - let index = buffer.findChild(this.index + 4, buffer.buffer[this.index + 3], side > 0 ? 1 : -1, pos - this.context.start, side); - return index < 0 ? null : new BufferNode(this.context, this, index); - } - get parent() { - return this._parent || this.context.parent.nextSignificantParent(); - } - externalSibling(dir) { - return this._parent ? null : this.context.parent.nextChild(this.context.index + dir, dir, 0, 4 /* DontCare */); - } - get nextSibling() { - let { buffer } = this.context; - let after = buffer.buffer[this.index + 3]; - if (after < (this._parent ? buffer.buffer[this._parent.index + 3] : buffer.buffer.length)) - return new BufferNode(this.context, this._parent, after); - return this.externalSibling(1); - } - get prevSibling() { - let { buffer } = this.context; - let parentStart = this._parent ? this._parent.index + 4 : 0; - if (this.index == parentStart) - return this.externalSibling(-1); - return new BufferNode(this.context, this._parent, buffer.findChild(parentStart, this.index, -1, 0, 4 /* DontCare */)); - } - get cursor() { return new TreeCursor(this); } - get tree() { return null; } - toTree() { - let children = [], positions = []; - let { buffer } = this.context; - let startI = this.index + 4, endI = buffer.buffer[this.index + 3]; - if (endI > startI) { - let from = buffer.buffer[this.index + 1], to = buffer.buffer[this.index + 2]; - children.push(buffer.slice(startI, endI, from, to)); - positions.push(0); - } - return new Tree(this.type, children, positions, this.to - this.from); - } - resolve(pos, side = 0) { - return resolveNode(this, pos, side, false); - } - resolveInner(pos, side = 0) { - return resolveNode(this, pos, side, true); - } - enterUnfinishedNodesBefore(pos) { return enterUnfinishedNodesBefore(this, pos); } - /// @internal - toString() { return this.context.buffer.childString(this.index); } - getChild(type, before = null, after = null) { - let r = getChildren(this, type, before, after); - return r.length ? r[0] : null; - } - getChildren(type, before = null, after = null) { - return getChildren(this, type, before, after); - } - } - /// A tree cursor object focuses on a given node in a syntax tree, and - /// allows you to move to adjacent nodes. - class TreeCursor { - /// @internal - constructor(node, - /// @internal - mode = 0) { - this.mode = mode; - this.buffer = null; - this.stack = []; - this.index = 0; - this.bufferNode = null; - if (node instanceof TreeNode) { - this.yieldNode(node); - } - else { - this._tree = node.context.parent; - this.buffer = node.context; - for (let n = node._parent; n; n = n._parent) - this.stack.unshift(n.index); - this.bufferNode = node; - this.yieldBuf(node.index); - } - } - /// Shorthand for `.type.name`. - get name() { return this.type.name; } - yieldNode(node) { - if (!node) - return false; - this._tree = node; - this.type = node.type; - this.from = node.from; - this.to = node.to; - return true; - } - yieldBuf(index, type) { - this.index = index; - let { start, buffer } = this.buffer; - this.type = type || buffer.set.types[buffer.buffer[index]]; - this.from = start + buffer.buffer[index + 1]; - this.to = start + buffer.buffer[index + 2]; - return true; - } - yield(node) { - if (!node) - return false; - if (node instanceof TreeNode) { - this.buffer = null; - return this.yieldNode(node); - } - this.buffer = node.context; - return this.yieldBuf(node.index, node.type); - } - /// @internal - toString() { - return this.buffer ? this.buffer.buffer.childString(this.index) : this._tree.toString(); - } - /// @internal - enterChild(dir, pos, side) { - if (!this.buffer) - return this.yield(this._tree.nextChild(dir < 0 ? this._tree.node.children.length - 1 : 0, dir, pos, side, this.mode)); - let { buffer } = this.buffer; - let index = buffer.findChild(this.index + 4, buffer.buffer[this.index + 3], dir, pos - this.buffer.start, side); - if (index < 0) - return false; - this.stack.push(this.index); - return this.yieldBuf(index); - } - /// Move the cursor to this node's first child. When this returns - /// false, the node has no child, and the cursor has not been moved. - firstChild() { return this.enterChild(1, 0, 4 /* DontCare */); } - /// Move the cursor to this node's last child. - lastChild() { return this.enterChild(-1, 0, 4 /* DontCare */); } - /// Move the cursor to the first child that ends after `pos`. - childAfter(pos) { return this.enterChild(1, pos, 2 /* After */); } - /// Move to the last child that starts before `pos`. - childBefore(pos) { return this.enterChild(-1, pos, -2 /* Before */); } - /// Move the cursor to the child around `pos`. If side is -1 the - /// child may end at that position, when 1 it may start there. This - /// will also enter [overlaid](#common.MountedTree.overlay) - /// [mounted](#common.NodeProp^mounted) trees unless `overlays` is - /// set to false. - enter(pos, side, overlays = true, buffers = true) { - if (!this.buffer) - return this.yield(this._tree.enter(pos, side, overlays && !(this.mode & 1 /* Full */), buffers)); - return buffers ? this.enterChild(1, pos, side) : false; - } - /// Move to the node's parent node, if this isn't the top node. - parent() { - if (!this.buffer) - return this.yieldNode((this.mode & 1 /* Full */) ? this._tree._parent : this._tree.parent); - if (this.stack.length) - return this.yieldBuf(this.stack.pop()); - let parent = (this.mode & 1 /* Full */) ? this.buffer.parent : this.buffer.parent.nextSignificantParent(); - this.buffer = null; - return this.yieldNode(parent); - } - /// @internal - sibling(dir) { - if (!this.buffer) - return !this._tree._parent ? false - : this.yield(this._tree.index < 0 ? null - : this._tree._parent.nextChild(this._tree.index + dir, dir, 0, 4 /* DontCare */, this.mode)); - let { buffer } = this.buffer, d = this.stack.length - 1; - if (dir < 0) { - let parentStart = d < 0 ? 0 : this.stack[d] + 4; - if (this.index != parentStart) - return this.yieldBuf(buffer.findChild(parentStart, this.index, -1, 0, 4 /* DontCare */)); - } - else { - let after = buffer.buffer[this.index + 3]; - if (after < (d < 0 ? buffer.buffer.length : buffer.buffer[this.stack[d] + 3])) - return this.yieldBuf(after); - } - return d < 0 ? this.yield(this.buffer.parent.nextChild(this.buffer.index + dir, dir, 0, 4 /* DontCare */, this.mode)) : false; - } - /// Move to this node's next sibling, if any. - nextSibling() { return this.sibling(1); } - /// Move to this node's previous sibling, if any. - prevSibling() { return this.sibling(-1); } - atLastNode(dir) { - let index, parent, { buffer } = this; - if (buffer) { - if (dir > 0) { - if (this.index < buffer.buffer.buffer.length) - return false; - } - else { - for (let i = 0; i < this.index; i++) - if (buffer.buffer.buffer[i + 3] < this.index) - return false; - } - ({ index, parent } = buffer); - } - else { - ({ index, _parent: parent } = this._tree); - } - for (; parent; { index, _parent: parent } = parent) { - if (index > -1) - for (let i = index + dir, e = dir < 0 ? -1 : parent.node.children.length; i != e; i += dir) { - let child = parent.node.children[i]; - if ((this.mode & 1 /* Full */) || child instanceof TreeBuffer || !child.type.isAnonymous || hasChild(child)) - return false; - } - } - return true; - } - move(dir, enter) { - if (enter && this.enterChild(dir, 0, 4 /* DontCare */)) - return true; - for (;;) { - if (this.sibling(dir)) - return true; - if (this.atLastNode(dir) || !this.parent()) - return false; - } - } - /// Move to the next node in a - /// [pre-order](https://en.wikipedia.org/wiki/Tree_traversal#Pre-order_(NLR)) - /// traversal, going from a node to its first child or, if the - /// current node is empty or `enter` is false, its next sibling or - /// the next sibling of the first parent node that has one. - next(enter = true) { return this.move(1, enter); } - /// Move to the next node in a last-to-first pre-order traveral. A - /// node is followed by its last child or, if it has none, its - /// previous sibling or the previous sibling of the first parent - /// node that has one. - prev(enter = true) { return this.move(-1, enter); } - /// Move the cursor to the innermost node that covers `pos`. If - /// `side` is -1, it will enter nodes that end at `pos`. If it is 1, - /// it will enter nodes that start at `pos`. - moveTo(pos, side = 0) { - // Move up to a node that actually holds the position, if possible - while (this.from == this.to || - (side < 1 ? this.from >= pos : this.from > pos) || - (side > -1 ? this.to <= pos : this.to < pos)) - if (!this.parent()) - break; - // Then scan down into child nodes as far as possible - while (this.enterChild(1, pos, side)) { } - return this; - } - /// Get a [syntax node](#common.SyntaxNode) at the cursor's current - /// position. - get node() { - if (!this.buffer) - return this._tree; - let cache = this.bufferNode, result = null, depth = 0; - if (cache && cache.context == this.buffer) { - scan: for (let index = this.index, d = this.stack.length; d >= 0;) { - for (let c = cache; c; c = c._parent) - if (c.index == index) { - if (index == this.index) - return c; - result = c; - depth = d + 1; - break scan; - } - index = this.stack[--d]; - } - } - for (let i = depth; i < this.stack.length; i++) - result = new BufferNode(this.buffer, result, this.stack[i]); - return this.bufferNode = new BufferNode(this.buffer, result, this.index); - } - /// Get the [tree](#common.Tree) that represents the current node, if - /// any. Will return null when the node is in a [tree - /// buffer](#common.TreeBuffer). - get tree() { - return this.buffer ? null : this._tree.node; - } - } - function hasChild(tree) { - return tree.children.some(ch => ch instanceof TreeBuffer || !ch.type.isAnonymous || hasChild(ch)); - } - function buildTree(data) { - var _a; - let { buffer, nodeSet, maxBufferLength = DefaultBufferLength, reused = [], minRepeatType = nodeSet.types.length } = data; - let cursor = Array.isArray(buffer) ? new FlatBufferCursor(buffer, buffer.length) : buffer; - let types = nodeSet.types; - let contextHash = 0, lookAhead = 0; - function takeNode(parentStart, minPos, children, positions, inRepeat) { - let { id, start, end, size } = cursor; - let lookAheadAtStart = lookAhead; - while (size < 0) { - cursor.next(); - if (size == -1 /* Reuse */) { - let node = reused[id]; - children.push(node); - positions.push(start - parentStart); - return; - } - else if (size == -3 /* ContextChange */) { // Context change - contextHash = id; - return; - } - else if (size == -4 /* LookAhead */) { - lookAhead = id; - return; - } - else { - throw new RangeError(`Unrecognized record size: ${size}`); - } - } - let type = types[id], node, buffer; - let startPos = start - parentStart; - if (end - start <= maxBufferLength && (buffer = findBufferSize(cursor.pos - minPos, inRepeat))) { - // Small enough for a buffer, and no reused nodes inside - let data = new Uint16Array(buffer.size - buffer.skip); - let endPos = cursor.pos - buffer.size, index = data.length; - while (cursor.pos > endPos) - index = copyToBuffer(buffer.start, data, index); - node = new TreeBuffer(data, end - buffer.start, nodeSet); - startPos = buffer.start - parentStart; - } - else { // Make it a node - let endPos = cursor.pos - size; - cursor.next(); - let localChildren = [], localPositions = []; - let localInRepeat = id >= minRepeatType ? id : -1; - let lastGroup = 0, lastEnd = end; - while (cursor.pos > endPos) { - if (localInRepeat >= 0 && cursor.id == localInRepeat && cursor.size >= 0) { - if (cursor.end <= lastEnd - maxBufferLength) { - makeRepeatLeaf(localChildren, localPositions, start, lastGroup, cursor.end, lastEnd, localInRepeat, lookAheadAtStart); - lastGroup = localChildren.length; - lastEnd = cursor.end; - } - cursor.next(); - } - else { - takeNode(start, endPos, localChildren, localPositions, localInRepeat); - } - } - if (localInRepeat >= 0 && lastGroup > 0 && lastGroup < localChildren.length) - makeRepeatLeaf(localChildren, localPositions, start, lastGroup, start, lastEnd, localInRepeat, lookAheadAtStart); - localChildren.reverse(); - localPositions.reverse(); - if (localInRepeat > -1 && lastGroup > 0) { - let make = makeBalanced(type); - node = balanceRange(type, localChildren, localPositions, 0, localChildren.length, 0, end - start, make, make); - } - else { - node = makeTree(type, localChildren, localPositions, end - start, lookAheadAtStart - end); - } - } - children.push(node); - positions.push(startPos); - } - function makeBalanced(type) { - return (children, positions, length) => { - let lookAhead = 0, lastI = children.length - 1, last, lookAheadProp; - if (lastI >= 0 && (last = children[lastI]) instanceof Tree) { - if (!lastI && last.type == type && last.length == length) - return last; - if (lookAheadProp = last.prop(NodeProp.lookAhead)) - lookAhead = positions[lastI] + last.length + lookAheadProp; - } - return makeTree(type, children, positions, length, lookAhead); - }; - } - function makeRepeatLeaf(children, positions, base, i, from, to, type, lookAhead) { - let localChildren = [], localPositions = []; - while (children.length > i) { - localChildren.push(children.pop()); - localPositions.push(positions.pop() + base - from); - } - children.push(makeTree(nodeSet.types[type], localChildren, localPositions, to - from, lookAhead - to)); - positions.push(from - base); - } - function makeTree(type, children, positions, length, lookAhead = 0, props) { - if (contextHash) { - let pair = [NodeProp.contextHash, contextHash]; - props = props ? [pair].concat(props) : [pair]; - } - if (lookAhead > 25) { - let pair = [NodeProp.lookAhead, lookAhead]; - props = props ? [pair].concat(props) : [pair]; - } - return new Tree(type, children, positions, length, props); - } - function findBufferSize(maxSize, inRepeat) { - // Scan through the buffer to find previous siblings that fit - // together in a TreeBuffer, and don't contain any reused nodes - // (which can't be stored in a buffer). - // If `inRepeat` is > -1, ignore node boundaries of that type for - // nesting, but make sure the end falls either at the start - // (`maxSize`) or before such a node. - let fork = cursor.fork(); - let size = 0, start = 0, skip = 0, minStart = fork.end - maxBufferLength; - let result = { size: 0, start: 0, skip: 0 }; - scan: for (let minPos = fork.pos - maxSize; fork.pos > minPos;) { - let nodeSize = fork.size; - // Pretend nested repeat nodes of the same type don't exist - if (fork.id == inRepeat && nodeSize >= 0) { - // Except that we store the current state as a valid return - // value. - result.size = size; - result.start = start; - result.skip = skip; - skip += 4; - size += 4; - fork.next(); - continue; - } - let startPos = fork.pos - nodeSize; - if (nodeSize < 0 || startPos < minPos || fork.start < minStart) - break; - let localSkipped = fork.id >= minRepeatType ? 4 : 0; - let nodeStart = fork.start; - fork.next(); - while (fork.pos > startPos) { - if (fork.size < 0) { - if (fork.size == -3 /* ContextChange */) - localSkipped += 4; - else - break scan; - } - else if (fork.id >= minRepeatType) { - localSkipped += 4; - } - fork.next(); - } - start = nodeStart; - size += nodeSize; - skip += localSkipped; - } - if (inRepeat < 0 || size == maxSize) { - result.size = size; - result.start = start; - result.skip = skip; - } - return result.size > 4 ? result : undefined; - } - function copyToBuffer(bufferStart, buffer, index) { - let { id, start, end, size } = cursor; - cursor.next(); - if (size >= 0 && id < minRepeatType) { - let startIndex = index; - if (size > 4) { - let endPos = cursor.pos - (size - 4); - while (cursor.pos > endPos) - index = copyToBuffer(bufferStart, buffer, index); - } - buffer[--index] = startIndex; - buffer[--index] = end - bufferStart; - buffer[--index] = start - bufferStart; - buffer[--index] = id; - } - else if (size == -3 /* ContextChange */) { - contextHash = id; - } - else if (size == -4 /* LookAhead */) { - lookAhead = id; - } - return index; - } - let children = [], positions = []; - while (cursor.pos > 0) - takeNode(data.start || 0, data.bufferStart || 0, children, positions, -1); - let length = (_a = data.length) !== null && _a !== void 0 ? _a : (children.length ? positions[0] + children[0].length : 0); - return new Tree(types[data.topID], children.reverse(), positions.reverse(), length); - } - const nodeSizeCache = new WeakMap; - function nodeSize(balanceType, node) { - if (!balanceType.isAnonymous || node instanceof TreeBuffer || node.type != balanceType) - return 1; - let size = nodeSizeCache.get(node); - if (size == null) { - size = 1; - for (let child of node.children) { - if (child.type != balanceType || !(child instanceof Tree)) { - size = 1; - break; - } - size += nodeSize(balanceType, child); - } - nodeSizeCache.set(node, size); - } - return size; - } - function balanceRange( - // The type the balanced tree's inner nodes. - balanceType, - // The direct children and their positions - children, positions, - // The index range in children/positions to use - from, to, - // The start position of the nodes, relative to their parent. - start, - // Length of the outer node - length, - // Function to build the top node of the balanced tree - mkTop, - // Function to build internal nodes for the balanced tree - mkTree) { - let total = 0; - for (let i = from; i < to; i++) - total += nodeSize(balanceType, children[i]); - let maxChild = Math.ceil((total * 1.5) / 8 /* BranchFactor */); - let localChildren = [], localPositions = []; - function divide(children, positions, from, to, offset) { - for (let i = from; i < to;) { - let groupFrom = i, groupStart = positions[i], groupSize = nodeSize(balanceType, children[i]); - i++; - for (; i < to; i++) { - let nextSize = nodeSize(balanceType, children[i]); - if (groupSize + nextSize >= maxChild) - break; - groupSize += nextSize; - } - if (i == groupFrom + 1) { - if (groupSize > maxChild) { - let only = children[groupFrom]; // Only trees can have a size > 1 - divide(only.children, only.positions, 0, only.children.length, positions[groupFrom] + offset); - continue; - } - localChildren.push(children[groupFrom]); - } - else { - let length = positions[i - 1] + children[i - 1].length - groupStart; - localChildren.push(balanceRange(balanceType, children, positions, groupFrom, i, groupStart, length, null, mkTree)); - } - localPositions.push(groupStart + offset - start); - } - } - divide(children, positions, from, to, 0); - return (mkTop || mkTree)(localChildren, localPositions, length); - } - - /// Tree fragments are used during [incremental - /// parsing](#common.Parser.startParse) to track parts of old trees - /// that can be reused in a new parse. An array of fragments is used - /// to track regions of an old tree whose nodes might be reused in new - /// parses. Use the static - /// [`applyChanges`](#common.TreeFragment^applyChanges) method to - /// update fragments for document changes. - class TreeFragment { - /// Construct a tree fragment. - constructor( - /// The start of the unchanged range pointed to by this fragment. - /// This refers to an offset in the _updated_ document (as opposed - /// to the original tree). - from, - /// The end of the unchanged range. - to, - /// The tree that this fragment is based on. - tree, - /// The offset between the fragment's tree and the document that - /// this fragment can be used against. Add this when going from - /// document to tree positions, subtract it to go from tree to - /// document positions. - offset, openStart = false, openEnd = false) { - this.from = from; - this.to = to; - this.tree = tree; - this.offset = offset; - this.open = (openStart ? 1 /* Start */ : 0) | (openEnd ? 2 /* End */ : 0); - } - /// Whether the start of the fragment represents the start of a - /// parse, or the end of a change. (In the second case, it may not - /// be safe to reuse some nodes at the start, depending on the - /// parsing algorithm.) - get openStart() { return (this.open & 1 /* Start */) > 0; } - /// Whether the end of the fragment represents the end of a - /// full-document parse, or the start of a change. - get openEnd() { return (this.open & 2 /* End */) > 0; } - /// Create a set of fragments from a freshly parsed tree, or update - /// an existing set of fragments by replacing the ones that overlap - /// with a tree with content from the new tree. When `partial` is - /// true, the parse is treated as incomplete, and the resulting - /// fragment has [`openEnd`](#common.TreeFragment.openEnd) set to - /// true. - static addTree(tree, fragments = [], partial = false) { - let result = [new TreeFragment(0, tree.length, tree, 0, false, partial)]; - for (let f of fragments) - if (f.to > tree.length) - result.push(f); - return result; - } - /// Apply a set of edits to an array of fragments, removing or - /// splitting fragments as necessary to remove edited ranges, and - /// adjusting offsets for fragments that moved. - static applyChanges(fragments, changes, minGap = 128) { - if (!changes.length) - return fragments; - let result = []; - let fI = 1, nextF = fragments.length ? fragments[0] : null; - for (let cI = 0, pos = 0, off = 0;; cI++) { - let nextC = cI < changes.length ? changes[cI] : null; - let nextPos = nextC ? nextC.fromA : 1e9; - if (nextPos - pos >= minGap) - while (nextF && nextF.from < nextPos) { - let cut = nextF; - if (pos >= cut.from || nextPos <= cut.to || off) { - let fFrom = Math.max(cut.from, pos) - off, fTo = Math.min(cut.to, nextPos) - off; - cut = fFrom >= fTo ? null : new TreeFragment(fFrom, fTo, cut.tree, cut.offset + off, cI > 0, !!nextC); - } - if (cut) - result.push(cut); - if (nextF.to > nextPos) - break; - nextF = fI < fragments.length ? fragments[fI++] : null; - } - if (!nextC) - break; - pos = nextC.toA; - off = nextC.toA - nextC.toB; - } - return result; - } - } - /// A superclass that parsers should extend. - class Parser { - /// Start a parse, returning a [partial parse](#common.PartialParse) - /// object. [`fragments`](#common.TreeFragment) can be passed in to - /// make the parse incremental. - /// - /// By default, the entire input is parsed. You can pass `ranges`, - /// which should be a sorted array of non-empty, non-overlapping - /// ranges, to parse only those ranges. The tree returned in that - /// case will start at `ranges[0].from`. - startParse(input, fragments, ranges) { - if (typeof input == "string") - input = new StringInput(input); - ranges = !ranges ? [new Range(0, input.length)] : ranges.length ? ranges.map(r => new Range(r.from, r.to)) : [new Range(0, 0)]; - return this.createParse(input, fragments || [], ranges); - } - /// Run a full parse, returning the resulting tree. - parse(input, fragments, ranges) { - let parse = this.startParse(input, fragments, ranges); - for (;;) { - let done = parse.advance(); - if (done) - return done; - } - } - } - class StringInput { - constructor(string) { - this.string = string; - } - get length() { return this.string.length; } - chunk(from) { return this.string.slice(from); } - get lineChunks() { return false; } - read(from, to) { return this.string.slice(from, to); } - } - new NodeProp({ perNode: true }); - - var _a; - /** - Node prop stored in a grammar's top syntax node to provide the - facet that stores language data for that language. - */ - const languageDataProp = /*@__PURE__*/new NodeProp(); - /** - Helper function to define a facet (to be added to the top syntax - node(s) for a language via - [`languageDataProp`](https://codemirror.net/6/docs/ref/#language.languageDataProp)), that will be - used to associate language data with the language. You - probably only need this when subclassing - [`Language`](https://codemirror.net/6/docs/ref/#language.Language). - */ - function defineLanguageFacet(baseData) { - return Facet.define({ - combine: baseData ? values => values.concat(baseData) : undefined - }); - } - /** - A language object manages parsing and per-language - [metadata](https://codemirror.net/6/docs/ref/#state.EditorState.languageDataAt). Parse data is - managed as a [Lezer](https://lezer.codemirror.net) tree. You'll - want to subclass this class for custom parsers, or use the - [`LRLanguage`](https://codemirror.net/6/docs/ref/#language.LRLanguage) or - [`StreamLanguage`](https://codemirror.net/6/docs/ref/#stream-parser.StreamLanguage) abstractions for - [Lezer](https://lezer.codemirror.net/) or stream parsers. - */ - class Language { - /** - Construct a language object. You usually don't need to invoke - this directly. But when you do, make sure you use - [`defineLanguageFacet`](https://codemirror.net/6/docs/ref/#language.defineLanguageFacet) to create - the first argument. - */ - constructor( - /** - The [language data](https://codemirror.net/6/docs/ref/#state.EditorState.languageDataAt) data - facet used for this language. - */ - data, parser, - /** - The node type of the top node of trees produced by this parser. - */ - topNode, extraExtensions = []) { - this.data = data; - this.topNode = topNode; - // Kludge to define EditorState.tree as a debugging helper, - // without the EditorState package actually knowing about - // languages and lezer trees. - if (!EditorState.prototype.hasOwnProperty("tree")) - Object.defineProperty(EditorState.prototype, "tree", { get() { return syntaxTree(this); } }); - this.parser = parser; - this.extension = [ - language.of(this), - EditorState.languageData.of((state, pos, side) => state.facet(languageDataFacetAt(state, pos, side))) - ].concat(extraExtensions); - } - /** - Query whether this language is active at the given position. - */ - isActiveAt(state, pos, side = -1) { - return languageDataFacetAt(state, pos, side) == this.data; - } - /** - Find the document regions that were parsed using this language. - The returned regions will _include_ any nested languages rooted - in this language, when those exist. - */ - findRegions(state) { - let lang = state.facet(language); - if ((lang === null || lang === void 0 ? void 0 : lang.data) == this.data) - return [{ from: 0, to: state.doc.length }]; - if (!lang || !lang.allowsNesting) - return []; - let result = []; - let explore = (tree, from) => { - if (tree.prop(languageDataProp) == this.data) { - result.push({ from, to: from + tree.length }); - return; - } - let mount = tree.prop(NodeProp.mounted); - if (mount) { - if (mount.tree.prop(languageDataProp) == this.data) { - if (mount.overlay) - for (let r of mount.overlay) - result.push({ from: r.from + from, to: r.to + from }); - else - result.push({ from: from, to: from + tree.length }); - return; - } - else if (mount.overlay) { - let size = result.length; - explore(mount.tree, mount.overlay[0].from + from); - if (result.length > size) - return; - } - } - for (let i = 0; i < tree.children.length; i++) { - let ch = tree.children[i]; - if (ch instanceof Tree) - explore(ch, tree.positions[i] + from); - } - }; - explore(syntaxTree(state), 0); - return result; - } - /** - Indicates whether this language allows nested languages. The - default implementation returns true. - */ - get allowsNesting() { return true; } - } - /** - @internal - */ - Language.setState = /*@__PURE__*/StateEffect.define(); - function languageDataFacetAt(state, pos, side) { - let topLang = state.facet(language); - if (!topLang) - return null; - let facet = topLang.data; - if (topLang.allowsNesting) { - for (let node = syntaxTree(state).topNode; node; node = node.enter(pos, side, true, false)) - facet = node.type.prop(languageDataProp) || facet; - } - return facet; - } - /** - A subclass of [`Language`](https://codemirror.net/6/docs/ref/#language.Language) for use with Lezer - [LR parsers](https://lezer.codemirror.net/docs/ref#lr.LRParser) - parsers. - */ - class LRLanguage extends Language { - constructor(data, parser) { - super(data, parser, parser.topNode); - this.parser = parser; - } - /** - Define a language from a parser. - */ - static define(spec) { - let data = defineLanguageFacet(spec.languageData); - return new LRLanguage(data, spec.parser.configure({ - props: [languageDataProp.add(type => type.isTop ? data : undefined)] - })); - } - /** - Create a new instance of this language with a reconfigured - version of its parser. - */ - configure(options) { - return new LRLanguage(this.data, this.parser.configure(options)); - } - get allowsNesting() { return this.parser.wrappers.length > 0; } // FIXME - } - /** - Get the syntax tree for a state, which is the current (possibly - incomplete) parse tree of active [language](https://codemirror.net/6/docs/ref/#language.Language), - or the empty tree if there is no language available. - */ - function syntaxTree(state) { - let field = state.field(Language.state, false); - return field ? field.tree : Tree.empty; - } - // Lezer-style Input object for a Text document. - class DocInput { - constructor(doc, length = doc.length) { - this.doc = doc; - this.length = length; - this.cursorPos = 0; - this.string = ""; - this.cursor = doc.iter(); - } - syncTo(pos) { - this.string = this.cursor.next(pos - this.cursorPos).value; - this.cursorPos = pos + this.string.length; - return this.cursorPos - this.string.length; - } - chunk(pos) { - this.syncTo(pos); - return this.string; - } - get lineChunks() { return true; } - read(from, to) { - let stringStart = this.cursorPos - this.string.length; - if (from < stringStart || to >= this.cursorPos) - return this.doc.sliceString(from, to); - else - return this.string.slice(from - stringStart, to - stringStart); - } - } - let currentContext = null; - /** - A parse context provided to parsers working on the editor content. - */ - class ParseContext { - /** - @internal - */ - constructor(parser, - /** - The current editor state. - */ - state, - /** - Tree fragments that can be reused by incremental re-parses. - */ - fragments = [], - /** - @internal - */ - tree, treeLen, - /** - The current editor viewport (or some overapproximation - thereof). Intended to be used for opportunistically avoiding - work (in which case - [`skipUntilInView`](https://codemirror.net/6/docs/ref/#language.ParseContext.skipUntilInView) - should be called to make sure the parser is restarted when the - skipped region becomes visible). - */ - viewport, - /** - @internal - */ - skipped, - /** - This is where skipping parsers can register a promise that, - when resolved, will schedule a new parse. It is cleared when - the parse worker picks up the promise. @internal - */ - scheduleOn) { - this.parser = parser; - this.state = state; - this.fragments = fragments; - this.tree = tree; - this.treeLen = treeLen; - this.viewport = viewport; - this.skipped = skipped; - this.scheduleOn = scheduleOn; - this.parse = null; - /** - @internal - */ - this.tempSkipped = []; - } - startParse() { - return this.parser.startParse(new DocInput(this.state.doc), this.fragments); - } - /** - @internal - */ - work(until, upto) { - if (upto != null && upto >= this.state.doc.length) - upto = undefined; - if (this.tree != Tree.empty && this.isDone(upto !== null && upto !== void 0 ? upto : this.state.doc.length)) { - this.takeTree(); - return true; - } - return this.withContext(() => { - var _a; - if (typeof until == "number") { - let endTime = Date.now() + until; - until = () => Date.now() > endTime; - } - if (!this.parse) - this.parse = this.startParse(); - if (upto != null && (this.parse.stoppedAt == null || this.parse.stoppedAt > upto) && - upto < this.state.doc.length) - this.parse.stopAt(upto); - for (;;) { - let done = this.parse.advance(); - if (done) { - this.fragments = this.withoutTempSkipped(TreeFragment.addTree(done, this.fragments, this.parse.stoppedAt != null)); - this.treeLen = (_a = this.parse.stoppedAt) !== null && _a !== void 0 ? _a : this.state.doc.length; - this.tree = done; - this.parse = null; - if (this.treeLen < (upto !== null && upto !== void 0 ? upto : this.state.doc.length)) - this.parse = this.startParse(); - else - return true; - } - if (until()) - return false; - } - }); - } - /** - @internal - */ - takeTree() { - let pos, tree; - if (this.parse && (pos = this.parse.parsedPos) >= this.treeLen) { - if (this.parse.stoppedAt == null || this.parse.stoppedAt > pos) - this.parse.stopAt(pos); - this.withContext(() => { while (!(tree = this.parse.advance())) { } }); - this.treeLen = pos; - this.tree = tree; - this.fragments = this.withoutTempSkipped(TreeFragment.addTree(this.tree, this.fragments, true)); - this.parse = null; - } - } - withContext(f) { - let prev = currentContext; - currentContext = this; - try { - return f(); - } - finally { - currentContext = prev; - } - } - withoutTempSkipped(fragments) { - for (let r; r = this.tempSkipped.pop();) - fragments = cutFragments(fragments, r.from, r.to); - return fragments; - } - /** - @internal - */ - changes(changes, newState) { - let { fragments, tree, treeLen, viewport, skipped } = this; - this.takeTree(); - if (!changes.empty) { - let ranges = []; - changes.iterChangedRanges((fromA, toA, fromB, toB) => ranges.push({ fromA, toA, fromB, toB })); - fragments = TreeFragment.applyChanges(fragments, ranges); - tree = Tree.empty; - treeLen = 0; - viewport = { from: changes.mapPos(viewport.from, -1), to: changes.mapPos(viewport.to, 1) }; - if (this.skipped.length) { - skipped = []; - for (let r of this.skipped) { - let from = changes.mapPos(r.from, 1), to = changes.mapPos(r.to, -1); - if (from < to) - skipped.push({ from, to }); - } - } - } - return new ParseContext(this.parser, newState, fragments, tree, treeLen, viewport, skipped, this.scheduleOn); - } - /** - @internal - */ - updateViewport(viewport) { - if (this.viewport.from == viewport.from && this.viewport.to == viewport.to) - return false; - this.viewport = viewport; - let startLen = this.skipped.length; - for (let i = 0; i < this.skipped.length; i++) { - let { from, to } = this.skipped[i]; - if (from < viewport.to && to > viewport.from) { - this.fragments = cutFragments(this.fragments, from, to); - this.skipped.splice(i--, 1); - } - } - if (this.skipped.length >= startLen) - return false; - this.reset(); - return true; - } - /** - @internal - */ - reset() { - if (this.parse) { - this.takeTree(); - this.parse = null; - } - } - /** - Notify the parse scheduler that the given region was skipped - because it wasn't in view, and the parse should be restarted - when it comes into view. - */ - skipUntilInView(from, to) { - this.skipped.push({ from, to }); - } - /** - Returns a parser intended to be used as placeholder when - asynchronously loading a nested parser. It'll skip its input and - mark it as not-really-parsed, so that the next update will parse - it again. - - When `until` is given, a reparse will be scheduled when that - promise resolves. - */ - static getSkippingParser(until) { - return new class extends Parser { - createParse(input, fragments, ranges) { - let from = ranges[0].from, to = ranges[ranges.length - 1].to; - let parser = { - parsedPos: from, - advance() { - let cx = currentContext; - if (cx) { - for (let r of ranges) - cx.tempSkipped.push(r); - if (until) - cx.scheduleOn = cx.scheduleOn ? Promise.all([cx.scheduleOn, until]) : until; - } - this.parsedPos = to; - return new Tree(NodeType.none, [], [], to - from); - }, - stoppedAt: null, - stopAt() { } - }; - return parser; - } - }; - } - /** - @internal - */ - isDone(upto) { - upto = Math.min(upto, this.state.doc.length); - let frags = this.fragments; - return this.treeLen >= upto && frags.length && frags[0].from == 0 && frags[0].to >= upto; - } - /** - Get the context for the current parse, or `null` if no editor - parse is in progress. - */ - static get() { return currentContext; } - } - function cutFragments(fragments, from, to) { - return TreeFragment.applyChanges(fragments, [{ fromA: from, toA: to, fromB: from, toB: to }]); - } - class LanguageState { - constructor( - // A mutable parse state that is used to preserve work done during - // the lifetime of a state when moving to the next state. - context) { - this.context = context; - this.tree = context.tree; - } - apply(tr) { - if (!tr.docChanged && this.tree == this.context.tree) - return this; - let newCx = this.context.changes(tr.changes, tr.state); - // If the previous parse wasn't done, go forward only up to its - // end position or the end of the viewport, to avoid slowing down - // state updates with parse work beyond the viewport. - let upto = this.context.treeLen == tr.startState.doc.length ? undefined - : Math.max(tr.changes.mapPos(this.context.treeLen), newCx.viewport.to); - if (!newCx.work(20 /* Apply */, upto)) - newCx.takeTree(); - return new LanguageState(newCx); - } - static init(state) { - let vpTo = Math.min(3000 /* InitViewport */, state.doc.length); - let parseState = new ParseContext(state.facet(language).parser, state, [], Tree.empty, 0, { from: 0, to: vpTo }, [], null); - if (!parseState.work(20 /* Apply */, vpTo)) - parseState.takeTree(); - return new LanguageState(parseState); - } - } - Language.state = /*@__PURE__*/StateField.define({ - create: LanguageState.init, - update(value, tr) { - for (let e of tr.effects) - if (e.is(Language.setState)) - return e.value; - if (tr.startState.facet(language) != tr.state.facet(language)) - return LanguageState.init(tr.state); - return value.apply(tr); - } - }); - let requestIdle = (callback) => { - let timeout = setTimeout(() => callback(), 500 /* MaxPause */); - return () => clearTimeout(timeout); - }; - if (typeof requestIdleCallback != "undefined") - requestIdle = (callback) => { - let idle = -1, timeout = setTimeout(() => { - idle = requestIdleCallback(callback, { timeout: 500 /* MaxPause */ - 100 /* MinPause */ }); - }, 100 /* MinPause */); - return () => idle < 0 ? clearTimeout(timeout) : cancelIdleCallback(idle); - }; - const isInputPending = typeof navigator != "undefined" && ((_a = navigator.scheduling) === null || _a === void 0 ? void 0 : _a.isInputPending) - ? () => navigator.scheduling.isInputPending() : null; - const parseWorker = /*@__PURE__*/ViewPlugin.fromClass(class ParseWorker { - constructor(view) { - this.view = view; - this.working = null; - this.workScheduled = 0; - // End of the current time chunk - this.chunkEnd = -1; - // Milliseconds of budget left for this chunk - this.chunkBudget = -1; - this.work = this.work.bind(this); - this.scheduleWork(); - } - update(update) { - let cx = this.view.state.field(Language.state).context; - if (cx.updateViewport(update.view.viewport) || this.view.viewport.to > cx.treeLen) - this.scheduleWork(); - if (update.docChanged) { - if (this.view.hasFocus) - this.chunkBudget += 50 /* ChangeBonus */; - this.scheduleWork(); - } - this.checkAsyncSchedule(cx); - } - scheduleWork() { - if (this.working) - return; - let { state } = this.view, field = state.field(Language.state); - if (field.tree != field.context.tree || !field.context.isDone(state.doc.length)) - this.working = requestIdle(this.work); - } - work(deadline) { - this.working = null; - let now = Date.now(); - if (this.chunkEnd < now && (this.chunkEnd < 0 || this.view.hasFocus)) { // Start a new chunk - this.chunkEnd = now + 30000 /* ChunkTime */; - this.chunkBudget = 3000 /* ChunkBudget */; - } - if (this.chunkBudget <= 0) - return; // No more budget - let { state, viewport: { to: vpTo } } = this.view, field = state.field(Language.state); - if (field.tree == field.context.tree && field.context.isDone(vpTo + 100000 /* MaxParseAhead */)) - return; - let endTime = Date.now() + Math.min(this.chunkBudget, 100 /* Slice */, deadline && !isInputPending ? Math.max(25 /* MinSlice */, deadline.timeRemaining() - 5) : 1e9); - let viewportFirst = field.context.treeLen < vpTo && state.doc.length > vpTo + 1000; - let done = field.context.work(() => { - return isInputPending && isInputPending() || Date.now() > endTime; - }, vpTo + (viewportFirst ? 0 : 100000 /* MaxParseAhead */)); - this.chunkBudget -= Date.now() - now; - if (done || this.chunkBudget <= 0) { - field.context.takeTree(); - this.view.dispatch({ effects: Language.setState.of(new LanguageState(field.context)) }); - } - if (this.chunkBudget > 0 && !(done && !viewportFirst)) - this.scheduleWork(); - this.checkAsyncSchedule(field.context); - } - checkAsyncSchedule(cx) { - if (cx.scheduleOn) { - this.workScheduled++; - cx.scheduleOn - .then(() => this.scheduleWork()) - .catch(err => logException(this.view.state, err)) - .then(() => this.workScheduled--); - cx.scheduleOn = null; - } - } - destroy() { - if (this.working) - this.working(); - } - isWorking() { - return !!(this.working || this.workScheduled > 0); - } - }, { - eventHandlers: { focus() { this.scheduleWork(); } } - }); - /** - The facet used to associate a language with an editor state. - */ - const language = /*@__PURE__*/Facet.define({ - combine(languages) { return languages.length ? languages[0] : null; }, - enables: [Language.state, parseWorker] - }); - /** - This class bundles a [language object](https://codemirror.net/6/docs/ref/#language.Language) with an - optional set of supporting extensions. Language packages are - encouraged to export a function that optionally takes a - configuration object and returns a `LanguageSupport` instance, as - the main way for client code to use the package. - */ - class LanguageSupport { - /** - Create a support object. - */ - constructor( - /** - The language object. - */ - language, - /** - An optional set of supporting extensions. When nesting a - language in another language, the outer language is encouraged - to include the supporting extensions for its inner languages - in its own set of support extensions. - */ - support = []) { - this.language = language; - this.support = support; - this.extension = [language, support]; - } - } - - /** - Facet that defines a way to provide a function that computes the - appropriate indentation depth at the start of a given line, or - `null` to indicate no appropriate indentation could be determined. - */ - const indentService = /*@__PURE__*/Facet.define(); - /** - Facet for overriding the unit by which indentation happens. - Should be a string consisting either entirely of spaces or - entirely of tabs. When not set, this defaults to 2 spaces. - */ - const indentUnit = /*@__PURE__*/Facet.define({ - combine: values => { - if (!values.length) - return " "; - if (!/^(?: +|\t+)$/.test(values[0])) - throw new Error("Invalid indent unit: " + JSON.stringify(values[0])); - return values[0]; - } - }); - /** - Return the _column width_ of an indent unit in the state. - Determined by the [`indentUnit`](https://codemirror.net/6/docs/ref/#language.indentUnit) - facet, and [`tabSize`](https://codemirror.net/6/docs/ref/#state.EditorState^tabSize) when that - contains tabs. - */ - function getIndentUnit(state) { - let unit = state.facet(indentUnit); - return unit.charCodeAt(0) == 9 ? state.tabSize * unit.length : unit.length; - } - /** - Create an indentation string that covers columns 0 to `cols`. - Will use tabs for as much of the columns as possible when the - [`indentUnit`](https://codemirror.net/6/docs/ref/#language.indentUnit) facet contains - tabs. - */ - function indentString(state, cols) { - let result = "", ts = state.tabSize; - if (state.facet(indentUnit).charCodeAt(0) == 9) - while (cols >= ts) { - result += "\t"; - cols -= ts; - } - for (let i = 0; i < cols; i++) - result += " "; - return result; - } - /** - Get the indentation at the given position. Will first consult any - [indent services](https://codemirror.net/6/docs/ref/#language.indentService) that are registered, - and if none of those return an indentation, this will check the - syntax tree for the [indent node prop](https://codemirror.net/6/docs/ref/#language.indentNodeProp) - and use that if found. Returns a number when an indentation could - be determined, and null otherwise. - */ - function getIndentation(context, pos) { - if (context instanceof EditorState) - context = new IndentContext(context); - for (let service of context.state.facet(indentService)) { - let result = service(context, pos); - if (result != null) - return result; - } - let tree = syntaxTree(context.state); - return tree ? syntaxIndentation(context, tree, pos) : null; - } - /** - Indentation contexts are used when calling [indentation - services](https://codemirror.net/6/docs/ref/#language.indentService). They provide helper utilities - useful in indentation logic, and can selectively override the - indentation reported for some lines. - */ - class IndentContext { - /** - Create an indent context. - */ - constructor( - /** - The editor state. - */ - state, - /** - @internal - */ - options = {}) { - this.state = state; - this.options = options; - this.unit = getIndentUnit(state); - } - /** - Get a description of the line at the given position, taking - [simulated line - breaks](https://codemirror.net/6/docs/ref/#language.IndentContext.constructor^options.simulateBreak) - into account. If there is such a break at `pos`, the `bias` - argument determines whether the part of the line line before or - after the break is used. - */ - lineAt(pos, bias = 1) { - let line = this.state.doc.lineAt(pos); - let { simulateBreak, simulateDoubleBreak } = this.options; - if (simulateBreak != null && simulateBreak >= line.from && simulateBreak <= line.to) { - if (simulateDoubleBreak && simulateBreak == pos) - return { text: "", from: pos }; - else if (bias < 0 ? simulateBreak < pos : simulateBreak <= pos) - return { text: line.text.slice(simulateBreak - line.from), from: simulateBreak }; - else - return { text: line.text.slice(0, simulateBreak - line.from), from: line.from }; - } - return line; - } - /** - Get the text directly after `pos`, either the entire line - or the next 100 characters, whichever is shorter. - */ - textAfterPos(pos, bias = 1) { - if (this.options.simulateDoubleBreak && pos == this.options.simulateBreak) - return ""; - let { text, from } = this.lineAt(pos, bias); - return text.slice(pos - from, Math.min(text.length, pos + 100 - from)); - } - /** - Find the column for the given position. - */ - column(pos, bias = 1) { - let { text, from } = this.lineAt(pos, bias); - let result = this.countColumn(text, pos - from); - let override = this.options.overrideIndentation ? this.options.overrideIndentation(from) : -1; - if (override > -1) - result += override - this.countColumn(text, text.search(/\S|$/)); - return result; - } - /** - Find the column position (taking tabs into account) of the given - position in the given string. - */ - countColumn(line, pos = line.length) { - return countColumn(line, this.state.tabSize, pos); - } - /** - Find the indentation column of the line at the given point. - */ - lineIndent(pos, bias = 1) { - let { text, from } = this.lineAt(pos, bias); - let override = this.options.overrideIndentation; - if (override) { - let overriden = override(from); - if (overriden > -1) - return overriden; - } - return this.countColumn(text, text.search(/\S|$/)); - } - /** - Returns the [simulated line - break](https://codemirror.net/6/docs/ref/#language.IndentContext.constructor^options.simulateBreak) - for this context, if any. - */ - get simulatedBreak() { - return this.options.simulateBreak || null; - } - } - /** - A syntax tree node prop used to associate indentation strategies - with node types. Such a strategy is a function from an indentation - context to a column number or null, where null indicates that no - definitive indentation can be determined. - */ - const indentNodeProp = /*@__PURE__*/new NodeProp(); - // Compute the indentation for a given position from the syntax tree. - function syntaxIndentation(cx, ast, pos) { - return indentFrom(ast.resolveInner(pos).enterUnfinishedNodesBefore(pos), pos, cx); - } - function ignoreClosed(cx) { - return cx.pos == cx.options.simulateBreak && cx.options.simulateDoubleBreak; - } - function indentStrategy(tree) { - let strategy = tree.type.prop(indentNodeProp); - if (strategy) - return strategy; - let first = tree.firstChild, close; - if (first && (close = first.type.prop(NodeProp.closedBy))) { - let last = tree.lastChild, closed = last && close.indexOf(last.name) > -1; - return cx => delimitedStrategy(cx, true, 1, undefined, closed && !ignoreClosed(cx) ? last.from : undefined); - } - return tree.parent == null ? topIndent$1 : null; - } - function indentFrom(node, pos, base) { - for (; node; node = node.parent) { - let strategy = indentStrategy(node); - if (strategy) - return strategy(new TreeIndentContext(base, pos, node)); - } - return null; - } - function topIndent$1() { return 0; } - /** - Objects of this type provide context information and helper - methods to indentation functions. - */ - class TreeIndentContext extends IndentContext { - /** - @internal - */ - constructor(base, - /** - The position at which indentation is being computed. - */ - pos, - /** - The syntax tree node to which the indentation strategy - applies. - */ - node) { - super(base.state, base.options); - this.base = base; - this.pos = pos; - this.node = node; - } - /** - Get the text directly after `this.pos`, either the entire line - or the next 100 characters, whichever is shorter. - */ - get textAfter() { - return this.textAfterPos(this.pos); - } - /** - Get the indentation at the reference line for `this.node`, which - is the line on which it starts, unless there is a node that is - _not_ a parent of this node covering the start of that line. If - so, the line at the start of that node is tried, again skipping - on if it is covered by another such node. - */ - get baseIndent() { - let line = this.state.doc.lineAt(this.node.from); - // Skip line starts that are covered by a sibling (or cousin, etc) - for (;;) { - let atBreak = this.node.resolve(line.from); - while (atBreak.parent && atBreak.parent.from == atBreak.from) - atBreak = atBreak.parent; - if (isParent(atBreak, this.node)) - break; - line = this.state.doc.lineAt(atBreak.from); - } - return this.lineIndent(line.from); - } - /** - Continue looking for indentations in the node's parent nodes, - and return the result of that. - */ - continue() { - let parent = this.node.parent; - return parent ? indentFrom(parent, this.pos, this.base) : 0; - } - } - function isParent(parent, of) { - for (let cur = of; cur; cur = cur.parent) - if (parent == cur) - return true; - return false; - } - // Check whether a delimited node is aligned (meaning there are - // non-skipped nodes on the same line as the opening delimiter). And - // if so, return the opening token. - function bracketedAligned(context) { - let tree = context.node; - let openToken = tree.childAfter(tree.from), last = tree.lastChild; - if (!openToken) - return null; - let sim = context.options.simulateBreak; - let openLine = context.state.doc.lineAt(openToken.from); - let lineEnd = sim == null || sim <= openLine.from ? openLine.to : Math.min(openLine.to, sim); - for (let pos = openToken.to;;) { - let next = tree.childAfter(pos); - if (!next || next == last) - return null; - if (!next.type.isSkipped) - return next.from < lineEnd ? openToken : null; - pos = next.to; - } - } - /** - An indentation strategy for delimited (usually bracketed) nodes. - Will, by default, indent one unit more than the parent's base - indent unless the line starts with a closing token. When `align` - is true and there are non-skipped nodes on the node's opening - line, the content of the node will be aligned with the end of the - opening node, like this: - - foo(bar, - baz) - */ - function delimitedIndent({ closing, align = true, units = 1 }) { - return (context) => delimitedStrategy(context, align, units, closing); - } - function delimitedStrategy(context, align, units, closing, closedAt) { - let after = context.textAfter, space = after.match(/^\s*/)[0].length; - let closed = closing && after.slice(space, space + closing.length) == closing || closedAt == context.pos + space; - let aligned = align ? bracketedAligned(context) : null; - if (aligned) - return closed ? context.column(aligned.from) : context.column(aligned.to); - return context.baseIndent + (closed ? 0 : context.unit * units); - } - const DontIndentBeyond = 200; - /** - Enables reindentation on input. When a language defines an - `indentOnInput` field in its [language - data](https://codemirror.net/6/docs/ref/#state.EditorState.languageDataAt), which must hold a regular - expression, the line at the cursor will be reindented whenever new - text is typed and the input from the start of the line up to the - cursor matches that regexp. - - To avoid unneccesary reindents, it is recommended to start the - regexp with `^` (usually followed by `\s*`), and end it with `$`. - For example, `/^\s*\}$/` will reindent when a closing brace is - added at the start of a line. - */ - function indentOnInput() { - return EditorState.transactionFilter.of(tr => { - if (!tr.docChanged || !tr.isUserEvent("input.type") && !tr.isUserEvent("input.complete")) - return tr; - let rules = tr.startState.languageDataAt("indentOnInput", tr.startState.selection.main.head); - if (!rules.length) - return tr; - let doc = tr.newDoc, { head } = tr.newSelection.main, line = doc.lineAt(head); - if (head > line.from + DontIndentBeyond) - return tr; - let lineStart = doc.sliceString(line.from, head); - if (!rules.some(r => r.test(lineStart))) - return tr; - let { state } = tr, last = -1, changes = []; - for (let { head } of state.selection.ranges) { - let line = state.doc.lineAt(head); - if (line.from == last) - continue; - last = line.from; - let indent = getIndentation(state, line.from); - if (indent == null) - continue; - let cur = /^\s*/.exec(line.text)[0]; - let norm = indentString(state, indent); - if (cur != norm) - changes.push({ from: line.from, to: line.from + cur.length, insert: norm }); - } - return changes.length ? [tr, { changes, sequential: true }] : tr; - }); - } - - /** - A facet that registers a code folding service. When called with - the extent of a line, such a function should return a foldable - range that starts on that line (but continues beyond it), if one - can be found. - */ - const foldService = /*@__PURE__*/Facet.define(); - /** - This node prop is used to associate folding information with - syntax node types. Given a syntax node, it should check whether - that tree is foldable and return the range that can be collapsed - when it is. - */ - const foldNodeProp = /*@__PURE__*/new NodeProp(); - /** - [Fold](https://codemirror.net/6/docs/ref/#language.foldNodeProp) function that folds everything but - the first and the last child of a syntax node. Useful for nodes - that start and end with delimiters. - */ - function foldInside$1(node) { - let first = node.firstChild, last = node.lastChild; - return first && first.to < last.from ? { from: first.to, to: last.type.isError ? node.to : last.from } : null; - } - function syntaxFolding(state, start, end) { - let tree = syntaxTree(state); - if (tree.length == 0) - return null; - let inner = tree.resolveInner(end); - let found = null; - for (let cur = inner; cur; cur = cur.parent) { - if (cur.to <= end || cur.from > end) - continue; - if (found && cur.from < start) - break; - let prop = cur.type.prop(foldNodeProp); - if (prop && (cur.to < tree.length - 50 || tree.length == state.doc.length || !isUnfinished(cur))) { - let value = prop(cur, state); - if (value && value.from <= end && value.from >= start && value.to > end) - found = value; - } - } - return found; - } - function isUnfinished(node) { - let ch = node.lastChild; - return ch && ch.to == node.to && ch.type.isError; - } - /** - Check whether the given line is foldable. First asks any fold - services registered through - [`foldService`](https://codemirror.net/6/docs/ref/#language.foldService), and if none of them return - a result, tries to query the [fold node - prop](https://codemirror.net/6/docs/ref/#language.foldNodeProp) of syntax nodes that cover the end - of the line. - */ - function foldable(state, lineStart, lineEnd) { - for (let service of state.facet(foldService)) { - let result = service(state, lineStart, lineEnd); - if (result) - return result; - } - return syntaxFolding(state, lineStart, lineEnd); - } - - /** - A gutter marker represents a bit of information attached to a line - in a specific gutter. Your own custom markers have to extend this - class. - */ - class GutterMarker extends RangeValue { - /** - @internal - */ - compare(other) { - return this == other || this.constructor == other.constructor && this.eq(other); - } - /** - Compare this marker to another marker of the same type. - */ - eq(other) { return false; } - /** - Called if the marker has a `toDOM` method and its representation - was removed from a gutter. - */ - destroy(dom) { } - } - GutterMarker.prototype.elementClass = ""; - GutterMarker.prototype.toDOM = undefined; - GutterMarker.prototype.mapMode = MapMode.TrackBefore; - GutterMarker.prototype.startSide = GutterMarker.prototype.endSide = -1; - GutterMarker.prototype.point = true; - /** - Facet used to add a class to all gutter elements for a given line. - Markers given to this facet should _only_ define an - [`elementclass`](https://codemirror.net/6/docs/ref/#gutter.GutterMarker.elementClass), not a - [`toDOM`](https://codemirror.net/6/docs/ref/#gutter.GutterMarker.toDOM) (or the marker will appear - in all gutters for the line). - */ - const gutterLineClass = /*@__PURE__*/Facet.define(); - const defaults$1 = { - class: "", - renderEmptyElements: false, - elementStyle: "", - markers: () => RangeSet.empty, - lineMarker: () => null, - lineMarkerChange: null, - initialSpacer: null, - updateSpacer: null, - domEventHandlers: {} - }; - const activeGutters = /*@__PURE__*/Facet.define(); - /** - Define an editor gutter. The order in which the gutters appear is - determined by their extension priority. - */ - function gutter(config) { - return [gutters(), activeGutters.of(Object.assign(Object.assign({}, defaults$1), config))]; - } - const baseTheme$7 = /*@__PURE__*/EditorView.baseTheme({ - ".cm-gutters": { - display: "flex", - height: "100%", - boxSizing: "border-box", - left: 0, - zIndex: 200 - }, - "&light .cm-gutters": { - backgroundColor: "#f5f5f5", - color: "#999", - 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" - } - }); - const unfixGutters = /*@__PURE__*/Facet.define({ - combine: values => values.some(x => x) - }); - /** - The gutter-drawing plugin is automatically enabled when you add a - gutter, but you can use this function to explicitly configure it. - - Unless `fixed` is explicitly set to `false`, the gutters are - fixed, meaning they don't scroll along with the content - horizontally (except on Internet Explorer, which doesn't support - CSS [`position: - sticky`](https://developer.mozilla.org/en-US/docs/Web/CSS/position#sticky)). - */ - function gutters(config) { - let result = [ - gutterView, - baseTheme$7 - ]; - if (config && config.fixed === false) - result.push(unfixGutters.of(true)); - return result; - } - const gutterView = /*@__PURE__*/ViewPlugin.fromClass(class { - constructor(view) { - this.view = view; - this.prevViewport = view.viewport; - this.dom = document.createElement("div"); - this.dom.className = "cm-gutters"; - this.dom.setAttribute("aria-hidden", "true"); - this.dom.style.minHeight = this.view.contentHeight + "px"; - this.gutters = view.state.facet(activeGutters).map(conf => new SingleGutterView(view, conf)); - for (let gutter of this.gutters) - this.dom.appendChild(gutter.dom); - this.fixed = !view.state.facet(unfixGutters); - if (this.fixed) { - // FIXME IE11 fallback, which doesn't support position: sticky, - // by using position: relative + event handlers that realign the - // gutter (or just force fixed=false on IE11?) - this.dom.style.position = "sticky"; - } - this.syncGutters(false); - view.scrollDOM.insertBefore(this.dom, view.contentDOM); - } - update(update) { - if (this.updateGutters(update)) { - // Detach during sync when the viewport changed significantly - // (such as during scrolling), since for large updates that is - // faster. - let vpA = this.prevViewport, vpB = update.view.viewport; - let vpOverlap = Math.min(vpA.to, vpB.to) - Math.max(vpA.from, vpB.from); - this.syncGutters(vpOverlap < (vpB.to - vpB.from) * 0.8); - } - if (update.geometryChanged) - this.dom.style.minHeight = this.view.contentHeight + "px"; - if (this.view.state.facet(unfixGutters) != !this.fixed) { - this.fixed = !this.fixed; - this.dom.style.position = this.fixed ? "sticky" : ""; - } - this.prevViewport = update.view.viewport; - } - syncGutters(detach) { - let after = this.dom.nextSibling; - if (detach) - this.dom.remove(); - let lineClasses = RangeSet.iter(this.view.state.facet(gutterLineClass), this.view.viewport.from); - let classSet = []; - let contexts = this.gutters.map(gutter => new UpdateContext(gutter, this.view.viewport, -this.view.documentPadding.top)); - for (let line of this.view.viewportLineBlocks) { - let text; - if (Array.isArray(line.type)) { - for (let b of line.type) - if (b.type == BlockType.Text) { - text = b; - break; - } - } - else { - text = line.type == BlockType.Text ? line : undefined; - } - if (!text) - continue; - if (classSet.length) - classSet = []; - advanceCursor(lineClasses, classSet, line.from); - for (let cx of contexts) - cx.line(this.view, text, classSet); - } - for (let cx of contexts) - cx.finish(); - if (detach) - this.view.scrollDOM.insertBefore(this.dom, after); - } - updateGutters(update) { - let prev = update.startState.facet(activeGutters), cur = update.state.facet(activeGutters); - let change = update.docChanged || update.heightChanged || update.viewportChanged || - !RangeSet.eq(update.startState.facet(gutterLineClass), update.state.facet(gutterLineClass), update.view.viewport.from, update.view.viewport.to); - if (prev == cur) { - for (let gutter of this.gutters) - if (gutter.update(update)) - change = true; - } - else { - change = true; - let gutters = []; - for (let conf of cur) { - let known = prev.indexOf(conf); - if (known < 0) { - gutters.push(new SingleGutterView(this.view, conf)); - } - else { - this.gutters[known].update(update); - gutters.push(this.gutters[known]); - } - } - for (let g of this.gutters) { - g.dom.remove(); - if (gutters.indexOf(g) < 0) - g.destroy(); - } - for (let g of gutters) - this.dom.appendChild(g.dom); - this.gutters = gutters; - } - return change; - } - destroy() { - for (let view of this.gutters) - view.destroy(); - this.dom.remove(); - } - }, { - provide: /*@__PURE__*/PluginField.scrollMargins.from(value => { - if (value.gutters.length == 0 || !value.fixed) - return null; - return value.view.textDirection == Direction.LTR ? { left: value.dom.offsetWidth } : { right: value.dom.offsetWidth }; - }) - }); - function asArray(val) { return (Array.isArray(val) ? val : [val]); } - function advanceCursor(cursor, collect, pos) { - while (cursor.value && cursor.from <= pos) { - if (cursor.from == pos) - collect.push(cursor.value); - cursor.next(); - } - } - class UpdateContext { - constructor(gutter, viewport, height) { - this.gutter = gutter; - this.height = height; - this.localMarkers = []; - this.i = 0; - this.cursor = RangeSet.iter(gutter.markers, viewport.from); - } - line(view, line, extraMarkers) { - if (this.localMarkers.length) - this.localMarkers = []; - advanceCursor(this.cursor, this.localMarkers, line.from); - let localMarkers = extraMarkers.length ? this.localMarkers.concat(extraMarkers) : this.localMarkers; - let forLine = this.gutter.config.lineMarker(view, line, localMarkers); - if (forLine) - localMarkers.unshift(forLine); - let gutter = this.gutter; - if (localMarkers.length == 0 && !gutter.config.renderEmptyElements) - return; - let above = line.top - this.height; - if (this.i == gutter.elements.length) { - let newElt = new GutterElement(view, line.height, above, localMarkers); - gutter.elements.push(newElt); - gutter.dom.appendChild(newElt.dom); - } - else { - gutter.elements[this.i].update(view, line.height, above, localMarkers); - } - this.height = line.bottom; - this.i++; - } - finish() { - let gutter = this.gutter; - while (gutter.elements.length > this.i) { - let last = gutter.elements.pop(); - gutter.dom.removeChild(last.dom); - last.destroy(); - } - } - } - class SingleGutterView { - constructor(view, config) { - this.view = view; - this.config = config; - this.elements = []; - this.spacer = null; - this.dom = document.createElement("div"); - this.dom.className = "cm-gutter" + (this.config.class ? " " + this.config.class : ""); - for (let prop in config.domEventHandlers) { - this.dom.addEventListener(prop, (event) => { - let line = view.lineBlockAtHeight(event.clientY - view.documentTop); - if (config.domEventHandlers[prop](view, line, event)) - event.preventDefault(); - }); - } - this.markers = asArray(config.markers(view)); - if (config.initialSpacer) { - this.spacer = new GutterElement(view, 0, 0, [config.initialSpacer(view)]); - this.dom.appendChild(this.spacer.dom); - this.spacer.dom.style.cssText += "visibility: hidden; pointer-events: none"; - } - } - update(update) { - let prevMarkers = this.markers; - this.markers = asArray(this.config.markers(update.view)); - if (this.spacer && this.config.updateSpacer) { - let updated = this.config.updateSpacer(this.spacer.markers[0], update); - if (updated != this.spacer.markers[0]) - this.spacer.update(update.view, 0, 0, [updated]); - } - let vp = update.view.viewport; - return !RangeSet.eq(this.markers, prevMarkers, vp.from, vp.to) || - (this.config.lineMarkerChange ? this.config.lineMarkerChange(update) : false); - } - destroy() { - for (let elt of this.elements) - elt.destroy(); - } - } - class GutterElement { - constructor(view, height, above, markers) { - this.height = -1; - this.above = 0; - this.markers = []; - this.dom = document.createElement("div"); - this.update(view, height, above, markers); - } - update(view, height, above, markers) { - if (this.height != height) - this.dom.style.height = (this.height = height) + "px"; - if (this.above != above) - this.dom.style.marginTop = (this.above = above) ? above + "px" : ""; - if (!sameMarkers(this.markers, markers)) - this.setMarkers(view, markers); - } - setMarkers(view, markers) { - let cls = "cm-gutterElement", domPos = this.dom.firstChild; - for (let iNew = 0, iOld = 0;;) { - let skipTo = iOld, marker = iNew < markers.length ? markers[iNew++] : null, matched = false; - if (marker) { - let c = marker.elementClass; - if (c) - cls += " " + c; - for (let i = iOld; i < this.markers.length; i++) - if (this.markers[i].compare(marker)) { - skipTo = i; - matched = true; - break; - } - } - else { - skipTo = this.markers.length; - } - while (iOld < skipTo) { - let next = this.markers[iOld++]; - if (next.toDOM) { - next.destroy(domPos); - let after = domPos.nextSibling; - domPos.remove(); - domPos = after; - } - } - if (!marker) - break; - if (marker.toDOM) { - if (matched) - domPos = domPos.nextSibling; - else - this.dom.insertBefore(marker.toDOM(view), domPos); - } - if (matched) - iOld++; - } - this.dom.className = cls; - this.markers = markers; - } - destroy() { - this.setMarkers(null, []); // First argument not used unless creating markers - } - } - function sameMarkers(a, b) { - if (a.length != b.length) - return false; - for (let i = 0; i < a.length; i++) - if (!a[i].compare(b[i])) - return false; - return true; - } - /** - Facet used to provide markers to the line number gutter. - */ - const lineNumberMarkers = /*@__PURE__*/Facet.define(); - const lineNumberConfig = /*@__PURE__*/Facet.define({ - combine(values) { - return combineConfig(values, { formatNumber: String, domEventHandlers: {} }, { - domEventHandlers(a, b) { - let result = Object.assign({}, a); - for (let event in b) { - let exists = result[event], add = b[event]; - result[event] = exists ? (view, line, event) => exists(view, line, event) || add(view, line, event) : add; - } - return result; - } - }); - } - }); - class NumberMarker extends GutterMarker { - constructor(number) { - super(); - this.number = number; - } - eq(other) { return this.number == other.number; } - toDOM() { return document.createTextNode(this.number); } - } - function formatNumber(view, number) { - return view.state.facet(lineNumberConfig).formatNumber(number, view.state); - } - const lineNumberGutter = /*@__PURE__*/activeGutters.compute([lineNumberConfig], state => ({ - class: "cm-lineNumbers", - renderEmptyElements: false, - markers(view) { return view.state.facet(lineNumberMarkers); }, - lineMarker(view, line, others) { - if (others.some(m => m.toDOM)) - return null; - return new NumberMarker(formatNumber(view, view.state.doc.lineAt(line.from).number)); - }, - lineMarkerChange: update => update.startState.facet(lineNumberConfig) != update.state.facet(lineNumberConfig), - initialSpacer(view) { - return new NumberMarker(formatNumber(view, maxLineNumber(view.state.doc.lines))); - }, - updateSpacer(spacer, update) { - let max = formatNumber(update.view, maxLineNumber(update.view.state.doc.lines)); - return max == spacer.number ? spacer : new NumberMarker(max); - }, - domEventHandlers: state.facet(lineNumberConfig).domEventHandlers - })); - /** - Create a line number gutter extension. - */ - function lineNumbers(config = {}) { - return [ - lineNumberConfig.of(config), - gutters(), - lineNumberGutter - ]; - } - function maxLineNumber(lines) { - let last = 9; - while (last < lines) - last = last * 10 + 9; - return last; - } - const activeLineGutterMarker = /*@__PURE__*/new class extends GutterMarker { - constructor() { - super(...arguments); - this.elementClass = "cm-activeLineGutter"; - } - }; - const activeLineGutterHighlighter = /*@__PURE__*/gutterLineClass.compute(["selection"], state => { - let marks = [], last = -1; - for (let range of state.selection.ranges) - if (range.empty) { - let linePos = state.doc.lineAt(range.head).from; - if (linePos > last) { - last = linePos; - marks.push(activeLineGutterMarker.range(linePos)); - } - } - return RangeSet.of(marks); - }); - /** - Returns an extension that adds a `cm-activeLineGutter` class to - all gutter elements on the [active - line](https://codemirror.net/6/docs/ref/#view.highlightActiveLine). - */ - function highlightActiveLineGutter() { - return activeLineGutterHighlighter; - } - - function mapRange(range, mapping) { - let from = mapping.mapPos(range.from, 1), to = mapping.mapPos(range.to, -1); - return from >= to ? undefined : { from, to }; - } - /** - State effect that can be attached to a transaction to fold the - given range. (You probably only need this in exceptional - circumstances—usually you'll just want to let - [`foldCode`](https://codemirror.net/6/docs/ref/#fold.foldCode) and the [fold - gutter](https://codemirror.net/6/docs/ref/#fold.foldGutter) create the transactions.) - */ - const foldEffect = /*@__PURE__*/StateEffect.define({ map: mapRange }); - /** - State effect that unfolds the given range (if it was folded). - */ - const unfoldEffect = /*@__PURE__*/StateEffect.define({ map: mapRange }); - function selectedLines(view) { - let lines = []; - for (let { head } of view.state.selection.ranges) { - if (lines.some(l => l.from <= head && l.to >= head)) - continue; - lines.push(view.lineBlockAt(head)); - } - return lines; - } - const foldState = /*@__PURE__*/StateField.define({ - create() { - return Decoration.none; - }, - update(folded, tr) { - folded = folded.map(tr.changes); - for (let e of tr.effects) { - if (e.is(foldEffect) && !foldExists(folded, e.value.from, e.value.to)) - folded = folded.update({ add: [foldWidget.range(e.value.from, e.value.to)] }); - else if (e.is(unfoldEffect)) - folded = folded.update({ filter: (from, to) => e.value.from != from || e.value.to != to, - filterFrom: e.value.from, filterTo: e.value.to }); - } - // Clear folded ranges that cover the selection head - if (tr.selection) { - let onSelection = false, { head } = tr.selection.main; - folded.between(head, head, (a, b) => { if (a < head && b > head) - onSelection = true; }); - if (onSelection) - folded = folded.update({ - filterFrom: head, - filterTo: head, - filter: (a, b) => b <= head || a >= head - }); - } - return folded; - }, - provide: f => EditorView.decorations.from(f) - }); - function foldInside(state, from, to) { - var _a; - let found = null; - (_a = state.field(foldState, false)) === null || _a === void 0 ? void 0 : _a.between(from, to, (from, to) => { - if (!found || found.from > from) - found = { from, to }; - }); - return found; - } - function foldExists(folded, from, to) { - let found = false; - folded.between(from, from, (a, b) => { if (a == from && b == to) - found = true; }); - return found; - } - function maybeEnable(state, other) { - return state.field(foldState, false) ? other : other.concat(StateEffect.appendConfig.of(codeFolding())); - } - /** - Fold the lines that are selected, if possible. - */ - const foldCode = view => { - for (let line of selectedLines(view)) { - let range = foldable(view.state, line.from, line.to); - if (range) { - view.dispatch({ effects: maybeEnable(view.state, [foldEffect.of(range), announceFold(view, range)]) }); - return true; - } - } - return false; - }; - /** - Unfold folded ranges on selected lines. - */ - const unfoldCode = view => { - if (!view.state.field(foldState, false)) - return false; - let effects = []; - for (let line of selectedLines(view)) { - let folded = foldInside(view.state, line.from, line.to); - if (folded) - effects.push(unfoldEffect.of(folded), announceFold(view, folded, false)); - } - if (effects.length) - view.dispatch({ effects }); - return effects.length > 0; - }; - function announceFold(view, range, fold = true) { - let lineFrom = view.state.doc.lineAt(range.from).number, lineTo = view.state.doc.lineAt(range.to).number; - return EditorView.announce.of(`${view.state.phrase(fold ? "Folded lines" : "Unfolded lines")} ${lineFrom} ${view.state.phrase("to")} ${lineTo}.`); - } - /** - Fold all top-level foldable ranges. - */ - const foldAll = view => { - let { state } = view, effects = []; - for (let pos = 0; pos < state.doc.length;) { - let line = view.lineBlockAt(pos), range = foldable(state, line.from, line.to); - if (range) - effects.push(foldEffect.of(range)); - pos = (range ? view.lineBlockAt(range.to) : line).to + 1; - } - if (effects.length) - view.dispatch({ effects: maybeEnable(view.state, effects) }); - return !!effects.length; - }; - /** - Unfold all folded code. - */ - const unfoldAll = view => { - let field = view.state.field(foldState, false); - if (!field || !field.size) - return false; - let effects = []; - field.between(0, view.state.doc.length, (from, to) => { effects.push(unfoldEffect.of({ from, to })); }); - view.dispatch({ effects }); - return true; - }; - /** - Default fold-related key bindings. - - - Ctrl-Shift-[ (Cmd-Alt-[ on macOS): [`foldCode`](https://codemirror.net/6/docs/ref/#fold.foldCode). - - Ctrl-Shift-] (Cmd-Alt-] on macOS): [`unfoldCode`](https://codemirror.net/6/docs/ref/#fold.unfoldCode). - - Ctrl-Alt-[: [`foldAll`](https://codemirror.net/6/docs/ref/#fold.foldAll). - - Ctrl-Alt-]: [`unfoldAll`](https://codemirror.net/6/docs/ref/#fold.unfoldAll). - */ - const foldKeymap = [ - { key: "Ctrl-Shift-[", mac: "Cmd-Alt-[", run: foldCode }, - { key: "Ctrl-Shift-]", mac: "Cmd-Alt-]", run: unfoldCode }, - { key: "Ctrl-Alt-[", run: foldAll }, - { key: "Ctrl-Alt-]", run: unfoldAll } - ]; - const defaultConfig = { - placeholderDOM: null, - placeholderText: "…" - }; - const foldConfig = /*@__PURE__*/Facet.define({ - combine(values) { return combineConfig(values, defaultConfig); } - }); - /** - Create an extension that configures code folding. - */ - function codeFolding(config) { - let result = [foldState, baseTheme$6]; - if (config) - result.push(foldConfig.of(config)); - return result; - } - const foldWidget = /*@__PURE__*/Decoration.replace({ widget: /*@__PURE__*/new class extends WidgetType { - toDOM(view) { - let { state } = view, conf = state.facet(foldConfig); - let onclick = (event) => { - let line = view.lineBlockAt(view.posAtDOM(event.target)); - let folded = foldInside(view.state, line.from, line.to); - if (folded) - view.dispatch({ effects: unfoldEffect.of(folded) }); - event.preventDefault(); - }; - if (conf.placeholderDOM) - return conf.placeholderDOM(view, onclick); - let element = document.createElement("span"); - element.textContent = conf.placeholderText; - element.setAttribute("aria-label", state.phrase("folded code")); - element.title = state.phrase("unfold"); - element.className = "cm-foldPlaceholder"; - element.onclick = onclick; - return element; - } - } }); - const foldGutterDefaults = { - openText: "⌄", - closedText: "›", - markerDOM: null, - domEventHandlers: {}, - }; - class FoldMarker extends GutterMarker { - constructor(config, open) { - super(); - this.config = config; - this.open = open; - } - eq(other) { return this.config == other.config && this.open == other.open; } - toDOM(view) { - if (this.config.markerDOM) - return this.config.markerDOM(this.open); - let span = document.createElement("span"); - span.textContent = this.open ? this.config.openText : this.config.closedText; - span.title = view.state.phrase(this.open ? "Fold line" : "Unfold line"); - return span; - } - } - /** - Create an extension that registers a fold gutter, which shows a - fold status indicator before foldable lines (which can be clicked - to fold or unfold the line). - */ - function foldGutter(config = {}) { - let fullConfig = Object.assign(Object.assign({}, foldGutterDefaults), config); - let canFold = new FoldMarker(fullConfig, true), canUnfold = new FoldMarker(fullConfig, false); - let markers = ViewPlugin.fromClass(class { - constructor(view) { - this.from = view.viewport.from; - this.markers = this.buildMarkers(view); - } - update(update) { - if (update.docChanged || update.viewportChanged || - update.startState.facet(language) != update.state.facet(language) || - update.startState.field(foldState, false) != update.state.field(foldState, false) || - syntaxTree(update.startState) != syntaxTree(update.state)) - this.markers = this.buildMarkers(update.view); - } - buildMarkers(view) { - let builder = new RangeSetBuilder(); - for (let line of view.viewportLineBlocks) { - let mark = foldInside(view.state, line.from, line.to) ? canUnfold - : foldable(view.state, line.from, line.to) ? canFold : null; - if (mark) - builder.add(line.from, line.from, mark); - } - return builder.finish(); - } - }); - let { domEventHandlers } = fullConfig; - return [ - markers, - gutter({ - class: "cm-foldGutter", - markers(view) { var _a; return ((_a = view.plugin(markers)) === null || _a === void 0 ? void 0 : _a.markers) || RangeSet.empty; }, - initialSpacer() { - return new FoldMarker(fullConfig, false); - }, - domEventHandlers: Object.assign(Object.assign({}, domEventHandlers), { click: (view, line, event) => { - if (domEventHandlers.click && domEventHandlers.click(view, line, event)) - return true; - let folded = foldInside(view.state, line.from, line.to); - if (folded) { - view.dispatch({ effects: unfoldEffect.of(folded) }); - return true; - } - let range = foldable(view.state, line.from, line.to); - if (range) { - view.dispatch({ effects: foldEffect.of(range) }); - return true; - } - return false; - } }) - }), - codeFolding() - ]; - } - const baseTheme$6 = /*@__PURE__*/EditorView.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" - } - }); - - const baseTheme$5 = /*@__PURE__*/EditorView.baseTheme({ - "&.cm-focused .cm-matchingBracket": { backgroundColor: "#328c8252" }, - "&.cm-focused .cm-nonmatchingBracket": { backgroundColor: "#bb555544" } - }); - const DefaultScanDist = 10000, DefaultBrackets = "()[]{}"; - const bracketMatchingConfig = /*@__PURE__*/Facet.define({ - combine(configs) { - return combineConfig(configs, { - afterCursor: true, - brackets: DefaultBrackets, - maxScanDistance: DefaultScanDist - }); - } - }); - const matchingMark = /*@__PURE__*/Decoration.mark({ class: "cm-matchingBracket" }), nonmatchingMark = /*@__PURE__*/Decoration.mark({ class: "cm-nonmatchingBracket" }); - const bracketMatchingState = /*@__PURE__*/StateField.define({ - create() { return Decoration.none; }, - update(deco, tr) { - if (!tr.docChanged && !tr.selection) - return deco; - let decorations = []; - let config = tr.state.facet(bracketMatchingConfig); - for (let range of tr.state.selection.ranges) { - if (!range.empty) - continue; - let match = matchBrackets(tr.state, range.head, -1, config) - || (range.head > 0 && matchBrackets(tr.state, range.head - 1, 1, config)) - || (config.afterCursor && - (matchBrackets(tr.state, range.head, 1, config) || - (range.head < tr.state.doc.length && matchBrackets(tr.state, range.head + 1, -1, config)))); - if (!match) - continue; - let mark = match.matched ? matchingMark : nonmatchingMark; - decorations.push(mark.range(match.start.from, match.start.to)); - if (match.end) - decorations.push(mark.range(match.end.from, match.end.to)); - } - return Decoration.set(decorations, true); - }, - provide: f => EditorView.decorations.from(f) - }); - const bracketMatchingUnique = [ - bracketMatchingState, - baseTheme$5 - ]; - /** - Create an extension that enables bracket matching. Whenever the - cursor is next to a bracket, that bracket and the one it matches - are highlighted. Or, when no matching bracket is found, another - highlighting style is used to indicate this. - */ - function bracketMatching(config = {}) { - return [bracketMatchingConfig.of(config), bracketMatchingUnique]; - } - function matchingNodes(node, dir, brackets) { - let byProp = node.prop(dir < 0 ? NodeProp.openedBy : NodeProp.closedBy); - if (byProp) - return byProp; - if (node.name.length == 1) { - let index = brackets.indexOf(node.name); - if (index > -1 && index % 2 == (dir < 0 ? 1 : 0)) - return [brackets[index + dir]]; - } - return null; - } - /** - Find the matching bracket for the token at `pos`, scanning - direction `dir`. Only the `brackets` and `maxScanDistance` - properties are used from `config`, if given. Returns null if no - bracket was found at `pos`, or a match result otherwise. - */ - function matchBrackets(state, pos, dir, config = {}) { - let maxScanDistance = config.maxScanDistance || DefaultScanDist, brackets = config.brackets || DefaultBrackets; - let tree = syntaxTree(state), node = tree.resolveInner(pos, dir); - for (let cur = node; cur; cur = cur.parent) { - let matches = matchingNodes(cur.type, dir, brackets); - if (matches && cur.from < cur.to) - return matchMarkedBrackets(state, pos, dir, cur, matches, brackets); - } - return matchPlainBrackets(state, pos, dir, tree, node.type, maxScanDistance, brackets); - } - function matchMarkedBrackets(_state, _pos, dir, token, matching, brackets) { - let parent = token.parent, firstToken = { from: token.from, to: token.to }; - let depth = 0, cursor = parent === null || parent === void 0 ? void 0 : parent.cursor; - if (cursor && (dir < 0 ? cursor.childBefore(token.from) : cursor.childAfter(token.to))) - do { - if (dir < 0 ? cursor.to <= token.from : cursor.from >= token.to) { - if (depth == 0 && matching.indexOf(cursor.type.name) > -1 && cursor.from < cursor.to) { - return { start: firstToken, end: { from: cursor.from, to: cursor.to }, matched: true }; - } - else if (matchingNodes(cursor.type, dir, brackets)) { - depth++; - } - else if (matchingNodes(cursor.type, -dir, brackets)) { - depth--; - if (depth == 0) - return { - start: firstToken, - end: cursor.from == cursor.to ? undefined : { from: cursor.from, to: cursor.to }, - matched: false - }; - } - } - } while (dir < 0 ? cursor.prevSibling() : cursor.nextSibling()); - return { start: firstToken, matched: false }; - } - function matchPlainBrackets(state, pos, dir, tree, tokenType, maxScanDistance, brackets) { - let startCh = dir < 0 ? state.sliceDoc(pos - 1, pos) : state.sliceDoc(pos, pos + 1); - let bracket = brackets.indexOf(startCh); - if (bracket < 0 || (bracket % 2 == 0) != (dir > 0)) - return null; - let startToken = { from: dir < 0 ? pos - 1 : pos, to: dir > 0 ? pos + 1 : pos }; - let iter = state.doc.iterRange(pos, dir > 0 ? state.doc.length : 0), depth = 0; - for (let distance = 0; !(iter.next()).done && distance <= maxScanDistance;) { - let text = iter.value; - if (dir < 0) - distance += text.length; - let basePos = pos + distance * dir; - for (let pos = dir > 0 ? 0 : text.length - 1, end = dir > 0 ? text.length : -1; pos != end; pos += dir) { - let found = brackets.indexOf(text[pos]); - if (found < 0 || tree.resolve(basePos + pos, 1).type != tokenType) - continue; - if ((found % 2 == 0) == (dir > 0)) { - depth++; - } - else if (depth == 1) { // Closing - return { start: startToken, end: { from: basePos + pos, to: basePos + pos + 1 }, matched: (found >> 1) == (bracket >> 1) }; - } - else { - depth--; - } - } - if (dir > 0) - distance += text.length; - } - return iter.done ? { start: startToken, matched: false } : null; - } - - function updateSel(sel, by) { - return EditorSelection.create(sel.ranges.map(by), sel.mainIndex); - } - function setSel(state, selection) { - return state.update({ selection, scrollIntoView: true, userEvent: "select" }); - } - function moveSel({ state, dispatch }, how) { - let selection = updateSel(state.selection, how); - if (selection.eq(state.selection)) - return false; - dispatch(setSel(state, selection)); - return true; - } - function rangeEnd(range, forward) { - return EditorSelection.cursor(forward ? range.to : range.from); - } - function cursorByChar(view, forward) { - return moveSel(view, range => range.empty ? view.moveByChar(range, forward) : rangeEnd(range, forward)); - } - /** - Move the selection one character to the left (which is backward in - left-to-right text, forward in right-to-left text). - */ - const cursorCharLeft = view => cursorByChar(view, view.textDirection != Direction.LTR); - /** - Move the selection one character to the right. - */ - const cursorCharRight = view => cursorByChar(view, view.textDirection == Direction.LTR); - function cursorByGroup(view, forward) { - return moveSel(view, range => range.empty ? view.moveByGroup(range, forward) : rangeEnd(range, forward)); - } - /** - Move the selection to the left across one group of word or - non-word (but also non-space) characters. - */ - const cursorGroupLeft = view => cursorByGroup(view, view.textDirection != Direction.LTR); - /** - Move the selection one group to the right. - */ - const cursorGroupRight = view => cursorByGroup(view, view.textDirection == Direction.LTR); - function interestingNode(state, node, bracketProp) { - if (node.type.prop(bracketProp)) - return true; - let len = node.to - node.from; - return len && (len > 2 || /[^\s,.;:]/.test(state.sliceDoc(node.from, node.to))) || node.firstChild; - } - function moveBySyntax(state, start, forward) { - let pos = syntaxTree(state).resolveInner(start.head); - let bracketProp = forward ? NodeProp.closedBy : NodeProp.openedBy; - // Scan forward through child nodes to see if there's an interesting - // node ahead. - for (let at = start.head;;) { - let next = forward ? pos.childAfter(at) : pos.childBefore(at); - if (!next) - break; - if (interestingNode(state, next, bracketProp)) - pos = next; - else - at = forward ? next.to : next.from; - } - let bracket = pos.type.prop(bracketProp), match, newPos; - if (bracket && (match = forward ? matchBrackets(state, pos.from, 1) : matchBrackets(state, pos.to, -1)) && match.matched) - newPos = forward ? match.end.to : match.end.from; - else - newPos = forward ? pos.to : pos.from; - return EditorSelection.cursor(newPos, forward ? -1 : 1); - } - /** - Move the cursor over the next syntactic element to the left. - */ - const cursorSyntaxLeft = view => moveSel(view, range => moveBySyntax(view.state, range, view.textDirection != Direction.LTR)); - /** - Move the cursor over the next syntactic element to the right. - */ - const cursorSyntaxRight = view => moveSel(view, range => moveBySyntax(view.state, range, view.textDirection == Direction.LTR)); - function cursorByLine(view, forward) { - return moveSel(view, range => { - if (!range.empty) - return rangeEnd(range, forward); - let moved = view.moveVertically(range, forward); - return moved.head != range.head ? moved : view.moveToLineBoundary(range, forward); - }); - } - /** - Move the selection one line up. - */ - const cursorLineUp = view => cursorByLine(view, false); - /** - Move the selection one line down. - */ - const cursorLineDown = view => cursorByLine(view, true); - function cursorByPage(view, forward) { - let { state } = view, selection = updateSel(state.selection, range => { - return range.empty ? view.moveVertically(range, forward, view.dom.clientHeight) : rangeEnd(range, forward); - }); - if (selection.eq(state.selection)) - return false; - let startPos = view.coordsAtPos(state.selection.main.head); - let scrollRect = view.scrollDOM.getBoundingClientRect(); - view.dispatch(setSel(state, selection), { - effects: startPos && startPos.top > scrollRect.top && startPos.bottom < scrollRect.bottom - ? EditorView.scrollIntoView(selection.main.head, { y: "start", yMargin: startPos.top - scrollRect.top }) - : undefined - }); - return true; - } - /** - Move the selection one page up. - */ - const cursorPageUp = view => cursorByPage(view, false); - /** - Move the selection one page down. - */ - const cursorPageDown = view => cursorByPage(view, true); - function moveByLineBoundary(view, start, forward) { - let line = view.lineBlockAt(start.head), moved = view.moveToLineBoundary(start, forward); - if (moved.head == start.head && moved.head != (forward ? line.to : line.from)) - moved = view.moveToLineBoundary(start, forward, false); - if (!forward && moved.head == line.from && line.length) { - let space = /^\s*/.exec(view.state.sliceDoc(line.from, Math.min(line.from + 100, line.to)))[0].length; - if (space && start.head != line.from + space) - moved = EditorSelection.cursor(line.from + space); - } - return moved; - } - /** - Move the selection to the next line wrap point, or to the end of - the line if there isn't one left on this line. - */ - const cursorLineBoundaryForward = view => moveSel(view, range => moveByLineBoundary(view, range, true)); - /** - Move the selection to previous line wrap point, or failing that to - the start of the line. If the line is indented, and the cursor - isn't already at the end of the indentation, this will move to the - end of the indentation instead of the start of the line. - */ - const cursorLineBoundaryBackward = view => moveSel(view, range => moveByLineBoundary(view, range, false)); - /** - Move the selection to the start of the line. - */ - const cursorLineStart = view => moveSel(view, range => EditorSelection.cursor(view.lineBlockAt(range.head).from, 1)); - /** - Move the selection to the end of the line. - */ - const cursorLineEnd = view => moveSel(view, range => EditorSelection.cursor(view.lineBlockAt(range.head).to, -1)); - function toMatchingBracket(state, dispatch, extend) { - let found = false, selection = updateSel(state.selection, range => { - let matching = matchBrackets(state, range.head, -1) - || matchBrackets(state, range.head, 1) - || (range.head > 0 && matchBrackets(state, range.head - 1, 1)) - || (range.head < state.doc.length && matchBrackets(state, range.head + 1, -1)); - if (!matching || !matching.end) - return range; - found = true; - let head = matching.start.from == range.head ? matching.end.to : matching.end.from; - return extend ? EditorSelection.range(range.anchor, head) : EditorSelection.cursor(head); - }); - if (!found) - return false; - dispatch(setSel(state, selection)); - return true; - } - /** - Move the selection to the bracket matching the one it is currently - on, if any. - */ - const cursorMatchingBracket = ({ state, dispatch }) => toMatchingBracket(state, dispatch, false); - function extendSel(view, how) { - let selection = updateSel(view.state.selection, range => { - let head = how(range); - return EditorSelection.range(range.anchor, head.head, head.goalColumn); - }); - if (selection.eq(view.state.selection)) - return false; - view.dispatch(setSel(view.state, selection)); - return true; - } - function selectByChar(view, forward) { - return extendSel(view, range => view.moveByChar(range, forward)); - } - /** - Move the selection head one character to the left, while leaving - the anchor in place. - */ - const selectCharLeft = view => selectByChar(view, view.textDirection != Direction.LTR); - /** - Move the selection head one character to the right. - */ - const selectCharRight = view => selectByChar(view, view.textDirection == Direction.LTR); - function selectByGroup(view, forward) { - return extendSel(view, range => view.moveByGroup(range, forward)); - } - /** - Move the selection head one [group](https://codemirror.net/6/docs/ref/#commands.cursorGroupLeft) to - the left. - */ - const selectGroupLeft = view => selectByGroup(view, view.textDirection != Direction.LTR); - /** - Move the selection head one group to the right. - */ - const selectGroupRight = view => selectByGroup(view, view.textDirection == Direction.LTR); - /** - Move the selection head over the next syntactic element to the left. - */ - const selectSyntaxLeft = view => extendSel(view, range => moveBySyntax(view.state, range, view.textDirection != Direction.LTR)); - /** - Move the selection head over the next syntactic element to the right. - */ - const selectSyntaxRight = view => extendSel(view, range => moveBySyntax(view.state, range, view.textDirection == Direction.LTR)); - function selectByLine(view, forward) { - return extendSel(view, range => view.moveVertically(range, forward)); - } - /** - Move the selection head one line up. - */ - const selectLineUp = view => selectByLine(view, false); - /** - Move the selection head one line down. - */ - const selectLineDown = view => selectByLine(view, true); - function selectByPage(view, forward) { - return extendSel(view, range => view.moveVertically(range, forward, view.dom.clientHeight)); - } - /** - Move the selection head one page up. - */ - const selectPageUp = view => selectByPage(view, false); - /** - Move the selection head one page down. - */ - const selectPageDown = view => selectByPage(view, true); - /** - Move the selection head to the next line boundary. - */ - const selectLineBoundaryForward = view => extendSel(view, range => moveByLineBoundary(view, range, true)); - /** - Move the selection head to the previous line boundary. - */ - const selectLineBoundaryBackward = view => extendSel(view, range => moveByLineBoundary(view, range, false)); - /** - Move the selection head to the start of the line. - */ - const selectLineStart = view => extendSel(view, range => EditorSelection.cursor(view.lineBlockAt(range.head).from)); - /** - Move the selection head to the end of the line. - */ - const selectLineEnd = view => extendSel(view, range => EditorSelection.cursor(view.lineBlockAt(range.head).to)); - /** - Move the selection to the start of the document. - */ - const cursorDocStart = ({ state, dispatch }) => { - dispatch(setSel(state, { anchor: 0 })); - return true; - }; - /** - Move the selection to the end of the document. - */ - const cursorDocEnd = ({ state, dispatch }) => { - dispatch(setSel(state, { anchor: state.doc.length })); - return true; - }; - /** - Move the selection head to the start of the document. - */ - const selectDocStart = ({ state, dispatch }) => { - dispatch(setSel(state, { anchor: state.selection.main.anchor, head: 0 })); - return true; - }; - /** - Move the selection head to the end of the document. - */ - const selectDocEnd = ({ state, dispatch }) => { - dispatch(setSel(state, { anchor: state.selection.main.anchor, head: state.doc.length })); - return true; - }; - /** - Select the entire document. - */ - const selectAll = ({ state, dispatch }) => { - dispatch(state.update({ selection: { anchor: 0, head: state.doc.length }, userEvent: "select" })); - return true; - }; - /** - Expand the selection to cover entire lines. - */ - const selectLine = ({ state, dispatch }) => { - let ranges = selectedLineBlocks(state).map(({ from, to }) => EditorSelection.range(from, Math.min(to + 1, state.doc.length))); - dispatch(state.update({ selection: EditorSelection.create(ranges), userEvent: "select" })); - return true; - }; - /** - Select the next syntactic construct that is larger than the - selection. Note that this will only work insofar as the language - [provider](https://codemirror.net/6/docs/ref/#language.language) you use builds up a full - syntax tree. - */ - const selectParentSyntax = ({ state, dispatch }) => { - let selection = updateSel(state.selection, range => { - var _a; - let context = syntaxTree(state).resolveInner(range.head, 1); - while (!((context.from < range.from && context.to >= range.to) || - (context.to > range.to && context.from <= range.from) || - !((_a = context.parent) === null || _a === void 0 ? void 0 : _a.parent))) - context = context.parent; - return EditorSelection.range(context.to, context.from); - }); - dispatch(setSel(state, selection)); - return true; - }; - /** - Simplify the current selection. When multiple ranges are selected, - reduce it to its main range. Otherwise, if the selection is - non-empty, convert it to a cursor selection. - */ - const simplifySelection = ({ state, dispatch }) => { - let cur = state.selection, selection = null; - if (cur.ranges.length > 1) - selection = EditorSelection.create([cur.main]); - else if (!cur.main.empty) - selection = EditorSelection.create([EditorSelection.cursor(cur.main.head)]); - if (!selection) - return false; - dispatch(setSel(state, selection)); - return true; - }; - function deleteBy({ state, dispatch }, by) { - if (state.readOnly) - return false; - let event = "delete.selection"; - let changes = state.changeByRange(range => { - let { from, to } = range; - if (from == to) { - let towards = by(from); - if (towards < from) - event = "delete.backward"; - else if (towards > from) - event = "delete.forward"; - from = Math.min(from, towards); - to = Math.max(to, towards); - } - return from == to ? { range } : { changes: { from, to }, range: EditorSelection.cursor(from) }; - }); - if (changes.changes.empty) - return false; - dispatch(state.update(changes, { scrollIntoView: true, userEvent: event })); - return true; - } - function skipAtomic(target, pos, forward) { - if (target instanceof EditorView) - for (let ranges of target.pluginField(PluginField.atomicRanges)) - ranges.between(pos, pos, (from, to) => { - if (from < pos && to > pos) - pos = forward ? to : from; - }); - return pos; - } - const deleteByChar = (target, forward) => deleteBy(target, pos => { - let { state } = target, line = state.doc.lineAt(pos), before, targetPos; - if (!forward && pos > line.from && pos < line.from + 200 && - !/[^ \t]/.test(before = line.text.slice(0, pos - line.from))) { - if (before[before.length - 1] == "\t") - return pos - 1; - let col = countColumn(before, state.tabSize), drop = col % getIndentUnit(state) || getIndentUnit(state); - for (let i = 0; i < drop && before[before.length - 1 - i] == " "; i++) - pos--; - targetPos = pos; - } - else { - targetPos = findClusterBreak(line.text, pos - line.from, forward, forward) + line.from; - if (targetPos == pos && line.number != (forward ? state.doc.lines : 1)) - targetPos += forward ? 1 : -1; - } - return skipAtomic(target, targetPos, forward); - }); - /** - Delete the selection, or, for cursor selections, the character - before the cursor. - */ - const deleteCharBackward = view => deleteByChar(view, false); - /** - Delete the selection or the character after the cursor. - */ - const deleteCharForward = view => deleteByChar(view, true); - const deleteByGroup = (target, forward) => deleteBy(target, start => { - let pos = start, { state } = target, line = state.doc.lineAt(pos); - let categorize = state.charCategorizer(pos); - for (let cat = null;;) { - if (pos == (forward ? line.to : line.from)) { - if (pos == start && line.number != (forward ? state.doc.lines : 1)) - pos += forward ? 1 : -1; - break; - } - let next = findClusterBreak(line.text, pos - line.from, forward) + line.from; - let nextChar = line.text.slice(Math.min(pos, next) - line.from, Math.max(pos, next) - line.from); - let nextCat = categorize(nextChar); - if (cat != null && nextCat != cat) - break; - if (nextChar != " " || pos != start) - cat = nextCat; - pos = next; - } - return skipAtomic(target, pos, forward); - }); - /** - Delete the selection or backward until the end of the next - [group](https://codemirror.net/6/docs/ref/#view.EditorView.moveByGroup), only skipping groups of - whitespace when they consist of a single space. - */ - const deleteGroupBackward = target => deleteByGroup(target, false); - /** - Delete the selection or forward until the end of the next group. - */ - const deleteGroupForward = target => deleteByGroup(target, true); - /** - Delete the selection, or, if it is a cursor selection, delete to - the end of the line. If the cursor is directly at the end of the - line, delete the line break after it. - */ - const deleteToLineEnd = view => deleteBy(view, pos => { - let lineEnd = view.lineBlockAt(pos).to; - return skipAtomic(view, pos < lineEnd ? lineEnd : Math.min(view.state.doc.length, pos + 1), true); - }); - /** - Delete the selection, or, if it is a cursor selection, delete to - the start of the line. If the cursor is directly at the start of the - line, delete the line break before it. - */ - const deleteToLineStart = view => deleteBy(view, pos => { - let lineStart = view.lineBlockAt(pos).from; - return skipAtomic(view, pos > lineStart ? lineStart : Math.max(0, pos - 1), false); - }); - /** - Replace each selection range with a line break, leaving the cursor - on the line before the break. - */ - const splitLine = ({ state, dispatch }) => { - if (state.readOnly) - return false; - let changes = state.changeByRange(range => { - return { changes: { from: range.from, to: range.to, insert: Text.of(["", ""]) }, - range: EditorSelection.cursor(range.from) }; - }); - dispatch(state.update(changes, { scrollIntoView: true, userEvent: "input" })); - return true; - }; - /** - Flip the characters before and after the cursor(s). - */ - const transposeChars = ({ state, dispatch }) => { - if (state.readOnly) - return false; - let changes = state.changeByRange(range => { - if (!range.empty || range.from == 0 || range.from == state.doc.length) - return { range }; - let pos = range.from, line = state.doc.lineAt(pos); - let from = pos == line.from ? pos - 1 : findClusterBreak(line.text, pos - line.from, false) + line.from; - let to = pos == line.to ? pos + 1 : findClusterBreak(line.text, pos - line.from, true) + line.from; - return { changes: { from, to, insert: state.doc.slice(pos, to).append(state.doc.slice(from, pos)) }, - range: EditorSelection.cursor(to) }; - }); - if (changes.changes.empty) - return false; - dispatch(state.update(changes, { scrollIntoView: true, userEvent: "move.character" })); - return true; - }; - function selectedLineBlocks(state) { - let blocks = [], upto = -1; - for (let range of state.selection.ranges) { - let startLine = state.doc.lineAt(range.from), endLine = state.doc.lineAt(range.to); - if (!range.empty && range.to == endLine.from) - endLine = state.doc.lineAt(range.to - 1); - if (upto >= startLine.number) { - let prev = blocks[blocks.length - 1]; - prev.to = endLine.to; - prev.ranges.push(range); - } - else { - blocks.push({ from: startLine.from, to: endLine.to, ranges: [range] }); - } - upto = endLine.number + 1; - } - return blocks; - } - function moveLine(state, dispatch, forward) { - if (state.readOnly) - return false; - let changes = [], ranges = []; - for (let block of selectedLineBlocks(state)) { - if (forward ? block.to == state.doc.length : block.from == 0) - continue; - let nextLine = state.doc.lineAt(forward ? block.to + 1 : block.from - 1); - let size = nextLine.length + 1; - if (forward) { - changes.push({ from: block.to, to: nextLine.to }, { from: block.from, insert: nextLine.text + state.lineBreak }); - for (let r of block.ranges) - ranges.push(EditorSelection.range(Math.min(state.doc.length, r.anchor + size), Math.min(state.doc.length, r.head + size))); - } - else { - changes.push({ from: nextLine.from, to: block.from }, { from: block.to, insert: state.lineBreak + nextLine.text }); - for (let r of block.ranges) - ranges.push(EditorSelection.range(r.anchor - size, r.head - size)); - } - } - if (!changes.length) - return false; - dispatch(state.update({ - changes, - scrollIntoView: true, - selection: EditorSelection.create(ranges, state.selection.mainIndex), - userEvent: "move.line" - })); - return true; - } - /** - Move the selected lines up one line. - */ - const moveLineUp = ({ state, dispatch }) => moveLine(state, dispatch, false); - /** - Move the selected lines down one line. - */ - const moveLineDown = ({ state, dispatch }) => moveLine(state, dispatch, true); - function copyLine(state, dispatch, forward) { - if (state.readOnly) - return false; - let changes = []; - for (let block of selectedLineBlocks(state)) { - if (forward) - changes.push({ from: block.from, insert: state.doc.slice(block.from, block.to) + state.lineBreak }); - else - changes.push({ from: block.to, insert: state.lineBreak + state.doc.slice(block.from, block.to) }); - } - dispatch(state.update({ changes, scrollIntoView: true, userEvent: "input.copyline" })); - return true; - } - /** - Create a copy of the selected lines. Keep the selection in the top copy. - */ - const copyLineUp = ({ state, dispatch }) => copyLine(state, dispatch, false); - /** - Create a copy of the selected lines. Keep the selection in the bottom copy. - */ - const copyLineDown = ({ state, dispatch }) => copyLine(state, dispatch, true); - /** - Delete selected lines. - */ - const deleteLine = view => { - if (view.state.readOnly) - return false; - let { state } = view, changes = state.changes(selectedLineBlocks(state).map(({ from, to }) => { - if (from > 0) - from--; - else if (to < state.doc.length) - to++; - return { from, to }; - })); - let selection = updateSel(state.selection, range => view.moveVertically(range, true)).map(changes); - view.dispatch({ changes, selection, scrollIntoView: true, userEvent: "delete.line" }); - return true; - }; - function isBetweenBrackets(state, pos) { - if (/\(\)|\[\]|\{\}/.test(state.sliceDoc(pos - 1, pos + 1))) - return { from: pos, to: pos }; - let context = syntaxTree(state).resolveInner(pos); - let before = context.childBefore(pos), after = context.childAfter(pos), closedBy; - if (before && after && before.to <= pos && after.from >= pos && - (closedBy = before.type.prop(NodeProp.closedBy)) && closedBy.indexOf(after.name) > -1 && - state.doc.lineAt(before.to).from == state.doc.lineAt(after.from).from) - return { from: before.to, to: after.from }; - return null; - } - /** - Replace the selection with a newline and indent the newly created - line(s). If the current line consists only of whitespace, this - will also delete that whitespace. When the cursor is between - matching brackets, an additional newline will be inserted after - the cursor. - */ - const insertNewlineAndIndent = /*@__PURE__*/newlineAndIndent(false); - /** - Create a blank, indented line below the current line. - */ - const insertBlankLine = /*@__PURE__*/newlineAndIndent(true); - function newlineAndIndent(atEof) { - return ({ state, dispatch }) => { - if (state.readOnly) - return false; - let changes = state.changeByRange(range => { - let { from, to } = range, line = state.doc.lineAt(from); - let explode = !atEof && from == to && isBetweenBrackets(state, from); - if (atEof) - from = to = (to <= line.to ? line : state.doc.lineAt(to)).to; - let cx = new IndentContext(state, { simulateBreak: from, simulateDoubleBreak: !!explode }); - let indent = getIndentation(cx, from); - if (indent == null) - indent = /^\s*/.exec(state.doc.lineAt(from).text)[0].length; - while (to < line.to && /\s/.test(line.text[to - line.from])) - to++; - if (explode) - ({ from, to } = explode); - else if (from > line.from && from < line.from + 100 && !/\S/.test(line.text.slice(0, from))) - from = line.from; - let insert = ["", indentString(state, indent)]; - if (explode) - insert.push(indentString(state, cx.lineIndent(line.from, -1))); - return { changes: { from, to, insert: Text.of(insert) }, - range: EditorSelection.cursor(from + 1 + insert[1].length) }; - }); - dispatch(state.update(changes, { scrollIntoView: true, userEvent: "input" })); - return true; - }; - } - function changeBySelectedLine(state, f) { - let atLine = -1; - return state.changeByRange(range => { - let changes = []; - for (let pos = range.from; pos <= range.to;) { - let line = state.doc.lineAt(pos); - if (line.number > atLine && (range.empty || range.to > line.from)) { - f(line, changes, range); - atLine = line.number; - } - pos = line.to + 1; - } - let changeSet = state.changes(changes); - return { changes, - range: EditorSelection.range(changeSet.mapPos(range.anchor, 1), changeSet.mapPos(range.head, 1)) }; - }); - } - /** - Auto-indent the selected lines. This uses the [indentation service - facet](https://codemirror.net/6/docs/ref/#language.indentService) as source for auto-indent - information. - */ - const indentSelection = ({ state, dispatch }) => { - if (state.readOnly) - return false; - let updated = Object.create(null); - let context = new IndentContext(state, { overrideIndentation: start => { - let found = updated[start]; - return found == null ? -1 : found; - } }); - let changes = changeBySelectedLine(state, (line, changes, range) => { - let indent = getIndentation(context, line.from); - if (indent == null) - return; - if (!/\S/.test(line.text)) - indent = 0; - let cur = /^\s*/.exec(line.text)[0]; - let norm = indentString(state, indent); - if (cur != norm || range.from < line.from + cur.length) { - updated[line.from] = indent; - changes.push({ from: line.from, to: line.from + cur.length, insert: norm }); - } - }); - if (!changes.changes.empty) - dispatch(state.update(changes, { userEvent: "indent" })); - return true; - }; - /** - Add a [unit](https://codemirror.net/6/docs/ref/#language.indentUnit) of indentation to all selected - lines. - */ - const indentMore = ({ state, dispatch }) => { - if (state.readOnly) - return false; - dispatch(state.update(changeBySelectedLine(state, (line, changes) => { - changes.push({ from: line.from, insert: state.facet(indentUnit) }); - }), { userEvent: "input.indent" })); - return true; - }; - /** - Remove a [unit](https://codemirror.net/6/docs/ref/#language.indentUnit) of indentation from all - selected lines. - */ - const indentLess = ({ state, dispatch }) => { - if (state.readOnly) - return false; - dispatch(state.update(changeBySelectedLine(state, (line, changes) => { - let space = /^\s*/.exec(line.text)[0]; - if (!space) - return; - let col = countColumn(space, state.tabSize), keep = 0; - let insert = indentString(state, Math.max(0, col - getIndentUnit(state))); - while (keep < space.length && keep < insert.length && space.charCodeAt(keep) == insert.charCodeAt(keep)) - keep++; - changes.push({ from: line.from + keep, to: line.from + space.length, insert: insert.slice(keep) }); - }), { userEvent: "delete.dedent" })); - return true; - }; - /** - Array of key bindings containing the Emacs-style bindings that are - available on macOS by default. - - - Ctrl-b: [`cursorCharLeft`](https://codemirror.net/6/docs/ref/#commands.cursorCharLeft) ([`selectCharLeft`](https://codemirror.net/6/docs/ref/#commands.selectCharLeft) with Shift) - - Ctrl-f: [`cursorCharRight`](https://codemirror.net/6/docs/ref/#commands.cursorCharRight) ([`selectCharRight`](https://codemirror.net/6/docs/ref/#commands.selectCharRight) with Shift) - - Ctrl-p: [`cursorLineUp`](https://codemirror.net/6/docs/ref/#commands.cursorLineUp) ([`selectLineUp`](https://codemirror.net/6/docs/ref/#commands.selectLineUp) with Shift) - - Ctrl-n: [`cursorLineDown`](https://codemirror.net/6/docs/ref/#commands.cursorLineDown) ([`selectLineDown`](https://codemirror.net/6/docs/ref/#commands.selectLineDown) with Shift) - - Ctrl-a: [`cursorLineStart`](https://codemirror.net/6/docs/ref/#commands.cursorLineStart) ([`selectLineStart`](https://codemirror.net/6/docs/ref/#commands.selectLineStart) with Shift) - - Ctrl-e: [`cursorLineEnd`](https://codemirror.net/6/docs/ref/#commands.cursorLineEnd) ([`selectLineEnd`](https://codemirror.net/6/docs/ref/#commands.selectLineEnd) with Shift) - - Ctrl-d: [`deleteCharForward`](https://codemirror.net/6/docs/ref/#commands.deleteCharForward) - - Ctrl-h: [`deleteCharBackward`](https://codemirror.net/6/docs/ref/#commands.deleteCharBackward) - - Ctrl-k: [`deleteToLineEnd`](https://codemirror.net/6/docs/ref/#commands.deleteToLineEnd) - - Ctrl-Alt-h: [`deleteGroupBackward`](https://codemirror.net/6/docs/ref/#commands.deleteGroupBackward) - - Ctrl-o: [`splitLine`](https://codemirror.net/6/docs/ref/#commands.splitLine) - - Ctrl-t: [`transposeChars`](https://codemirror.net/6/docs/ref/#commands.transposeChars) - - Ctrl-v: [`cursorPageDown`](https://codemirror.net/6/docs/ref/#commands.cursorPageDown) - - Alt-v: [`cursorPageUp`](https://codemirror.net/6/docs/ref/#commands.cursorPageUp) - */ - const emacsStyleKeymap = [ - { key: "Ctrl-b", run: cursorCharLeft, shift: selectCharLeft, preventDefault: true }, - { key: "Ctrl-f", run: cursorCharRight, shift: selectCharRight }, - { key: "Ctrl-p", run: cursorLineUp, shift: selectLineUp }, - { key: "Ctrl-n", run: cursorLineDown, shift: selectLineDown }, - { key: "Ctrl-a", run: cursorLineStart, shift: selectLineStart }, - { key: "Ctrl-e", run: cursorLineEnd, shift: selectLineEnd }, - { key: "Ctrl-d", run: deleteCharForward }, - { key: "Ctrl-h", run: deleteCharBackward }, - { key: "Ctrl-k", run: deleteToLineEnd }, - { key: "Ctrl-Alt-h", run: deleteGroupBackward }, - { key: "Ctrl-o", run: splitLine }, - { key: "Ctrl-t", run: transposeChars }, - { key: "Ctrl-v", run: cursorPageDown }, - ]; - /** - An array of key bindings closely sticking to platform-standard or - widely used bindings. (This includes the bindings from - [`emacsStyleKeymap`](https://codemirror.net/6/docs/ref/#commands.emacsStyleKeymap), with their `key` - property changed to `mac`.) - - - ArrowLeft: [`cursorCharLeft`](https://codemirror.net/6/docs/ref/#commands.cursorCharLeft) ([`selectCharLeft`](https://codemirror.net/6/docs/ref/#commands.selectCharLeft) with Shift) - - ArrowRight: [`cursorCharRight`](https://codemirror.net/6/docs/ref/#commands.cursorCharRight) ([`selectCharRight`](https://codemirror.net/6/docs/ref/#commands.selectCharRight) with Shift) - - Ctrl-ArrowLeft (Alt-ArrowLeft on macOS): [`cursorGroupLeft`](https://codemirror.net/6/docs/ref/#commands.cursorGroupLeft) ([`selectGroupLeft`](https://codemirror.net/6/docs/ref/#commands.selectGroupLeft) with Shift) - - Ctrl-ArrowRight (Alt-ArrowRight on macOS): [`cursorGroupRight`](https://codemirror.net/6/docs/ref/#commands.cursorGroupRight) ([`selectGroupRight`](https://codemirror.net/6/docs/ref/#commands.selectGroupRight) with Shift) - - Cmd-ArrowLeft (on macOS): [`cursorLineStart`](https://codemirror.net/6/docs/ref/#commands.cursorLineStart) ([`selectLineStart`](https://codemirror.net/6/docs/ref/#commands.selectLineStart) with Shift) - - Cmd-ArrowRight (on macOS): [`cursorLineEnd`](https://codemirror.net/6/docs/ref/#commands.cursorLineEnd) ([`selectLineEnd`](https://codemirror.net/6/docs/ref/#commands.selectLineEnd) with Shift) - - ArrowUp: [`cursorLineUp`](https://codemirror.net/6/docs/ref/#commands.cursorLineUp) ([`selectLineUp`](https://codemirror.net/6/docs/ref/#commands.selectLineUp) with Shift) - - ArrowDown: [`cursorLineDown`](https://codemirror.net/6/docs/ref/#commands.cursorLineDown) ([`selectLineDown`](https://codemirror.net/6/docs/ref/#commands.selectLineDown) with Shift) - - Cmd-ArrowUp (on macOS): [`cursorDocStart`](https://codemirror.net/6/docs/ref/#commands.cursorDocStart) ([`selectDocStart`](https://codemirror.net/6/docs/ref/#commands.selectDocStart) with Shift) - - Cmd-ArrowDown (on macOS): [`cursorDocEnd`](https://codemirror.net/6/docs/ref/#commands.cursorDocEnd) ([`selectDocEnd`](https://codemirror.net/6/docs/ref/#commands.selectDocEnd) with Shift) - - Ctrl-ArrowUp (on macOS): [`cursorPageUp`](https://codemirror.net/6/docs/ref/#commands.cursorPageUp) ([`selectPageUp`](https://codemirror.net/6/docs/ref/#commands.selectPageUp) with Shift) - - Ctrl-ArrowDown (on macOS): [`cursorPageDown`](https://codemirror.net/6/docs/ref/#commands.cursorPageDown) ([`selectPageDown`](https://codemirror.net/6/docs/ref/#commands.selectPageDown) with Shift) - - PageUp: [`cursorPageUp`](https://codemirror.net/6/docs/ref/#commands.cursorPageUp) ([`selectPageUp`](https://codemirror.net/6/docs/ref/#commands.selectPageUp) with Shift) - - PageDown: [`cursorPageDown`](https://codemirror.net/6/docs/ref/#commands.cursorPageDown) ([`selectPageDown`](https://codemirror.net/6/docs/ref/#commands.selectPageDown) with Shift) - - Home: [`cursorLineBoundaryBackward`](https://codemirror.net/6/docs/ref/#commands.cursorLineBoundaryBackward) ([`selectLineBoundaryBackward`](https://codemirror.net/6/docs/ref/#commands.selectLineBoundaryBackward) with Shift) - - End: [`cursorLineBoundaryForward`](https://codemirror.net/6/docs/ref/#commands.cursorLineBoundaryForward) ([`selectLineBoundaryForward`](https://codemirror.net/6/docs/ref/#commands.selectLineBoundaryForward) with Shift) - - Ctrl-Home (Cmd-Home on macOS): [`cursorDocStart`](https://codemirror.net/6/docs/ref/#commands.cursorDocStart) ([`selectDocStart`](https://codemirror.net/6/docs/ref/#commands.selectDocStart) with Shift) - - Ctrl-End (Cmd-Home on macOS): [`cursorDocEnd`](https://codemirror.net/6/docs/ref/#commands.cursorDocEnd) ([`selectDocEnd`](https://codemirror.net/6/docs/ref/#commands.selectDocEnd) with Shift) - - Enter: [`insertNewlineAndIndent`](https://codemirror.net/6/docs/ref/#commands.insertNewlineAndIndent) - - Ctrl-a (Cmd-a on macOS): [`selectAll`](https://codemirror.net/6/docs/ref/#commands.selectAll) - - Backspace: [`deleteCharBackward`](https://codemirror.net/6/docs/ref/#commands.deleteCharBackward) - - Delete: [`deleteCharForward`](https://codemirror.net/6/docs/ref/#commands.deleteCharForward) - - Ctrl-Backspace (Alt-Backspace on macOS): [`deleteGroupBackward`](https://codemirror.net/6/docs/ref/#commands.deleteGroupBackward) - - Ctrl-Delete (Alt-Delete on macOS): [`deleteGroupForward`](https://codemirror.net/6/docs/ref/#commands.deleteGroupForward) - - Cmd-Backspace (macOS): [`deleteToLineStart`](https://codemirror.net/6/docs/ref/#commands.deleteToLineStart). - - Cmd-Delete (macOS): [`deleteToLineEnd`](https://codemirror.net/6/docs/ref/#commands.deleteToLineEnd). - */ - const standardKeymap = /*@__PURE__*/[ - { key: "ArrowLeft", run: cursorCharLeft, shift: selectCharLeft, preventDefault: true }, - { key: "Mod-ArrowLeft", mac: "Alt-ArrowLeft", run: cursorGroupLeft, shift: selectGroupLeft }, - { mac: "Cmd-ArrowLeft", run: cursorLineBoundaryBackward, shift: selectLineBoundaryBackward }, - { key: "ArrowRight", run: cursorCharRight, shift: selectCharRight, preventDefault: true }, - { key: "Mod-ArrowRight", mac: "Alt-ArrowRight", run: cursorGroupRight, shift: selectGroupRight }, - { mac: "Cmd-ArrowRight", run: cursorLineBoundaryForward, shift: selectLineBoundaryForward }, - { key: "ArrowUp", run: cursorLineUp, shift: selectLineUp, preventDefault: true }, - { mac: "Cmd-ArrowUp", run: cursorDocStart, shift: selectDocStart }, - { mac: "Ctrl-ArrowUp", run: cursorPageUp, shift: selectPageUp }, - { key: "ArrowDown", run: cursorLineDown, shift: selectLineDown, preventDefault: true }, - { mac: "Cmd-ArrowDown", run: cursorDocEnd, shift: selectDocEnd }, - { mac: "Ctrl-ArrowDown", run: cursorPageDown, shift: selectPageDown }, - { key: "PageUp", run: cursorPageUp, shift: selectPageUp }, - { key: "PageDown", run: cursorPageDown, shift: selectPageDown }, - { key: "Home", run: cursorLineBoundaryBackward, shift: selectLineBoundaryBackward }, - { key: "Mod-Home", run: cursorDocStart, shift: selectDocStart }, - { key: "End", run: cursorLineBoundaryForward, shift: selectLineBoundaryForward }, - { key: "Mod-End", run: cursorDocEnd, shift: selectDocEnd }, - { key: "Enter", run: insertNewlineAndIndent }, - { key: "Mod-a", run: selectAll }, - { key: "Backspace", run: deleteCharBackward, shift: deleteCharBackward }, - { key: "Delete", run: deleteCharForward }, - { key: "Mod-Backspace", mac: "Alt-Backspace", run: deleteGroupBackward }, - { key: "Mod-Delete", mac: "Alt-Delete", run: deleteGroupForward }, - { mac: "Mod-Backspace", run: deleteToLineStart }, - { mac: "Mod-Delete", run: deleteToLineEnd } - ].concat(/*@__PURE__*/emacsStyleKeymap.map(b => ({ mac: b.key, run: b.run, shift: b.shift }))); - /** - The default keymap. Includes all bindings from - [`standardKeymap`](https://codemirror.net/6/docs/ref/#commands.standardKeymap) plus the following: - - - Alt-ArrowLeft (Ctrl-ArrowLeft on macOS): [`cursorSyntaxLeft`](https://codemirror.net/6/docs/ref/#commands.cursorSyntaxLeft) ([`selectSyntaxLeft`](https://codemirror.net/6/docs/ref/#commands.selectSyntaxLeft) with Shift) - - Alt-ArrowRight (Ctrl-ArrowRight on macOS): [`cursorSyntaxRight`](https://codemirror.net/6/docs/ref/#commands.cursorSyntaxRight) ([`selectSyntaxRight`](https://codemirror.net/6/docs/ref/#commands.selectSyntaxRight) with Shift) - - Alt-ArrowUp: [`moveLineUp`](https://codemirror.net/6/docs/ref/#commands.moveLineUp) - - Alt-ArrowDown: [`moveLineDown`](https://codemirror.net/6/docs/ref/#commands.moveLineDown) - - Shift-Alt-ArrowUp: [`copyLineUp`](https://codemirror.net/6/docs/ref/#commands.copyLineUp) - - Shift-Alt-ArrowDown: [`copyLineDown`](https://codemirror.net/6/docs/ref/#commands.copyLineDown) - - Escape: [`simplifySelection`](https://codemirror.net/6/docs/ref/#commands.simplifySelection) - - Ctrl-Enter (Comd-Enter on macOS): [`insertBlankLine`](https://codemirror.net/6/docs/ref/#commands.insertBlankLine) - - Alt-l (Ctrl-l on macOS): [`selectLine`](https://codemirror.net/6/docs/ref/#commands.selectLine) - - Ctrl-i (Cmd-i on macOS): [`selectParentSyntax`](https://codemirror.net/6/docs/ref/#commands.selectParentSyntax) - - Ctrl-[ (Cmd-[ on macOS): [`indentLess`](https://codemirror.net/6/docs/ref/#commands.indentLess) - - Ctrl-] (Cmd-] on macOS): [`indentMore`](https://codemirror.net/6/docs/ref/#commands.indentMore) - - Ctrl-Alt-\\ (Cmd-Alt-\\ on macOS): [`indentSelection`](https://codemirror.net/6/docs/ref/#commands.indentSelection) - - Shift-Ctrl-k (Shift-Cmd-k on macOS): [`deleteLine`](https://codemirror.net/6/docs/ref/#commands.deleteLine) - - Shift-Ctrl-\\ (Shift-Cmd-\\ on macOS): [`cursorMatchingBracket`](https://codemirror.net/6/docs/ref/#commands.cursorMatchingBracket) - */ - const defaultKeymap = /*@__PURE__*/[ - { key: "Alt-ArrowLeft", mac: "Ctrl-ArrowLeft", run: cursorSyntaxLeft, shift: selectSyntaxLeft }, - { key: "Alt-ArrowRight", mac: "Ctrl-ArrowRight", run: cursorSyntaxRight, shift: selectSyntaxRight }, - { key: "Alt-ArrowUp", run: moveLineUp }, - { key: "Shift-Alt-ArrowUp", run: copyLineUp }, - { key: "Alt-ArrowDown", run: moveLineDown }, - { key: "Shift-Alt-ArrowDown", run: copyLineDown }, - { key: "Escape", run: simplifySelection }, - { key: "Mod-Enter", run: insertBlankLine }, - { key: "Alt-l", mac: "Ctrl-l", run: selectLine }, - { key: "Mod-i", run: selectParentSyntax, preventDefault: true }, - { key: "Mod-[", run: indentLess }, - { key: "Mod-]", run: indentMore }, - { key: "Mod-Alt-\\", run: indentSelection }, - { key: "Shift-Mod-k", run: deleteLine }, - { key: "Shift-Mod-\\", run: cursorMatchingBracket } - ].concat(standardKeymap); - - const defaults = { - brackets: ["(", "[", "{", "'", '"'], - before: ")]}:;>" - }; - const closeBracketEffect = /*@__PURE__*/StateEffect.define({ - map(value, mapping) { - let mapped = mapping.mapPos(value, -1, MapMode.TrackAfter); - return mapped == null ? undefined : mapped; - } - }); - const skipBracketEffect = /*@__PURE__*/StateEffect.define({ - map(value, mapping) { return mapping.mapPos(value); } - }); - const closedBracket = /*@__PURE__*/new class extends RangeValue { - }; - closedBracket.startSide = 1; - closedBracket.endSide = -1; - const bracketState = /*@__PURE__*/StateField.define({ - create() { return RangeSet.empty; }, - update(value, tr) { - if (tr.selection) { - let lineStart = tr.state.doc.lineAt(tr.selection.main.head).from; - let prevLineStart = tr.startState.doc.lineAt(tr.startState.selection.main.head).from; - if (lineStart != tr.changes.mapPos(prevLineStart, -1)) - value = RangeSet.empty; - } - value = value.map(tr.changes); - for (let effect of tr.effects) { - if (effect.is(closeBracketEffect)) - value = value.update({ add: [closedBracket.range(effect.value, effect.value + 1)] }); - else if (effect.is(skipBracketEffect)) - value = value.update({ filter: from => from != effect.value }); - } - return value; - } - }); - /** - Extension to enable bracket-closing behavior. When a closeable - bracket is typed, its closing bracket is immediately inserted - after the cursor. When closing a bracket directly in front of a - closing bracket inserted by the extension, the cursor moves over - that bracket. - */ - function closeBrackets() { - return [inputHandler, bracketState]; - } - const definedClosing = "()[]{}<>"; - function closing(ch) { - for (let i = 0; i < definedClosing.length; i += 2) - if (definedClosing.charCodeAt(i) == ch) - return definedClosing.charAt(i + 1); - return fromCodePoint(ch < 128 ? ch : ch + 1); - } - function config$1(state, pos) { - return state.languageDataAt("closeBrackets", pos)[0] || defaults; - } - const android = typeof navigator == "object" && /*@__PURE__*//Android\b/.test(navigator.userAgent); - const inputHandler = /*@__PURE__*/EditorView.inputHandler.of((view, from, to, insert) => { - if ((android ? view.composing : view.compositionStarted) || view.state.readOnly) - return false; - let sel = view.state.selection.main; - if (insert.length > 2 || insert.length == 2 && codePointSize(codePointAt(insert, 0)) == 1 || - from != sel.from || to != sel.to) - return false; - let tr = insertBracket(view.state, insert); - if (!tr) - return false; - view.dispatch(tr); - return true; - }); - /** - Command that implements deleting a pair of matching brackets when - the cursor is between them. - */ - const deleteBracketPair = ({ state, dispatch }) => { - if (state.readOnly) - return false; - let conf = config$1(state, state.selection.main.head); - let tokens = conf.brackets || defaults.brackets; - let dont = null, changes = state.changeByRange(range => { - if (range.empty) { - let before = prevChar(state.doc, range.head); - for (let token of tokens) { - if (token == before && nextChar(state.doc, range.head) == closing(codePointAt(token, 0))) - return { changes: { from: range.head - token.length, to: range.head + token.length }, - range: EditorSelection.cursor(range.head - token.length), - userEvent: "delete.backward" }; - } - } - return { range: dont = range }; - }); - if (!dont) - dispatch(state.update(changes, { scrollIntoView: true })); - return !dont; - }; - /** - Close-brackets related key bindings. Binds Backspace to - [`deleteBracketPair`](https://codemirror.net/6/docs/ref/#closebrackets.deleteBracketPair). - */ - const closeBracketsKeymap = [ - { key: "Backspace", run: deleteBracketPair } - ]; - /** - Implements the extension's behavior on text insertion. If the - given string counts as a bracket in the language around the - selection, and replacing the selection with it requires custom - behavior (inserting a closing version or skipping past a - previously-closed bracket), this function returns a transaction - representing that custom behavior. (You only need this if you want - to programmatically insert brackets—the - [`closeBrackets`](https://codemirror.net/6/docs/ref/#closebrackets.closeBrackets) extension will - take care of running this for user input.) - */ - function insertBracket(state, bracket) { - let conf = config$1(state, state.selection.main.head); - let tokens = conf.brackets || defaults.brackets; - for (let tok of tokens) { - let closed = closing(codePointAt(tok, 0)); - if (bracket == tok) - return closed == tok ? handleSame(state, tok, tokens.indexOf(tok + tok + tok) > -1) - : handleOpen(state, tok, closed, conf.before || defaults.before); - if (bracket == closed && closedBracketAt(state, state.selection.main.from)) - return handleClose(state, tok, closed); - } - return null; - } - function closedBracketAt(state, pos) { - let found = false; - state.field(bracketState).between(0, state.doc.length, from => { - if (from == pos) - found = true; - }); - return found; - } - function nextChar(doc, pos) { - let next = doc.sliceString(pos, pos + 2); - return next.slice(0, codePointSize(codePointAt(next, 0))); - } - function prevChar(doc, pos) { - let prev = doc.sliceString(pos - 2, pos); - return codePointSize(codePointAt(prev, 0)) == prev.length ? prev : prev.slice(1); - } - function handleOpen(state, open, close, closeBefore) { - let dont = null, changes = state.changeByRange(range => { - if (!range.empty) - return { changes: [{ insert: open, from: range.from }, { insert: close, from: range.to }], - effects: closeBracketEffect.of(range.to + open.length), - range: EditorSelection.range(range.anchor + open.length, range.head + open.length) }; - let next = nextChar(state.doc, range.head); - if (!next || /\s/.test(next) || closeBefore.indexOf(next) > -1) - return { changes: { insert: open + close, from: range.head }, - effects: closeBracketEffect.of(range.head + open.length), - range: EditorSelection.cursor(range.head + open.length) }; - return { range: dont = range }; - }); - return dont ? null : state.update(changes, { - scrollIntoView: true, - userEvent: "input.type" - }); - } - function handleClose(state, _open, close) { - let dont = null, moved = state.selection.ranges.map(range => { - if (range.empty && nextChar(state.doc, range.head) == close) - return EditorSelection.cursor(range.head + close.length); - return dont = range; - }); - return dont ? null : state.update({ - selection: EditorSelection.create(moved, state.selection.mainIndex), - scrollIntoView: true, - effects: state.selection.ranges.map(({ from }) => skipBracketEffect.of(from)) - }); - } - // Handles cases where the open and close token are the same, and - // possibly triple quotes (as in `"""abc"""`-style quoting). - function handleSame(state, token, allowTriple) { - let dont = null, changes = state.changeByRange(range => { - if (!range.empty) - return { changes: [{ insert: token, from: range.from }, { insert: token, from: range.to }], - effects: closeBracketEffect.of(range.to + token.length), - range: EditorSelection.range(range.anchor + token.length, range.head + token.length) }; - let pos = range.head, next = nextChar(state.doc, pos); - if (next == token) { - if (nodeStart(state, pos)) { - return { changes: { insert: token + token, from: pos }, - effects: closeBracketEffect.of(pos + token.length), - range: EditorSelection.cursor(pos + token.length) }; - } - else if (closedBracketAt(state, pos)) { - let isTriple = allowTriple && state.sliceDoc(pos, pos + token.length * 3) == token + token + token; - return { range: EditorSelection.cursor(pos + token.length * (isTriple ? 3 : 1)), - effects: skipBracketEffect.of(pos) }; - } - } - else if (allowTriple && state.sliceDoc(pos - 2 * token.length, pos) == token + token && - nodeStart(state, pos - 2 * token.length)) { - return { changes: { insert: token + token + token + token, from: pos }, - effects: closeBracketEffect.of(pos + token.length), - range: EditorSelection.cursor(pos + token.length) }; - } - else if (state.charCategorizer(pos)(next) != CharCategory.Word) { - let prev = state.sliceDoc(pos - 1, pos); - if (prev != token && state.charCategorizer(pos)(prev) != CharCategory.Word && !probablyInString(state, pos, token)) - return { changes: { insert: token + token, from: pos }, - effects: closeBracketEffect.of(pos + token.length), - range: EditorSelection.cursor(pos + token.length) }; - } - return { range: dont = range }; - }); - return dont ? null : state.update(changes, { - scrollIntoView: true, - userEvent: "input.type" - }); - } - function nodeStart(state, pos) { - let tree = syntaxTree(state).resolveInner(pos + 1); - return tree.parent && tree.from == pos; - } - function probablyInString(state, pos, quoteToken) { - let node = syntaxTree(state).resolveInner(pos, -1); - for (let i = 0; i < 5; i++) { - if (state.sliceDoc(node.from, node.from + quoteToken.length) == quoteToken) - return true; - let parent = node.to == pos && node.parent; - if (!parent) - break; - node = parent; - } - return false; - } - - const panelConfig = /*@__PURE__*/Facet.define({ - combine(configs) { - let topContainer, bottomContainer; - for (let c of configs) { - topContainer = topContainer || c.topContainer; - bottomContainer = bottomContainer || c.bottomContainer; - } - return { topContainer, bottomContainer }; - } - }); - /** - Get the active panel created by the given constructor, if any. - This can be useful when you need access to your panels' DOM - structure. - */ - function getPanel(view, panel) { - let plugin = view.plugin(panelPlugin); - let index = plugin ? plugin.specs.indexOf(panel) : -1; - return index > -1 ? plugin.panels[index] : null; - } - const panelPlugin = /*@__PURE__*/ViewPlugin.fromClass(class { - constructor(view) { - this.input = view.state.facet(showPanel); - this.specs = this.input.filter(s => s); - this.panels = this.specs.map(spec => spec(view)); - let conf = view.state.facet(panelConfig); - this.top = new PanelGroup(view, true, conf.topContainer); - this.bottom = new PanelGroup(view, false, conf.bottomContainer); - this.top.sync(this.panels.filter(p => p.top)); - this.bottom.sync(this.panels.filter(p => !p.top)); - for (let p of this.panels) { - p.dom.classList.add("cm-panel"); - if (p.mount) - p.mount(); - } - } - update(update) { - let conf = update.state.facet(panelConfig); - if (this.top.container != conf.topContainer) { - this.top.sync([]); - this.top = new PanelGroup(update.view, true, conf.topContainer); - } - if (this.bottom.container != conf.bottomContainer) { - this.bottom.sync([]); - this.bottom = new PanelGroup(update.view, false, conf.bottomContainer); - } - this.top.syncClasses(); - this.bottom.syncClasses(); - let input = update.state.facet(showPanel); - if (input != this.input) { - let specs = input.filter(x => x); - let panels = [], top = [], bottom = [], mount = []; - for (let spec of specs) { - let known = this.specs.indexOf(spec), panel; - if (known < 0) { - panel = spec(update.view); - mount.push(panel); - } - else { - panel = this.panels[known]; - if (panel.update) - panel.update(update); - } - panels.push(panel); - (panel.top ? top : bottom).push(panel); - } - this.specs = specs; - this.panels = panels; - this.top.sync(top); - this.bottom.sync(bottom); - for (let p of mount) { - p.dom.classList.add("cm-panel"); - if (p.mount) - p.mount(); - } - } - else { - for (let p of this.panels) - if (p.update) - p.update(update); - } - } - destroy() { - this.top.sync([]); - this.bottom.sync([]); - } - }, { - provide: /*@__PURE__*/PluginField.scrollMargins.from(value => ({ top: value.top.scrollMargin(), bottom: value.bottom.scrollMargin() })) - }); - class PanelGroup { - constructor(view, top, container) { - this.view = view; - this.top = top; - this.container = container; - this.dom = undefined; - this.classes = ""; - this.panels = []; - this.syncClasses(); - } - sync(panels) { - for (let p of this.panels) - if (p.destroy && panels.indexOf(p) < 0) - p.destroy(); - this.panels = panels; - this.syncDOM(); - } - syncDOM() { - if (this.panels.length == 0) { - if (this.dom) { - this.dom.remove(); - this.dom = undefined; - } - return; - } - 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 parent = this.container || this.view.dom; - parent.insertBefore(this.dom, this.top ? parent.firstChild : null); - } - let curDOM = this.dom.firstChild; - for (let panel of this.panels) { - if (panel.dom.parentNode == this.dom) { - while (curDOM != panel.dom) - curDOM = rm(curDOM); - curDOM = curDOM.nextSibling; - } - else { - this.dom.insertBefore(panel.dom, curDOM); - } - } - while (curDOM) - curDOM = rm(curDOM); - } - 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) - return; - for (let cls of this.classes.split(" ")) - if (cls) - this.container.classList.remove(cls); - for (let cls of (this.classes = this.view.themeClasses).split(" ")) - if (cls) - this.container.classList.add(cls); - } - } - function rm(node) { - let next = node.nextSibling; - node.remove(); - return next; - } - const baseTheme$4 = /*@__PURE__*/EditorView.baseTheme({ - ".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" - } - }); - /** - Opening a panel is done by providing a constructor function for - the panel through this facet. (The panel is closed again when its - constructor is no longer provided.) Values of `null` are ignored. - */ - const showPanel = /*@__PURE__*/Facet.define({ - enables: [panelPlugin, baseTheme$4] - }); - - function crelt() { - var elt = arguments[0]; - if (typeof elt == "string") elt = document.createElement(elt); - var i = 1, next = arguments[1]; - if (next && typeof next == "object" && next.nodeType == null && !Array.isArray(next)) { - for (var name in next) if (Object.prototype.hasOwnProperty.call(next, name)) { - var value = next[name]; - if (typeof value == "string") elt.setAttribute(name, value); - else if (value != null) elt[name] = value; - } - i++; + /** + * Fetch python plugins from a filePath, saves it on the FS and import + * it as a module, executing any plugin define the module scope. + * + * @param interpreter - the interpreter that will execute the plugins + * @param filePath - path to the python file to fetch + */ + async fetchPythonPlugin(interpreter, filePath) { + const pathArr = filePath.split('/'); + const filename = pathArr.pop(); + // TODO: Would be probably be better to store plugins somewhere like /plugins/python/ or similar + await interpreter._remote.loadFromFile(filename, filePath); + //refresh module cache before trying to import module files into interpreter + interpreter._remote.invalidate_module_path_cache(); + const modulename = filePath.replace(/^.*[\\/]/, '').replace('.py', ''); + console.log(`importing ${modulename}`); + // TODO: This is very specific to Pyodide API and will not work for other interpreters, + // when we add support for other interpreters we will need to move this to the + // interpreter API level and allow each one to implement it in its own way + const module = interpreter._remote.interface.pyimport(modulename); + if (typeof module.plugin !== 'undefined') { + const py_plugin = module.plugin; + py_plugin.init(this); + this.plugins.addPythonPlugin(py_plugin); + } + else { + logger.error(`Cannot find plugin on Python module ${modulename}! Python plugins \ +modules must contain a "plugin" attribute. For more information check the plugins documentation.`); + } } - for (; i < arguments.length; i++) add(elt, arguments[i]); - return elt - } - - function add(elt, child) { - if (typeof child == "string") { - elt.appendChild(document.createTextNode(child)); - } else if (child == null) ; else if (child.nodeType != null) { - elt.appendChild(child); - } else if (Array.isArray(child)) { - for (var i = 0; i < child.length; i++) add(elt, child[i]); - } else { - throw new RangeError("Unsupported child node: " + child) + // lifecycle (7) + executeScripts(interpreter) { + // make_PyScript takes an interpreter and a PyScriptApp as arguments + this.PyScript = make_PyScript(interpreter, this); + customElements.define('py-script', this.PyScript); } - } - - const basicNormalize = typeof String.prototype.normalize == "function" - ? x => x.normalize("NFKD") : x => x; - /** - A search cursor provides an iterator over text matches in a - document. - */ - class SearchCursor { - /** - Create a text cursor. The query is the search string, `from` to - `to` provides the region to search. - - When `normalize` is given, it will be called, on both the query - string and the content it is matched against, before comparing. - You can, for example, create a case-insensitive search by - passing `s => s.toLowerCase()`. - - Text is always normalized with - [`.normalize("NFKD")`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/normalize) - (when supported). - */ - constructor(text, query, from = 0, to = text.length, normalize) { - /** - The current match (only holds a meaningful value after - [`next`](https://codemirror.net/6/docs/ref/#search.SearchCursor.next) has been called and when - `done` is false). - */ - this.value = { from: 0, to: 0 }; - /** - Whether the end of the iterated region has been reached. - */ - this.done = false; - this.matches = []; - this.buffer = ""; - this.bufferPos = 0; - this.iter = text.iterRange(from, to); - this.bufferStart = from; - this.normalize = normalize ? x => normalize(basicNormalize(x)) : basicNormalize; - this.query = this.normalize(query); - } - peek() { - if (this.bufferPos == this.buffer.length) { - this.bufferStart += this.buffer.length; - this.iter.next(); - if (this.iter.done) - return -1; - this.bufferPos = 0; - this.buffer = this.iter.value; - } - return codePointAt(this.buffer, this.bufferPos); - } - /** - Look for the next match. Updates the iterator's - [`value`](https://codemirror.net/6/docs/ref/#search.SearchCursor.value) and - [`done`](https://codemirror.net/6/docs/ref/#search.SearchCursor.done) properties. Should be called - at least once before using the cursor. - */ - next() { - while (this.matches.length) - this.matches.pop(); - return this.nextOverlapping(); - } - /** - The `next` method will ignore matches that partially overlap a - previous match. This method behaves like `next`, but includes - such matches. - */ - nextOverlapping() { - for (;;) { - let next = this.peek(); - if (next < 0) { - this.done = true; - return this; - } - let str = fromCodePoint(next), start = this.bufferStart + this.bufferPos; - this.bufferPos += codePointSize(next); - let norm = this.normalize(str); - for (let i = 0, pos = start;; i++) { - let code = norm.charCodeAt(i); - let match = this.match(code, pos); - if (match) { - this.value = match; - return this; - } - if (i == norm.length - 1) - break; - if (pos == start && i < str.length && str.charCodeAt(i) == code) - pos++; - } - } - } - match(code, pos) { - let match = null; - for (let i = 0; i < this.matches.length; i += 2) { - let index = this.matches[i], keep = false; - if (this.query.charCodeAt(index) == code) { - if (index == this.query.length - 1) { - match = { from: this.matches[i + 1], to: pos + 1 }; - } - else { - this.matches[i]++; - keep = true; - } - } - if (!keep) { - this.matches.splice(i, 2); - i -= 2; - } - } - if (this.query.charCodeAt(0) == code) { - if (this.query.length == 1) - match = { from: pos, to: pos + 1 }; - else - this.matches.push(1, pos); - } - return match; - } - } - if (typeof Symbol != "undefined") - SearchCursor.prototype[Symbol.iterator] = function () { return this; }; - - const empty = { from: -1, to: -1, match: /*@__PURE__*//.*/.exec("") }; - const baseFlags = "gm" + (/x/.unicode == null ? "" : "u"); - /** - This class is similar to [`SearchCursor`](https://codemirror.net/6/docs/ref/#search.SearchCursor) - but searches for a regular expression pattern instead of a plain - string. - */ - class RegExpCursor { - /** - Create a cursor that will search the given range in the given - document. `query` should be the raw pattern (as you'd pass it to - `new RegExp`). - */ - constructor(text, query, options, from = 0, to = text.length) { - this.to = to; - this.curLine = ""; - /** - Set to `true` when the cursor has reached the end of the search - range. - */ - this.done = false; - /** - Will contain an object with the extent of the match and the - match object when [`next`](https://codemirror.net/6/docs/ref/#search.RegExpCursor.next) - sucessfully finds a match. - */ - this.value = empty; - if (/\\[sWDnr]|\n|\r|\[\^/.test(query)) - return new MultilineRegExpCursor(text, query, options, from, to); - this.re = new RegExp(query, baseFlags + ((options === null || options === void 0 ? void 0 : options.ignoreCase) ? "i" : "")); - this.iter = text.iter(); - let startLine = text.lineAt(from); - this.curLineStart = startLine.from; - this.matchPos = from; - this.getLine(this.curLineStart); - } - getLine(skip) { - this.iter.next(skip); - if (this.iter.lineBreak) { - this.curLine = ""; - } - else { - this.curLine = this.iter.value; - if (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; - if (this.curLineStart > this.to) - this.curLine = ""; - else - this.getLine(0); - } - /** - Move to the next match, if there is one. - */ - next() { - for (let off = this.matchPos - this.curLineStart;;) { - this.re.lastIndex = off; - let match = this.matchPos <= this.to && this.re.exec(this.curLine); - if (match) { - let from = this.curLineStart + match.index, to = from + match[0].length; - this.matchPos = to + (from == to ? 1 : 0); - if (from == this.curLine.length) - this.nextLine(); - if (from < to || from > this.value.to) { - this.value = { from, to, match }; - return this; - } - off = this.matchPos - this.curLineStart; - } - else if (this.curLineStart + this.curLine.length < this.to) { - this.nextLine(); - off = 0; - } - else { - this.done = true; - return this; - } - } - } - } - const flattened = /*@__PURE__*/new WeakMap(); - // Reusable (partially) flattened document strings - class FlattenedDoc { - constructor(from, text) { - this.from = from; - this.text = text; - } - get to() { return this.from + this.text.length; } - static get(doc, from, to) { - let cached = flattened.get(doc); - if (!cached || cached.from >= to || cached.to <= from) { - let flat = new FlattenedDoc(from, doc.sliceString(from, to)); - flattened.set(doc, flat); - return flat; - } - if (cached.from == from && cached.to == to) - return cached; - let { text, from: cachedFrom } = cached; - if (cachedFrom > from) { - text = doc.sliceString(from, cachedFrom) + text; - cachedFrom = from; - } - if (cached.to < to) - text += doc.sliceString(cached.to, to); - flattened.set(doc, new FlattenedDoc(cachedFrom, text)); - return new FlattenedDoc(from, text.slice(from - cachedFrom, to - cachedFrom)); - } - } - class MultilineRegExpCursor { - constructor(text, query, options, from, to) { - this.text = text; - this.to = to; - this.done = false; - this.value = empty; - this.matchPos = from; - this.re = new RegExp(query, baseFlags + ((options === null || options === void 0 ? void 0 : options.ignoreCase) ? "i" : "")); - this.flat = FlattenedDoc.get(text, from, this.chunkEnd(from + 5000 /* Base */)); - } - chunkEnd(pos) { - return pos >= this.to ? this.to : this.text.lineAt(pos).to; - } - next() { - for (;;) { - let off = this.re.lastIndex = this.matchPos - this.flat.from; - let match = this.re.exec(this.flat.text); - // Skip empty matches directly after the last match - if (match && !match[0] && match.index == off) { - this.re.lastIndex = off + 1; - match = this.re.exec(this.flat.text); - } - // If a match goes almost to the end of a noncomplete chunk, try - // again, since it'll likely be able to match more - if (match && this.flat.to < this.to && match.index + match[0].length > this.flat.text.length - 10) - match = null; - if (match) { - let from = this.flat.from + match.index, to = from + match[0].length; - this.value = { from, to, match }; - this.matchPos = to + (from == to ? 1 : 0); - return this; - } - else { - if (this.flat.to == this.to) { - this.done = true; - return this; - } - // Grow the flattened doc - this.flat = FlattenedDoc.get(this.text, this.flat.from, this.chunkEnd(this.flat.from + this.flat.text.length * 2)); - } - } - } - } - if (typeof Symbol != "undefined") { - RegExpCursor.prototype[Symbol.iterator] = MultilineRegExpCursor.prototype[Symbol.iterator] = - function () { return this; }; - } - function validRegExp(source) { - try { - new RegExp(source, baseFlags); - return true; - } - catch (_a) { - return false; - } - } - - function createLineDialog(view) { - let input = crelt("input", { class: "cm-textfield", name: "line" }); - let dom = crelt("form", { - class: "cm-gotoLine", - onkeydown: (event) => { - if (event.keyCode == 27) { // Escape - event.preventDefault(); - view.dispatch({ effects: dialogEffect.of(false) }); - view.focus(); - } - else if (event.keyCode == 13) { // Enter - event.preventDefault(); - go(); - } - }, - onsubmit: (event) => { - event.preventDefault(); - go(); - } - }, crelt("label", view.state.phrase("Go to line"), ": ", input), " ", crelt("button", { class: "cm-button", type: "submit" }, view.state.phrase("go"))); - function go() { - let match = /^([+-])?(\d+)?(:\d+)?(%)?$/.exec(input.value); - if (!match) - return; - let { state } = view, startLine = state.doc.lineAt(state.selection.main.head); - let [, sign, ln, cl, percent] = match; - let col = cl ? +cl.slice(1) : 0; - let line = ln ? +ln : startLine.number; - if (ln && percent) { - let pc = line / 100; - if (sign) - pc = pc * (sign == "-" ? -1 : 1) + (startLine.number / state.doc.lines); - line = Math.round(state.doc.lines * pc); - } - else if (ln && sign) { - line = line * (sign == "-" ? -1 : 1) + startLine.number; - } - let docLine = state.doc.line(Math.max(1, Math.min(state.doc.lines, line))); - view.dispatch({ - effects: dialogEffect.of(false), - selection: EditorSelection.cursor(docLine.from + Math.max(0, Math.min(col, docLine.length))), - scrollIntoView: true - }); - view.focus(); - } - return { dom, pos: -10 }; - } - const dialogEffect = /*@__PURE__*/StateEffect.define(); - const dialogField = /*@__PURE__*/StateField.define({ - create() { return true; }, - update(value, tr) { - for (let e of tr.effects) - if (e.is(dialogEffect)) - value = e.value; - return value; - }, - provide: f => showPanel.from(f, val => val ? createLineDialog : null) - }); - /** - Command that shows a dialog asking the user for a line number, and - when a valid position is provided, moves the cursor to that line. - - Supports line numbers, relative line offsets prefixed with `+` or - `-`, document percentages suffixed with `%`, and an optional - column position by adding `:` and a second number after the line - number. - - The dialog can be styled with the `panel.gotoLine` theme - selector. - */ - const gotoLine = view => { - let panel = getPanel(view, createLineDialog); - if (!panel) { - let effects = [dialogEffect.of(true)]; - if (view.state.field(dialogField, false) == null) - effects.push(StateEffect.appendConfig.of([dialogField, baseTheme$1$1])); - view.dispatch({ effects }); - panel = getPanel(view, createLineDialog); - } - if (panel) - panel.dom.querySelector("input").focus(); - return true; - }; - const baseTheme$1$1 = /*@__PURE__*/EditorView.baseTheme({ - ".cm-panel.cm-gotoLine": { - padding: "2px 6px 4px", - "& label": { fontSize: "80%" } - } - }); - - const defaultHighlightOptions = { - highlightWordAroundCursor: false, - minSelectionLength: 1, - maxMatches: 100, - wholeWords: true - }; - const highlightConfig = /*@__PURE__*/Facet.define({ - combine(options) { - return combineConfig(options, defaultHighlightOptions, { - highlightWordAroundCursor: (a, b) => a || b, - minSelectionLength: Math.min, - maxMatches: Math.min - }); - } - }); - /** - This extension highlights text that matches the selection. It uses - the `"cm-selectionMatch"` class for the highlighting. When - `highlightWordAroundCursor` is enabled, the word at the cursor - itself will be highlighted with `"cm-selectionMatch-main"`. - */ - function highlightSelectionMatches(options) { - let ext = [defaultTheme, matchHighlighter]; - if (options) - ext.push(highlightConfig.of(options)); - return ext; - } - const matchDeco = /*@__PURE__*/Decoration.mark({ class: "cm-selectionMatch" }); - const mainMatchDeco = /*@__PURE__*/Decoration.mark({ class: "cm-selectionMatch cm-selectionMatch-main" }); - // Whether the characters directly outside the given positions are non-word characters - function insideWordBoundaries(check, state, from, to) { - return (from == 0 || check(state.sliceDoc(from - 1, from)) != CharCategory.Word) && - (to == state.doc.length || check(state.sliceDoc(to, to + 1)) != CharCategory.Word); - } - // Whether the characters directly at the given positions are word characters - function insideWord(check, state, from, to) { - return check(state.sliceDoc(from, from + 1)) == CharCategory.Word - && check(state.sliceDoc(to - 1, to)) == CharCategory.Word; - } - const matchHighlighter = /*@__PURE__*/ViewPlugin.fromClass(class { - constructor(view) { - this.decorations = this.getDeco(view); - } - update(update) { - if (update.selectionSet || update.docChanged || update.viewportChanged) - this.decorations = this.getDeco(update.view); - } - getDeco(view) { - let conf = view.state.facet(highlightConfig); - let { state } = view, sel = state.selection; - if (sel.ranges.length > 1) - return Decoration.none; - let range = sel.main, query, check = null; - if (range.empty) { - if (!conf.highlightWordAroundCursor) - return Decoration.none; - let word = state.wordAt(range.head); - if (!word) - return Decoration.none; - check = state.charCategorizer(range.head); - query = state.sliceDoc(word.from, word.to); - } - else { - let len = range.to - range.from; - if (len < conf.minSelectionLength || len > 200) - return Decoration.none; - if (conf.wholeWords) { - query = state.sliceDoc(range.from, range.to); // TODO: allow and include leading/trailing space? - check = state.charCategorizer(range.head); - if (!(insideWordBoundaries(check, state, range.from, range.to) - && insideWord(check, state, range.from, range.to))) - return Decoration.none; - } - else { - query = state.sliceDoc(range.from, range.to).trim(); - if (!query) - return Decoration.none; - } - } - let deco = []; - for (let part of view.visibleRanges) { - let cursor = new SearchCursor(state.doc, query, part.from, part.to); - while (!cursor.next().done) { - let { from, to } = cursor.value; - if (!check || insideWordBoundaries(check, state, from, to)) { - if (range.empty && from <= range.from && to >= range.to) - deco.push(mainMatchDeco.range(from, to)); - else if (from >= range.to || to <= range.from) - deco.push(matchDeco.range(from, to)); - if (deco.length > conf.maxMatches) - return Decoration.none; - } - } - } - return Decoration.set(deco); - } - }, { - decorations: v => v.decorations - }); - const defaultTheme = /*@__PURE__*/EditorView.baseTheme({ - ".cm-selectionMatch": { backgroundColor: "#99ff7780" }, - ".cm-searchMatch .cm-selectionMatch": { backgroundColor: "transparent" } - }); - // Select the words around the cursors. - const selectWord = ({ state, dispatch }) => { - let { selection } = state; - let newSel = EditorSelection.create(selection.ranges.map(range => state.wordAt(range.head) || EditorSelection.cursor(range.head)), selection.mainIndex); - if (newSel.eq(selection)) - return false; - dispatch(state.update({ selection: newSel })); - return true; - }; - // Find next occurrence of query relative to last cursor. Wrap around - // the document if there are no more matches. - function findNextOccurrence(state, query) { - let { main, ranges } = state.selection; - let word = state.wordAt(main.head), fullWord = word && word.from == main.from && word.to == main.to; - for (let cycled = false, cursor = new SearchCursor(state.doc, query, ranges[ranges.length - 1].to);;) { - cursor.next(); - if (cursor.done) { - if (cycled) - return null; - cursor = new SearchCursor(state.doc, query, 0, Math.max(0, ranges[ranges.length - 1].from - 1)); - cycled = true; - } - else { - if (cycled && ranges.some(r => r.from == cursor.value.from)) - continue; - if (fullWord) { - let word = state.wordAt(cursor.value.from); - if (!word || word.from != cursor.value.from || word.to != cursor.value.to) - continue; - } - return cursor.value; - } - } - } - /** - Select next occurrence of the current selection. - Expand selection to the word when selection range is empty. - */ - const selectNextOccurrence = ({ state, dispatch }) => { - let { ranges } = state.selection; - if (ranges.some(sel => sel.from === sel.to)) - return selectWord({ state, dispatch }); - let searchedText = state.sliceDoc(ranges[0].from, ranges[0].to); - if (state.selection.ranges.some(r => state.sliceDoc(r.from, r.to) != searchedText)) - return false; - let range = findNextOccurrence(state, searchedText); - if (!range) - return false; - dispatch(state.update({ - selection: state.selection.addRange(EditorSelection.range(range.from, range.to), false), - effects: EditorView.scrollIntoView(range.to) - })); - return true; - }; - - const searchConfigFacet = /*@__PURE__*/Facet.define({ - combine(configs) { - var _a; - return { - top: configs.reduce((val, conf) => val !== null && val !== void 0 ? val : conf.top, undefined) || false, - caseSensitive: configs.reduce((val, conf) => val !== null && val !== void 0 ? val : (conf.caseSensitive || conf.matchCase), undefined) || false, - createPanel: ((_a = configs.find(c => c.createPanel)) === null || _a === void 0 ? void 0 : _a.createPanel) || (view => new SearchPanel(view)) - }; - } - }); - /** - A search query. Part of the editor's search state. - */ - class SearchQuery { - /** - Create a query object. - */ - constructor(config) { - this.search = config.search; - this.caseSensitive = !!config.caseSensitive; - this.regexp = !!config.regexp; - this.replace = config.replace || ""; - this.valid = !!this.search && (!this.regexp || validRegExp(this.search)); - this.unquoted = this.search.replace(/\\([nrt\\])/g, (_, ch) => ch == "n" ? "\n" : ch == "r" ? "\r" : ch == "t" ? "\t" : "\\"); - } - /** - Compare this query to another query. - */ - eq(other) { - return this.search == other.search && this.replace == other.replace && - this.caseSensitive == other.caseSensitive && this.regexp == other.regexp; - } - /** - @internal - */ - create() { - return this.regexp ? new RegExpQuery(this) : new StringQuery(this); - } - getCursor(doc, from = 0, to = doc.length) { - return this.regexp ? regexpCursor(this, doc, from, to) : stringCursor(this, doc, from, to); - } - } - class QueryType { - constructor(spec) { - this.spec = spec; - } - } - function stringCursor(spec, doc, from, to) { - return new SearchCursor(doc, spec.unquoted, from, to, spec.caseSensitive ? undefined : x => x.toLowerCase()); - } - class StringQuery extends QueryType { - constructor(spec) { - super(spec); - } - nextMatch(doc, curFrom, curTo) { - let cursor = stringCursor(this.spec, doc, curTo, doc.length).nextOverlapping(); - if (cursor.done) - cursor = stringCursor(this.spec, doc, 0, curFrom).nextOverlapping(); - return cursor.done ? null : cursor.value; - } - // Searching in reverse is, rather than implementing inverted search - // cursor, done by scanning chunk after chunk forward. - prevMatchInRange(doc, from, to) { - for (let pos = to;;) { - let start = Math.max(from, pos - 10000 /* ChunkSize */ - this.spec.unquoted.length); - let cursor = stringCursor(this.spec, doc, start, pos), range = null; - while (!cursor.nextOverlapping().done) - range = cursor.value; - if (range) - return range; - if (start == from) - return null; - pos -= 10000 /* ChunkSize */; - } - } - prevMatch(doc, curFrom, curTo) { - return this.prevMatchInRange(doc, 0, curFrom) || - this.prevMatchInRange(doc, curTo, doc.length); - } - getReplacement(_result) { return this.spec.replace; } - matchAll(doc, limit) { - let cursor = stringCursor(this.spec, doc, 0, doc.length), ranges = []; - while (!cursor.next().done) { - if (ranges.length >= limit) - return null; - ranges.push(cursor.value); - } - return ranges; - } - highlight(doc, from, to, add) { - let cursor = stringCursor(this.spec, doc, Math.max(0, from - this.spec.unquoted.length), Math.min(to + this.spec.unquoted.length, doc.length)); - while (!cursor.next().done) - add(cursor.value.from, cursor.value.to); - } - } - function regexpCursor(spec, doc, from, to) { - return new RegExpCursor(doc, spec.search, spec.caseSensitive ? undefined : { ignoreCase: true }, from, to); - } - class RegExpQuery extends QueryType { - nextMatch(doc, curFrom, curTo) { - let cursor = regexpCursor(this.spec, doc, curTo, doc.length).next(); - if (cursor.done) - cursor = regexpCursor(this.spec, doc, 0, curFrom).next(); - return cursor.done ? null : cursor.value; - } - prevMatchInRange(doc, from, to) { - for (let size = 1;; size++) { - let start = Math.max(from, to - size * 10000 /* ChunkSize */); - let cursor = regexpCursor(this.spec, doc, start, to), range = null; - while (!cursor.next().done) - range = cursor.value; - if (range && (start == from || range.from > start + 10)) - return range; - if (start == from) - return null; - } - } - prevMatch(doc, curFrom, curTo) { - return this.prevMatchInRange(doc, 0, curFrom) || - this.prevMatchInRange(doc, curTo, doc.length); - } - getReplacement(result) { - return this.spec.replace.replace(/\$([$&\d+])/g, (m, i) => i == "$" ? "$" - : i == "&" ? result.match[0] - : i != "0" && +i < result.match.length ? result.match[i] - : m); - } - matchAll(doc, limit) { - let cursor = regexpCursor(this.spec, doc, 0, doc.length), ranges = []; - while (!cursor.next().done) { - if (ranges.length >= limit) - return null; - ranges.push(cursor.value); - } - return ranges; - } - highlight(doc, from, to, add) { - let cursor = regexpCursor(this.spec, doc, Math.max(0, from - 250 /* HighlightMargin */), Math.min(to + 250 /* HighlightMargin */, doc.length)); - while (!cursor.next().done) - add(cursor.value.from, cursor.value.to); - } - } - /** - A state effect that updates the current search query. Note that - this only has an effect if the search state has been initialized - (by including [`search`](https://codemirror.net/6/docs/ref/#search.search) in your configuration or - by running [`openSearchPanel`](https://codemirror.net/6/docs/ref/#search.openSearchPanel) at least - once). - */ - const setSearchQuery = /*@__PURE__*/StateEffect.define(); - const togglePanel$1 = /*@__PURE__*/StateEffect.define(); - const searchState = /*@__PURE__*/StateField.define({ - create(state) { - return new SearchState(defaultQuery(state).create(), null); - }, - update(value, tr) { - for (let effect of tr.effects) { - if (effect.is(setSearchQuery)) - value = new SearchState(effect.value.create(), value.panel); - else if (effect.is(togglePanel$1)) - value = new SearchState(value.query, effect.value ? createSearchPanel : null); - } - return value; - }, - provide: f => showPanel.from(f, val => val.panel) - }); - class SearchState { - constructor(query, panel) { - this.query = query; - this.panel = panel; - } - } - const matchMark = /*@__PURE__*/Decoration.mark({ class: "cm-searchMatch" }), selectedMatchMark = /*@__PURE__*/Decoration.mark({ class: "cm-searchMatch cm-searchMatch-selected" }); - const searchHighlighter = /*@__PURE__*/ViewPlugin.fromClass(class { - constructor(view) { - this.view = view; - this.decorations = this.highlight(view.state.field(searchState)); - } - update(update) { - let state = update.state.field(searchState); - if (state != update.startState.field(searchState) || update.docChanged || update.selectionSet || update.viewportChanged) - this.decorations = this.highlight(state); - } - highlight({ query, panel }) { - if (!panel || !query.spec.valid) - return Decoration.none; - let { view } = this; - let builder = new RangeSetBuilder(); - for (let i = 0, ranges = view.visibleRanges, l = ranges.length; i < l; i++) { - let { from, to } = ranges[i]; - while (i < l - 1 && to > ranges[i + 1].from - 2 * 250 /* HighlightMargin */) - to = ranges[++i].to; - query.highlight(view.state.doc, from, to, (from, to) => { - let selected = view.state.selection.ranges.some(r => r.from == from && r.to == to); - builder.add(from, to, selected ? selectedMatchMark : matchMark); - }); - } - return builder.finish(); - } - }, { - decorations: v => v.decorations - }); - function searchCommand(f) { - return view => { - let state = view.state.field(searchState, false); - return state && state.query.spec.valid ? f(view, state) : openSearchPanel(view); - }; - } - /** - Open the search panel if it isn't already open, and move the - selection to the first match after the current main selection. - Will wrap around to the start of the document when it reaches the - end. - */ - const findNext = /*@__PURE__*/searchCommand((view, { query }) => { - let { from, to } = view.state.selection.main; - let next = query.nextMatch(view.state.doc, from, to); - if (!next || next.from == from && next.to == to) - return false; - view.dispatch({ - selection: { anchor: next.from, head: next.to }, - scrollIntoView: true, - effects: announceMatch(view, next), - userEvent: "select.search" - }); - return true; - }); - /** - Move the selection to the previous instance of the search query, - before the current main selection. Will wrap past the start - of the document to start searching at the end again. - */ - const findPrevious = /*@__PURE__*/searchCommand((view, { query }) => { - let { state } = view, { from, to } = state.selection.main; - let range = query.prevMatch(state.doc, from, to); - if (!range) - return false; - view.dispatch({ - selection: { anchor: range.from, head: range.to }, - scrollIntoView: true, - effects: announceMatch(view, range), - userEvent: "select.search" - }); - return true; - }); - /** - Select all instances of the search query. - */ - const selectMatches = /*@__PURE__*/searchCommand((view, { query }) => { - let ranges = query.matchAll(view.state.doc, 1000); - if (!ranges || !ranges.length) - return false; - view.dispatch({ - selection: EditorSelection.create(ranges.map(r => EditorSelection.range(r.from, r.to))), - userEvent: "select.search.matches" - }); - return true; - }); - /** - Select all instances of the currently selected text. - */ - const selectSelectionMatches = ({ state, dispatch }) => { - let sel = state.selection; - if (sel.ranges.length > 1 || sel.main.empty) - return false; - let { from, to } = sel.main; - let ranges = [], main = 0; - for (let cur = new SearchCursor(state.doc, state.sliceDoc(from, to)); !cur.next().done;) { - if (ranges.length > 1000) - return false; - if (cur.value.from == from) - main = ranges.length; - ranges.push(EditorSelection.range(cur.value.from, cur.value.to)); - } - dispatch(state.update({ - selection: EditorSelection.create(ranges, main), - userEvent: "select.search.matches" - })); - return true; - }; - /** - Replace the current match of the search query. - */ - const replaceNext = /*@__PURE__*/searchCommand((view, { query }) => { - let { state } = view, { from, to } = state.selection.main; - if (state.readOnly) - return false; - let next = query.nextMatch(state.doc, from, from); - if (!next) - return false; - let changes = [], selection, replacement; - if (next.from == from && next.to == to) { - replacement = state.toText(query.getReplacement(next)); - changes.push({ from: next.from, to: next.to, insert: replacement }); - next = query.nextMatch(state.doc, next.from, next.to); - } - if (next) { - let off = changes.length == 0 || changes[0].from >= next.to ? 0 : next.to - next.from - replacement.length; - selection = { anchor: next.from - off, head: next.to - off }; - } - view.dispatch({ - changes, selection, - scrollIntoView: !!selection, - effects: next ? announceMatch(view, next) : undefined, - userEvent: "input.replace" - }); - return true; - }); - /** - Replace all instances of the search query with the given - replacement. - */ - const replaceAll = /*@__PURE__*/searchCommand((view, { query }) => { - if (view.state.readOnly) - return false; - let changes = query.matchAll(view.state.doc, 1e9).map(match => { - let { from, to } = match; - return { from, to, insert: query.getReplacement(match) }; - }); - if (!changes.length) - return false; - view.dispatch({ - changes, - userEvent: "input.replace.all" - }); - return true; - }); - function createSearchPanel(view) { - return view.state.facet(searchConfigFacet).createPanel(view); - } - function defaultQuery(state, fallback) { - var _a; - let sel = state.selection.main; - let selText = sel.empty || sel.to > sel.from + 100 ? "" : state.sliceDoc(sel.from, sel.to); - let caseSensitive = (_a = fallback === null || fallback === void 0 ? void 0 : fallback.caseSensitive) !== null && _a !== void 0 ? _a : state.facet(searchConfigFacet).caseSensitive; - return fallback && !selText ? fallback : new SearchQuery({ search: selText.replace(/\n/g, "\\n"), caseSensitive }); - } - /** - Make sure the search panel is open and focused. - */ - const openSearchPanel = view => { - let state = view.state.field(searchState, false); - if (state && state.panel) { - let panel = getPanel(view, createSearchPanel); - if (!panel) - return false; - let searchInput = panel.dom.querySelector("[name=search]"); - if (searchInput != view.root.activeElement) { - let query = defaultQuery(view.state, state.query.spec); - if (query.valid) - view.dispatch({ effects: setSearchQuery.of(query) }); - searchInput.focus(); - searchInput.select(); - } - } - else { - view.dispatch({ effects: [ - togglePanel$1.of(true), - state ? setSearchQuery.of(defaultQuery(view.state, state.query.spec)) : StateEffect.appendConfig.of(searchExtensions) - ] }); - } - return true; - }; - /** - Close the search panel. - */ - const closeSearchPanel = view => { - let state = view.state.field(searchState, false); - if (!state || !state.panel) - return false; - let panel = getPanel(view, createSearchPanel); - if (panel && panel.dom.contains(view.root.activeElement)) - view.focus(); - view.dispatch({ effects: togglePanel$1.of(false) }); - return true; - }; - /** - Default search-related key bindings. - - - Mod-f: [`openSearchPanel`](https://codemirror.net/6/docs/ref/#search.openSearchPanel) - - F3, Mod-g: [`findNext`](https://codemirror.net/6/docs/ref/#search.findNext) - - Shift-F3, Shift-Mod-g: [`findPrevious`](https://codemirror.net/6/docs/ref/#search.findPrevious) - - Alt-g: [`gotoLine`](https://codemirror.net/6/docs/ref/#search.gotoLine) - - Mod-d: [`selectNextOccurrence`](https://codemirror.net/6/docs/ref/#search.selectNextOccurrence) - */ - const searchKeymap = [ - { key: "Mod-f", run: openSearchPanel, scope: "editor search-panel" }, - { key: "F3", run: findNext, shift: findPrevious, scope: "editor search-panel", preventDefault: true }, - { key: "Mod-g", run: findNext, shift: findPrevious, scope: "editor search-panel", preventDefault: true }, - { key: "Escape", run: closeSearchPanel, scope: "editor search-panel" }, - { key: "Mod-Shift-l", run: selectSelectionMatches }, - { key: "Alt-g", run: gotoLine }, - { key: "Mod-d", run: selectNextOccurrence, preventDefault: true }, - ]; - class SearchPanel { - constructor(view) { - this.view = view; - let query = this.query = view.state.field(searchState).query.spec; - this.commit = this.commit.bind(this); - this.searchField = crelt("input", { - value: query.search, - placeholder: phrase(view, "Find"), - "aria-label": phrase(view, "Find"), - class: "cm-textfield", - name: "search", - onchange: this.commit, - onkeyup: this.commit - }); - this.replaceField = crelt("input", { - value: query.replace, - placeholder: phrase(view, "Replace"), - "aria-label": phrase(view, "Replace"), - class: "cm-textfield", - name: "replace", - onchange: this.commit, - onkeyup: this.commit - }); - this.caseField = crelt("input", { - type: "checkbox", - name: "case", - checked: query.caseSensitive, - onchange: this.commit - }); - this.reField = crelt("input", { - type: "checkbox", - name: "re", - checked: query.regexp, - onchange: this.commit - }); - function button(name, onclick, content) { - return crelt("button", { class: "cm-button", name, onclick, type: "button" }, content); - } - this.dom = crelt("div", { onkeydown: (e) => this.keydown(e), class: "cm-search" }, [ - this.searchField, - button("next", () => findNext(view), [phrase(view, "next")]), - button("prev", () => findPrevious(view), [phrase(view, "previous")]), - button("select", () => selectMatches(view), [phrase(view, "all")]), - crelt("label", null, [this.caseField, phrase(view, "match case")]), - crelt("label", null, [this.reField, phrase(view, "regexp")]), - ...view.state.readOnly ? [] : [ - crelt("br"), - this.replaceField, - button("replace", () => replaceNext(view), [phrase(view, "replace")]), - button("replaceAll", () => replaceAll(view), [phrase(view, "replace all")]), - crelt("button", { - name: "close", - onclick: () => closeSearchPanel(view), - "aria-label": phrase(view, "close"), - type: "button" - }, ["×"]) - ] - ]); - } - commit() { - let query = new SearchQuery({ - search: this.searchField.value, - caseSensitive: this.caseField.checked, - regexp: this.reField.checked, - replace: this.replaceField.value - }); - if (!query.eq(this.query)) { - this.query = query; - this.view.dispatch({ effects: setSearchQuery.of(query) }); - } - } - keydown(e) { - if (runScopeHandlers(this.view, e, "search-panel")) { - e.preventDefault(); - } - else if (e.keyCode == 13 && e.target == this.searchField) { - e.preventDefault(); - (e.shiftKey ? findPrevious : findNext)(this.view); - } - else if (e.keyCode == 13 && e.target == this.replaceField) { - e.preventDefault(); - replaceNext(this.view); - } - } - update(update) { - for (let tr of update.transactions) - for (let effect of tr.effects) { - if (effect.is(setSearchQuery) && !effect.value.eq(this.query)) - this.setQuery(effect.value); - } - } - setQuery(query) { - this.query = query; - this.searchField.value = query.search; - this.replaceField.value = query.replace; - this.caseField.checked = query.caseSensitive; - this.reField.checked = query.regexp; - } - mount() { - this.searchField.select(); - } - get pos() { return 80; } - get top() { return this.view.state.facet(searchConfigFacet).top; } - } - function phrase(view, phrase) { return view.state.phrase(phrase); } - const AnnounceMargin = 30; - const Break = /[\s\.,:;?!]/; - function announceMatch(view, { from, to }) { - let lineStart = view.state.doc.lineAt(from).from, lineEnd = view.state.doc.lineAt(to).to; - let start = Math.max(lineStart, from - AnnounceMargin), end = Math.min(lineEnd, to + AnnounceMargin); - let text = view.state.sliceDoc(start, end); - if (start != lineStart) { - for (let i = 0; i < AnnounceMargin; i++) - if (!Break.test(text[i + 1]) && Break.test(text[i])) { - text = text.slice(i); - break; - } - } - if (end != lineEnd) { - for (let i = text.length - 1; i > text.length - AnnounceMargin; i--) - if (!Break.test(text[i - 1]) && Break.test(text[i])) { - text = text.slice(0, i); - break; - } - } - return EditorView.announce.of(`${view.state.phrase("current match")}. ${text} ${view.state.phrase("on line")} ${view.state.doc.lineAt(from).number}`); - } - const baseTheme$3 = /*@__PURE__*/EditorView.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" } - }); - const searchExtensions = [ - searchState, - /*@__PURE__*/Prec.lowest(searchHighlighter), - baseTheme$3 - ]; - - const ios = typeof navigator != "undefined" && - !/*@__PURE__*//Edge\/(\d+)/.exec(navigator.userAgent) && /*@__PURE__*//Apple Computer/.test(navigator.vendor) && - (/*@__PURE__*//Mobile\/\w+/.test(navigator.userAgent) || navigator.maxTouchPoints > 2); - const Outside = "-10000px"; - class TooltipViewManager { - constructor(view, facet, createTooltipView) { - this.facet = facet; - this.createTooltipView = createTooltipView; - this.input = view.state.facet(facet); - this.tooltips = this.input.filter(t => t); - this.tooltipViews = this.tooltips.map(createTooltipView); - } - update(update) { - let input = update.state.facet(this.facet); - let tooltips = input.filter(x => x); - if (input === this.input) { - for (let t of this.tooltipViews) - if (t.update) - t.update(update); - return false; - } - let tooltipViews = []; - for (let i = 0; i < tooltips.length; i++) { - let tip = tooltips[i], known = -1; - if (!tip) - continue; - for (let i = 0; i < this.tooltips.length; i++) { - let other = this.tooltips[i]; - if (other && other.create == tip.create) - known = i; - } - if (known < 0) { - tooltipViews[i] = this.createTooltipView(tip); - } - else { - let tooltipView = tooltipViews[i] = this.tooltipViews[known]; - if (tooltipView.update) - tooltipView.update(update); - } - } - for (let t of this.tooltipViews) - if (tooltipViews.indexOf(t) < 0) - t.dom.remove(); - this.input = input; - this.tooltips = tooltips; - this.tooltipViews = tooltipViews; - return true; - } - } - function windowSpace() { - return { top: 0, left: 0, bottom: innerHeight, right: innerWidth }; - } - const tooltipConfig = /*@__PURE__*/Facet.define({ - combine: values => { - var _a, _b, _c; - return ({ - position: ios ? "absolute" : ((_a = values.find(conf => conf.position)) === null || _a === void 0 ? void 0 : _a.position) || "fixed", - parent: ((_b = values.find(conf => conf.parent)) === null || _b === void 0 ? void 0 : _b.parent) || null, - tooltipSpace: ((_c = values.find(conf => conf.tooltipSpace)) === null || _c === void 0 ? void 0 : _c.tooltipSpace) || windowSpace, - }); - } - }); - const tooltipPlugin = /*@__PURE__*/ViewPlugin.fromClass(class { - constructor(view) { - var _a; - this.view = view; - this.inView = true; - this.lastTransaction = 0; - this.measureTimeout = -1; - let config = view.state.facet(tooltipConfig); - this.position = config.position; - this.parent = config.parent; - this.classes = view.themeClasses; - this.createContainer(); - this.measureReq = { read: this.readMeasure.bind(this), write: this.writeMeasure.bind(this), key: this }; - this.manager = new TooltipViewManager(view, showTooltip, t => this.createTooltip(t)); - this.intersectionObserver = typeof IntersectionObserver == "function" ? new IntersectionObserver(entries => { - if (Date.now() > this.lastTransaction - 50 && - entries.length > 0 && entries[entries.length - 1].intersectionRatio < 1) - this.measureSoon(); - }, { threshold: [1] }) : null; - this.observeIntersection(); - (_a = view.dom.ownerDocument.defaultView) === null || _a === void 0 ? void 0 : _a.addEventListener("resize", this.measureSoon = this.measureSoon.bind(this)); - this.maybeMeasure(); - } - createContainer() { - if (this.parent) { - this.container = document.createElement("div"); - this.container.style.position = "relative"; - this.container.className = this.view.themeClasses; - this.parent.appendChild(this.container); - } - else { - this.container = this.view.dom; - } - } - observeIntersection() { - if (this.intersectionObserver) { - this.intersectionObserver.disconnect(); - for (let tooltip of this.manager.tooltipViews) - this.intersectionObserver.observe(tooltip.dom); - } - } - measureSoon() { - if (this.measureTimeout < 0) - this.measureTimeout = setTimeout(() => { - this.measureTimeout = -1; - this.maybeMeasure(); - }, 50); - } - update(update) { - if (update.transactions.length) - this.lastTransaction = Date.now(); - let updated = this.manager.update(update); - if (updated) - this.observeIntersection(); - let shouldMeasure = updated || update.geometryChanged; - let newConfig = update.state.facet(tooltipConfig); - if (newConfig.position != this.position) { - this.position = newConfig.position; - for (let t of this.manager.tooltipViews) - t.dom.style.position = this.position; - shouldMeasure = true; - } - if (newConfig.parent != this.parent) { - if (this.parent) - this.container.remove(); - this.parent = newConfig.parent; - this.createContainer(); - for (let t of this.manager.tooltipViews) - this.container.appendChild(t.dom); - shouldMeasure = true; - } - else if (this.parent && this.view.themeClasses != this.classes) { - this.classes = this.container.className = this.view.themeClasses; - } - if (shouldMeasure) - this.maybeMeasure(); - } - createTooltip(tooltip) { - let tooltipView = tooltip.create(this.view); - tooltipView.dom.classList.add("cm-tooltip"); - if (tooltip.arrow && !tooltipView.dom.querySelector(".cm-tooltip > .cm-tooltip-arrow")) { - let arrow = document.createElement("div"); - arrow.className = "cm-tooltip-arrow"; - tooltipView.dom.appendChild(arrow); - } - tooltipView.dom.style.position = this.position; - tooltipView.dom.style.top = Outside; - this.container.appendChild(tooltipView.dom); - if (tooltipView.mount) - tooltipView.mount(this.view); - return tooltipView; - } - destroy() { - var _a, _b; - (_a = this.view.dom.ownerDocument.defaultView) === null || _a === void 0 ? void 0 : _a.removeEventListener("resize", this.measureSoon); - for (let { dom } of this.manager.tooltipViews) - dom.remove(); - (_b = this.intersectionObserver) === null || _b === void 0 ? void 0 : _b.disconnect(); - clearTimeout(this.measureTimeout); - } - readMeasure() { - let editor = this.view.dom.getBoundingClientRect(); - return { - editor, - parent: this.parent ? this.container.getBoundingClientRect() : editor, - pos: this.manager.tooltips.map((t, i) => { - let tv = this.manager.tooltipViews[i]; - return tv.getCoords ? tv.getCoords(t.pos) : this.view.coordsAtPos(t.pos); - }), - size: this.manager.tooltipViews.map(({ dom }) => dom.getBoundingClientRect()), - space: this.view.state.facet(tooltipConfig).tooltipSpace(this.view), - }; - } - writeMeasure(measured) { - let { editor, space } = measured; - let others = []; - for (let i = 0; i < this.manager.tooltips.length; i++) { - let tooltip = this.manager.tooltips[i], tView = this.manager.tooltipViews[i], { dom } = tView; - let pos = measured.pos[i], size = measured.size[i]; - // Hide tooltips that are outside of the editor. - if (!pos || pos.bottom <= Math.max(editor.top, space.top) || - pos.top >= Math.min(editor.bottom, space.bottom) || - pos.right < Math.max(editor.left, space.left) - .1 || - pos.left > Math.min(editor.right, space.right) + .1) { - dom.style.top = Outside; - continue; - } - let arrow = tooltip.arrow ? tView.dom.querySelector(".cm-tooltip-arrow") : null; - let arrowHeight = arrow ? 7 /* Size */ : 0; - let width = size.right - size.left, height = size.bottom - size.top; - let offset = tView.offset || noOffset, ltr = this.view.textDirection == Direction.LTR; - let left = size.width > space.right - space.left ? (ltr ? space.left : space.right - size.width) - : ltr ? Math.min(pos.left - (arrow ? 14 /* Offset */ : 0) + offset.x, space.right - width) - : Math.max(space.left, pos.left - width + (arrow ? 14 /* Offset */ : 0) - offset.x); - let above = !!tooltip.above; - if (!tooltip.strictSide && (above - ? pos.top - (size.bottom - size.top) - offset.y < space.top - : pos.bottom + (size.bottom - size.top) + offset.y > space.bottom) && - above == (space.bottom - pos.bottom > pos.top - space.top)) - above = !above; - let top = above ? pos.top - height - arrowHeight - offset.y : pos.bottom + arrowHeight + offset.y; - let right = left + width; - if (tView.overlap !== true) - for (let r of others) - if (r.left < right && r.right > left && r.top < top + height && r.bottom > top) - top = above ? r.top - height - 2 - arrowHeight : r.bottom + arrowHeight + 2; - if (this.position == "absolute") { - dom.style.top = (top - measured.parent.top) + "px"; - dom.style.left = (left - measured.parent.left) + "px"; - } - else { - dom.style.top = top + "px"; - dom.style.left = left + "px"; - } - if (arrow) - arrow.style.left = `${pos.left + (ltr ? offset.x : -offset.x) - (left + 14 /* Offset */ - 7 /* Size */)}px`; - if (tView.overlap !== true) - others.push({ left, top, right, bottom: top + height }); - dom.classList.toggle("cm-tooltip-above", above); - dom.classList.toggle("cm-tooltip-below", !above); - if (tView.positioned) - tView.positioned(); - } - } - maybeMeasure() { - if (this.manager.tooltips.length) { - if (this.view.inView) - this.view.requestMeasure(this.measureReq); - if (this.inView != this.view.inView) { - this.inView = this.view.inView; - if (!this.inView) - for (let tv of this.manager.tooltipViews) - tv.dom.style.top = Outside; - } - } - } - }, { - eventHandlers: { - scroll() { this.maybeMeasure(); } - } - }); - const baseTheme$2 = /*@__PURE__*/EditorView.baseTheme({ - ".cm-tooltip": { - zIndex: 100 - }, - "&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: `${7 /* Size */}px`, - width: `${7 /* Size */ * 2}px`, - position: "absolute", - zIndex: -1, - overflow: "hidden", - "&:before, &:after": { - content: "''", - position: "absolute", - width: 0, - height: 0, - borderLeft: `${7 /* Size */}px solid transparent`, - borderRight: `${7 /* Size */}px solid transparent`, - }, - ".cm-tooltip-above &": { - bottom: `-${7 /* Size */}px`, - "&:before": { - borderTop: `${7 /* Size */}px solid #bbb`, - }, - "&:after": { - borderTop: `${7 /* Size */}px solid #f5f5f5`, - bottom: "1px" - } - }, - ".cm-tooltip-below &": { - top: `-${7 /* Size */}px`, - "&:before": { - borderBottom: `${7 /* Size */}px solid #bbb`, - }, - "&:after": { - borderBottom: `${7 /* Size */}px solid #f5f5f5`, - top: "1px" - } - }, - }, - "&dark .cm-tooltip .cm-tooltip-arrow": { - "&:before": { - borderTopColor: "#333338", - borderBottomColor: "#333338" - }, - "&:after": { - borderTopColor: "transparent", - borderBottomColor: "transparent" - } - } - }); - const noOffset = { x: 0, y: 0 }; - /** - Behavior by which an extension can provide a tooltip to be shown. - */ - const showTooltip = /*@__PURE__*/Facet.define({ - enables: [tooltipPlugin, baseTheme$2] - }); - const showHoverTooltip = /*@__PURE__*/Facet.define(); - class HoverTooltipHost { - constructor(view) { - this.view = view; - this.mounted = false; - this.dom = document.createElement("div"); - this.dom.classList.add("cm-tooltip-hover"); - this.manager = new TooltipViewManager(view, showHoverTooltip, t => this.createHostedView(t)); - } - // Needs to be static so that host tooltip instances always match - static create(view) { - return new HoverTooltipHost(view); - } - createHostedView(tooltip) { - let hostedView = tooltip.create(this.view); - hostedView.dom.classList.add("cm-tooltip-section"); - this.dom.appendChild(hostedView.dom); - if (this.mounted && hostedView.mount) - hostedView.mount(this.view); - return hostedView; - } - mount(view) { - for (let hostedView of this.manager.tooltipViews) { - if (hostedView.mount) - hostedView.mount(view); - } - this.mounted = true; - } - positioned() { - for (let hostedView of this.manager.tooltipViews) { - if (hostedView.positioned) - hostedView.positioned(); - } - } - update(update) { - this.manager.update(update); - } - } - const showHoverTooltipHost = /*@__PURE__*/showTooltip.compute([showHoverTooltip], state => { - let tooltips = state.facet(showHoverTooltip).filter(t => t); - if (tooltips.length === 0) - return null; - return { - pos: Math.min(...tooltips.map(t => t.pos)), - end: Math.max(...tooltips.filter(t => t.end != null).map(t => t.end)), - create: HoverTooltipHost.create, - above: tooltips[0].above, - arrow: tooltips.some(t => t.arrow), - }; - }); - class HoverPlugin { - constructor(view, source, field, setHover, hoverTime) { - this.view = view; - this.source = source; - this.field = field; - this.setHover = setHover; - this.hoverTime = hoverTime; - this.hoverTimeout = -1; - this.restartTimeout = -1; - this.pending = null; - this.lastMove = { x: 0, y: 0, target: view.dom, time: 0 }; - this.checkHover = this.checkHover.bind(this); - view.dom.addEventListener("mouseleave", this.mouseleave = this.mouseleave.bind(this)); - view.dom.addEventListener("mousemove", this.mousemove = this.mousemove.bind(this)); - } - update() { - if (this.pending) { - this.pending = null; - clearTimeout(this.restartTimeout); - this.restartTimeout = setTimeout(() => this.startHover(), 20); - } - } - get active() { - return this.view.state.field(this.field); - } - checkHover() { - this.hoverTimeout = -1; - if (this.active) - return; - let hovered = Date.now() - this.lastMove.time; - if (hovered < this.hoverTime) - this.hoverTimeout = setTimeout(this.checkHover, this.hoverTime - hovered); - else - this.startHover(); - } - startHover() { - var _a; - clearTimeout(this.restartTimeout); - let { lastMove } = this; - let pos = this.view.contentDOM.contains(lastMove.target) ? this.view.posAtCoords(lastMove) : null; - if (pos == null) - return; - let posCoords = this.view.coordsAtPos(pos); - if (posCoords == null || lastMove.y < posCoords.top || lastMove.y > posCoords.bottom || - lastMove.x < posCoords.left - this.view.defaultCharacterWidth || - lastMove.x > posCoords.right + this.view.defaultCharacterWidth) - return; - let bidi = this.view.bidiSpans(this.view.state.doc.lineAt(pos)).find(s => s.from <= pos && s.to >= pos); - let rtl = bidi && bidi.dir == Direction.RTL ? -1 : 1; - let open = this.source(this.view, pos, (lastMove.x < posCoords.left ? -rtl : rtl)); - if ((_a = open) === null || _a === void 0 ? void 0 : _a.then) { - let pending = this.pending = { pos }; - open.then(result => { - if (this.pending == pending) { - this.pending = null; - if (result) - this.view.dispatch({ effects: this.setHover.of(result) }); - } - }, e => logException(this.view.state, e, "hover tooltip")); - } - else if (open) { - this.view.dispatch({ effects: this.setHover.of(open) }); - } - } - mousemove(event) { - var _a; - this.lastMove = { x: event.clientX, y: event.clientY, target: event.target, time: Date.now() }; - if (this.hoverTimeout < 0) - this.hoverTimeout = setTimeout(this.checkHover, this.hoverTime); - let tooltip = this.active; - if (tooltip && !isInTooltip(this.lastMove.target) || this.pending) { - let { pos } = tooltip || this.pending, end = (_a = tooltip === null || tooltip === void 0 ? void 0 : tooltip.end) !== null && _a !== void 0 ? _a : pos; - if ((pos == end ? this.view.posAtCoords(this.lastMove) != pos - : !isOverRange(this.view, pos, end, event.clientX, event.clientY, 6 /* MaxDist */))) { - this.view.dispatch({ effects: this.setHover.of(null) }); - this.pending = null; - } - } - } - mouseleave() { - clearTimeout(this.hoverTimeout); - this.hoverTimeout = -1; - if (this.active) - this.view.dispatch({ effects: this.setHover.of(null) }); - } - destroy() { - clearTimeout(this.hoverTimeout); - this.view.dom.removeEventListener("mouseleave", this.mouseleave); - this.view.dom.removeEventListener("mousemove", this.mousemove); - } - } - function isInTooltip(elt) { - for (let cur = elt; cur; cur = cur.parentNode) - if (cur.nodeType == 1 && cur.classList.contains("cm-tooltip")) - return true; - return false; - } - function isOverRange(view, from, to, x, y, margin) { - let range = document.createRange(); - let fromDOM = view.domAtPos(from), toDOM = view.domAtPos(to); - range.setEnd(toDOM.node, toDOM.offset); - range.setStart(fromDOM.node, fromDOM.offset); - let rects = range.getClientRects(); - range.detach(); - for (let i = 0; i < rects.length; i++) { - let rect = rects[i]; - let dist = Math.max(rect.top - y, y - rect.bottom, rect.left - x, x - rect.right); - if (dist <= margin) - return true; - } - return false; - } - /** - Enable a hover tooltip, which shows up when the pointer hovers - over ranges of text. The callback is called when the mouse hovers - over the document text. It should, if there is a tooltip - associated with position `pos` return the tooltip description - (either directly or in a promise). The `side` argument indicates - on which side of the position the pointer is—it will be -1 if the - pointer is before the position, 1 if after the position. - - Note that all hover tooltips are hosted within a single tooltip - container element. This allows multiple tooltips over the same - range to be "merged" together without overlapping. - */ - function hoverTooltip(source, options = {}) { - let setHover = StateEffect.define(); - let hoverState = StateField.define({ - create() { return null; }, - update(value, tr) { - if (value && (options.hideOnChange && (tr.docChanged || tr.selection))) - return null; - for (let effect of tr.effects) { - if (effect.is(setHover)) - return effect.value; - if (effect.is(closeHoverTooltipEffect)) - return null; - } - if (value && tr.docChanged) { - let newPos = tr.changes.mapPos(value.pos, -1, MapMode.TrackDel); - if (newPos == null) - return null; - let copy = Object.assign(Object.create(null), value); - copy.pos = newPos; - if (value.end != null) - copy.end = tr.changes.mapPos(value.end); - return copy; - } - return value; - }, - provide: f => showHoverTooltip.from(f) - }); - return [ - hoverState, - ViewPlugin.define(view => new HoverPlugin(view, source, hoverState, setHover, options.hoverTime || 300 /* Time */)), - showHoverTooltipHost - ]; - } - /** - Get the active tooltip view for a given tooltip, if available. - */ - function getTooltip(view, tooltip) { - let plugin = view.plugin(tooltipPlugin); - if (!plugin) - return null; - let found = plugin.manager.tooltips.indexOf(tooltip); - return found < 0 ? null : plugin.manager.tooltipViews[found]; - } - const closeHoverTooltipEffect = /*@__PURE__*/StateEffect.define(); - - /** - An instance of this is passed to completion source functions. - */ - class CompletionContext { - /** - Create a new completion context. (Mostly useful for testing - completion sources—in the editor, the extension will create - these for you.) - */ - constructor( - /** - The editor state that the completion happens in. - */ - state, - /** - The position at which the completion is happening. - */ - pos, - /** - Indicates whether completion was activated explicitly, or - implicitly by typing. The usual way to respond to this is to - only return completions when either there is part of a - completable entity before the cursor, or `explicit` is true. - */ - explicit) { - this.state = state; - this.pos = pos; - this.explicit = explicit; - /** - @internal - */ - this.abortListeners = []; - } - /** - Get the extent, content, and (if there is a token) type of the - token before `this.pos`. - */ - tokenBefore(types) { - let token = syntaxTree(this.state).resolveInner(this.pos, -1); - while (token && types.indexOf(token.name) < 0) - token = token.parent; - return token ? { from: token.from, to: this.pos, - text: this.state.sliceDoc(token.from, this.pos), - type: token.type } : null; - } - /** - Get the match of the given expression directly before the - cursor. - */ - matchBefore(expr) { - let line = this.state.doc.lineAt(this.pos); - let start = Math.max(line.from, this.pos - 250); - let str = line.text.slice(start - line.from, this.pos - line.from); - let found = str.search(ensureAnchor(expr, false)); - return found < 0 ? null : { from: start + found, to: this.pos, text: str.slice(found) }; - } - /** - Yields true when the query has been aborted. Can be useful in - asynchronous queries to avoid doing work that will be ignored. - */ - get aborted() { return this.abortListeners == null; } - /** - Allows you to register abort handlers, which will be called when - the query is - [aborted](https://codemirror.net/6/docs/ref/#autocomplete.CompletionContext.aborted). - */ - addEventListener(type, listener) { - if (type == "abort" && this.abortListeners) - this.abortListeners.push(listener); - } - } - function toSet(chars) { - let flat = Object.keys(chars).join(""); - let words = /\w/.test(flat); - if (words) - flat = flat.replace(/\w/g, ""); - return `[${words ? "\\w" : ""}${flat.replace(/[^\w\s]/g, "\\$&")}]`; - } - function prefixMatch(options) { - let first = Object.create(null), rest = Object.create(null); - for (let { label } of options) { - first[label[0]] = true; - for (let i = 1; i < label.length; i++) - rest[label[i]] = true; - } - let source = toSet(first) + toSet(rest) + "*$"; - return [new RegExp("^" + source), new RegExp(source)]; - } - /** - Given a a fixed array of options, return an autocompleter that - completes them. - */ - function completeFromList(list) { - let options = list.map(o => typeof o == "string" ? { label: o } : o); - let [span, match] = options.every(o => /^\w+$/.test(o.label)) ? [/\w*$/, /\w+$/] : prefixMatch(options); - return (context) => { - let token = context.matchBefore(match); - return token || context.explicit ? { from: token ? token.from : context.pos, options, span } : null; - }; - } - class Option { - constructor(completion, source, match) { - this.completion = completion; - this.source = source; - this.match = match; - } - } - function cur(state) { return state.selection.main.head; } - // Make sure the given regexp has a $ at its end and, if `start` is - // true, a ^ at its start. - function ensureAnchor(expr, start) { - var _a; - let { source } = expr; - let addStart = start && source[0] != "^", addEnd = source[source.length - 1] != "$"; - if (!addStart && !addEnd) - return expr; - return new RegExp(`${addStart ? "^" : ""}(?:${source})${addEnd ? "$" : ""}`, (_a = expr.flags) !== null && _a !== void 0 ? _a : (expr.ignoreCase ? "i" : "")); - } - /** - This annotation is added to transactions that are produced by - picking a completion. - */ - const pickedCompletion = /*@__PURE__*/Annotation.define(); - function applyCompletion(view, option) { - let apply = option.completion.apply || option.completion.label; - let result = option.source; - if (typeof apply == "string") { - view.dispatch({ - changes: { from: result.from, to: result.to, insert: apply }, - selection: { anchor: result.from + apply.length }, - userEvent: "input.complete", - annotations: pickedCompletion.of(option.completion) - }); - } - else { - apply(view, option.completion, result.from, result.to); - } - } - const SourceCache = /*@__PURE__*/new WeakMap(); - function asSource(source) { - if (!Array.isArray(source)) - return source; - let known = SourceCache.get(source); - if (!known) - SourceCache.set(source, known = completeFromList(source)); - return known; - } - - // A pattern matcher for fuzzy completion matching. Create an instance - // once for a pattern, and then use that to match any number of - // completions. - class FuzzyMatcher { - constructor(pattern) { - this.pattern = pattern; - this.chars = []; - this.folded = []; - // Buffers reused by calls to `match` to track matched character - // positions. - this.any = []; - this.precise = []; - this.byWord = []; - for (let p = 0; p < pattern.length;) { - let char = codePointAt(pattern, p), size = codePointSize(char); - this.chars.push(char); - let part = pattern.slice(p, p + size), upper = part.toUpperCase(); - this.folded.push(codePointAt(upper == part ? part.toLowerCase() : upper, 0)); - p += size; - } - this.astral = pattern.length != this.chars.length; - } - // Matches a given word (completion) against the pattern (input). - // Will return null for no match, and otherwise an array that starts - // with the match score, followed by any number of `from, to` pairs - // indicating the matched parts of `word`. - // - // The score is a number that is more negative the worse the match - // is. See `Penalty` above. - match(word) { - if (this.pattern.length == 0) - return [0]; - if (word.length < this.pattern.length) - return null; - let { chars, folded, any, precise, byWord } = this; - // For single-character queries, only match when they occur right - // at the start - if (chars.length == 1) { - let first = codePointAt(word, 0); - return first == chars[0] ? [0, 0, codePointSize(first)] - : first == folded[0] ? [-200 /* CaseFold */, 0, codePointSize(first)] : null; - } - let direct = word.indexOf(this.pattern); - if (direct == 0) - return [0, 0, this.pattern.length]; - let len = chars.length, anyTo = 0; - if (direct < 0) { - for (let i = 0, e = Math.min(word.length, 200); i < e && anyTo < len;) { - let next = codePointAt(word, i); - if (next == chars[anyTo] || next == folded[anyTo]) - any[anyTo++] = i; - i += codePointSize(next); - } - // No match, exit immediately - if (anyTo < len) - return null; - } - // This tracks the extent of the precise (non-folded, not - // necessarily adjacent) match - let preciseTo = 0; - // Tracks whether there is a match that hits only characters that - // appear to be starting words. `byWordFolded` is set to true when - // a case folded character is encountered in such a match - let byWordTo = 0, byWordFolded = false; - // If we've found a partial adjacent match, these track its state - let adjacentTo = 0, adjacentStart = -1, adjacentEnd = -1; - let hasLower = /[a-z]/.test(word), wordAdjacent = true; - // Go over the option's text, scanning for the various kinds of matches - for (let i = 0, e = Math.min(word.length, 200), prevType = 0 /* NonWord */; i < e && byWordTo < len;) { - let next = codePointAt(word, i); - if (direct < 0) { - if (preciseTo < len && next == chars[preciseTo]) - precise[preciseTo++] = i; - if (adjacentTo < len) { - if (next == chars[adjacentTo] || next == folded[adjacentTo]) { - if (adjacentTo == 0) - adjacentStart = i; - adjacentEnd = i + 1; - adjacentTo++; - } - else { - adjacentTo = 0; - } - } - } - let ch, type = next < 0xff - ? (next >= 48 && next <= 57 || next >= 97 && next <= 122 ? 2 /* Lower */ : next >= 65 && next <= 90 ? 1 /* Upper */ : 0 /* NonWord */) - : ((ch = fromCodePoint(next)) != ch.toLowerCase() ? 1 /* Upper */ : ch != ch.toUpperCase() ? 2 /* Lower */ : 0 /* NonWord */); - if (!i || type == 1 /* Upper */ && hasLower || prevType == 0 /* NonWord */ && type != 0 /* NonWord */) { - if (chars[byWordTo] == next || (folded[byWordTo] == next && (byWordFolded = true))) - byWord[byWordTo++] = i; - else if (byWord.length) - wordAdjacent = false; - } - prevType = type; - i += codePointSize(next); - } - if (byWordTo == len && byWord[0] == 0 && wordAdjacent) - return this.result(-100 /* ByWord */ + (byWordFolded ? -200 /* CaseFold */ : 0), byWord, word); - if (adjacentTo == len && adjacentStart == 0) - return [-200 /* CaseFold */ - word.length, 0, adjacentEnd]; - if (direct > -1) - return [-700 /* NotStart */ - word.length, direct, direct + this.pattern.length]; - if (adjacentTo == len) - return [-200 /* CaseFold */ + -700 /* NotStart */ - word.length, adjacentStart, adjacentEnd]; - if (byWordTo == len) - return this.result(-100 /* ByWord */ + (byWordFolded ? -200 /* CaseFold */ : 0) + -700 /* NotStart */ + - (wordAdjacent ? 0 : -1100 /* Gap */), byWord, word); - return chars.length == 2 ? null : this.result((any[0] ? -700 /* NotStart */ : 0) + -200 /* CaseFold */ + -1100 /* Gap */, any, word); - } - result(score, positions, word) { - let result = [score - word.length], i = 1; - for (let pos of positions) { - let to = pos + (this.astral ? codePointSize(codePointAt(word, pos)) : 1); - if (i > 1 && result[i - 1] == pos) - result[i - 1] = to; - else { - result[i++] = pos; - result[i++] = to; - } - } - return result; - } - } - - const completionConfig = /*@__PURE__*/Facet.define({ - combine(configs) { - return combineConfig(configs, { - activateOnTyping: true, - override: null, - maxRenderedOptions: 100, - defaultKeymap: true, - optionClass: () => "", - aboveCursor: false, - icons: true, - addToOptions: [] - }, { - defaultKeymap: (a, b) => a && b, - icons: (a, b) => a && b, - optionClass: (a, b) => c => joinClass(a(c), b(c)), - addToOptions: (a, b) => a.concat(b) - }); - } - }); - function joinClass(a, b) { - return a ? b ? a + " " + b : a : b; - } - - function optionContent(config) { - let content = config.addToOptions.slice(); - if (config.icons) - content.push({ - render(completion) { - let icon = document.createElement("div"); - icon.classList.add("cm-completionIcon"); - if (completion.type) - icon.classList.add(...completion.type.split(/\s+/g).map(cls => "cm-completionIcon-" + cls)); - icon.setAttribute("aria-hidden", "true"); - return icon; - }, - position: 20 - }); - content.push({ - render(completion, _s, match) { - let labelElt = document.createElement("span"); - labelElt.className = "cm-completionLabel"; - let { label } = completion, off = 0; - for (let j = 1; j < match.length;) { - let from = match[j++], to = match[j++]; - if (from > off) - labelElt.appendChild(document.createTextNode(label.slice(off, from))); - let span = labelElt.appendChild(document.createElement("span")); - span.appendChild(document.createTextNode(label.slice(from, to))); - span.className = "cm-completionMatchedText"; - off = to; - } - if (off < label.length) - labelElt.appendChild(document.createTextNode(label.slice(off))); - return labelElt; - }, - position: 50 - }, { - render(completion) { - if (!completion.detail) - return null; - let detailElt = document.createElement("span"); - detailElt.className = "cm-completionDetail"; - detailElt.textContent = completion.detail; - return detailElt; - }, - position: 80 - }); - return content.sort((a, b) => a.position - b.position).map(a => a.render); - } - function rangeAroundSelected(total, selected, max) { - if (total <= max) - return { from: 0, to: total }; - if (selected <= (total >> 1)) { - let off = Math.floor(selected / max); - return { from: off * max, to: (off + 1) * max }; - } - let off = Math.floor((total - selected) / max); - return { from: total - (off + 1) * max, to: total - off * max }; - } - class CompletionTooltip { - constructor(view, stateField) { - this.view = view; - this.stateField = stateField; - this.info = null; - this.placeInfo = { - read: () => this.measureInfo(), - write: (pos) => this.positionInfo(pos), - key: this - }; - let cState = view.state.field(stateField); - let { options, selected } = cState.open; - let config = view.state.facet(completionConfig); - this.optionContent = optionContent(config); - this.optionClass = config.optionClass; - this.range = rangeAroundSelected(options.length, selected, config.maxRenderedOptions); - this.dom = document.createElement("div"); - this.dom.className = "cm-tooltip-autocomplete"; - this.dom.addEventListener("mousedown", (e) => { - for (let dom = e.target, match; dom && dom != this.dom; dom = dom.parentNode) { - if (dom.nodeName == "LI" && (match = /-(\d+)$/.exec(dom.id)) && +match[1] < options.length) { - applyCompletion(view, options[+match[1]]); - e.preventDefault(); - return; - } - } - }); - this.list = this.dom.appendChild(this.createListBox(options, cState.id, this.range)); - this.list.addEventListener("scroll", () => { - if (this.info) - this.view.requestMeasure(this.placeInfo); - }); - } - mount() { this.updateSel(); } - update(update) { - if (update.state.field(this.stateField) != update.startState.field(this.stateField)) - this.updateSel(); - } - positioned() { - if (this.info) - this.view.requestMeasure(this.placeInfo); - } - updateSel() { - let cState = this.view.state.field(this.stateField), open = cState.open; - if (open.selected < this.range.from || open.selected >= this.range.to) { - this.range = rangeAroundSelected(open.options.length, open.selected, this.view.state.facet(completionConfig).maxRenderedOptions); - this.list.remove(); - this.list = this.dom.appendChild(this.createListBox(open.options, cState.id, this.range)); - this.list.addEventListener("scroll", () => { - if (this.info) - this.view.requestMeasure(this.placeInfo); - }); - } - if (this.updateSelectedOption(open.selected)) { - if (this.info) { - this.info.remove(); - this.info = null; - } - let { completion } = open.options[open.selected]; - let { info } = completion; - if (!info) - return; - let infoResult = typeof info === 'string' ? document.createTextNode(info) : info(completion); - if (!infoResult) - return; - if ('then' in infoResult) { - infoResult.then(node => { - if (node && this.view.state.field(this.stateField, false) == cState) - this.addInfoPane(node); - }).catch(e => logException(this.view.state, e, "completion info")); - } - else { - this.addInfoPane(infoResult); - } - } - } - addInfoPane(content) { - let dom = this.info = document.createElement("div"); - dom.className = "cm-tooltip cm-completionInfo"; - dom.appendChild(content); - this.dom.appendChild(dom); - this.view.requestMeasure(this.placeInfo); - } - updateSelectedOption(selected) { - let set = null; - for (let opt = this.list.firstChild, i = this.range.from; opt; opt = opt.nextSibling, i++) { - if (i == selected) { - if (!opt.hasAttribute("aria-selected")) { - opt.setAttribute("aria-selected", "true"); - set = opt; - } - } - else { - if (opt.hasAttribute("aria-selected")) - opt.removeAttribute("aria-selected"); - } - } - if (set) - scrollIntoView(this.list, set); - return set; - } - measureInfo() { - let sel = this.dom.querySelector("[aria-selected]"); - if (!sel || !this.info) - return null; - let listRect = this.dom.getBoundingClientRect(); - let infoRect = this.info.getBoundingClientRect(); - let selRect = sel.getBoundingClientRect(); - if (selRect.top > Math.min(innerHeight, listRect.bottom) - 10 || selRect.bottom < Math.max(0, listRect.top) + 10) - return null; - let top = Math.max(0, Math.min(selRect.top, innerHeight - infoRect.height)) - listRect.top; - let left = this.view.textDirection == Direction.RTL; - let spaceLeft = listRect.left, spaceRight = innerWidth - listRect.right; - if (left && spaceLeft < Math.min(infoRect.width, spaceRight)) - left = false; - else if (!left && spaceRight < Math.min(infoRect.width, spaceLeft)) - left = true; - return { top, left }; - } - positionInfo(pos) { - if (this.info) { - this.info.style.top = (pos ? pos.top : -1e6) + "px"; - if (pos) { - this.info.classList.toggle("cm-completionInfo-left", pos.left); - this.info.classList.toggle("cm-completionInfo-right", !pos.left); - } - } - } - createListBox(options, id, range) { - const ul = document.createElement("ul"); - ul.id = id; - ul.setAttribute("role", "listbox"); - ul.setAttribute("aria-expanded", "true"); - for (let i = range.from; i < range.to; i++) { - let { completion, match } = options[i]; - const li = ul.appendChild(document.createElement("li")); - li.id = id + "-" + i; - li.setAttribute("role", "option"); - let cls = this.optionClass(completion); - if (cls) - li.className = cls; - for (let source of this.optionContent) { - let node = source(completion, this.view.state, match); - if (node) - li.appendChild(node); - } - } - if (range.from) - ul.classList.add("cm-completionListIncompleteTop"); - if (range.to < options.length) - ul.classList.add("cm-completionListIncompleteBottom"); - return ul; - } - } - // We allocate a new function instance every time the completion - // changes to force redrawing/repositioning of the tooltip - function completionTooltip(stateField) { - return (view) => new CompletionTooltip(view, stateField); - } - function scrollIntoView(container, element) { - let parent = container.getBoundingClientRect(); - let self = element.getBoundingClientRect(); - if (self.top < parent.top) - container.scrollTop -= parent.top - self.top; - else if (self.bottom > parent.bottom) - container.scrollTop += self.bottom - parent.bottom; - } - - const MaxOptions = 300; - // Used to pick a preferred option when two options with the same - // label occur in the result. - function score(option) { - return (option.boost || 0) * 100 + (option.apply ? 10 : 0) + (option.info ? 5 : 0) + - (option.type ? 1 : 0); - } - function sortOptions(active, state) { - let options = [], i = 0; - for (let a of active) - if (a.hasResult()) { - if (a.result.filter === false) { - for (let option of a.result.options) - options.push(new Option(option, a, [1e9 - i++])); - } - else { - let matcher = new FuzzyMatcher(state.sliceDoc(a.from, a.to)), match; - for (let option of a.result.options) - if (match = matcher.match(option.label)) { - if (option.boost != null) - match[0] += option.boost; - options.push(new Option(option, a, match)); - } - } - } - let result = [], prev = null; - for (let opt of options.sort(cmpOption)) { - if (result.length == MaxOptions) - break; - if (!prev || prev.label != opt.completion.label || prev.detail != opt.completion.detail || - prev.type != opt.completion.type || prev.apply != opt.completion.apply) - result.push(opt); - else if (score(opt.completion) > score(prev)) - result[result.length - 1] = opt; - prev = opt.completion; - } - return result; - } - class CompletionDialog { - constructor(options, attrs, tooltip, timestamp, selected) { - this.options = options; - this.attrs = attrs; - this.tooltip = tooltip; - this.timestamp = timestamp; - this.selected = selected; - } - setSelected(selected, id) { - return selected == this.selected || selected >= this.options.length ? this - : new CompletionDialog(this.options, makeAttrs(id, selected), this.tooltip, this.timestamp, selected); - } - static build(active, state, id, prev, conf) { - let options = sortOptions(active, state); - if (!options.length) - return null; - let selected = 0; - if (prev && prev.selected) { - let selectedValue = prev.options[prev.selected].completion; - for (let i = 0; i < options.length; i++) - if (options[i].completion == selectedValue) { - selected = i; - break; - } - } - return new CompletionDialog(options, makeAttrs(id, selected), { - pos: active.reduce((a, b) => b.hasResult() ? Math.min(a, b.from) : a, 1e8), - create: completionTooltip(completionState), - above: conf.aboveCursor, - }, prev ? prev.timestamp : Date.now(), selected); - } - map(changes) { - return new CompletionDialog(this.options, this.attrs, Object.assign(Object.assign({}, this.tooltip), { pos: changes.mapPos(this.tooltip.pos) }), this.timestamp, this.selected); - } - } - class CompletionState { - constructor(active, id, open) { - this.active = active; - this.id = id; - this.open = open; - } - static start() { - return new CompletionState(none, "cm-ac-" + Math.floor(Math.random() * 2e6).toString(36), null); - } - update(tr) { - let { state } = tr, conf = state.facet(completionConfig); - let sources = conf.override || - state.languageDataAt("autocomplete", cur(state)).map(asSource); - let active = sources.map(source => { - let value = this.active.find(s => s.source == source) || - new ActiveSource(source, this.active.some(a => a.state != 0 /* Inactive */) ? 1 /* Pending */ : 0 /* Inactive */); - return value.update(tr, conf); - }); - if (active.length == this.active.length && active.every((a, i) => a == this.active[i])) - active = this.active; - let open = tr.selection || active.some(a => a.hasResult() && tr.changes.touchesRange(a.from, a.to)) || - !sameResults(active, this.active) ? CompletionDialog.build(active, state, this.id, this.open, conf) - : this.open && tr.docChanged ? this.open.map(tr.changes) : this.open; - if (!open && active.every(a => a.state != 1 /* Pending */) && active.some(a => a.hasResult())) - active = active.map(a => a.hasResult() ? new ActiveSource(a.source, 0 /* Inactive */) : a); - for (let effect of tr.effects) - if (effect.is(setSelectedEffect)) - open = open && open.setSelected(effect.value, this.id); - return active == this.active && open == this.open ? this : new CompletionState(active, this.id, open); - } - get tooltip() { return this.open ? this.open.tooltip : null; } - get attrs() { return this.open ? this.open.attrs : baseAttrs; } - } - function sameResults(a, b) { - if (a == b) - return true; - for (let iA = 0, iB = 0;;) { - while (iA < a.length && !a[iA].hasResult) - iA++; - while (iB < b.length && !b[iB].hasResult) - iB++; - let endA = iA == a.length, endB = iB == b.length; - if (endA || endB) - return endA == endB; - if (a[iA++].result != b[iB++].result) - return false; - } - } - const baseAttrs = { - "aria-autocomplete": "list" - }; - function makeAttrs(id, selected) { - return { - "aria-autocomplete": "list", - "aria-haspopup": "listbox", - "aria-activedescendant": id + "-" + selected, - "aria-controls": id - }; - } - const none = []; - function cmpOption(a, b) { - let dScore = b.match[0] - a.match[0]; - if (dScore) - return dScore; - return a.completion.label.localeCompare(b.completion.label); - } - function getUserEvent(tr) { - return tr.isUserEvent("input.type") ? "input" : tr.isUserEvent("delete.backward") ? "delete" : null; - } - class ActiveSource { - constructor(source, state, explicitPos = -1) { - this.source = source; - this.state = state; - this.explicitPos = explicitPos; - } - hasResult() { return false; } - update(tr, conf) { - let event = getUserEvent(tr), value = this; - if (event) - value = value.handleUserEvent(tr, event, conf); - else if (tr.docChanged) - value = value.handleChange(tr); - else if (tr.selection && value.state != 0 /* Inactive */) - value = new ActiveSource(value.source, 0 /* Inactive */); - for (let effect of tr.effects) { - if (effect.is(startCompletionEffect)) - value = new ActiveSource(value.source, 1 /* Pending */, effect.value ? cur(tr.state) : -1); - else if (effect.is(closeCompletionEffect)) - value = new ActiveSource(value.source, 0 /* Inactive */); - else if (effect.is(setActiveEffect)) - for (let active of effect.value) - if (active.source == value.source) - value = active; - } - return value; - } - handleUserEvent(tr, type, conf) { - return type == "delete" || !conf.activateOnTyping ? this.map(tr.changes) : new ActiveSource(this.source, 1 /* Pending */); - } - handleChange(tr) { - return tr.changes.touchesRange(cur(tr.startState)) ? new ActiveSource(this.source, 0 /* Inactive */) : this.map(tr.changes); - } - map(changes) { - return changes.empty || this.explicitPos < 0 ? this : new ActiveSource(this.source, this.state, changes.mapPos(this.explicitPos)); - } - } - class ActiveResult extends ActiveSource { - constructor(source, explicitPos, result, from, to, span) { - super(source, 2 /* Result */, explicitPos); - this.result = result; - this.from = from; - this.to = to; - this.span = span; - } - hasResult() { return true; } - handleUserEvent(tr, type, conf) { - let from = tr.changes.mapPos(this.from), to = tr.changes.mapPos(this.to, 1); - let pos = cur(tr.state); - if ((this.explicitPos < 0 ? pos <= from : pos < this.from) || - pos > to || - type == "delete" && cur(tr.startState) == this.from) - return new ActiveSource(this.source, type == "input" && conf.activateOnTyping ? 1 /* Pending */ : 0 /* Inactive */); - let explicitPos = this.explicitPos < 0 ? -1 : tr.changes.mapPos(this.explicitPos); - if (this.span && (from == to || this.span.test(tr.state.sliceDoc(from, to)))) - return new ActiveResult(this.source, explicitPos, this.result, from, to, this.span); - return new ActiveSource(this.source, 1 /* Pending */, explicitPos); - } - handleChange(tr) { - return tr.changes.touchesRange(this.from, this.to) ? new ActiveSource(this.source, 0 /* Inactive */) : this.map(tr.changes); - } - map(mapping) { - return mapping.empty ? this : - new ActiveResult(this.source, this.explicitPos < 0 ? -1 : mapping.mapPos(this.explicitPos), this.result, mapping.mapPos(this.from), mapping.mapPos(this.to, 1), this.span); - } - } - const startCompletionEffect = /*@__PURE__*/StateEffect.define(); - const closeCompletionEffect = /*@__PURE__*/StateEffect.define(); - const setActiveEffect = /*@__PURE__*/StateEffect.define({ - map(sources, mapping) { return sources.map(s => s.map(mapping)); } - }); - const setSelectedEffect = /*@__PURE__*/StateEffect.define(); - const completionState = /*@__PURE__*/StateField.define({ - create() { return CompletionState.start(); }, - update(value, tr) { return value.update(tr); }, - provide: f => [ - showTooltip.from(f, val => val.tooltip), - EditorView.contentAttributes.from(f, state => state.attrs) - ] - }); - - const CompletionInteractMargin = 75; - /** - Returns a command that moves the completion selection forward or - backward by the given amount. - */ - function moveCompletionSelection(forward, by = "option") { - return (view) => { - let cState = view.state.field(completionState, false); - if (!cState || !cState.open || Date.now() - cState.open.timestamp < CompletionInteractMargin) - return false; - let step = 1, tooltip; - if (by == "page" && (tooltip = getTooltip(view, cState.open.tooltip))) - step = Math.max(2, Math.floor(tooltip.dom.offsetHeight / - tooltip.dom.querySelector("li").offsetHeight) - 1); - let selected = cState.open.selected + step * (forward ? 1 : -1), { length } = cState.open.options; - if (selected < 0) - selected = by == "page" ? 0 : length - 1; - else if (selected >= length) - selected = by == "page" ? length - 1 : 0; - view.dispatch({ effects: setSelectedEffect.of(selected) }); - return true; - }; - } - /** - Accept the current completion. - */ - const acceptCompletion = (view) => { - let cState = view.state.field(completionState, false); - if (view.state.readOnly || !cState || !cState.open || Date.now() - cState.open.timestamp < CompletionInteractMargin) - return false; - applyCompletion(view, cState.open.options[cState.open.selected]); - return true; - }; - /** - Explicitly start autocompletion. - */ - const startCompletion = (view) => { - let cState = view.state.field(completionState, false); - if (!cState) - return false; - view.dispatch({ effects: startCompletionEffect.of(true) }); - return true; - }; - /** - Close the currently active completion. - */ - const closeCompletion = (view) => { - let cState = view.state.field(completionState, false); - if (!cState || !cState.active.some(a => a.state != 0 /* Inactive */)) - return false; - view.dispatch({ effects: closeCompletionEffect.of(null) }); - return true; - }; - class RunningQuery { - constructor(active, context) { - this.active = active; - this.context = context; - this.time = Date.now(); - this.updates = []; - // Note that 'undefined' means 'not done yet', whereas 'null' means - // 'query returned null'. - this.done = undefined; - } - } - const DebounceTime = 50, MaxUpdateCount = 50, MinAbortTime = 1000; - const completionPlugin = /*@__PURE__*/ViewPlugin.fromClass(class { - constructor(view) { - this.view = view; - this.debounceUpdate = -1; - this.running = []; - this.debounceAccept = -1; - this.composing = 0 /* None */; - for (let active of view.state.field(completionState).active) - if (active.state == 1 /* Pending */) - this.startQuery(active); - } - update(update) { - let cState = update.state.field(completionState); - if (!update.selectionSet && !update.docChanged && update.startState.field(completionState) == cState) - return; - let doesReset = update.transactions.some(tr => { - return (tr.selection || tr.docChanged) && !getUserEvent(tr); - }); - for (let i = 0; i < this.running.length; i++) { - let query = this.running[i]; - if (doesReset || - query.updates.length + update.transactions.length > MaxUpdateCount && Date.now() - query.time > MinAbortTime) { - for (let handler of query.context.abortListeners) { - try { - handler(); - } - catch (e) { - logException(this.view.state, e); - } - } - query.context.abortListeners = null; - this.running.splice(i--, 1); - } - else { - query.updates.push(...update.transactions); - } - } - if (this.debounceUpdate > -1) - clearTimeout(this.debounceUpdate); - this.debounceUpdate = cState.active.some(a => a.state == 1 /* Pending */ && !this.running.some(q => q.active.source == a.source)) - ? setTimeout(() => this.startUpdate(), DebounceTime) : -1; - if (this.composing != 0 /* None */) - for (let tr of update.transactions) { - if (getUserEvent(tr) == "input") - this.composing = 2 /* Changed */; - else if (this.composing == 2 /* Changed */ && tr.selection) - this.composing = 3 /* ChangedAndMoved */; - } - } - startUpdate() { - this.debounceUpdate = -1; - let { state } = this.view, cState = state.field(completionState); - for (let active of cState.active) { - if (active.state == 1 /* Pending */ && !this.running.some(r => r.active.source == active.source)) - this.startQuery(active); - } - } - startQuery(active) { - let { state } = this.view, pos = cur(state); - let context = new CompletionContext(state, pos, active.explicitPos == pos); - let pending = new RunningQuery(active, context); - this.running.push(pending); - Promise.resolve(active.source(context)).then(result => { - if (!pending.context.aborted) { - pending.done = result || null; - this.scheduleAccept(); - } - }, err => { - this.view.dispatch({ effects: closeCompletionEffect.of(null) }); - logException(this.view.state, err); - }); - } - scheduleAccept() { - if (this.running.every(q => q.done !== undefined)) - this.accept(); - else if (this.debounceAccept < 0) - this.debounceAccept = setTimeout(() => this.accept(), DebounceTime); - } - // For each finished query in this.running, try to create a result - // or, if appropriate, restart the query. - accept() { - var _a; - if (this.debounceAccept > -1) - clearTimeout(this.debounceAccept); - this.debounceAccept = -1; - let updated = []; - let conf = this.view.state.facet(completionConfig); - for (let i = 0; i < this.running.length; i++) { - let query = this.running[i]; - if (query.done === undefined) - continue; - this.running.splice(i--, 1); - if (query.done) { - let active = new ActiveResult(query.active.source, query.active.explicitPos, query.done, query.done.from, (_a = query.done.to) !== null && _a !== void 0 ? _a : cur(query.updates.length ? query.updates[0].startState : this.view.state), query.done.span && query.done.filter !== false ? ensureAnchor(query.done.span, true) : null); - // Replay the transactions that happened since the start of - // the request and see if that preserves the result - for (let tr of query.updates) - active = active.update(tr, conf); - if (active.hasResult()) { - updated.push(active); - continue; - } - } - let current = this.view.state.field(completionState).active.find(a => a.source == query.active.source); - if (current && current.state == 1 /* Pending */) { - if (query.done == null) { - // Explicitly failed. Should clear the pending status if it - // hasn't been re-set in the meantime. - let active = new ActiveSource(query.active.source, 0 /* Inactive */); - for (let tr of query.updates) - active = active.update(tr, conf); - if (active.state != 1 /* Pending */) - updated.push(active); - } - else { - // Cleared by subsequent transactions. Restart. - this.startQuery(current); - } - } - } - if (updated.length) - this.view.dispatch({ effects: setActiveEffect.of(updated) }); - } - }, { - eventHandlers: { - compositionstart() { - this.composing = 1 /* Started */; - }, - compositionend() { - if (this.composing == 3 /* ChangedAndMoved */) { - // Safari fires compositionend events synchronously, possibly - // from inside an update, so dispatch asynchronously to avoid reentrancy - setTimeout(() => this.view.dispatch({ effects: startCompletionEffect.of(false) }), 20); - } - this.composing = 0 /* None */; - } - } - }); - - const baseTheme$1 = /*@__PURE__*/EditorView.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", - listStyle: "none", - margin: 0, - padding: 0, - "& > li": { - overflowX: "hidden", - textOverflow: "ellipsis", - cursor: "pointer", - padding: "1px 3px", - lineHeight: 1.2 - }, - } - }, - "&light .cm-tooltip-autocomplete ul li[aria-selected]": { - background: "#17c", - color: "white", - }, - "&dark .cm-tooltip-autocomplete ul li[aria-selected]": { - background: "#347", - color: "white", - }, - ".cm-completionListIncompleteTop:before, .cm-completionListIncompleteBottom:after": { - content: '"···"', - opacity: 0.5, - display: "block", - textAlign: "center" - }, - ".cm-tooltip.cm-completionInfo": { - position: "absolute", - padding: "3px 9px", - width: "max-content", - maxWidth: "300px", - }, - ".cm-completionInfo.cm-completionInfo-left": { right: "100%" }, - ".cm-completionInfo.cm-completionInfo-right": { left: "100%" }, - "&light .cm-snippetField": { backgroundColor: "#00000022" }, - "&dark .cm-snippetField": { backgroundColor: "#ffffff22" }, - ".cm-snippetFieldPosition": { - verticalAlign: "text-top", - width: 0, - height: "1.15em", - 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" - }, - ".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: "'🔑\uFE0E'" } // Disable emoji rendering - }, - ".cm-completionIcon-namespace": { - "&:after": { content: "'▢'" } - }, - ".cm-completionIcon-text": { - "&:after": { content: "'abc'", fontSize: "50%", verticalAlign: "middle" } - } - }); - - /** - Returns an extension that enables autocompletion. - */ - function autocompletion(config = {}) { - return [ - completionState, - completionConfig.of(config), - completionPlugin, - completionKeymapExt, - baseTheme$1 - ]; - } - /** - Basic keybindings for autocompletion. - - - Ctrl-Space: [`startCompletion`](https://codemirror.net/6/docs/ref/#autocomplete.startCompletion) - - Escape: [`closeCompletion`](https://codemirror.net/6/docs/ref/#autocomplete.closeCompletion) - - ArrowDown: [`moveCompletionSelection`](https://codemirror.net/6/docs/ref/#autocomplete.moveCompletionSelection)`(true)` - - ArrowUp: [`moveCompletionSelection`](https://codemirror.net/6/docs/ref/#autocomplete.moveCompletionSelection)`(false)` - - PageDown: [`moveCompletionSelection`](https://codemirror.net/6/docs/ref/#autocomplete.moveCompletionSelection)`(true, "page")` - - PageDown: [`moveCompletionSelection`](https://codemirror.net/6/docs/ref/#autocomplete.moveCompletionSelection)`(true, "page")` - - Enter: [`acceptCompletion`](https://codemirror.net/6/docs/ref/#autocomplete.acceptCompletion) - */ - const completionKeymap = [ - { key: "Ctrl-Space", run: startCompletion }, - { key: "Escape", run: closeCompletion }, - { key: "ArrowDown", run: /*@__PURE__*/moveCompletionSelection(true) }, - { key: "ArrowUp", run: /*@__PURE__*/moveCompletionSelection(false) }, - { key: "PageDown", run: /*@__PURE__*/moveCompletionSelection(true, "page") }, - { key: "PageUp", run: /*@__PURE__*/moveCompletionSelection(false, "page") }, - { key: "Enter", run: acceptCompletion } - ]; - const completionKeymapExt = /*@__PURE__*/Prec.highest(/*@__PURE__*/keymap.computeN([completionConfig], state => state.facet(completionConfig).defaultKeymap ? [completionKeymap] : [])); - - /** - Comment or uncomment the current selection. Will use line comments - if available, otherwise falling back to block comments. - */ - const toggleComment = target => { - let config = getConfig(target.state); - return config.line ? toggleLineComment(target) : config.block ? toggleBlockCommentByLine(target) : false; - }; - function command(f, option) { - return ({ state, dispatch }) => { - if (state.readOnly) - return false; - let tr = f(option, state); - if (!tr) - return false; - dispatch(state.update(tr)); - return true; - }; - } - /** - Comment or uncomment the current selection using line comments. - The line comment syntax is taken from the - [`commentTokens`](https://codemirror.net/6/docs/ref/#comment.CommentTokens) [language - data](https://codemirror.net/6/docs/ref/#state.EditorState.languageDataAt). - */ - const toggleLineComment = /*@__PURE__*/command(changeLineComment, 0 /* Toggle */); - /** - Comment or uncomment the current selection using block comments. - The block comment syntax is taken from the - [`commentTokens`](https://codemirror.net/6/docs/ref/#comment.CommentTokens) [language - data](https://codemirror.net/6/docs/ref/#state.EditorState.languageDataAt). - */ - const toggleBlockComment = /*@__PURE__*/command(changeBlockComment, 0 /* Toggle */); - /** - Comment or uncomment the lines around the current selection using - block comments. - */ - const toggleBlockCommentByLine = /*@__PURE__*/command((o, s) => changeBlockComment(o, s, selectedLineRanges(s)), 0 /* Toggle */); - /** - Default key bindings for this package. - - - Ctrl-/ (Cmd-/ on macOS): [`toggleComment`](https://codemirror.net/6/docs/ref/#comment.toggleComment). - - Shift-Alt-a: [`toggleBlockComment`](https://codemirror.net/6/docs/ref/#comment.toggleBlockComment). - */ - const commentKeymap = [ - { key: "Mod-/", run: toggleComment }, - { key: "Alt-A", run: toggleBlockComment } - ]; - function getConfig(state, pos = state.selection.main.head) { - let data = state.languageDataAt("commentTokens", pos); - return data.length ? data[0] : {}; - } - const SearchMargin = 50; - /** - Determines if the given range is block-commented in the given - state. - */ - function findBlockComment(state, { open, close }, from, to) { - let textBefore = state.sliceDoc(from - SearchMargin, from); - let textAfter = state.sliceDoc(to, to + SearchMargin); - let spaceBefore = /\s*$/.exec(textBefore)[0].length, spaceAfter = /^\s*/.exec(textAfter)[0].length; - let beforeOff = textBefore.length - spaceBefore; - if (textBefore.slice(beforeOff - open.length, beforeOff) == open && - textAfter.slice(spaceAfter, spaceAfter + close.length) == close) { - return { open: { pos: from - spaceBefore, margin: spaceBefore && 1 }, - close: { pos: to + spaceAfter, margin: spaceAfter && 1 } }; - } - let startText, endText; - if (to - from <= 2 * SearchMargin) { - startText = endText = state.sliceDoc(from, to); - } - else { - startText = state.sliceDoc(from, from + SearchMargin); - endText = state.sliceDoc(to - SearchMargin, to); - } - let startSpace = /^\s*/.exec(startText)[0].length, endSpace = /\s*$/.exec(endText)[0].length; - let endOff = endText.length - endSpace - close.length; - if (startText.slice(startSpace, startSpace + open.length) == open && - endText.slice(endOff, endOff + close.length) == close) { - return { open: { pos: from + startSpace + open.length, - margin: /\s/.test(startText.charAt(startSpace + open.length)) ? 1 : 0 }, - close: { pos: to - endSpace - close.length, - margin: /\s/.test(endText.charAt(endOff - 1)) ? 1 : 0 } }; - } - return null; - } - function selectedLineRanges(state) { - let ranges = []; - for (let r of state.selection.ranges) { - let fromLine = state.doc.lineAt(r.from); - let toLine = r.to <= fromLine.to ? fromLine : state.doc.lineAt(r.to); - let last = ranges.length - 1; - if (last >= 0 && ranges[last].to > fromLine.from) - ranges[last].to = toLine.to; - else - ranges.push({ from: fromLine.from, to: toLine.to }); - } - return ranges; - } - // Performs toggle, comment and uncomment of block comments in - // languages that support them. - function changeBlockComment(option, state, ranges = state.selection.ranges) { - let tokens = ranges.map(r => getConfig(state, r.from).block); - if (!tokens.every(c => c)) - return null; - let comments = ranges.map((r, i) => findBlockComment(state, tokens[i], r.from, r.to)); - if (option != 2 /* Uncomment */ && !comments.every(c => c)) { - return { changes: state.changes(ranges.map((range, i) => { - if (comments[i]) - return []; - return [{ from: range.from, insert: tokens[i].open + " " }, { from: range.to, insert: " " + tokens[i].close }]; - })) }; - } - else if (option != 1 /* Comment */ && comments.some(c => c)) { - let changes = []; - for (let i = 0, comment; i < comments.length; i++) - if (comment = comments[i]) { - let token = tokens[i], { open, close } = comment; - changes.push({ from: open.pos - token.open.length, to: open.pos + open.margin }, { from: close.pos - close.margin, to: close.pos + token.close.length }); - } - return { changes }; - } - return null; - } - // Performs toggle, comment and uncomment of line comments. - function changeLineComment(option, state, ranges = state.selection.ranges) { - let lines = []; - let prevLine = -1; - for (let { from, to } of ranges) { - let startI = lines.length, minIndent = 1e9; - for (let pos = from; pos <= to;) { - let line = state.doc.lineAt(pos); - if (line.from > prevLine && (from == to || to > line.from)) { - prevLine = line.from; - let token = getConfig(state, pos).line; - if (!token) - continue; - let indent = /^\s*/.exec(line.text)[0].length; - let empty = indent == line.length; - let comment = line.text.slice(indent, indent + token.length) == token ? indent : -1; - if (indent < line.text.length && indent < minIndent) - minIndent = indent; - lines.push({ line, comment, token, indent, empty, single: false }); - } - pos = line.to + 1; - } - if (minIndent < 1e9) - for (let i = startI; i < lines.length; i++) - if (lines[i].indent < lines[i].line.text.length) - lines[i].indent = minIndent; - if (lines.length == startI + 1) - lines[startI].single = true; - } - if (option != 2 /* Uncomment */ && lines.some(l => l.comment < 0 && (!l.empty || l.single))) { - let changes = []; - for (let { line, token, indent, empty, single } of lines) - if (single || !empty) - changes.push({ from: line.from + indent, insert: token + " " }); - let changeSet = state.changes(changes); - return { changes: changeSet, selection: state.selection.map(changeSet, 1) }; - } - else if (option != 1 /* Comment */ && lines.some(l => l.comment >= 0)) { - let changes = []; - for (let { line, comment, token } of lines) - if (comment >= 0) { - let from = line.from + comment, to = from + token.length; - if (line.text[to - line.from] == " ") - to++; - changes.push({ from, to }); - } - return { changes }; - } - return null; - } - - // Don't compute precise column positions for line offsets above this - // (since it could get expensive). Assume offset==column for them. - const MaxOff = 2000; - function rectangleFor(state, a, b) { - let startLine = Math.min(a.line, b.line), endLine = Math.max(a.line, b.line); - let ranges = []; - if (a.off > MaxOff || b.off > MaxOff || a.col < 0 || b.col < 0) { - let startOff = Math.min(a.off, b.off), endOff = Math.max(a.off, b.off); - for (let i = startLine; i <= endLine; i++) { - let line = state.doc.line(i); - if (line.length <= endOff) - ranges.push(EditorSelection.range(line.from + startOff, line.to + endOff)); - } - } - else { - let startCol = Math.min(a.col, b.col), endCol = Math.max(a.col, b.col); - for (let i = startLine; i <= endLine; i++) { - let line = state.doc.line(i); - let start = findColumn(line.text, startCol, state.tabSize, true); - if (start > -1) { - let end = findColumn(line.text, endCol, state.tabSize); - ranges.push(EditorSelection.range(line.from + start, line.from + end)); - } - } - } - return ranges; - } - function absoluteColumn(view, x) { - let ref = view.coordsAtPos(view.viewport.from); - return ref ? Math.round(Math.abs((ref.left - x) / view.defaultCharacterWidth)) : -1; - } - function getPos(view, event) { - let offset = view.posAtCoords({ x: event.clientX, y: event.clientY }, false); - let line = view.state.doc.lineAt(offset), off = offset - line.from; - let col = off > MaxOff ? -1 - : off == line.length ? absoluteColumn(view, event.clientX) - : countColumn(line.text, view.state.tabSize, offset - line.from); - return { line: line.number, col, off }; - } - function rectangleSelectionStyle(view, event) { - let start = getPos(view, event), startSel = view.state.selection; - if (!start) - return null; - return { - update(update) { - if (update.docChanged) { - let newStart = update.changes.mapPos(update.startState.doc.line(start.line).from); - let newLine = update.state.doc.lineAt(newStart); - start = { line: newLine.number, col: start.col, off: Math.min(start.off, newLine.length) }; - startSel = startSel.map(update.changes); - } - }, - get(event, _extend, multiple) { - let cur = getPos(view, event); - if (!cur) - return startSel; - let ranges = rectangleFor(view.state, start, cur); - if (!ranges.length) - return startSel; - if (multiple) - return EditorSelection.create(ranges.concat(startSel.ranges)); - else - return EditorSelection.create(ranges); - } - }; - } - /** - Create an extension that enables rectangular selections. By - default, it will react to left mouse drag with the Alt key held - down. When such a selection occurs, the text within the rectangle - that was dragged over will be selected, as one selection - [range](https://codemirror.net/6/docs/ref/#state.SelectionRange) per line. - */ - function rectangularSelection(options) { - let filter = (options === null || options === void 0 ? void 0 : options.eventFilter) || (e => e.altKey && e.button == 0); - return EditorView.mouseSelectionStyle.of((view, event) => filter(event) ? rectangleSelectionStyle(view, event) : null); - } - const keys = { - Alt: [18, e => e.altKey], - Control: [17, e => e.ctrlKey], - Shift: [16, e => e.shiftKey], - Meta: [91, e => e.metaKey] - }; - const showCrosshair = { style: "cursor: crosshair" }; - /** - Returns an extension that turns the pointer cursor into a - crosshair when a given modifier key, defaulting to Alt, is held - down. Can serve as a visual hint that rectangular selection is - going to happen when paired with - [`rectangularSelection`](https://codemirror.net/6/docs/ref/#rectangular-selection.rectangularSelection). - */ - function crosshairCursor(options = {}) { - let [code, getter] = keys[options.key || "Alt"]; - let plugin = ViewPlugin.fromClass(class { - constructor(view) { - this.view = view; - this.isDown = false; - } - set(isDown) { - if (this.isDown != isDown) { - this.isDown = isDown; - this.view.update([]); - } - } - }, { - eventHandlers: { - keydown(e) { - this.set(e.keyCode == code || getter(e)); - }, - keyup(e) { - if (e.keyCode == code || !getter(e)) - this.set(false); - } - } - }); - return [ - plugin, - EditorView.contentAttributes.of(view => { var _a; return ((_a = view.plugin(plugin)) === null || _a === void 0 ? void 0 : _a.isDown) ? showCrosshair : null; }) - ]; - } - - let nextTagID = 0; - /** - Highlighting tags are markers that denote a highlighting category. - They are [associated](https://codemirror.net/6/docs/ref/#highlight.styleTags) with parts of a syntax - tree by a language mode, and then mapped to an actual CSS style by - a [highlight style](https://codemirror.net/6/docs/ref/#highlight.HighlightStyle). - - Because syntax tree node types and highlight styles have to be - able to talk the same language, CodeMirror uses a mostly _closed_ - [vocabulary](https://codemirror.net/6/docs/ref/#highlight.tags) of syntax tags (as opposed to - traditional open string-based systems, which make it hard for - highlighting themes to cover all the tokens produced by the - various languages). - - It _is_ possible to [define](https://codemirror.net/6/docs/ref/#highlight.Tag^define) your own - highlighting tags for system-internal use (where you control both - the language package and the highlighter), but such tags will not - be picked up by regular highlighters (though you can derive them - from standard tags to allow highlighters to fall back to those). - */ - class Tag { - /** - @internal - */ - constructor( - /** - The set of tags that match this tag, starting with this one - itself, sorted in order of decreasing specificity. @internal - */ - set, - /** - The base unmodified tag that this one is based on, if it's - modified @internal - */ - base, - /** - The modifiers applied to this.base @internal - */ - modified) { - this.set = set; - this.base = base; - this.modified = modified; - /** - @internal - */ - this.id = nextTagID++; - } - /** - Define a new tag. If `parent` is given, the tag is treated as a - sub-tag of that parent, and [highlight - styles](https://codemirror.net/6/docs/ref/#highlight.HighlightStyle) that don't mention this tag - will try to fall back to the parent tag (or grandparent tag, - etc). - */ - static define(parent) { - if (parent === null || parent === void 0 ? void 0 : parent.base) - throw new Error("Can not derive from a modified tag"); - let tag = new Tag([], null, []); - tag.set.push(tag); - if (parent) - for (let t of parent.set) - tag.set.push(t); - return tag; - } - /** - Define a tag _modifier_, which is a function that, given a tag, - will return a tag that is a subtag of the original. Applying the - same modifier to a twice tag will return the same value (`m1(t1) - == m1(t1)`) and applying multiple modifiers will, regardless or - order, produce the same tag (`m1(m2(t1)) == m2(m1(t1))`). - - When multiple modifiers are applied to a given base tag, each - smaller set of modifiers is registered as a parent, so that for - example `m1(m2(m3(t1)))` is a subtype of `m1(m2(t1))`, - `m1(m3(t1)`, and so on. - */ - static defineModifier() { - let mod = new Modifier; - return (tag) => { - if (tag.modified.indexOf(mod) > -1) - return tag; - return Modifier.get(tag.base || tag, tag.modified.concat(mod).sort((a, b) => a.id - b.id)); - }; - } - } - let nextModifierID = 0; - class Modifier { - constructor() { - this.instances = []; - this.id = nextModifierID++; - } - static get(base, mods) { - if (!mods.length) - return base; - let exists = mods[0].instances.find(t => t.base == base && sameArray(mods, t.modified)); - if (exists) - return exists; - let set = [], tag = new Tag(set, base, mods); - for (let m of mods) - m.instances.push(tag); - let configs = permute(mods); - for (let parent of base.set) - for (let config of configs) - set.push(Modifier.get(parent, config)); - return tag; - } - } - function sameArray(a, b) { - return a.length == b.length && a.every((x, i) => x == b[i]); - } - function permute(array) { - let result = [array]; - for (let i = 0; i < array.length; i++) { - for (let a of permute(array.slice(0, i).concat(array.slice(i + 1)))) - result.push(a); - } - return result; - } - /** - This function is used to add a set of tags to a language syntax - via - [`LRParser.configure`](https://lezer.codemirror.net/docs/ref#lr.LRParser.configure). - - The argument object maps node selectors to [highlighting - tags](https://codemirror.net/6/docs/ref/#highlight.Tag) or arrays of tags. - - Node selectors may hold one or more (space-separated) node paths. - Such a path can be a [node - name](https://lezer.codemirror.net/docs/ref#common.NodeType.name), - or multiple node names (or `*` wildcards) separated by slash - characters, as in `"Block/Declaration/VariableName"`. Such a path - matches the final node but only if its direct parent nodes are the - other nodes mentioned. A `*` in such a path matches any parent, - but only a single level—wildcards that match multiple parents - aren't supported, both for efficiency reasons and because Lezer - trees make it rather hard to reason about what they would match.) - - A path can be ended with `/...` to indicate that the tag assigned - to the node should also apply to all child nodes, even if they - match their own style (by default, only the innermost style is - used). - - When a path ends in `!`, as in `Attribute!`, no further matching - happens for the node's child nodes, and the entire node gets the - given style. - - In this notation, node names that contain `/`, `!`, `*`, or `...` - must be quoted as JSON strings. - - For example: - - ```javascript - parser.withProps( - styleTags({ - // Style Number and BigNumber nodes - "Number BigNumber": tags.number, - // Style Escape nodes whose parent is String - "String/Escape": tags.escape, - // Style anything inside Attributes nodes - "Attributes!": tags.meta, - // Add a style to all content inside Italic nodes - "Italic/...": tags.emphasis, - // Style InvalidString nodes as both `string` and `invalid` - "InvalidString": [tags.string, tags.invalid], - // Style the node named "/" as punctuation - '"/"': tags.punctuation - }) - ) - ``` - */ - function styleTags(spec) { - let byName = Object.create(null); - for (let prop in spec) { - let tags = spec[prop]; - if (!Array.isArray(tags)) - tags = [tags]; - for (let part of prop.split(" ")) - if (part) { - let pieces = [], mode = 2 /* Normal */, rest = part; - for (let pos = 0;;) { - if (rest == "..." && pos > 0 && pos + 3 == part.length) { - mode = 1 /* Inherit */; - break; - } - let m = /^"(?:[^"\\]|\\.)*?"|[^\/!]+/.exec(rest); - if (!m) - throw new RangeError("Invalid path: " + part); - pieces.push(m[0] == "*" ? null : m[0][0] == '"' ? JSON.parse(m[0]) : m[0]); - pos += m[0].length; - if (pos == part.length) - break; - let next = part[pos++]; - if (pos == part.length && next == "!") { - mode = 0 /* Opaque */; - break; - } - if (next != "/") - throw new RangeError("Invalid path: " + part); - rest = part.slice(pos); - } - let last = pieces.length - 1, inner = pieces[last]; - if (!inner) - throw new RangeError("Invalid path: " + part); - let rule = new Rule(tags, mode, last > 0 ? pieces.slice(0, last) : null); - byName[inner] = rule.sort(byName[inner]); - } - } - return ruleNodeProp.add(byName); - } - const ruleNodeProp = /*@__PURE__*/new NodeProp(); - const highlightStyle = /*@__PURE__*/Facet.define({ - combine(stylings) { return stylings.length ? HighlightStyle.combinedMatch(stylings) : null; } - }); - const fallbackHighlightStyle = /*@__PURE__*/Facet.define({ - combine(values) { return values.length ? values[0].match : null; } - }); - function getHighlightStyle(state) { - return state.facet(highlightStyle) || state.facet(fallbackHighlightStyle); - } - class Rule { - constructor(tags, mode, context, next) { - this.tags = tags; - this.mode = mode; - this.context = context; - this.next = next; - } - sort(other) { - if (!other || other.depth < this.depth) { - this.next = other; - return this; - } - other.next = this.sort(other.next); - return other; - } - get depth() { return this.context ? this.context.length : 0; } - } - /** - A highlight style associates CSS styles with higlighting - [tags](https://codemirror.net/6/docs/ref/#highlight.Tag). - */ - class HighlightStyle { - constructor(spec, options) { - this.map = Object.create(null); - let modSpec; - function def(spec) { - let cls = StyleModule.newName(); - (modSpec || (modSpec = Object.create(null)))["." + cls] = spec; - return cls; - } - this.all = typeof options.all == "string" ? options.all : options.all ? def(options.all) : null; - for (let style of spec) { - let cls = (style.class || def(Object.assign({}, style, { tag: null }))) + - (this.all ? " " + this.all : ""); - let tags = style.tag; - if (!Array.isArray(tags)) - this.map[tags.id] = cls; - else - for (let tag of tags) - this.map[tag.id] = cls; - } - this.module = modSpec ? new StyleModule(modSpec) : null; - this.scope = options.scope || null; - this.match = this.match.bind(this); - let ext = [treeHighlighter]; - if (this.module) - ext.push(EditorView.styleModule.of(this.module)); - this.extension = ext.concat(options.themeType == null ? highlightStyle.of(this) : - highlightStyle.computeN([EditorView.darkTheme], state => { - return state.facet(EditorView.darkTheme) == (options.themeType == "dark") ? [this] : []; - })); - this.fallback = ext.concat(fallbackHighlightStyle.of(this)); - } - /** - Returns the CSS class associated with the given tag, if any. - This method is bound to the instance by the constructor. - */ - match(tag, scope) { - if (this.scope && scope != this.scope) - return null; - for (let t of tag.set) { - let match = this.map[t.id]; - if (match !== undefined) { - if (t != tag) - this.map[tag.id] = match; - return match; - } - } - return this.map[tag.id] = this.all; - } - /** - Combines an array of highlight styles into a single match - function that returns all of the classes assigned by the styles - for a given tag. - */ - static combinedMatch(styles) { - if (styles.length == 1) - return styles[0].match; - let cache = styles.some(s => s.scope) ? undefined : Object.create(null); - return (tag, scope) => { - let cached = cache && cache[tag.id]; - if (cached !== undefined) - return cached; - let result = null; - for (let style of styles) { - let value = style.match(tag, scope); - if (value) - result = result ? result + " " + value : value; - } - if (cache) - cache[tag.id] = result; - return result; - }; - } - /** - Create a highlighter style that associates the given styles to - the given tags. The spec must be objects that hold a style tag - or array of tags in their `tag` property, and either a single - `class` property providing a static CSS class (for highlighters - like [`classHighlightStyle`](https://codemirror.net/6/docs/ref/#highlight.classHighlightStyle) - that rely on external styling), or a - [`style-mod`](https://github.com/marijnh/style-mod#documentation)-style - set of CSS properties (which define the styling for those tags). - - The CSS rules created for a highlighter will be emitted in the - order of the spec's properties. That means that for elements that - have multiple tags associated with them, styles defined further - down in the list will have a higher CSS precedence than styles - defined earlier. - */ - static define(specs, options) { - return new HighlightStyle(specs, options || {}); - } - /** - Returns the CSS classes (if any) that the highlight styles - active in the given state would assign to the given a style - [tag](https://codemirror.net/6/docs/ref/#highlight.Tag) and (optional) language - [scope](https://codemirror.net/6/docs/ref/#highlight.HighlightStyle^define^options.scope). - */ - static get(state, tag, scope) { - let style = getHighlightStyle(state); - return style && style(tag, scope || NodeType.none); - } - } - class TreeHighlighter { - constructor(view) { - this.markCache = Object.create(null); - this.tree = syntaxTree(view.state); - this.decorations = this.buildDeco(view, getHighlightStyle(view.state)); - } - update(update) { - let tree = syntaxTree(update.state), style = getHighlightStyle(update.state); - let styleChange = style != update.startState.facet(highlightStyle); - if (tree.length < update.view.viewport.to && !styleChange && tree.type == this.tree.type) { - this.decorations = this.decorations.map(update.changes); - } - else if (tree != this.tree || update.viewportChanged || styleChange) { - this.tree = tree; - this.decorations = this.buildDeco(update.view, style); - } - } - buildDeco(view, match) { - if (!match || !this.tree.length) - return Decoration.none; - let builder = new RangeSetBuilder(); - for (let { from, to } of view.visibleRanges) { - highlightTreeRange(this.tree, from, to, match, (from, to, style) => { - builder.add(from, to, this.markCache[style] || (this.markCache[style] = Decoration.mark({ class: style }))); - }); - } - return builder.finish(); - } - } - // This extension installs a highlighter that highlights based on the - // syntax tree and highlight style. - const treeHighlighter = /*@__PURE__*/Prec.high(/*@__PURE__*/ViewPlugin.fromClass(TreeHighlighter, { - decorations: v => v.decorations - })); - const nodeStack = [""]; - class HighlightBuilder { - constructor(at, style, span) { - this.at = at; - this.style = style; - this.span = span; - this.class = ""; - } - startSpan(at, cls) { - if (cls != this.class) { - this.flush(at); - if (at > this.at) - this.at = at; - this.class = cls; - } - } - flush(to) { - if (to > this.at && this.class) - this.span(this.at, to, this.class); - } - highlightRange(cursor, from, to, inheritedClass, depth, scope) { - let { type, from: start, to: end } = cursor; - if (start >= to || end <= from) - return; - nodeStack[depth] = type.name; - if (type.isTop) - scope = type; - let cls = inheritedClass; - let rule = type.prop(ruleNodeProp), opaque = false; - while (rule) { - if (!rule.context || matchContext(rule.context, nodeStack, depth)) { - for (let tag of rule.tags) { - let st = this.style(tag, scope); - if (st) { - if (cls) - cls += " "; - cls += st; - if (rule.mode == 1 /* Inherit */) - inheritedClass += (inheritedClass ? " " : "") + st; - else if (rule.mode == 0 /* Opaque */) - opaque = true; - } - } - break; - } - rule = rule.next; - } - this.startSpan(cursor.from, cls); - if (opaque) - return; - let mounted = cursor.tree && cursor.tree.prop(NodeProp.mounted); - if (mounted && mounted.overlay) { - let inner = cursor.node.enter(mounted.overlay[0].from + start, 1); - let hasChild = cursor.firstChild(); - for (let i = 0, pos = start;; i++) { - let next = i < mounted.overlay.length ? mounted.overlay[i] : null; - let nextPos = next ? next.from + start : end; - let rangeFrom = Math.max(from, pos), rangeTo = Math.min(to, nextPos); - if (rangeFrom < rangeTo && hasChild) { - while (cursor.from < rangeTo) { - this.highlightRange(cursor, rangeFrom, rangeTo, inheritedClass, depth + 1, scope); - this.startSpan(Math.min(to, cursor.to), cls); - if (cursor.to >= nextPos || !cursor.nextSibling()) - break; - } - } - if (!next || nextPos > to) - break; - pos = next.to + start; - if (pos > from) { - this.highlightRange(inner.cursor, Math.max(from, next.from + start), Math.min(to, pos), inheritedClass, depth, mounted.tree.type); - this.startSpan(pos, cls); - } - } - if (hasChild) - cursor.parent(); - } - else if (cursor.firstChild()) { - do { - if (cursor.to <= from) - continue; - if (cursor.from >= to) - break; - this.highlightRange(cursor, from, to, inheritedClass, depth + 1, scope); - this.startSpan(Math.min(to, cursor.to), cls); - } while (cursor.nextSibling()); - cursor.parent(); - } - } - } - function highlightTreeRange(tree, from, to, style, span) { - let builder = new HighlightBuilder(from, style, span); - builder.highlightRange(tree.cursor(), from, to, "", 0, tree.type); - builder.flush(to); - } - function matchContext(context, stack, depth) { - if (context.length > depth - 1) - return false; - for (let d = depth - 1, i = context.length - 1; i >= 0; i--, d--) { - let check = context[i]; - if (check && check != stack[d]) - return false; - } - return true; - } - const t = Tag.define; - const comment = /*@__PURE__*/t(), name = /*@__PURE__*/t(), typeName = /*@__PURE__*/t(name), propertyName = /*@__PURE__*/t(name), literal = /*@__PURE__*/t(), string = /*@__PURE__*/t(literal), number = /*@__PURE__*/t(literal), content = /*@__PURE__*/t(), heading = /*@__PURE__*/t(content), keyword = /*@__PURE__*/t(), operator = /*@__PURE__*/t(), punctuation = /*@__PURE__*/t(), bracket = /*@__PURE__*/t(punctuation), meta = /*@__PURE__*/t(); - /** - The default set of highlighting [tags](https://codemirror.net/6/docs/ref/#highlight.Tag^define) used - by regular language packages and themes. - - This collection is heavily biased towards programming languages, - and necessarily incomplete. A full ontology of syntactic - constructs would fill a stack of books, and be impractical to - write themes for. So try to make do with this set. If all else - fails, [open an - issue](https://github.com/codemirror/codemirror.next) to propose a - new tag, or [define](https://codemirror.net/6/docs/ref/#highlight.Tag^define) a local custom tag for - your use case. - - Note that it is not obligatory to always attach the most specific - tag possible to an element—if your grammar can't easily - distinguish a certain type of element (such as a local variable), - it is okay to style it as its more general variant (a variable). - - For tags that extend some parent tag, the documentation links to - the parent. - */ - const tags = { - /** - A comment. - */ - comment, - /** - A line [comment](https://codemirror.net/6/docs/ref/#highlight.tags.comment). - */ - lineComment: /*@__PURE__*/t(comment), - /** - A block [comment](https://codemirror.net/6/docs/ref/#highlight.tags.comment). - */ - blockComment: /*@__PURE__*/t(comment), - /** - A documentation [comment](https://codemirror.net/6/docs/ref/#highlight.tags.comment). - */ - docComment: /*@__PURE__*/t(comment), - /** - Any kind of identifier. - */ - name, - /** - The [name](https://codemirror.net/6/docs/ref/#highlight.tags.name) of a variable. - */ - variableName: /*@__PURE__*/t(name), - /** - A type [name](https://codemirror.net/6/docs/ref/#highlight.tags.name). - */ - typeName: typeName, - /** - A tag name (subtag of [`typeName`](https://codemirror.net/6/docs/ref/#highlight.tags.typeName)). - */ - tagName: /*@__PURE__*/t(typeName), - /** - A property or field [name](https://codemirror.net/6/docs/ref/#highlight.tags.name). - */ - propertyName: propertyName, - /** - An attribute name (subtag of [`propertyName`](https://codemirror.net/6/docs/ref/#highlight.tags.propertyName)). - */ - attributeName: /*@__PURE__*/t(propertyName), - /** - The [name](https://codemirror.net/6/docs/ref/#highlight.tags.name) of a class. - */ - className: /*@__PURE__*/t(name), - /** - A label [name](https://codemirror.net/6/docs/ref/#highlight.tags.name). - */ - labelName: /*@__PURE__*/t(name), - /** - A namespace [name](https://codemirror.net/6/docs/ref/#highlight.tags.name). - */ - namespace: /*@__PURE__*/t(name), - /** - The [name](https://codemirror.net/6/docs/ref/#highlight.tags.name) of a macro. - */ - macroName: /*@__PURE__*/t(name), - /** - A literal value. - */ - literal, - /** - A string [literal](https://codemirror.net/6/docs/ref/#highlight.tags.literal). - */ - string, - /** - A documentation [string](https://codemirror.net/6/docs/ref/#highlight.tags.string). - */ - docString: /*@__PURE__*/t(string), - /** - A character literal (subtag of [string](https://codemirror.net/6/docs/ref/#highlight.tags.string)). - */ - character: /*@__PURE__*/t(string), - /** - An attribute value (subtag of [string](https://codemirror.net/6/docs/ref/#highlight.tags.string)). - */ - attributeValue: /*@__PURE__*/t(string), - /** - A number [literal](https://codemirror.net/6/docs/ref/#highlight.tags.literal). - */ - number, - /** - An integer [number](https://codemirror.net/6/docs/ref/#highlight.tags.number) literal. - */ - integer: /*@__PURE__*/t(number), - /** - A floating-point [number](https://codemirror.net/6/docs/ref/#highlight.tags.number) literal. - */ - float: /*@__PURE__*/t(number), - /** - A boolean [literal](https://codemirror.net/6/docs/ref/#highlight.tags.literal). - */ - bool: /*@__PURE__*/t(literal), - /** - Regular expression [literal](https://codemirror.net/6/docs/ref/#highlight.tags.literal). - */ - regexp: /*@__PURE__*/t(literal), - /** - An escape [literal](https://codemirror.net/6/docs/ref/#highlight.tags.literal), for example a - backslash escape in a string. - */ - escape: /*@__PURE__*/t(literal), - /** - A color [literal](https://codemirror.net/6/docs/ref/#highlight.tags.literal). - */ - color: /*@__PURE__*/t(literal), - /** - A URL [literal](https://codemirror.net/6/docs/ref/#highlight.tags.literal). - */ - url: /*@__PURE__*/t(literal), - /** - A language keyword. - */ - keyword, - /** - The [keyword](https://codemirror.net/6/docs/ref/#highlight.tags.keyword) for the self or this - object. - */ - self: /*@__PURE__*/t(keyword), - /** - The [keyword](https://codemirror.net/6/docs/ref/#highlight.tags.keyword) for null. - */ - null: /*@__PURE__*/t(keyword), - /** - A [keyword](https://codemirror.net/6/docs/ref/#highlight.tags.keyword) denoting some atomic value. - */ - atom: /*@__PURE__*/t(keyword), - /** - A [keyword](https://codemirror.net/6/docs/ref/#highlight.tags.keyword) that represents a unit. - */ - unit: /*@__PURE__*/t(keyword), - /** - A modifier [keyword](https://codemirror.net/6/docs/ref/#highlight.tags.keyword). - */ - modifier: /*@__PURE__*/t(keyword), - /** - A [keyword](https://codemirror.net/6/docs/ref/#highlight.tags.keyword) that acts as an operator. - */ - operatorKeyword: /*@__PURE__*/t(keyword), - /** - A control-flow related [keyword](https://codemirror.net/6/docs/ref/#highlight.tags.keyword). - */ - controlKeyword: /*@__PURE__*/t(keyword), - /** - A [keyword](https://codemirror.net/6/docs/ref/#highlight.tags.keyword) that defines something. - */ - definitionKeyword: /*@__PURE__*/t(keyword), - /** - A [keyword](https://codemirror.net/6/docs/ref/#highlight.tags.keyword) related to defining or - interfacing with modules. - */ - moduleKeyword: /*@__PURE__*/t(keyword), - /** - An operator. - */ - operator, - /** - An [operator](https://codemirror.net/6/docs/ref/#highlight.tags.operator) that defines something. - */ - derefOperator: /*@__PURE__*/t(operator), - /** - Arithmetic-related [operator](https://codemirror.net/6/docs/ref/#highlight.tags.operator). - */ - arithmeticOperator: /*@__PURE__*/t(operator), - /** - Logical [operator](https://codemirror.net/6/docs/ref/#highlight.tags.operator). - */ - logicOperator: /*@__PURE__*/t(operator), - /** - Bit [operator](https://codemirror.net/6/docs/ref/#highlight.tags.operator). - */ - bitwiseOperator: /*@__PURE__*/t(operator), - /** - Comparison [operator](https://codemirror.net/6/docs/ref/#highlight.tags.operator). - */ - compareOperator: /*@__PURE__*/t(operator), - /** - [Operator](https://codemirror.net/6/docs/ref/#highlight.tags.operator) that updates its operand. - */ - updateOperator: /*@__PURE__*/t(operator), - /** - [Operator](https://codemirror.net/6/docs/ref/#highlight.tags.operator) that defines something. - */ - definitionOperator: /*@__PURE__*/t(operator), - /** - Type-related [operator](https://codemirror.net/6/docs/ref/#highlight.tags.operator). - */ - typeOperator: /*@__PURE__*/t(operator), - /** - Control-flow [operator](https://codemirror.net/6/docs/ref/#highlight.tags.operator). - */ - controlOperator: /*@__PURE__*/t(operator), - /** - Program or markup punctuation. - */ - punctuation, - /** - [Punctuation](https://codemirror.net/6/docs/ref/#highlight.tags.punctuation) that separates - things. - */ - separator: /*@__PURE__*/t(punctuation), - /** - Bracket-style [punctuation](https://codemirror.net/6/docs/ref/#highlight.tags.punctuation). - */ - bracket, - /** - Angle [brackets](https://codemirror.net/6/docs/ref/#highlight.tags.bracket) (usually `<` and `>` - tokens). - */ - angleBracket: /*@__PURE__*/t(bracket), - /** - Square [brackets](https://codemirror.net/6/docs/ref/#highlight.tags.bracket) (usually `[` and `]` - tokens). - */ - squareBracket: /*@__PURE__*/t(bracket), - /** - Parentheses (usually `(` and `)` tokens). Subtag of - [bracket](https://codemirror.net/6/docs/ref/#highlight.tags.bracket). - */ - paren: /*@__PURE__*/t(bracket), - /** - Braces (usually `{` and `}` tokens). Subtag of - [bracket](https://codemirror.net/6/docs/ref/#highlight.tags.bracket). - */ - brace: /*@__PURE__*/t(bracket), - /** - Content, for example plain text in XML or markup documents. - */ - content, - /** - [Content](https://codemirror.net/6/docs/ref/#highlight.tags.content) that represents a heading. - */ - heading, - /** - A level 1 [heading](https://codemirror.net/6/docs/ref/#highlight.tags.heading). - */ - heading1: /*@__PURE__*/t(heading), - /** - A level 2 [heading](https://codemirror.net/6/docs/ref/#highlight.tags.heading). - */ - heading2: /*@__PURE__*/t(heading), - /** - A level 3 [heading](https://codemirror.net/6/docs/ref/#highlight.tags.heading). - */ - heading3: /*@__PURE__*/t(heading), - /** - A level 4 [heading](https://codemirror.net/6/docs/ref/#highlight.tags.heading). - */ - heading4: /*@__PURE__*/t(heading), - /** - A level 5 [heading](https://codemirror.net/6/docs/ref/#highlight.tags.heading). - */ - heading5: /*@__PURE__*/t(heading), - /** - A level 6 [heading](https://codemirror.net/6/docs/ref/#highlight.tags.heading). - */ - heading6: /*@__PURE__*/t(heading), - /** - A prose separator (such as a horizontal rule). - */ - contentSeparator: /*@__PURE__*/t(content), - /** - [Content](https://codemirror.net/6/docs/ref/#highlight.tags.content) that represents a list. - */ - list: /*@__PURE__*/t(content), - /** - [Content](https://codemirror.net/6/docs/ref/#highlight.tags.content) that represents a quote. - */ - quote: /*@__PURE__*/t(content), - /** - [Content](https://codemirror.net/6/docs/ref/#highlight.tags.content) that is emphasized. - */ - emphasis: /*@__PURE__*/t(content), - /** - [Content](https://codemirror.net/6/docs/ref/#highlight.tags.content) that is styled strong. - */ - strong: /*@__PURE__*/t(content), - /** - [Content](https://codemirror.net/6/docs/ref/#highlight.tags.content) that is part of a link. - */ - link: /*@__PURE__*/t(content), - /** - [Content](https://codemirror.net/6/docs/ref/#highlight.tags.content) that is styled as code or - monospace. - */ - monospace: /*@__PURE__*/t(content), - /** - [Content](https://codemirror.net/6/docs/ref/#highlight.tags.content) that has a strike-through - style. - */ - strikethrough: /*@__PURE__*/t(content), - /** - Inserted text in a change-tracking format. - */ - inserted: /*@__PURE__*/t(), - /** - Deleted text. - */ - deleted: /*@__PURE__*/t(), - /** - Changed text. - */ - changed: /*@__PURE__*/t(), - /** - An invalid or unsyntactic element. - */ - invalid: /*@__PURE__*/t(), - /** - Metadata or meta-instruction. - */ - meta, - /** - [Metadata](https://codemirror.net/6/docs/ref/#highlight.tags.meta) that applies to the entire - document. - */ - documentMeta: /*@__PURE__*/t(meta), - /** - [Metadata](https://codemirror.net/6/docs/ref/#highlight.tags.meta) that annotates or adds - attributes to a given syntactic element. - */ - annotation: /*@__PURE__*/t(meta), - /** - Processing instruction or preprocessor directive. Subtag of - [meta](https://codemirror.net/6/docs/ref/#highlight.tags.meta). - */ - processingInstruction: /*@__PURE__*/t(meta), - /** - [Modifier](https://codemirror.net/6/docs/ref/#highlight.Tag^defineModifier) that indicates that a - given element is being defined. Expected to be used with the - various [name](https://codemirror.net/6/docs/ref/#highlight.tags.name) tags. - */ - definition: /*@__PURE__*/Tag.defineModifier(), - /** - [Modifier](https://codemirror.net/6/docs/ref/#highlight.Tag^defineModifier) that indicates that - something is constant. Mostly expected to be used with - [variable names](https://codemirror.net/6/docs/ref/#highlight.tags.variableName). - */ - constant: /*@__PURE__*/Tag.defineModifier(), - /** - [Modifier](https://codemirror.net/6/docs/ref/#highlight.Tag^defineModifier) used to indicate that - a [variable](https://codemirror.net/6/docs/ref/#highlight.tags.variableName) or [property - name](https://codemirror.net/6/docs/ref/#highlight.tags.propertyName) is being called or defined - as a function. - */ - function: /*@__PURE__*/Tag.defineModifier(), - /** - [Modifier](https://codemirror.net/6/docs/ref/#highlight.Tag^defineModifier) that can be applied to - [names](https://codemirror.net/6/docs/ref/#highlight.tags.name) to indicate that they belong to - the language's standard environment. - */ - standard: /*@__PURE__*/Tag.defineModifier(), - /** - [Modifier](https://codemirror.net/6/docs/ref/#highlight.Tag^defineModifier) that indicates a given - [names](https://codemirror.net/6/docs/ref/#highlight.tags.name) is local to some scope. - */ - local: /*@__PURE__*/Tag.defineModifier(), - /** - A generic variant [modifier](https://codemirror.net/6/docs/ref/#highlight.Tag^defineModifier) that - can be used to tag language-specific alternative variants of - some common tag. It is recommended for themes to define special - forms of at least the [string](https://codemirror.net/6/docs/ref/#highlight.tags.string) and - [variable name](https://codemirror.net/6/docs/ref/#highlight.tags.variableName) tags, since those - come up a lot. - */ - special: /*@__PURE__*/Tag.defineModifier() - }; - /** - A default highlight style (works well with light themes). - */ - const defaultHighlightStyle = /*@__PURE__*/HighlightStyle.define([ - { tag: tags.link, - textDecoration: "underline" }, - { tag: tags.heading, - textDecoration: "underline", - fontWeight: "bold" }, - { tag: tags.emphasis, - fontStyle: "italic" }, - { tag: tags.strong, - fontWeight: "bold" }, - { tag: tags.strikethrough, - textDecoration: "line-through" }, - { tag: tags.keyword, - color: "#708" }, - { tag: [tags.atom, tags.bool, tags.url, tags.contentSeparator, tags.labelName], - color: "#219" }, - { tag: [tags.literal, tags.inserted], - color: "#164" }, - { tag: [tags.string, tags.deleted], - color: "#a11" }, - { tag: [tags.regexp, tags.escape, /*@__PURE__*/tags.special(tags.string)], - color: "#e40" }, - { tag: /*@__PURE__*/tags.definition(tags.variableName), - color: "#00f" }, - { tag: /*@__PURE__*/tags.local(tags.variableName), - color: "#30a" }, - { tag: [tags.typeName, tags.namespace], - color: "#085" }, - { tag: tags.className, - color: "#167" }, - { tag: [/*@__PURE__*/tags.special(tags.variableName), tags.macroName], - color: "#256" }, - { tag: /*@__PURE__*/tags.definition(tags.propertyName), - color: "#00c" }, - { tag: tags.comment, - color: "#940" }, - { tag: tags.meta, - color: "#7a757a" }, - { tag: tags.invalid, - color: "#f00" } - ]); - /** - This is a highlight style that adds stable, predictable classes to - tokens, for styling with external CSS. - - These tags are mapped to their name prefixed with `"cmt-"` (for - example `"cmt-comment"`): - - * [`link`](https://codemirror.net/6/docs/ref/#highlight.tags.link) - * [`heading`](https://codemirror.net/6/docs/ref/#highlight.tags.heading) - * [`emphasis`](https://codemirror.net/6/docs/ref/#highlight.tags.emphasis) - * [`strong`](https://codemirror.net/6/docs/ref/#highlight.tags.strong) - * [`keyword`](https://codemirror.net/6/docs/ref/#highlight.tags.keyword) - * [`atom`](https://codemirror.net/6/docs/ref/#highlight.tags.atom) - * [`bool`](https://codemirror.net/6/docs/ref/#highlight.tags.bool) - * [`url`](https://codemirror.net/6/docs/ref/#highlight.tags.url) - * [`labelName`](https://codemirror.net/6/docs/ref/#highlight.tags.labelName) - * [`inserted`](https://codemirror.net/6/docs/ref/#highlight.tags.inserted) - * [`deleted`](https://codemirror.net/6/docs/ref/#highlight.tags.deleted) - * [`literal`](https://codemirror.net/6/docs/ref/#highlight.tags.literal) - * [`string`](https://codemirror.net/6/docs/ref/#highlight.tags.string) - * [`number`](https://codemirror.net/6/docs/ref/#highlight.tags.number) - * [`variableName`](https://codemirror.net/6/docs/ref/#highlight.tags.variableName) - * [`typeName`](https://codemirror.net/6/docs/ref/#highlight.tags.typeName) - * [`namespace`](https://codemirror.net/6/docs/ref/#highlight.tags.namespace) - * [`className`](https://codemirror.net/6/docs/ref/#highlight.tags.className) - * [`macroName`](https://codemirror.net/6/docs/ref/#highlight.tags.macroName) - * [`propertyName`](https://codemirror.net/6/docs/ref/#highlight.tags.propertyName) - * [`operator`](https://codemirror.net/6/docs/ref/#highlight.tags.operator) - * [`comment`](https://codemirror.net/6/docs/ref/#highlight.tags.comment) - * [`meta`](https://codemirror.net/6/docs/ref/#highlight.tags.meta) - * [`punctuation`](https://codemirror.net/6/docs/ref/#highlight.tags.puncutation) - * [`invalid`](https://codemirror.net/6/docs/ref/#highlight.tags.invalid) - - In addition, these mappings are provided: - - * [`regexp`](https://codemirror.net/6/docs/ref/#highlight.tags.regexp), - [`escape`](https://codemirror.net/6/docs/ref/#highlight.tags.escape), and - [`special`](https://codemirror.net/6/docs/ref/#highlight.tags.special)[`(string)`](https://codemirror.net/6/docs/ref/#highlight.tags.string) - are mapped to `"cmt-string2"` - * [`special`](https://codemirror.net/6/docs/ref/#highlight.tags.special)[`(variableName)`](https://codemirror.net/6/docs/ref/#highlight.tags.variableName) - to `"cmt-variableName2"` - * [`local`](https://codemirror.net/6/docs/ref/#highlight.tags.local)[`(variableName)`](https://codemirror.net/6/docs/ref/#highlight.tags.variableName) - to `"cmt-variableName cmt-local"` - * [`definition`](https://codemirror.net/6/docs/ref/#highlight.tags.definition)[`(variableName)`](https://codemirror.net/6/docs/ref/#highlight.tags.variableName) - to `"cmt-variableName cmt-definition"` - * [`definition`](https://codemirror.net/6/docs/ref/#highlight.tags.definition)[`(propertyName)`](https://codemirror.net/6/docs/ref/#highlight.tags.propertyName) - to `"cmt-propertyName cmt-definition"` - */ - /*@__PURE__*/HighlightStyle.define([ - { tag: tags.link, class: "cmt-link" }, - { tag: tags.heading, class: "cmt-heading" }, - { tag: tags.emphasis, class: "cmt-emphasis" }, - { tag: tags.strong, class: "cmt-strong" }, - { tag: tags.keyword, class: "cmt-keyword" }, - { tag: tags.atom, class: "cmt-atom" }, - { tag: tags.bool, class: "cmt-bool" }, - { tag: tags.url, class: "cmt-url" }, - { tag: tags.labelName, class: "cmt-labelName" }, - { tag: tags.inserted, class: "cmt-inserted" }, - { tag: tags.deleted, class: "cmt-deleted" }, - { tag: tags.literal, class: "cmt-literal" }, - { tag: tags.string, class: "cmt-string" }, - { tag: tags.number, class: "cmt-number" }, - { tag: [tags.regexp, tags.escape, /*@__PURE__*/tags.special(tags.string)], class: "cmt-string2" }, - { tag: tags.variableName, class: "cmt-variableName" }, - { tag: /*@__PURE__*/tags.local(tags.variableName), class: "cmt-variableName cmt-local" }, - { tag: /*@__PURE__*/tags.definition(tags.variableName), class: "cmt-variableName cmt-definition" }, - { tag: /*@__PURE__*/tags.special(tags.variableName), class: "cmt-variableName2" }, - { tag: /*@__PURE__*/tags.definition(tags.propertyName), class: "cmt-propertyName cmt-definition" }, - { tag: tags.typeName, class: "cmt-typeName" }, - { tag: tags.namespace, class: "cmt-namespace" }, - { tag: tags.className, class: "cmt-className" }, - { tag: tags.macroName, class: "cmt-macroName" }, - { tag: tags.propertyName, class: "cmt-propertyName" }, - { tag: tags.operator, class: "cmt-operator" }, - { tag: tags.comment, class: "cmt-comment" }, - { tag: tags.meta, class: "cmt-meta" }, - { tag: tags.invalid, class: "cmt-invalid" }, - { tag: tags.punctuation, class: "cmt-punctuation" } - ]); - - class SelectedDiagnostic { - constructor(from, to, diagnostic) { - this.from = from; - this.to = to; - this.diagnostic = diagnostic; - } - } - class LintState { - constructor(diagnostics, panel, selected) { - this.diagnostics = diagnostics; - this.panel = panel; - this.selected = selected; - } - static init(diagnostics, panel, state) { - let ranges = Decoration.set(diagnostics.map((d) => { - // For zero-length ranges or ranges covering only a line break, create a widget - return d.from == d.to || (d.from == d.to - 1 && state.doc.lineAt(d.from).to == d.from) - ? Decoration.widget({ - widget: new DiagnosticWidget(d), - diagnostic: d - }).range(d.from) - : Decoration.mark({ - attributes: { class: "cm-lintRange cm-lintRange-" + d.severity }, - diagnostic: d - }).range(d.from, d.to); - }), true); - return new LintState(ranges, panel, findDiagnostic(ranges)); - } - } - function findDiagnostic(diagnostics, diagnostic = null, after = 0) { - let found = null; - diagnostics.between(after, 1e9, (from, to, { spec }) => { - if (diagnostic && spec.diagnostic != diagnostic) - return; - found = new SelectedDiagnostic(from, to, spec.diagnostic); - return false; - }); - return found; - } - function maybeEnableLint(state, effects) { - return state.field(lintState, false) ? effects : effects.concat(StateEffect.appendConfig.of([ - lintState, - EditorView.decorations.compute([lintState], state => { - let { selected, panel } = state.field(lintState); - return !selected || !panel || selected.from == selected.to ? Decoration.none : Decoration.set([ - activeMark.range(selected.from, selected.to) - ]); - }), - hoverTooltip(lintTooltip), - baseTheme - ])); - } - /** - The state effect that updates the set of active diagnostics. Can - be useful when writing an extension that needs to track these. - */ - const setDiagnosticsEffect = /*@__PURE__*/StateEffect.define(); - const togglePanel = /*@__PURE__*/StateEffect.define(); - const movePanelSelection = /*@__PURE__*/StateEffect.define(); - const lintState = /*@__PURE__*/StateField.define({ - create() { - return new LintState(Decoration.none, null, null); - }, - update(value, tr) { - if (tr.docChanged) { - let mapped = value.diagnostics.map(tr.changes), selected = null; - if (value.selected) { - let selPos = tr.changes.mapPos(value.selected.from, 1); - selected = findDiagnostic(mapped, value.selected.diagnostic, selPos) || findDiagnostic(mapped, null, selPos); - } - value = new LintState(mapped, value.panel, selected); - } - for (let effect of tr.effects) { - if (effect.is(setDiagnosticsEffect)) { - value = LintState.init(effect.value, value.panel, tr.state); - } - else if (effect.is(togglePanel)) { - value = new LintState(value.diagnostics, effect.value ? LintPanel.open : null, value.selected); - } - else if (effect.is(movePanelSelection)) { - value = new LintState(value.diagnostics, value.panel, effect.value); - } - } - return value; - }, - provide: f => [showPanel.from(f, val => val.panel), - EditorView.decorations.from(f, s => s.diagnostics)] - }); - const activeMark = /*@__PURE__*/Decoration.mark({ class: "cm-lintRange cm-lintRange-active" }); - function lintTooltip(view, pos, side) { - let { diagnostics } = view.state.field(lintState); - let found = [], stackStart = 2e8, stackEnd = 0; - diagnostics.between(pos - (side < 0 ? 1 : 0), pos + (side > 0 ? 1 : 0), (from, to, { spec }) => { - if (pos >= from && pos <= to && - (from == to || ((pos > from || side > 0) && (pos < to || side < 0)))) { - found.push(spec.diagnostic); - stackStart = Math.min(from, stackStart); - stackEnd = Math.max(to, stackEnd); - } - }); - if (!found.length) - return null; - return { - pos: stackStart, - end: stackEnd, - above: view.state.doc.lineAt(stackStart).to < stackEnd, - create() { - return { dom: diagnosticsTooltip(view, found) }; - } - }; - } - function diagnosticsTooltip(view, diagnostics) { - return crelt("ul", { class: "cm-tooltip-lint" }, diagnostics.map(d => renderDiagnostic(view, d, false))); - } - /** - Command to open and focus the lint panel. - */ - const openLintPanel = (view) => { - let field = view.state.field(lintState, false); - if (!field || !field.panel) - view.dispatch({ effects: maybeEnableLint(view.state, [togglePanel.of(true)]) }); - let panel = getPanel(view, LintPanel.open); - if (panel) - panel.dom.querySelector(".cm-panel-lint ul").focus(); - return true; - }; - /** - Command to close the lint panel, when open. - */ - const closeLintPanel = (view) => { - let field = view.state.field(lintState, false); - if (!field || !field.panel) - return false; - view.dispatch({ effects: togglePanel.of(false) }); - return true; - }; - /** - Move the selection to the next diagnostic. - */ - const nextDiagnostic = (view) => { - let field = view.state.field(lintState, false); - if (!field) - return false; - let sel = view.state.selection.main, next = field.diagnostics.iter(sel.to + 1); - if (!next.value) { - next = field.diagnostics.iter(0); - if (!next.value || next.from == sel.from && next.to == sel.to) - return false; - } - view.dispatch({ selection: { anchor: next.from, head: next.to }, scrollIntoView: true }); - return true; - }; - /** - A set of default key bindings for the lint functionality. - - - Ctrl-Shift-m (Cmd-Shift-m on macOS): [`openLintPanel`](https://codemirror.net/6/docs/ref/#lint.openLintPanel) - - F8: [`nextDiagnostic`](https://codemirror.net/6/docs/ref/#lint.nextDiagnostic) - */ - const lintKeymap = [ - { key: "Mod-Shift-m", run: openLintPanel }, - { key: "F8", run: nextDiagnostic } - ]; - function assignKeys(actions) { - let assigned = []; - if (actions) - actions: for (let { name } of actions) { - for (let i = 0; i < name.length; i++) { - let ch = name[i]; - if (/[a-zA-Z]/.test(ch) && !assigned.some(c => c.toLowerCase() == ch.toLowerCase())) { - assigned.push(ch); - continue actions; - } - } - assigned.push(""); - } - return assigned; - } - function renderDiagnostic(view, diagnostic, inPanel) { - var _a; - let keys = inPanel ? assignKeys(diagnostic.actions) : []; - return crelt("li", { class: "cm-diagnostic cm-diagnostic-" + diagnostic.severity }, crelt("span", { class: "cm-diagnosticText" }, diagnostic.message), (_a = diagnostic.actions) === null || _a === void 0 ? void 0 : _a.map((action, i) => { - let click = (e) => { - e.preventDefault(); - let found = findDiagnostic(view.state.field(lintState).diagnostics, diagnostic); - if (found) - action.apply(view, found.from, found.to); - }; - let { name } = action, keyIndex = keys[i] ? name.indexOf(keys[i]) : -1; - let nameElt = keyIndex < 0 ? name : [name.slice(0, keyIndex), - crelt("u", name.slice(keyIndex, keyIndex + 1)), - name.slice(keyIndex + 1)]; - return crelt("button", { - type: "button", - class: "cm-diagnosticAction", - onclick: click, - onmousedown: click, - "aria-label": ` Action: ${name}${keyIndex < 0 ? "" : ` (access key "${keys[i]})"`}.` - }, nameElt); - }), diagnostic.source && crelt("div", { class: "cm-diagnosticSource" }, diagnostic.source)); - } - class DiagnosticWidget extends WidgetType { - constructor(diagnostic) { - super(); - this.diagnostic = diagnostic; - } - eq(other) { return other.diagnostic == this.diagnostic; } - toDOM() { - return crelt("span", { class: "cm-lintPoint cm-lintPoint-" + this.diagnostic.severity }); - } - } - class PanelItem { - constructor(view, diagnostic) { - this.diagnostic = diagnostic; - this.id = "item_" + Math.floor(Math.random() * 0xffffffff).toString(16); - this.dom = renderDiagnostic(view, diagnostic, true); - this.dom.id = this.id; - this.dom.setAttribute("role", "option"); - } - } - class LintPanel { - constructor(view) { - this.view = view; - this.items = []; - let onkeydown = (event) => { - if (event.keyCode == 27) { // Escape - closeLintPanel(this.view); - this.view.focus(); - } - else if (event.keyCode == 38 || event.keyCode == 33) { // ArrowUp, PageUp - this.moveSelection((this.selectedIndex - 1 + this.items.length) % this.items.length); - } - else if (event.keyCode == 40 || event.keyCode == 34) { // ArrowDown, PageDown - this.moveSelection((this.selectedIndex + 1) % this.items.length); - } - else if (event.keyCode == 36) { // Home - this.moveSelection(0); - } - else if (event.keyCode == 35) { // End - this.moveSelection(this.items.length - 1); - } - else if (event.keyCode == 13) { // Enter - this.view.focus(); - } - else if (event.keyCode >= 65 && event.keyCode <= 90 && this.selectedIndex >= 0) { // A-Z - let { diagnostic } = this.items[this.selectedIndex], keys = assignKeys(diagnostic.actions); - for (let i = 0; i < keys.length; i++) - if (keys[i].toUpperCase().charCodeAt(0) == event.keyCode) { - let found = findDiagnostic(this.view.state.field(lintState).diagnostics, diagnostic); - if (found) - diagnostic.actions[i].apply(view, found.from, found.to); - } - } - else { - return; - } - event.preventDefault(); - }; - let onclick = (event) => { - for (let i = 0; i < this.items.length; i++) { - if (this.items[i].dom.contains(event.target)) - this.moveSelection(i); - } - }; - this.list = crelt("ul", { - tabIndex: 0, - role: "listbox", - "aria-label": this.view.state.phrase("Diagnostics"), - onkeydown, - onclick - }); - this.dom = crelt("div", { class: "cm-panel-lint" }, this.list, crelt("button", { - type: "button", - name: "close", - "aria-label": this.view.state.phrase("close"), - onclick: () => closeLintPanel(this.view) - }, "×")); - this.update(); - } - get selectedIndex() { - let selected = this.view.state.field(lintState).selected; - if (!selected) - return -1; - for (let i = 0; i < this.items.length; i++) - if (this.items[i].diagnostic == selected.diagnostic) - return i; - return -1; - } - update() { - let { diagnostics, selected } = this.view.state.field(lintState); - let i = 0, needsSync = false, newSelectedItem = null; - diagnostics.between(0, this.view.state.doc.length, (_start, _end, { spec }) => { - let found = -1, item; - for (let j = i; j < this.items.length; j++) - if (this.items[j].diagnostic == spec.diagnostic) { - found = j; - break; - } - if (found < 0) { - item = new PanelItem(this.view, spec.diagnostic); - this.items.splice(i, 0, item); - needsSync = true; - } - else { - item = this.items[found]; - if (found > i) { - this.items.splice(i, found - i); - needsSync = true; - } - } - if (selected && item.diagnostic == selected.diagnostic) { - if (!item.dom.hasAttribute("aria-selected")) { - item.dom.setAttribute("aria-selected", "true"); - newSelectedItem = item; - } - } - else if (item.dom.hasAttribute("aria-selected")) { - item.dom.removeAttribute("aria-selected"); - } - i++; - }); - while (i < this.items.length && !(this.items.length == 1 && this.items[0].diagnostic.from < 0)) { - needsSync = true; - this.items.pop(); - } - if (this.items.length == 0) { - this.items.push(new PanelItem(this.view, { - from: -1, to: -1, - severity: "info", - message: this.view.state.phrase("No diagnostics") - })); - needsSync = true; - } - if (newSelectedItem) { - this.list.setAttribute("aria-activedescendant", newSelectedItem.id); - this.view.requestMeasure({ - key: this, - read: () => ({ sel: newSelectedItem.dom.getBoundingClientRect(), panel: this.list.getBoundingClientRect() }), - write: ({ sel, panel }) => { - if (sel.top < panel.top) - this.list.scrollTop -= panel.top - sel.top; - else if (sel.bottom > panel.bottom) - this.list.scrollTop += sel.bottom - panel.bottom; - } - }); - } - else if (this.selectedIndex < 0) { - this.list.removeAttribute("aria-activedescendant"); - } - if (needsSync) - this.sync(); - } - sync() { - let domPos = this.list.firstChild; - function rm() { - let prev = domPos; - domPos = prev.nextSibling; - prev.remove(); - } - for (let item of this.items) { - if (item.dom.parentNode == this.list) { - while (domPos != item.dom) - rm(); - domPos = item.dom.nextSibling; - } - else { - this.list.insertBefore(item.dom, domPos); - } - } - while (domPos) - rm(); - } - moveSelection(selectedIndex) { - if (this.selectedIndex < 0) - return; - let field = this.view.state.field(lintState); - let selection = findDiagnostic(field.diagnostics, this.items[selectedIndex].diagnostic); - if (!selection) - return; - this.view.dispatch({ - selection: { anchor: selection.from, head: selection.to }, - scrollIntoView: true, - effects: movePanelSelection.of(selection) - }); - } - static open(view) { return new LintPanel(view); } - } - function svg(content, attrs = `viewBox="0 0 40 40"`) { - return `url('data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" ${attrs}>${encodeURIComponent(content)}</svg>')`; - } - function underline(color) { - return svg(`<path d="m0 2.5 l2 -1.5 l1 0 l2 1.5 l1 0" stroke="${color}" fill="none" stroke-width=".7"/>`, `width="6" height="3"`); - } - const baseTheme = /*@__PURE__*/EditorView.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-diagnosticAction": { - font: "inherit", - border: "none", - padding: "2px 4px", - backgroundColor: "#444", - color: "white", - borderRadius: "3px", - marginLeft: "8px" - }, - ".cm-diagnosticSource": { - fontSize: "70%", - opacity: .7 - }, - ".cm-lintRange": { - backgroundPosition: "left bottom", - backgroundRepeat: "repeat-x", - paddingBottom: "0.7px", - }, - ".cm-lintRange-error": { backgroundImage: /*@__PURE__*/underline("#d11") }, - ".cm-lintRange-warning": { backgroundImage: /*@__PURE__*/underline("orange") }, - ".cm-lintRange-info": { backgroundImage: /*@__PURE__*/underline("#999") }, - ".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-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 - } - } - }); - - /** - This is an extension value that just pulls together a whole lot of - extensions that you might want in a basic editor. It is meant as a - convenient helper to quickly set up CodeMirror without installing - and importing a lot of packages. - - Specifically, it includes... - - - [the default command bindings](https://codemirror.net/6/docs/ref/#commands.defaultKeymap) - - [line numbers](https://codemirror.net/6/docs/ref/#gutter.lineNumbers) - - [special character highlighting](https://codemirror.net/6/docs/ref/#view.highlightSpecialChars) - - [the undo history](https://codemirror.net/6/docs/ref/#history.history) - - [a fold gutter](https://codemirror.net/6/docs/ref/#fold.foldGutter) - - [custom selection drawing](https://codemirror.net/6/docs/ref/#view.drawSelection) - - [drop cursor](https://codemirror.net/6/docs/ref/#view.dropCursor) - - [multiple selections](https://codemirror.net/6/docs/ref/#state.EditorState^allowMultipleSelections) - - [reindentation on input](https://codemirror.net/6/docs/ref/#language.indentOnInput) - - [the default highlight style](https://codemirror.net/6/docs/ref/#highlight.defaultHighlightStyle) (as fallback) - - [bracket matching](https://codemirror.net/6/docs/ref/#matchbrackets.bracketMatching) - - [bracket closing](https://codemirror.net/6/docs/ref/#closebrackets.closeBrackets) - - [autocompletion](https://codemirror.net/6/docs/ref/#autocomplete.autocompletion) - - [rectangular selection](https://codemirror.net/6/docs/ref/#rectangular-selection.rectangularSelection) and [crosshair cursor](https://codemirror.net/6/docs/ref/#rectangular-selection.crosshairCursor) - - [active line highlighting](https://codemirror.net/6/docs/ref/#view.highlightActiveLine) - - [active line gutter highlighting](https://codemirror.net/6/docs/ref/#gutter.highlightActiveLineGutter) - - [selection match highlighting](https://codemirror.net/6/docs/ref/#search.highlightSelectionMatches) - - [search](https://codemirror.net/6/docs/ref/#search.searchKeymap) - - [commenting](https://codemirror.net/6/docs/ref/#comment.commentKeymap) - - [linting](https://codemirror.net/6/docs/ref/#lint.lintKeymap) - - (You'll probably want to add some language package to your setup - too.) - - This package does not allow customization. The idea is that, once - you decide you want to configure your editor more precisely, you - take this package's source (which is just a bunch of imports and - an array literal), copy it into your own code, and adjust it as - desired. - */ - const basicSetup = [ - /*@__PURE__*/lineNumbers(), - /*@__PURE__*/highlightActiveLineGutter(), - /*@__PURE__*/highlightSpecialChars(), - /*@__PURE__*/history(), - /*@__PURE__*/foldGutter(), - /*@__PURE__*/drawSelection(), - /*@__PURE__*/dropCursor(), - /*@__PURE__*/EditorState.allowMultipleSelections.of(true), - /*@__PURE__*/indentOnInput(), - defaultHighlightStyle.fallback, - /*@__PURE__*/bracketMatching(), - /*@__PURE__*/closeBrackets(), - /*@__PURE__*/autocompletion(), - /*@__PURE__*/rectangularSelection(), - /*@__PURE__*/crosshairCursor(), - /*@__PURE__*/highlightActiveLine(), - /*@__PURE__*/highlightSelectionMatches(), - /*@__PURE__*/keymap.of([ - ...closeBracketsKeymap, - ...defaultKeymap, - ...searchKeymap, - ...historyKeymap, - ...foldKeymap, - ...commentKeymap, - ...completionKeymap, - ...lintKeymap - ]) - ]; - - /// A parse stack. These are used internally by the parser to track - /// parsing progress. They also provide some properties and methods - /// that external code such as a tokenizer can use to get information - /// about the parse state. - class Stack { - /// @internal - constructor( - /// The parse that this stack is part of @internal - p, - /// Holds state, input pos, buffer index triplets for all but the - /// top state @internal - stack, - /// The current parse state @internal - state, - // The position at which the next reduce should take place. This - // can be less than `this.pos` when skipped expressions have been - // added to the stack (which should be moved outside of the next - // reduction) - /// @internal - reducePos, - /// The input position up to which this stack has parsed. - pos, - /// The dynamic score of the stack, including dynamic precedence - /// and error-recovery penalties - /// @internal - score, - // The output buffer. Holds (type, start, end, size) quads - // representing nodes created by the parser, where `size` is - // amount of buffer array entries covered by this node. - /// @internal - buffer, - // The base offset of the buffer. When stacks are split, the split - // instance shared the buffer history with its parent up to - // `bufferBase`, which is the absolute offset (including the - // offset of previous splits) into the buffer at which this stack - // starts writing. - /// @internal - bufferBase, - /// @internal - curContext, - /// @internal - lookAhead = 0, - // A parent stack from which this was split off, if any. This is - // set up so that it always points to a stack that has some - // additional buffer content, never to a stack with an equal - // `bufferBase`. - /// @internal - parent) { - this.p = p; - this.stack = stack; - this.state = state; - this.reducePos = reducePos; - this.pos = pos; - this.score = score; - this.buffer = buffer; - this.bufferBase = bufferBase; - this.curContext = curContext; - this.lookAhead = lookAhead; - this.parent = parent; - } - /// @internal - toString() { - return `[${this.stack.filter((_, i) => i % 3 == 0).concat(this.state)}]@${this.pos}${this.score ? "!" + this.score : ""}`; - } - // Start an empty stack - /// @internal - static start(p, state, pos = 0) { - let cx = p.parser.context; - return new Stack(p, [], state, pos, pos, 0, [], 0, cx ? new StackContext(cx, cx.start) : null, 0, null); - } - /// The stack's current [context](#lr.ContextTracker) value, if - /// any. Its type will depend on the context tracker's type - /// parameter, or it will be `null` if there is no context - /// tracker. - get context() { return this.curContext ? this.curContext.context : null; } - // Push a state onto the stack, tracking its start position as well - // as the buffer base at that point. - /// @internal - pushState(state, start) { - this.stack.push(this.state, start, this.bufferBase + this.buffer.length); - this.state = state; - } - // Apply a reduce action - /// @internal - reduce(action) { - let depth = action >> 19 /* ReduceDepthShift */, type = action & 65535 /* ValueMask */; - let { parser } = this.p; - let dPrec = parser.dynamicPrecedence(type); - if (dPrec) - this.score += dPrec; - if (depth == 0) { - this.pushState(parser.getGoto(this.state, type, true), this.reducePos); - // Zero-depth reductions are a special case—they add stuff to - // the stack without popping anything off. - if (type < parser.minRepeatTerm) - this.storeNode(type, this.reducePos, this.reducePos, 4, true); - this.reduceContext(type, this.reducePos); - return; - } - // Find the base index into `this.stack`, content after which will - // be dropped. Note that with `StayFlag` reductions we need to - // consume two extra frames (the dummy parent node for the skipped - // expression and the state that we'll be staying in, which should - // be moved to `this.state`). - let base = this.stack.length - ((depth - 1) * 3) - (action & 262144 /* StayFlag */ ? 6 : 0); - let start = this.stack[base - 2]; - let bufferBase = this.stack[base - 1], count = this.bufferBase + this.buffer.length - bufferBase; - // Store normal terms or `R -> R R` repeat reductions - if (type < parser.minRepeatTerm || (action & 131072 /* RepeatFlag */)) { - let pos = parser.stateFlag(this.state, 1 /* Skipped */) ? this.pos : this.reducePos; - this.storeNode(type, start, pos, count + 4, true); - } - if (action & 262144 /* StayFlag */) { - this.state = this.stack[base]; - } - else { - let baseStateID = this.stack[base - 3]; - this.state = parser.getGoto(baseStateID, type, true); - } - while (this.stack.length > base) - this.stack.pop(); - this.reduceContext(type, start); - } - // Shift a value into the buffer - /// @internal - storeNode(term, start, end, size = 4, isReduce = false) { - if (term == 0 /* Err */) { // Try to omit/merge adjacent error nodes - let cur = this, top = this.buffer.length; - if (top == 0 && cur.parent) { - top = cur.bufferBase - cur.parent.bufferBase; - cur = cur.parent; - } - if (top > 0 && cur.buffer[top - 4] == 0 /* Err */ && cur.buffer[top - 1] > -1) { - if (start == end) - return; - if (cur.buffer[top - 2] >= start) { - cur.buffer[top - 2] = end; - return; - } - } - } - if (!isReduce || this.pos == end) { // Simple case, just append - this.buffer.push(term, start, end, size); - } - else { // There may be skipped nodes that have to be moved forward - let index = this.buffer.length; - if (index > 0 && this.buffer[index - 4] != 0 /* Err */) - while (index > 0 && this.buffer[index - 2] > end) { - // Move this record forward - this.buffer[index] = this.buffer[index - 4]; - this.buffer[index + 1] = this.buffer[index - 3]; - this.buffer[index + 2] = this.buffer[index - 2]; - this.buffer[index + 3] = this.buffer[index - 1]; - index -= 4; - if (size > 4) - size -= 4; - } - this.buffer[index] = term; - this.buffer[index + 1] = start; - this.buffer[index + 2] = end; - this.buffer[index + 3] = size; - } - } - // Apply a shift action - /// @internal - shift(action, next, nextEnd) { - let start = this.pos; - if (action & 131072 /* GotoFlag */) { - this.pushState(action & 65535 /* ValueMask */, this.pos); - } - else if ((action & 262144 /* StayFlag */) == 0) { // Regular shift - let nextState = action, { parser } = this.p; - if (nextEnd > this.pos || next <= parser.maxNode) { - this.pos = nextEnd; - if (!parser.stateFlag(nextState, 1 /* Skipped */)) - this.reducePos = nextEnd; - } - this.pushState(nextState, start); - this.shiftContext(next, start); - if (next <= parser.maxNode) - this.buffer.push(next, start, nextEnd, 4); - } - else { // Shift-and-stay, which means this is a skipped token - this.pos = nextEnd; - this.shiftContext(next, start); - if (next <= this.p.parser.maxNode) - this.buffer.push(next, start, nextEnd, 4); - } - } - // Apply an action - /// @internal - apply(action, next, nextEnd) { - if (action & 65536 /* ReduceFlag */) - this.reduce(action); - else - this.shift(action, next, nextEnd); - } - // Add a prebuilt (reused) node into the buffer. - /// @internal - useNode(value, next) { - let index = this.p.reused.length - 1; - if (index < 0 || this.p.reused[index] != value) { - this.p.reused.push(value); - index++; - } - let start = this.pos; - this.reducePos = this.pos = start + value.length; - this.pushState(next, start); - this.buffer.push(index, start, this.reducePos, -1 /* size == -1 means this is a reused value */); - if (this.curContext) - this.updateContext(this.curContext.tracker.reuse(this.curContext.context, value, this, this.p.stream.reset(this.pos - value.length))); - } - // Split the stack. Due to the buffer sharing and the fact - // that `this.stack` tends to stay quite shallow, this isn't very - // expensive. - /// @internal - split() { - let parent = this; - let off = parent.buffer.length; - // Because the top of the buffer (after this.pos) may be mutated - // to reorder reductions and skipped tokens, and shared buffers - // should be immutable, this copies any outstanding skipped tokens - // to the new buffer, and puts the base pointer before them. - while (off > 0 && parent.buffer[off - 2] > parent.reducePos) - off -= 4; - let buffer = parent.buffer.slice(off), base = parent.bufferBase + off; - // Make sure parent points to an actual parent with content, if there is such a parent. - while (parent && base == parent.bufferBase) - parent = parent.parent; - return new Stack(this.p, this.stack.slice(), this.state, this.reducePos, this.pos, this.score, buffer, base, this.curContext, this.lookAhead, parent); - } - // Try to recover from an error by 'deleting' (ignoring) one token. - /// @internal - recoverByDelete(next, nextEnd) { - let isNode = next <= this.p.parser.maxNode; - if (isNode) - this.storeNode(next, this.pos, nextEnd, 4); - this.storeNode(0 /* Err */, this.pos, nextEnd, isNode ? 8 : 4); - this.pos = this.reducePos = nextEnd; - this.score -= 190 /* Delete */; - } - /// Check if the given term would be able to be shifted (optionally - /// after some reductions) on this stack. This can be useful for - /// external tokenizers that want to make sure they only provide a - /// given token when it applies. - canShift(term) { - for (let sim = new SimulatedStack(this);;) { - let action = this.p.parser.stateSlot(sim.state, 4 /* DefaultReduce */) || this.p.parser.hasAction(sim.state, term); - if ((action & 65536 /* ReduceFlag */) == 0) - return true; - if (action == 0) - return false; - sim.reduce(action); - } - } - // Apply up to Recover.MaxNext recovery actions that conceptually - // inserts some missing token or rule. - /// @internal - recoverByInsert(next) { - if (this.stack.length >= 300 /* MaxInsertStackDepth */) - return []; - let nextStates = this.p.parser.nextStates(this.state); - if (nextStates.length > 4 /* MaxNext */ << 1 || this.stack.length >= 120 /* DampenInsertStackDepth */) { - let best = []; - for (let i = 0, s; i < nextStates.length; i += 2) { - if ((s = nextStates[i + 1]) != this.state && this.p.parser.hasAction(s, next)) - best.push(nextStates[i], s); - } - if (this.stack.length < 120 /* DampenInsertStackDepth */) - for (let i = 0; best.length < 4 /* MaxNext */ << 1 && i < nextStates.length; i += 2) { - let s = nextStates[i + 1]; - if (!best.some((v, i) => (i & 1) && v == s)) - best.push(nextStates[i], s); - } - nextStates = best; - } - let result = []; - for (let i = 0; i < nextStates.length && result.length < 4 /* MaxNext */; i += 2) { - let s = nextStates[i + 1]; - if (s == this.state) - continue; - let stack = this.split(); - stack.storeNode(0 /* Err */, stack.pos, stack.pos, 4, true); - stack.pushState(s, this.pos); - stack.shiftContext(nextStates[i], this.pos); - stack.score -= 200 /* Insert */; - result.push(stack); - } - return result; - } - // Force a reduce, if possible. Return false if that can't - // be done. - /// @internal - forceReduce() { - let reduce = this.p.parser.stateSlot(this.state, 5 /* ForcedReduce */); - if ((reduce & 65536 /* ReduceFlag */) == 0) - return false; - let { parser } = this.p; - if (!parser.validAction(this.state, reduce)) { - let depth = reduce >> 19 /* ReduceDepthShift */, term = reduce & 65535 /* ValueMask */; - let target = this.stack.length - depth * 3; - if (target < 0 || parser.getGoto(this.stack[target], term, false) < 0) - return false; - this.storeNode(0 /* Err */, this.reducePos, this.reducePos, 4, true); - this.score -= 100 /* Reduce */; - } - this.reduce(reduce); - return true; - } - /// @internal - forceAll() { - while (!this.p.parser.stateFlag(this.state, 2 /* Accepting */)) { - if (!this.forceReduce()) { - this.storeNode(0 /* Err */, this.pos, this.pos, 4, true); - break; - } - } - return this; - } - /// Check whether this state has no further actions (assumed to be a direct descendant of the - /// top state, since any other states must be able to continue - /// somehow). @internal - get deadEnd() { - if (this.stack.length != 3) - return false; - let { parser } = this.p; - return parser.data[parser.stateSlot(this.state, 1 /* Actions */)] == 65535 /* End */ && - !parser.stateSlot(this.state, 4 /* DefaultReduce */); - } - /// Restart the stack (put it back in its start state). Only safe - /// when this.stack.length == 3 (state is directly below the top - /// state). @internal - restart() { - this.state = this.stack[0]; - this.stack.length = 0; - } - /// @internal - sameState(other) { - if (this.state != other.state || this.stack.length != other.stack.length) - return false; - for (let i = 0; i < this.stack.length; i += 3) - if (this.stack[i] != other.stack[i]) - return false; - return true; - } - /// Get the parser used by this stack. - get parser() { return this.p.parser; } - /// Test whether a given dialect (by numeric ID, as exported from - /// the terms file) is enabled. - dialectEnabled(dialectID) { return this.p.parser.dialect.flags[dialectID]; } - shiftContext(term, start) { - if (this.curContext) - this.updateContext(this.curContext.tracker.shift(this.curContext.context, term, this, this.p.stream.reset(start))); - } - reduceContext(term, start) { - if (this.curContext) - this.updateContext(this.curContext.tracker.reduce(this.curContext.context, term, this, this.p.stream.reset(start))); - } - /// @internal - emitContext() { - let last = this.buffer.length - 1; - if (last < 0 || this.buffer[last] != -3) - this.buffer.push(this.curContext.hash, this.reducePos, this.reducePos, -3); - } - /// @internal - emitLookAhead() { - let last = this.buffer.length - 1; - if (last < 0 || this.buffer[last] != -4) - this.buffer.push(this.lookAhead, this.reducePos, this.reducePos, -4); - } - updateContext(context) { - if (context != this.curContext.context) { - let newCx = new StackContext(this.curContext.tracker, context); - if (newCx.hash != this.curContext.hash) - this.emitContext(); - this.curContext = newCx; - } - } - /// @internal - setLookAhead(lookAhead) { - if (lookAhead > this.lookAhead) { - this.emitLookAhead(); - this.lookAhead = lookAhead; - } - } - /// @internal - close() { - if (this.curContext && this.curContext.tracker.strict) - this.emitContext(); - if (this.lookAhead > 0) - this.emitLookAhead(); - } - } - class StackContext { - constructor(tracker, context) { - this.tracker = tracker; - this.context = context; - this.hash = tracker.strict ? tracker.hash(context) : 0; - } - } - var Recover; - (function (Recover) { - Recover[Recover["Insert"] = 200] = "Insert"; - Recover[Recover["Delete"] = 190] = "Delete"; - Recover[Recover["Reduce"] = 100] = "Reduce"; - Recover[Recover["MaxNext"] = 4] = "MaxNext"; - Recover[Recover["MaxInsertStackDepth"] = 300] = "MaxInsertStackDepth"; - Recover[Recover["DampenInsertStackDepth"] = 120] = "DampenInsertStackDepth"; - })(Recover || (Recover = {})); - // Used to cheaply run some reductions to scan ahead without mutating - // an entire stack - class SimulatedStack { - constructor(start) { - this.start = start; - this.state = start.state; - this.stack = start.stack; - this.base = this.stack.length; - } - reduce(action) { - let term = action & 65535 /* ValueMask */, depth = action >> 19 /* ReduceDepthShift */; - if (depth == 0) { - if (this.stack == this.start.stack) - this.stack = this.stack.slice(); - this.stack.push(this.state, 0, 0); - this.base += 3; - } - else { - this.base -= (depth - 1) * 3; - } - let goto = this.start.p.parser.getGoto(this.stack[this.base - 3], term, true); - this.state = goto; - } - } - // This is given to `Tree.build` to build a buffer, and encapsulates - // the parent-stack-walking necessary to read the nodes. - class StackBufferCursor { - constructor(stack, pos, index) { - this.stack = stack; - this.pos = pos; - this.index = index; - this.buffer = stack.buffer; - if (this.index == 0) - this.maybeNext(); - } - static create(stack, pos = stack.bufferBase + stack.buffer.length) { - return new StackBufferCursor(stack, pos, pos - stack.bufferBase); - } - maybeNext() { - let next = this.stack.parent; - if (next != null) { - this.index = this.stack.bufferBase - next.bufferBase; - this.stack = next; - this.buffer = next.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; - if (this.index == 0) - this.maybeNext(); - } - fork() { - return new StackBufferCursor(this.stack, this.pos, this.index); - } - } - - class CachedToken { - constructor() { - this.start = -1; - this.value = -1; - this.end = -1; - this.extended = -1; - this.lookAhead = 0; - this.mask = 0; - this.context = 0; - } - } - const nullToken = new CachedToken; - /// [Tokenizers](#lr.ExternalTokenizer) interact with the input - /// through this interface. It presents the input as a stream of - /// characters, tracking lookahead and hiding the complexity of - /// [ranges](#common.Parser.parse^ranges) from tokenizer code. - class InputStream { - /// @internal - constructor( - /// @internal - input, - /// @internal - ranges) { - this.input = input; - this.ranges = ranges; - /// @internal - this.chunk = ""; - /// @internal - this.chunkOff = 0; - /// Backup chunk - this.chunk2 = ""; - this.chunk2Pos = 0; - /// The character code of the next code unit in the input, or -1 - /// when the stream is at the end of the input. - this.next = -1; - /// @internal - this.token = nullToken; - this.rangeIndex = 0; - this.pos = this.chunkPos = ranges[0].from; - this.range = ranges[0]; - this.end = ranges[ranges.length - 1].to; - this.readNext(); - } - resolveOffset(offset, assoc) { - let range = this.range, index = this.rangeIndex; - let pos = this.pos + offset; - while (pos < range.from) { - if (!index) - return null; - let next = this.ranges[--index]; - pos -= range.from - next.to; - range = next; - } - while (assoc < 0 ? pos > range.to : pos >= range.to) { - if (index == this.ranges.length - 1) - return null; - let next = this.ranges[++index]; - pos += next.from - range.to; - range = next; - } - return pos; - } - /// Look at a code unit near the stream position. `.peek(0)` equals - /// `.next`, `.peek(-1)` gives you the previous character, and so - /// on. - /// - /// Note that looking around during tokenizing creates dependencies - /// on potentially far-away content, which may reduce the - /// effectiveness incremental parsing—when looking forward—or even - /// cause invalid reparses when looking backward more than 25 code - /// units, since the library does not track lookbehind. - peek(offset) { - let idx = this.chunkOff + offset, pos, result; - if (idx >= 0 && idx < this.chunk.length) { - pos = this.pos + offset; - result = this.chunk.charCodeAt(idx); - } - else { - let resolved = this.resolveOffset(offset, 1); - if (resolved == null) - return -1; - pos = resolved; - if (pos >= this.chunk2Pos && pos < this.chunk2Pos + this.chunk2.length) { - result = this.chunk2.charCodeAt(pos - this.chunk2Pos); - } - else { - let i = this.rangeIndex, range = this.range; - while (range.to <= pos) - range = this.ranges[++i]; - this.chunk2 = this.input.chunk(this.chunk2Pos = pos); - if (pos + this.chunk2.length > range.to) - this.chunk2 = this.chunk2.slice(0, range.to - pos); - result = this.chunk2.charCodeAt(0); - } - } - if (pos >= this.token.lookAhead) - this.token.lookAhead = pos + 1; - return result; - } - /// Accept a token. By default, the end of the token is set to the - /// current stream position, but you can pass an offset (relative to - /// the stream position) to change that. - acceptToken(token, endOffset = 0) { - let end = endOffset ? this.resolveOffset(endOffset, -1) : this.pos; - if (end == null || end < this.token.start) - throw new RangeError("Token end out of bounds"); - this.token.value = token; - this.token.end = end; - } - getChunk() { - if (this.pos >= this.chunk2Pos && this.pos < this.chunk2Pos + this.chunk2.length) { - let { chunk, chunkPos } = this; - this.chunk = this.chunk2; - this.chunkPos = this.chunk2Pos; - this.chunk2 = chunk; - this.chunk2Pos = chunkPos; - this.chunkOff = this.pos - this.chunkPos; - } - else { - this.chunk2 = this.chunk; - this.chunk2Pos = this.chunkPos; - let nextChunk = this.input.chunk(this.pos); - let end = this.pos + nextChunk.length; - this.chunk = end > this.range.to ? nextChunk.slice(0, this.range.to - this.pos) : nextChunk; - this.chunkPos = this.pos; - this.chunkOff = 0; - } - } - readNext() { - if (this.chunkOff >= this.chunk.length) { - this.getChunk(); - if (this.chunkOff == this.chunk.length) - return this.next = -1; - } - return this.next = this.chunk.charCodeAt(this.chunkOff); - } - /// Move the stream forward N (defaults to 1) code units. Returns - /// the new value of [`next`](#lr.InputStream.next). - advance(n = 1) { - this.chunkOff += n; - while (this.pos + n >= this.range.to) { - if (this.rangeIndex == this.ranges.length - 1) - return this.setDone(); - n -= this.range.to - this.pos; - this.range = this.ranges[++this.rangeIndex]; - this.pos = this.range.from; - } - this.pos += n; - if (this.pos >= this.token.lookAhead) - this.token.lookAhead = this.pos + 1; - return this.readNext(); - } - setDone() { - this.pos = this.chunkPos = this.end; - this.range = this.ranges[this.rangeIndex = this.ranges.length - 1]; - this.chunk = ""; - return this.next = -1; - } - /// @internal - reset(pos, token) { - if (token) { - this.token = token; - token.start = pos; - token.lookAhead = pos + 1; - token.value = token.extended = -1; - } - else { - this.token = nullToken; - } - if (this.pos != pos) { - this.pos = pos; - if (pos == this.end) { - this.setDone(); - return this; - } - while (pos < this.range.from) - this.range = this.ranges[--this.rangeIndex]; - while (pos >= this.range.to) - this.range = this.ranges[++this.rangeIndex]; - if (pos >= this.chunkPos && pos < this.chunkPos + this.chunk.length) { - this.chunkOff = pos - this.chunkPos; - } - else { - this.chunk = ""; - this.chunkOff = 0; - } - this.readNext(); - } - return this; - } - /// @internal - read(from, to) { - if (from >= this.chunkPos && to <= this.chunkPos + this.chunk.length) - return this.chunk.slice(from - this.chunkPos, to - this.chunkPos); - if (from >= this.chunk2Pos && to <= this.chunk2Pos + this.chunk2.length) - return this.chunk2.slice(from - this.chunk2Pos, to - this.chunk2Pos); - if (from >= this.range.from && to <= this.range.to) - return this.input.read(from, to); - let result = ""; - for (let r of this.ranges) { - if (r.from >= to) - break; - if (r.to > from) - result += this.input.read(Math.max(r.from, from), Math.min(r.to, to)); - } - return result; - } - } - /// @internal - class TokenGroup { - constructor(data, id) { - this.data = data; - this.id = id; - } - token(input, stack) { readToken(this.data, input, stack, this.id); } - } - TokenGroup.prototype.contextual = TokenGroup.prototype.fallback = TokenGroup.prototype.extend = false; - /// `@external tokens` declarations in the grammar should resolve to - /// an instance of this class. - class ExternalTokenizer { - /// Create a tokenizer. The first argument is the function that, - /// given an input stream, scans for the types of tokens it - /// recognizes at the stream's position, and calls - /// [`acceptToken`](#lr.InputStream.acceptToken) when it finds - /// one. - constructor( - /// @internal - token, options = {}) { - this.token = token; - this.contextual = !!options.contextual; - this.fallback = !!options.fallback; - this.extend = !!options.extend; - } - } - // Tokenizer data is stored a big uint16 array containing, for each - // state: - // - // - A group bitmask, indicating what token groups are reachable from - // this state, so that paths that can only lead to tokens not in - // any of the current groups can be cut off early. - // - // - The position of the end of the state's sequence of accepting - // tokens - // - // - The number of outgoing edges for the state - // - // - The accepting tokens, as (token id, group mask) pairs - // - // - The outgoing edges, as (start character, end character, state - // index) triples, with end character being exclusive - // - // This function interprets that data, running through a stream as - // long as new states with the a matching group mask can be reached, - // and updating `token` when it matches a token. - function readToken(data, input, stack, group) { - let state = 0, groupMask = 1 << group, { parser } = stack.p, { dialect } = parser; - scan: for (;;) { - if ((groupMask & data[state]) == 0) - break; - let accEnd = data[state + 1]; - // Check whether this state can lead to a token in the current group - // Accept tokens in this state, possibly overwriting - // lower-precedence / shorter tokens - for (let i = state + 3; i < accEnd; i += 2) - if ((data[i + 1] & groupMask) > 0) { - let term = data[i]; - if (dialect.allows(term) && - (input.token.value == -1 || input.token.value == term || parser.overrides(term, input.token.value))) { - input.acceptToken(term); - break; - } - } - // Do a binary search on the state's edges - for (let next = input.next, low = 0, high = data[state + 2]; low < high;) { - let mid = (low + high) >> 1; - let index = accEnd + mid + (mid << 1); - let from = data[index], to = data[index + 1]; - if (next < from) - high = mid; - else if (next >= to) - low = mid + 1; - else { - state = data[index + 2]; - input.advance(); - continue scan; - } - } - break; - } - } - - // See lezer-generator/src/encode.ts for comments about the encoding - // used here - function decodeArray(input, Type = Uint16Array) { - if (typeof input != "string") - return input; - let array = null; - for (let pos = 0, out = 0; pos < input.length;) { - let value = 0; - for (;;) { - let next = input.charCodeAt(pos++), stop = false; - if (next == 126 /* BigValCode */) { - value = 65535 /* BigVal */; - break; - } - if (next >= 92 /* Gap2 */) - next--; - if (next >= 34 /* Gap1 */) - next--; - let digit = next - 32 /* Start */; - if (digit >= 46 /* Base */) { - digit -= 46 /* Base */; - stop = true; - } - value += digit; - if (stop) - break; - value *= 46 /* Base */; - } - if (array) - array[out++] = value; - else - array = new Type(value); - } - return array; - } - - // FIXME find some way to reduce recovery work done when the input - // doesn't match the grammar at all. - // Environment variable used to control console output - const verbose = typeof process != "undefined" && /\bparse\b/.test(process.env.LOG); - let stackIDs = null; - var Safety; - (function (Safety) { - Safety[Safety["Margin"] = 25] = "Margin"; - })(Safety || (Safety = {})); - function cutAt(tree, pos, side) { - let cursor = tree.fullCursor(); - cursor.moveTo(pos); - for (;;) { - if (!(side < 0 ? cursor.childBefore(pos) : cursor.childAfter(pos))) - for (;;) { - if ((side < 0 ? cursor.to < pos : cursor.from > pos) && !cursor.type.isError) - return side < 0 ? Math.max(0, Math.min(cursor.to - 1, pos - 25 /* Margin */)) - : Math.min(tree.length, Math.max(cursor.from + 1, pos + 25 /* Margin */)); - if (side < 0 ? cursor.prevSibling() : cursor.nextSibling()) - break; - if (!cursor.parent()) - return side < 0 ? 0 : tree.length; - } - } - } - class FragmentCursor { - constructor(fragments, nodeSet) { - this.fragments = fragments; - this.nodeSet = nodeSet; - this.i = 0; - this.fragment = null; - this.safeFrom = -1; - this.safeTo = -1; - this.trees = []; - this.start = []; - this.index = []; - this.nextFragment(); - } - nextFragment() { - let fr = this.fragment = this.i == this.fragments.length ? null : this.fragments[this.i++]; - if (fr) { - this.safeFrom = fr.openStart ? cutAt(fr.tree, fr.from + fr.offset, 1) - fr.offset : fr.from; - this.safeTo = fr.openEnd ? cutAt(fr.tree, fr.to + fr.offset, -1) - fr.offset : fr.to; - while (this.trees.length) { - this.trees.pop(); - this.start.pop(); - this.index.pop(); - } - this.trees.push(fr.tree); - this.start.push(-fr.offset); - this.index.push(0); - this.nextStart = this.safeFrom; - } - else { - this.nextStart = 1e9; - } - } - // `pos` must be >= any previously given `pos` for this cursor - nodeAt(pos) { - if (pos < this.nextStart) - return null; - while (this.fragment && this.safeTo <= pos) - this.nextFragment(); - if (!this.fragment) - return null; - for (;;) { - let last = this.trees.length - 1; - if (last < 0) { // End of tree - this.nextFragment(); - return null; - } - let top = this.trees[last], index = this.index[last]; - if (index == top.children.length) { - this.trees.pop(); - this.start.pop(); - this.index.pop(); - continue; - } - let next = top.children[index]; - let start = this.start[last] + top.positions[index]; - if (start > pos) { - this.nextStart = start; - return null; - } - if (next instanceof Tree) { - if (start == pos) { - if (start < this.safeFrom) - return null; - let end = start + next.length; - if (end <= this.safeTo) { - let lookAhead = next.prop(NodeProp.lookAhead); - if (!lookAhead || end + lookAhead < this.fragment.to) - return next; - } - } - this.index[last]++; - if (start + next.length >= Math.max(this.safeFrom, pos)) { // Enter this node - this.trees.push(next); - this.start.push(start); - this.index.push(0); - } - } - else { - this.index[last]++; - this.nextStart = start + next.length; - } - } - } - } - class TokenCache { - constructor(parser, stream) { - this.stream = stream; - this.tokens = []; - this.mainToken = null; - this.actions = []; - this.tokens = parser.tokenizers.map(_ => new CachedToken); - } - getActions(stack) { - let actionIndex = 0; - let main = null; - let { parser } = stack.p, { tokenizers } = parser; - let mask = parser.stateSlot(stack.state, 3 /* TokenizerMask */); - let context = stack.curContext ? stack.curContext.hash : 0; - let lookAhead = 0; - for (let i = 0; i < tokenizers.length; i++) { - if (((1 << i) & mask) == 0) - continue; - let tokenizer = tokenizers[i], token = this.tokens[i]; - if (main && !tokenizer.fallback) - continue; - if (tokenizer.contextual || token.start != stack.pos || token.mask != mask || token.context != context) { - this.updateCachedToken(token, tokenizer, stack); - token.mask = mask; - token.context = context; - } - if (token.lookAhead > token.end + 25 /* Margin */) - lookAhead = Math.max(token.lookAhead, lookAhead); - if (token.value != 0 /* Err */) { - let startIndex = actionIndex; - if (token.extended > -1) - actionIndex = this.addActions(stack, token.extended, token.end, actionIndex); - actionIndex = this.addActions(stack, token.value, token.end, actionIndex); - if (!tokenizer.extend) { - main = token; - if (actionIndex > startIndex) - break; - } - } - } - while (this.actions.length > actionIndex) - this.actions.pop(); - if (lookAhead) - stack.setLookAhead(lookAhead); - if (!main && stack.pos == this.stream.end) { - main = new CachedToken; - main.value = stack.p.parser.eofTerm; - main.start = main.end = stack.pos; - actionIndex = this.addActions(stack, main.value, main.end, actionIndex); - } - this.mainToken = main; - return this.actions; - } - getMainToken(stack) { - if (this.mainToken) - return this.mainToken; - let main = new CachedToken, { pos, p } = stack; - main.start = pos; - main.end = Math.min(pos + 1, p.stream.end); - main.value = pos == p.stream.end ? p.parser.eofTerm : 0 /* Err */; - return main; - } - updateCachedToken(token, tokenizer, stack) { - tokenizer.token(this.stream.reset(stack.pos, token), stack); - if (token.value > -1) { - let { parser } = stack.p; - for (let i = 0; i < parser.specialized.length; i++) - if (parser.specialized[i] == token.value) { - let result = parser.specializers[i](this.stream.read(token.start, token.end), stack); - if (result >= 0 && stack.p.parser.dialect.allows(result >> 1)) { - if ((result & 1) == 0 /* Specialize */) - token.value = result >> 1; - else - token.extended = result >> 1; - break; - } - } - } - else { - token.value = 0 /* Err */; - token.end = Math.min(stack.p.stream.end, stack.pos + 1); - } - } - putAction(action, token, end, index) { - // Don't add duplicate actions - for (let i = 0; i < index; i += 3) - if (this.actions[i] == action) - return index; - this.actions[index++] = action; - this.actions[index++] = token; - this.actions[index++] = end; - return index; - } - addActions(stack, token, end, index) { - let { state } = stack, { parser } = stack.p, { data } = parser; - for (let set = 0; set < 2; set++) { - for (let i = parser.stateSlot(state, set ? 2 /* Skip */ : 1 /* Actions */);; i += 3) { - if (data[i] == 65535 /* End */) { - if (data[i + 1] == 1 /* Next */) { - i = pair(data, i + 2); - } - else { - if (index == 0 && data[i + 1] == 2 /* Other */) - index = this.putAction(pair(data, i + 2), token, end, index); - break; - } - } - if (data[i] == token) - index = this.putAction(pair(data, i + 1), token, end, index); - } - } - return index; - } - } - var Rec; - (function (Rec) { - Rec[Rec["Distance"] = 5] = "Distance"; - Rec[Rec["MaxRemainingPerStep"] = 3] = "MaxRemainingPerStep"; - // When two stacks have been running independently long enough to - // add this many elements to their buffers, prune one. - Rec[Rec["MinBufferLengthPrune"] = 500] = "MinBufferLengthPrune"; - Rec[Rec["ForceReduceLimit"] = 10] = "ForceReduceLimit"; - // Once a stack reaches this depth (in .stack.length) force-reduce - // it back to CutTo to avoid creating trees that overflow the stack - // on recursive traversal. - Rec[Rec["CutDepth"] = 15000] = "CutDepth"; - Rec[Rec["CutTo"] = 9000] = "CutTo"; - })(Rec || (Rec = {})); - class Parse { - constructor(parser, input, fragments, ranges) { - this.parser = parser; - this.input = input; - this.ranges = ranges; - this.recovering = 0; - this.nextStackID = 0x2654; // ♔, ♕, ♖, ♗, ♘, ♙, ♠, ♡, ♢, ♣, ♤, ♥, ♦, ♧ - this.minStackPos = 0; - this.reused = []; - this.stoppedAt = null; - this.stream = new InputStream(input, ranges); - this.tokens = new TokenCache(parser, this.stream); - this.topTerm = parser.top[1]; - let { from } = ranges[0]; - this.stacks = [Stack.start(this, parser.top[0], from)]; - this.fragments = fragments.length && this.stream.end - from > parser.bufferLength * 4 - ? new FragmentCursor(fragments, parser.nodeSet) : null; - } - get parsedPos() { - return this.minStackPos; - } - // Move the parser forward. This will process all parse stacks at - // `this.pos` and try to advance them to a further position. If no - // stack for such a position is found, it'll start error-recovery. - // - // When the parse is finished, this will return a syntax tree. When - // not, it returns `null`. - advance() { - let stacks = this.stacks, pos = this.minStackPos; - // This will hold stacks beyond `pos`. - let newStacks = this.stacks = []; - let stopped, stoppedTokens; - // Keep advancing any stacks at `pos` until they either move - // forward or can't be advanced. Gather stacks that can't be - // advanced further in `stopped`. - for (let i = 0; i < stacks.length; i++) { - let stack = stacks[i]; - for (;;) { - this.tokens.mainToken = null; - if (stack.pos > pos) { - newStacks.push(stack); - } - else if (this.advanceStack(stack, newStacks, stacks)) { - continue; - } - else { - if (!stopped) { - stopped = []; - stoppedTokens = []; - } - stopped.push(stack); - let tok = this.tokens.getMainToken(stack); - stoppedTokens.push(tok.value, tok.end); - } - break; - } - } - if (!newStacks.length) { - let finished = stopped && findFinished(stopped); - if (finished) - return this.stackToTree(finished); - if (this.parser.strict) { - if (verbose && stopped) - console.log("Stuck with token " + (this.tokens.mainToken ? this.parser.getName(this.tokens.mainToken.value) : "none")); - throw new SyntaxError("No parse at " + pos); - } - if (!this.recovering) - this.recovering = 5 /* Distance */; - } - if (this.recovering && stopped) { - let finished = this.stoppedAt != null && stopped[0].pos > this.stoppedAt ? stopped[0] - : this.runRecovery(stopped, stoppedTokens, newStacks); - if (finished) - return this.stackToTree(finished.forceAll()); - } - if (this.recovering) { - let maxRemaining = this.recovering == 1 ? 1 : this.recovering * 3 /* MaxRemainingPerStep */; - if (newStacks.length > maxRemaining) { - newStacks.sort((a, b) => b.score - a.score); - while (newStacks.length > maxRemaining) - newStacks.pop(); - } - if (newStacks.some(s => s.reducePos > pos)) - this.recovering--; - } - else if (newStacks.length > 1) { - // Prune stacks that are in the same state, or that have been - // running without splitting for a while, to avoid getting stuck - // with multiple successful stacks running endlessly on. - outer: for (let i = 0; i < newStacks.length - 1; i++) { - let stack = newStacks[i]; - for (let j = i + 1; j < newStacks.length; j++) { - let other = newStacks[j]; - if (stack.sameState(other) || - stack.buffer.length > 500 /* MinBufferLengthPrune */ && other.buffer.length > 500 /* MinBufferLengthPrune */) { - if (((stack.score - other.score) || (stack.buffer.length - other.buffer.length)) > 0) { - newStacks.splice(j--, 1); - } - else { - newStacks.splice(i--, 1); - continue outer; - } - } - } - } - } - this.minStackPos = newStacks[0].pos; - for (let i = 1; i < newStacks.length; i++) - if (newStacks[i].pos < this.minStackPos) - this.minStackPos = newStacks[i].pos; - return null; - } - stopAt(pos) { - if (this.stoppedAt != null && this.stoppedAt < pos) - throw new RangeError("Can't move stoppedAt forward"); - this.stoppedAt = pos; - } - // Returns an updated version of the given stack, or null if the - // stack can't advance normally. When `split` and `stacks` are - // given, stacks split off by ambiguous operations will be pushed to - // `split`, or added to `stacks` if they move `pos` forward. - advanceStack(stack, stacks, split) { - let start = stack.pos, { parser } = this; - let base = verbose ? this.stackID(stack) + " -> " : ""; - if (this.stoppedAt != null && start > this.stoppedAt) - return stack.forceReduce() ? stack : null; - if (this.fragments) { - let strictCx = stack.curContext && stack.curContext.tracker.strict, cxHash = strictCx ? stack.curContext.hash : 0; - for (let cached = this.fragments.nodeAt(start); cached;) { - let match = this.parser.nodeSet.types[cached.type.id] == cached.type ? parser.getGoto(stack.state, cached.type.id) : -1; - if (match > -1 && cached.length && (!strictCx || (cached.prop(NodeProp.contextHash) || 0) == cxHash)) { - stack.useNode(cached, match); - if (verbose) - console.log(base + this.stackID(stack) + ` (via reuse of ${parser.getName(cached.type.id)})`); - return true; - } - if (!(cached instanceof Tree) || cached.children.length == 0 || cached.positions[0] > 0) - break; - let inner = cached.children[0]; - if (inner instanceof Tree && cached.positions[0] == 0) - cached = inner; - else - break; - } - } - let defaultReduce = parser.stateSlot(stack.state, 4 /* DefaultReduce */); - if (defaultReduce > 0) { - stack.reduce(defaultReduce); - if (verbose) - console.log(base + this.stackID(stack) + ` (via always-reduce ${parser.getName(defaultReduce & 65535 /* ValueMask */)})`); - return true; - } - if (stack.stack.length >= 15000 /* CutDepth */) { - while (stack.stack.length > 9000 /* CutTo */ && stack.forceReduce()) { } - } - let actions = this.tokens.getActions(stack); - for (let i = 0; i < actions.length;) { - let action = actions[i++], term = actions[i++], end = actions[i++]; - let last = i == actions.length || !split; - let localStack = last ? stack : stack.split(); - localStack.apply(action, term, end); - if (verbose) - console.log(base + this.stackID(localStack) + ` (via ${(action & 65536 /* ReduceFlag */) == 0 ? "shift" - : `reduce of ${parser.getName(action & 65535 /* ValueMask */)}`} for ${parser.getName(term)} @ ${start}${localStack == stack ? "" : ", split"})`); - if (last) - return true; - else if (localStack.pos > start) - stacks.push(localStack); - else - split.push(localStack); - } - return false; - } - // Advance a given stack forward as far as it will go. Returns the - // (possibly updated) stack if it got stuck, or null if it moved - // forward and was given to `pushStackDedup`. - advanceFully(stack, newStacks) { - let pos = stack.pos; - for (;;) { - if (!this.advanceStack(stack, null, null)) - return false; - if (stack.pos > pos) { - pushStackDedup(stack, newStacks); - return true; - } - } - } - runRecovery(stacks, tokens, newStacks) { - let finished = null, restarted = false; - for (let i = 0; i < stacks.length; i++) { - let stack = stacks[i], token = tokens[i << 1], tokenEnd = tokens[(i << 1) + 1]; - let base = verbose ? this.stackID(stack) + " -> " : ""; - if (stack.deadEnd) { - if (restarted) - continue; - restarted = true; - stack.restart(); - if (verbose) - console.log(base + this.stackID(stack) + " (restarted)"); - let done = this.advanceFully(stack, newStacks); - if (done) - continue; - } - let force = stack.split(), forceBase = base; - for (let j = 0; force.forceReduce() && j < 10 /* ForceReduceLimit */; j++) { - if (verbose) - console.log(forceBase + this.stackID(force) + " (via force-reduce)"); - let done = this.advanceFully(force, newStacks); - if (done) - break; - if (verbose) - forceBase = this.stackID(force) + " -> "; - } - for (let insert of stack.recoverByInsert(token)) { - if (verbose) - console.log(base + this.stackID(insert) + " (via recover-insert)"); - this.advanceFully(insert, newStacks); - } - if (this.stream.end > stack.pos) { - if (tokenEnd == stack.pos) { - tokenEnd++; - token = 0 /* Err */; - } - stack.recoverByDelete(token, tokenEnd); - if (verbose) - console.log(base + this.stackID(stack) + ` (via recover-delete ${this.parser.getName(token)})`); - pushStackDedup(stack, newStacks); - } - else if (!finished || finished.score < stack.score) { - finished = stack; - } - } - return finished; - } - // Convert the stack's buffer to a syntax tree. - stackToTree(stack) { - stack.close(); - return Tree.build({ buffer: StackBufferCursor.create(stack), - nodeSet: this.parser.nodeSet, - topID: this.topTerm, - maxBufferLength: this.parser.bufferLength, - reused: this.reused, - start: this.ranges[0].from, - length: stack.pos - this.ranges[0].from, - minRepeatType: this.parser.minRepeatTerm }); - } - stackID(stack) { - let id = (stackIDs || (stackIDs = new WeakMap)).get(stack); - if (!id) - stackIDs.set(stack, id = String.fromCodePoint(this.nextStackID++)); - return id + stack; - } - } - function pushStackDedup(stack, newStacks) { - for (let i = 0; i < newStacks.length; i++) { - let other = newStacks[i]; - if (other.pos == stack.pos && other.sameState(stack)) { - if (newStacks[i].score < stack.score) - newStacks[i] = stack; - return; - } - } - newStacks.push(stack); - } - class Dialect { - constructor(source, flags, disabled) { - this.source = source; - this.flags = flags; - this.disabled = disabled; - } - allows(term) { return !this.disabled || this.disabled[term] == 0; } - } - const id = x => x; - /// Context trackers are used to track stateful context (such as - /// indentation in the Python grammar, or parent elements in the XML - /// grammar) needed by external tokenizers. You declare them in a - /// grammar file as `@context exportName from "module"`. - /// - /// Context values should be immutable, and can be updated (replaced) - /// on shift or reduce actions. - /// - /// The export used in a `@context` declaration should be of this - /// type. - class ContextTracker { - /// Define a context tracker. - constructor(spec) { - this.start = spec.start; - this.shift = spec.shift || id; - this.reduce = spec.reduce || id; - this.reuse = spec.reuse || id; - this.hash = spec.hash || (() => 0); - this.strict = spec.strict !== false; - } - } - /// A parser holds the parse tables for a given grammar, as generated - /// by `lezer-generator`. - class LRParser extends Parser { - /// @internal - constructor(spec) { - super(); - /// @internal - this.wrappers = []; - if (spec.version != 13 /* Version */) - throw new RangeError(`Parser version (${spec.version}) doesn't match runtime version (${13 /* Version */})`); - let nodeNames = spec.nodeNames.split(" "); - this.minRepeatTerm = nodeNames.length; - for (let i = 0; i < spec.repeatNodeCount; i++) - nodeNames.push(""); - let topTerms = Object.keys(spec.topRules).map(r => spec.topRules[r][1]); - let nodeProps = []; - for (let i = 0; i < nodeNames.length; i++) - nodeProps.push([]); - function setProp(nodeID, prop, value) { - nodeProps[nodeID].push([prop, prop.deserialize(String(value))]); - } - if (spec.nodeProps) - for (let propSpec of spec.nodeProps) { - let prop = propSpec[0]; - for (let i = 1; i < propSpec.length;) { - let next = propSpec[i++]; - if (next >= 0) { - setProp(next, prop, propSpec[i++]); - } - else { - let value = propSpec[i + -next]; - for (let j = -next; j > 0; j--) - setProp(propSpec[i++], prop, value); - i++; - } - } - } - this.nodeSet = new NodeSet(nodeNames.map((name, i) => NodeType.define({ - name: i >= this.minRepeatTerm ? undefined : name, - id: i, - props: nodeProps[i], - top: topTerms.indexOf(i) > -1, - error: i == 0, - skipped: spec.skippedNodes && spec.skippedNodes.indexOf(i) > -1 - }))); - this.strict = false; - this.bufferLength = DefaultBufferLength; - let tokenArray = decodeArray(spec.tokenData); - this.context = spec.context; - this.specialized = new Uint16Array(spec.specialized ? spec.specialized.length : 0); - this.specializers = []; - if (spec.specialized) - for (let i = 0; i < spec.specialized.length; i++) { - this.specialized[i] = spec.specialized[i].term; - this.specializers[i] = spec.specialized[i].get; - } - this.states = decodeArray(spec.states, Uint32Array); - this.data = decodeArray(spec.stateData); - this.goto = decodeArray(spec.goto); - this.maxTerm = spec.maxTerm; - this.tokenizers = spec.tokenizers.map(value => typeof value == "number" ? new TokenGroup(tokenArray, value) : value); - this.topRules = spec.topRules; - this.dialects = spec.dialects || {}; - this.dynamicPrecedences = spec.dynamicPrecedences || null; - this.tokenPrecTable = spec.tokenPrec; - this.termNames = spec.termNames || null; - this.maxNode = this.nodeSet.types.length - 1; - this.dialect = this.parseDialect(); - this.top = this.topRules[Object.keys(this.topRules)[0]]; - } - createParse(input, fragments, ranges) { - let parse = new Parse(this, input, fragments, ranges); - for (let w of this.wrappers) - parse = w(parse, input, fragments, ranges); - return parse; - } - /// Get a goto table entry @internal - getGoto(state, term, loose = false) { - let table = this.goto; - if (term >= table[0]) - return -1; - for (let pos = table[term + 1];;) { - let groupTag = table[pos++], last = groupTag & 1; - let target = table[pos++]; - if (last && loose) - return target; - for (let end = pos + (groupTag >> 1); pos < end; pos++) - if (table[pos] == state) - return target; - if (last) - return -1; - } - } - /// Check if this state has an action for a given terminal @internal - hasAction(state, terminal) { - let data = this.data; - for (let set = 0; set < 2; set++) { - for (let i = this.stateSlot(state, set ? 2 /* Skip */ : 1 /* Actions */), next;; i += 3) { - if ((next = data[i]) == 65535 /* End */) { - if (data[i + 1] == 1 /* Next */) - next = data[i = pair(data, i + 2)]; - else if (data[i + 1] == 2 /* Other */) - return pair(data, i + 2); - else - break; - } - if (next == terminal || next == 0 /* Err */) - return pair(data, i + 1); - } - } - return 0; - } - /// @internal - stateSlot(state, slot) { - return this.states[(state * 6 /* Size */) + slot]; - } - /// @internal - stateFlag(state, flag) { - return (this.stateSlot(state, 0 /* Flags */) & flag) > 0; - } - /// @internal - validAction(state, action) { - if (action == this.stateSlot(state, 4 /* DefaultReduce */)) - return true; - for (let i = this.stateSlot(state, 1 /* Actions */);; i += 3) { - if (this.data[i] == 65535 /* End */) { - if (this.data[i + 1] == 1 /* Next */) - i = pair(this.data, i + 2); - else - return false; - } - if (action == pair(this.data, i + 1)) - return true; - } - } - /// Get the states that can follow this one through shift actions or - /// goto jumps. @internal - nextStates(state) { - let result = []; - for (let i = this.stateSlot(state, 1 /* Actions */);; i += 3) { - if (this.data[i] == 65535 /* End */) { - if (this.data[i + 1] == 1 /* Next */) - i = pair(this.data, i + 2); - else - break; - } - if ((this.data[i + 2] & (65536 /* ReduceFlag */ >> 16)) == 0) { - let value = this.data[i + 1]; - if (!result.some((v, i) => (i & 1) && v == value)) - result.push(this.data[i], value); - } - } - return result; - } - /// @internal - overrides(token, prev) { - let iPrev = findOffset(this.data, this.tokenPrecTable, prev); - return iPrev < 0 || findOffset(this.data, this.tokenPrecTable, token) < iPrev; - } - /// Configure the parser. Returns a new parser instance that has the - /// given settings modified. Settings not provided in `config` are - /// kept from the original parser. - configure(config) { - // Hideous reflection-based kludge to make it easy to create a - // slightly modified copy of a parser. - let copy = Object.assign(Object.create(LRParser.prototype), this); - if (config.props) - copy.nodeSet = this.nodeSet.extend(...config.props); - if (config.top) { - let info = this.topRules[config.top]; - if (!info) - throw new RangeError(`Invalid top rule name ${config.top}`); - copy.top = info; - } - if (config.tokenizers) - copy.tokenizers = this.tokenizers.map(t => { - let found = config.tokenizers.find(r => r.from == t); - return found ? found.to : t; - }); - if (config.contextTracker) - copy.context = config.contextTracker; - if (config.dialect) - copy.dialect = this.parseDialect(config.dialect); - if (config.strict != null) - copy.strict = config.strict; - if (config.wrap) - copy.wrappers = copy.wrappers.concat(config.wrap); - if (config.bufferLength != null) - copy.bufferLength = config.bufferLength; - return copy; - } - /// Returns the name associated with a given term. This will only - /// work for all terms when the parser was generated with the - /// `--names` option. By default, only the names of tagged terms are - /// stored. - getName(term) { - return this.termNames ? this.termNames[term] : String(term <= this.maxNode && this.nodeSet.types[term].name || term); - } - /// The eof term id is always allocated directly after the node - /// types. @internal - get eofTerm() { return this.maxNode + 1; } - /// The type of top node produced by the parser. - get topNode() { return this.nodeSet.types[this.top[1]]; } - /// @internal - dynamicPrecedence(term) { - let prec = this.dynamicPrecedences; - return prec == null ? 0 : prec[term] || 0; - } - /// @internal - parseDialect(dialect) { - let values = Object.keys(this.dialects), flags = values.map(() => false); - if (dialect) - for (let part of dialect.split(" ")) { - let id = values.indexOf(part); - if (id >= 0) - flags[id] = true; - } - let disabled = null; - for (let i = 0; i < values.length; i++) - if (!flags[i]) { - for (let j = this.dialects[values[i]], id; (id = this.data[j++]) != 65535 /* End */;) - (disabled || (disabled = new Uint8Array(this.maxTerm + 1)))[id] = 1; - } - return new Dialect(dialect, flags, disabled); - } - /// (used by the output of the parser generator) @internal - static deserialize(spec) { - return new LRParser(spec); - } - } - function pair(data, off) { return data[off] | (data[off + 1] << 16); } - function findOffset(data, start, term) { - for (let i = start, next; (next = data[i]) != 65535 /* End */; i++) - if (next == term) - return i - start; - return -1; - } - function findFinished(stacks) { - let best = null; - for (let stack of stacks) { - let stopped = stack.p.stoppedAt; - if ((stack.pos == stack.p.stream.end || stopped != null && stack.pos > stopped) && - stack.p.parser.stateFlag(stack.state, 2 /* Accepting */) && - (!best || best.score < stack.score)) - best = stack; - } - return best; - } - - // This file was generated by lezer-generator. You probably shouldn't edit it. - const printKeyword = 1, - indent = 162, - dedent = 163, - newline$1 = 164, - newlineBracketed = 165, - newlineEmpty = 166, - eof = 167, - ParenthesizedExpression = 21, - ParenL = 22, - TupleExpression = 47, - ComprehensionExpression = 48, - ArrayExpression = 52, - BracketL = 53, - ArrayComprehensionExpression = 55, - DictionaryExpression = 56, - BraceL = 57, - DictionaryComprehensionExpression = 59, - SetExpression = 60, - SetComprehensionExpression = 61, - ArgList = 63, - subscript = 203, - FormatReplacement = 71, - importList = 228, - ParamList = 121; - - const newline = 10, carriageReturn = 13, space = 32, tab = 9, hash = 35, parenOpen = 40, dot = 46; - - const bracketed = [ - ParenthesizedExpression, TupleExpression, ComprehensionExpression, importList, ArgList, ParamList, - ArrayExpression, ArrayComprehensionExpression, subscript, - SetExpression, SetComprehensionExpression, - DictionaryExpression, DictionaryComprehensionExpression, FormatReplacement - ]; - - const newlines = new ExternalTokenizer((input, stack) => { - if (input.next < 0) { - input.acceptToken(eof); - } else if (input.next != newline && input.next != carriageReturn) ; else if (stack.context.depth < 0) { - input.acceptToken(newlineBracketed, 1); - } else { - input.advance(); - let spaces = 0; - while (input.next == space || input.next == tab) { input.advance(); spaces++; } - let empty = input.next == newline || input.next == carriageReturn || input.next == hash; - input.acceptToken(empty ? newlineEmpty : newline$1, -spaces); + // ================= registraton API ==================== + logStatus(msg) { + logger.info(msg); + const ev = new CustomEvent('py-status-message', { detail: msg }); + document.dispatchEvent(ev); } - }, {contextual: true, fallback: true}); - - const indentation = new ExternalTokenizer((input, stack) => { - let cDepth = stack.context.depth; - if (cDepth < 0) return - let prev = input.peek(-1); - if ((prev == newline || prev == carriageReturn) && stack.context.depth >= 0) { - let depth = 0, chars = 0; - for (;;) { - if (input.next == space) depth++; - else if (input.next == tab) depth += 8 - (depth % 8); - else break - input.advance(); - chars++; - } - if (depth != cDepth && - input.next != newline && input.next != carriageReturn && input.next != hash) { - if (depth < cDepth) input.acceptToken(dedent, -chars); - else input.acceptToken(indent); - } + registerStdioListener(stdio) { + this._stdioMultiplexer.addListener(stdio); } - }); + } + function pyscript_get_config() { + return globalApp.config; + } + globalExport('pyscript_get_config', pyscript_get_config); + // main entry point of execution + const globalApp = new PyScriptApp(); + globalApp.main(); + const interpreter = globalApp.interpreter; + // TODO: This is for backwards compatibility, it should be removed + // when we finish the deprecation cycle of `runtime` + const runtime = globalApp.interpreter; - function IndentLevel(parent, depth) { - this.parent = parent; - // -1 means this is not an actual indent level but a set of brackets - this.depth = depth; - this.hash = (parent ? parent.hash + parent.hash << 8 : 0) + depth + (depth << 4); - } + exports.PyScriptApp = PyScriptApp; + exports.interpreter = interpreter; + exports.runtime = runtime; + exports.version = version; - const topIndent = new IndentLevel(null, 0); + Object.defineProperty(exports, '__esModule', { value: true }); - function countIndent(space) { - let depth = 0; - for (let i = 0; i < space.length; i++) - depth += space.charCodeAt(i) == tab ? 8 - (depth % 8) : 1; - return depth - } + return exports; - const trackIndent = new ContextTracker({ - start: topIndent, - reduce(context, term) { - return context.depth < 0 && bracketed.indexOf(term) > -1 ? context.parent : context - }, - shift(context, term, stack, input) { - if (term == indent) return new IndentLevel(context, countIndent(input.read(input.pos, stack.pos))) - if (term == dedent) return context.parent - if (term == ParenL || term == BracketL || term == BraceL) return new IndentLevel(context, -1) - return context - }, - hash(context) { return context.hash } - }); - - const legacyPrint = new ExternalTokenizer(input => { - for (let i = 0; i < 5; i++) { - if (input.next != "print".charCodeAt(i)) return - input.advance(); - } - if (/\w/.test(String.fromCharCode(input.next))) return - for (let off = 0;; off++) { - let next = input.peek(off); - if (next == space || next == tab) continue - if (next != parenOpen && next != dot && next != newline && next != carriageReturn && next != hash) - input.acceptToken(printKeyword); - return - } - }); - - // This file was generated by lezer-generator. You probably shouldn't edit it. - const spec_identifier = {__proto__:null,await:40, or:48, and:50, in:54, not:56, is:58, if:64, else:66, lambda:70, yield:88, from:90, async:98, for:100, None:152, True:154, False:154, del:168, pass:172, break:176, continue:180, return:184, raise:192, import:196, as:198, global:202, nonlocal:204, assert:208, elif:218, while:222, try:228, except:230, finally:232, with:236, def:240, class:250}; - const parser = LRParser.deserialize({ - version: 13, - states: "!?pO`Q$IXOOO%cQ$I[O'#GaOOQ$IS'#Cm'#CmOOQ$IS'#Cn'#CnO'RQ$IWO'#ClO(tQ$I[O'#G`OOQ$IS'#Ga'#GaOOQ$IS'#DR'#DROOQ$IS'#G`'#G`O)bQ$IWO'#CqO)rQ$IWO'#DbO*SQ$IWO'#DfOOQ$IS'#Ds'#DsO*gO`O'#DsO*oOpO'#DsO*wO!bO'#DtO+SO#tO'#DtO+_O&jO'#DtO+jO,UO'#DtO-lQ$I[O'#GQOOQ$IS'#GQ'#GQO'RQ$IWO'#GPO/OQ$I[O'#GPOOQ$IS'#E]'#E]O/gQ$IWO'#E^OOQ$IS'#GO'#GOO/qQ$IWO'#F}OOQ$IV'#F}'#F}O/|Q$IWO'#FPOOQ$IS'#Fr'#FrO0RQ$IWO'#FOOOQ$IV'#H]'#H]OOQ$IV'#F|'#F|OOQ$IT'#FR'#FRQ`Q$IXOOO'RQ$IWO'#CoO0aQ$IWO'#CzO0hQ$IWO'#DOO0vQ$IWO'#GeO1WQ$I[O'#EQO'RQ$IWO'#EROOQ$IS'#ET'#ETOOQ$IS'#EV'#EVOOQ$IS'#EX'#EXO1lQ$IWO'#EZO2SQ$IWO'#E_O/|Q$IWO'#EaO2gQ$I[O'#EaO/|Q$IWO'#EdO/gQ$IWO'#EgO/gQ$IWO'#EkO/gQ$IWO'#EnO2rQ$IWO'#EpO2yQ$IWO'#EuO3UQ$IWO'#EqO/gQ$IWO'#EuO/|Q$IWO'#EwO/|Q$IWO'#E|OOQ$IS'#Cc'#CcOOQ$IS'#Cd'#CdOOQ$IS'#Ce'#CeOOQ$IS'#Cf'#CfOOQ$IS'#Cg'#CgOOQ$IS'#Ch'#ChOOQ$IS'#Cj'#CjO'RQ$IWO,58|O'RQ$IWO,58|O'RQ$IWO,58|O'RQ$IWO,58|O'RQ$IWO,58|O'RQ$IWO,58|O3ZQ$IWO'#DmOOQ$IS,5:W,5:WO3nQ$IWO'#GoOOQ$IS,5:Z,5:ZO3{Q%1`O,5:ZO4QQ$I[O,59WO0aQ$IWO,59_O0aQ$IWO,59_O0aQ$IWO,59_O6pQ$IWO,59_O6uQ$IWO,59_O6|Q$IWO,59gO7TQ$IWO'#G`O8ZQ$IWO'#G_OOQ$IS'#G_'#G_OOQ$IS'#DX'#DXO8rQ$IWO,59]O'RQ$IWO,59]O9QQ$IWO,59]O9VQ$IWO,5:PO'RQ$IWO,5:POOQ$IS,59|,59|O9eQ$IWO,59|O9jQ$IWO,5:VO'RQ$IWO,5:VO'RQ$IWO,5:TOOQ$IS,5:Q,5:QO9{Q$IWO,5:QO:QQ$IWO,5:UOOOO'#FZ'#FZO:VO`O,5:_OOQ$IS,5:_,5:_OOOO'#F['#F[O:_OpO,5:_O:gQ$IWO'#DuOOOO'#F]'#F]O:wO!bO,5:`OOQ$IS,5:`,5:`OOOO'#F`'#F`O;SO#tO,5:`OOOO'#Fa'#FaO;_O&jO,5:`OOOO'#Fb'#FbO;jO,UO,5:`OOQ$IS'#Fc'#FcO;uQ$I[O,5:dO>gQ$I[O,5<kO?QQ%GlO,5<kO?qQ$I[O,5<kOOQ$IS,5:x,5:xO@YQ$IXO'#FkOAiQ$IWO,5;TOOQ$IV,5<i,5<iOAtQ$I[O'#HXOB]Q$IWO,5;kOOQ$IS-E9p-E9pOOQ$IV,5;j,5;jO3PQ$IWO'#EwOOQ$IT-E9P-E9POBeQ$I[O,59ZODlQ$I[O,59fOEVQ$IWO'#GbOEbQ$IWO'#GbO/|Q$IWO'#GbOEmQ$IWO'#DQOEuQ$IWO,59jOEzQ$IWO'#GfO'RQ$IWO'#GfO/gQ$IWO,5=POOQ$IS,5=P,5=PO/gQ$IWO'#D|OOQ$IS'#D}'#D}OFiQ$IWO'#FeOFyQ$IWO,58zOFyQ$IWO,58zO)eQ$IWO,5:jOGXQ$I[O'#GhOOQ$IS,5:m,5:mOOQ$IS,5:u,5:uOGlQ$IWO,5:yOG}Q$IWO,5:{OOQ$IS'#Fh'#FhOH]Q$I[O,5:{OHkQ$IWO,5:{OHpQ$IWO'#H[OOQ$IS,5;O,5;OOIOQ$IWO'#HWOOQ$IS,5;R,5;RO3UQ$IWO,5;VO3UQ$IWO,5;YOIaQ$I[O'#H^O'RQ$IWO'#H^OIkQ$IWO,5;[O2rQ$IWO,5;[O/gQ$IWO,5;aO/|Q$IWO,5;cOIpQ$IXO'#ElOJyQ$IZO,5;]ON[Q$IWO'#H_O3UQ$IWO,5;aONgQ$IWO,5;cONlQ$IWO,5;hO!#aQ$I[O1G.hO!#hQ$I[O1G.hO!&XQ$I[O1G.hO!&cQ$I[O1G.hO!(|Q$I[O1G.hO!)aQ$I[O1G.hO!)tQ$IWO'#GnO!*SQ$I[O'#GQO/gQ$IWO'#GnO!*^Q$IWO'#GmOOQ$IS,5:X,5:XO!*fQ$IWO,5:XO!*kQ$IWO'#GpO!*vQ$IWO'#GpO!+ZQ$IWO,5=ZOOQ$IS'#Dq'#DqOOQ$IS1G/u1G/uOOQ$IS1G.y1G.yO!,ZQ$I[O1G.yO!,bQ$I[O1G.yO0aQ$IWO1G.yO!,}Q$IWO1G/ROOQ$IS'#DW'#DWO/gQ$IWO,59qOOQ$IS1G.w1G.wO!-UQ$IWO1G/cO!-fQ$IWO1G/cO!-nQ$IWO1G/dO'RQ$IWO'#GgO!-sQ$IWO'#GgO!-xQ$I[O1G.wO!.YQ$IWO,59fO!/`Q$IWO,5=VO!/pQ$IWO,5=VO!/xQ$IWO1G/kO!/}Q$I[O1G/kOOQ$IS1G/h1G/hO!0_Q$IWO,5=QO!1UQ$IWO,5=QO/gQ$IWO1G/oO!1sQ$IWO1G/qO!1xQ$I[O1G/qO!2YQ$I[O1G/oOOQ$IS1G/l1G/lOOQ$IS1G/p1G/pOOOO-E9X-E9XOOQ$IS1G/y1G/yOOOO-E9Y-E9YO!2jQ$IWO'#G{O/gQ$IWO'#G{O!2xQ$IWO,5:aOOOO-E9Z-E9ZOOQ$IS1G/z1G/zOOOO-E9^-E9^OOOO-E9_-E9_OOOO-E9`-E9`OOQ$IS-E9a-E9aO!3TQ%GlO1G2VO!3tQ$I[O1G2VO'RQ$IWO,5<OOOQ$IS,5<O,5<OOOQ$IS-E9b-E9bOOQ$IS,5<V,5<VOOQ$IS-E9i-E9iOOQ$IV1G0o1G0oO/|Q$IWO'#FgO!4]Q$I[O,5=sOOQ$IS1G1V1G1VO!4tQ$IWO1G1VOOQ$IS'#DS'#DSO/gQ$IWO,5<|OOQ$IS,5<|,5<|O!4yQ$IWO'#FSO!5UQ$IWO,59lO!5^Q$IWO1G/UO!5hQ$I[O,5=QOOQ$IS1G2k1G2kOOQ$IS,5:h,5:hO!6XQ$IWO'#GPOOQ$IS,5<P,5<POOQ$IS-E9c-E9cO!6jQ$IWO1G.fOOQ$IS1G0U1G0UO!6xQ$IWO,5=SO!7YQ$IWO,5=SO/gQ$IWO1G0eO/gQ$IWO1G0eO/|Q$IWO1G0gOOQ$IS-E9f-E9fO!7kQ$IWO1G0gO!7vQ$IWO1G0gO!7{Q$IWO,5=vO!8ZQ$IWO,5=vO!8iQ$IWO,5=rO!9PQ$IWO,5=rO!9bQ$IZO1G0qO!<pQ$IZO1G0tO!?{Q$IWO,5=xO!@VQ$IWO,5=xO!@_Q$I[O,5=xO/gQ$IWO1G0vO!@iQ$IWO1G0vO3UQ$IWO1G0{ONgQ$IWO1G0}OOQ$IV,5;W,5;WO!@nQ$IYO,5;WO!@sQ$IZO1G0wO!DUQ$IWO'#FoO3UQ$IWO1G0wO3UQ$IWO1G0wO!DcQ$IWO,5=yO!DpQ$IWO,5=yO/|Q$IWO,5=yOOQ$IV1G0{1G0{O!DxQ$IWO'#EyO!EZQ%1`O1G0}OOQ$IV1G1S1G1SO3UQ$IWO1G1SOOQ$IS,5=Y,5=YOOQ$IS'#Dn'#DnO/gQ$IWO,5=YO!EcQ$IWO,5=XO!EvQ$IWO,5=XOOQ$IS1G/s1G/sO!FOQ$IWO,5=[O!F`Q$IWO,5=[O!FhQ$IWO,5=[O!F{Q$IWO,5=[O!G]Q$IWO,5=[OOQ$IS1G2u1G2uOOQ$IS7+$e7+$eO!5^Q$IWO7+$mO!IOQ$IWO1G.yO!IVQ$IWO1G.yOOQ$IS1G/]1G/]OOQ$IS,5;p,5;pO'RQ$IWO,5;pOOQ$IS7+$}7+$}O!I^Q$IWO7+$}OOQ$IS-E9S-E9SOOQ$IS7+%O7+%OO!InQ$IWO,5=RO'RQ$IWO,5=ROOQ$IS7+$c7+$cO!IsQ$IWO7+$}O!I{Q$IWO7+%OO!JQQ$IWO1G2qOOQ$IS7+%V7+%VO!JbQ$IWO1G2qO!JjQ$IWO7+%VOOQ$IS,5;o,5;oO'RQ$IWO,5;oO!JoQ$IWO1G2lOOQ$IS-E9R-E9RO!KfQ$IWO7+%ZOOQ$IS7+%]7+%]O!KtQ$IWO1G2lO!LcQ$IWO7+%]O!LhQ$IWO1G2rO!LxQ$IWO1G2rO!MQQ$IWO7+%ZO!MVQ$IWO,5=gO!MmQ$IWO,5=gO!MmQ$IWO,5=gO!M{O!LQO'#DwO!NWOSO'#G|OOOO1G/{1G/{O!N]Q$IWO1G/{O!NeQ%GlO7+'qO# UQ$I[O1G1jP# oQ$IWO'#FdOOQ$IS,5<R,5<ROOQ$IS-E9e-E9eOOQ$IS7+&q7+&qOOQ$IS1G2h1G2hOOQ$IS,5;n,5;nOOQ$IS-E9Q-E9QOOQ$IS7+$p7+$pO# |Q$IWO,5<kO#!gQ$IWO,5<kO#!xQ$I[O,5;qO##]Q$IWO1G2nOOQ$IS-E9T-E9TOOQ$IS7+&P7+&PO##mQ$IWO7+&POOQ$IS7+&R7+&RO##{Q$IWO'#HZO/|Q$IWO'#HYO#$aQ$IWO7+&ROOQ$IS,5<U,5<UO#$lQ$IWO1G3bOOQ$IS-E9h-E9hOOQ$IS,5<Q,5<QO#$zQ$IWO1G3^OOQ$IS-E9d-E9dO#%bQ$IZO7+&]O!DUQ$IWO'#FmO3UQ$IWO7+&]O3UQ$IWO7+&`O#(pQ$I[O,5<YO'RQ$IWO,5<YO#(zQ$IWO1G3dOOQ$IS-E9l-E9lO#)UQ$IWO1G3dO3UQ$IWO7+&bO/gQ$IWO7+&bOOQ$IV7+&g7+&gO!EZQ%1`O7+&iO#)^Q$IXO1G0rOOQ$IV-E9m-E9mO3UQ$IWO7+&cO3UQ$IWO7+&cOOQ$IV,5<Z,5<ZO#+PQ$IWO,5<ZOOQ$IV7+&c7+&cO#+[Q$IZO7+&cO#.gQ$IWO,5<[O#.rQ$IWO1G3eOOQ$IS-E9n-E9nO#/PQ$IWO1G3eO#/XQ$IWO'#HaO#/gQ$IWO'#HaO/|Q$IWO'#HaOOQ$IS'#Ha'#HaO#/rQ$IWO'#H`OOQ$IS,5;e,5;eO#/zQ$IWO,5;eO/gQ$IWO'#E{OOQ$IV7+&i7+&iO3UQ$IWO7+&iOOQ$IV7+&n7+&nOOQ$IS1G2t1G2tOOQ$IS,5;s,5;sO#0PQ$IWO1G2sOOQ$IS-E9V-E9VO#0dQ$IWO,5;tO#0oQ$IWO,5;tO#1SQ$IWO1G2vOOQ$IS-E9W-E9WO#1dQ$IWO1G2vO#1lQ$IWO1G2vO#1|Q$IWO1G2vO#1dQ$IWO1G2vOOQ$IS<<HX<<HXO#2XQ$I[O1G1[OOQ$IS<<Hi<<HiP#2fQ$IWO'#FUO6|Q$IWO1G2mO#2sQ$IWO1G2mO#2xQ$IWO<<HiOOQ$IS<<Hj<<HjO#3YQ$IWO7+(]OOQ$IS<<Hq<<HqO#3jQ$I[O1G1ZP#4ZQ$IWO'#FTO#4hQ$IWO7+(^O#4xQ$IWO7+(^O#5QQ$IWO<<HuO#5VQ$IWO7+(WOOQ$IS<<Hw<<HwO#5|Q$IWO,5;rO'RQ$IWO,5;rOOQ$IS-E9U-E9UOOQ$IS<<Hu<<HuOOQ$IS,5;x,5;xO/gQ$IWO,5;xO#6RQ$IWO1G3ROOQ$IS-E9[-E9[O#6iQ$IWO1G3ROOOO'#F_'#F_O#6wO!LQO,5:cOOOO,5=h,5=hOOOO7+%g7+%gO#7SQ$IWO1G2VO#7mQ$IWO1G2VP'RQ$IWO'#FVO/gQ$IWO<<IkO#8OQ$IWO,5=uO#8aQ$IWO,5=uO/|Q$IWO,5=uO#8rQ$IWO,5=tOOQ$IS<<Im<<ImP/|Q$IWO'#FjP/gQ$IWO'#FfOOQ$IV-E9k-E9kO3UQ$IWO<<IwOOQ$IV,5<X,5<XO3UQ$IWO,5<XOOQ$IV<<Iw<<IwOOQ$IV<<Iz<<IzO#8wQ$I[O1G1tP#9RQ$IWO'#FnO#9YQ$IWO7+)OO#9dQ$IZO<<I|O3UQ$IWO<<I|OOQ$IV<<JT<<JTO3UQ$IWO<<JTOOQ$IV'#Fl'#FlO#<oQ$IZO7+&^OOQ$IV<<I}<<I}O#>hQ$IZO<<I}OOQ$IV1G1u1G1uO/|Q$IWO1G1uO3UQ$IWO<<I}O/|Q$IWO1G1vP/gQ$IWO'#FpO#AsQ$IWO7+)PO#BQQ$IWO7+)POOQ$IS'#Ez'#EzO/gQ$IWO,5={O#BYQ$IWO,5={OOQ$IS,5={,5={O#BeQ$IWO,5=zO#BvQ$IWO,5=zOOQ$IS1G1P1G1POOQ$IS,5;g,5;gP#COQ$IWO'#FXO#C`Q$IWO1G1`O#CsQ$IWO1G1`O#DTQ$IWO1G1`P#D`Q$IWO'#FYO#DmQ$IWO7+(bO#D}Q$IWO7+(bO#D}Q$IWO7+(bO#EVQ$IWO7+(bO#EgQ$IWO7+(XO6|Q$IWO7+(XOOQ$ISAN>TAN>TO#FQQ$IWO<<KxOOQ$ISAN>aAN>aO/gQ$IWO1G1^O#FbQ$I[O1G1^P#FlQ$IWO'#FWOOQ$IS1G1d1G1dP#FyQ$IWO'#F^O#GWQ$IWO7+(mOOOO-E9]-E9]O#GnQ$IWO7+'qOOQ$ISAN?VAN?VO#HXQ$IWO,5<TO#HmQ$IWO1G3aOOQ$IS-E9g-E9gO#IOQ$IWO1G3aOOQ$IS1G3`1G3`OOQ$IVAN?cAN?cOOQ$IV1G1s1G1sO3UQ$IWOAN?hO#IaQ$IZOAN?hOOQ$IVAN?oAN?oOOQ$IV-E9j-E9jOOQ$IV<<Ix<<IxO3UQ$IWOAN?iO3UQ$IWO7+'aOOQ$IVAN?iAN?iOOQ$IS7+'b7+'bO#LlQ$IWO<<LkOOQ$IS1G3g1G3gO/gQ$IWO1G3gOOQ$IS,5<],5<]O#LyQ$IWO1G3fOOQ$IS-E9o-E9oO#M[Q$IWO7+&zO#MlQ$IWO7+&zOOQ$IS7+&z7+&zO#MwQ$IWO<<K|O#NXQ$IWO<<K|O#NXQ$IWO<<K|O#NaQ$IWO'#GiOOQ$IS<<Ks<<KsO#NkQ$IWO<<KsOOQ$IS7+&x7+&xO/|Q$IWO1G1oP/|Q$IWO'#FiO$ UQ$IWO7+({O$ gQ$IWO7+({OOQ$IVG25SG25SO3UQ$IWOG25SOOQ$IVG25TG25TOOQ$IV<<J{<<J{OOQ$IS7+)R7+)RP$ xQ$IWO'#FqOOQ$IS<<Jf<<JfO$!WQ$IWO<<JfO$!hQ$IWOANAhO$!xQ$IWOANAhO$#QQ$IWO'#GjOOQ$IS'#Gj'#GjO0hQ$IWO'#DaO$#kQ$IWO,5=TOOQ$ISANA_ANA_OOQ$IS7+'Z7+'ZO$$SQ$IWO<<LgOOQ$IVLD*nLD*nOOQ$ISAN@QAN@QO$$eQ$IWOG27SO$$uQ$IWO,59{OOQ$IS1G2o1G2oO#NaQ$IWO1G/gOOQ$IS7+%R7+%RO6|Q$IWO'#CzO6|Q$IWO,59_O6|Q$IWO,59_O6|Q$IWO,59_O$$zQ$I[O,5<kO6|Q$IWO1G.yO/gQ$IWO1G/UO/gQ$IWO7+$mP$%_Q$IWO'#FdO'RQ$IWO'#GPO$%lQ$IWO,59_O$%qQ$IWO,59_O$%xQ$IWO,59jO$%}Q$IWO1G/RO0hQ$IWO'#DOO6|Q$IWO,59g", - stateData: "$&e~O$oOS$lOS$kOSQOS~OPhOTeOdsOfXOltOp!SOsuO|vO}!PO!R!VO!S!UO!VYO!ZZO!fdO!mdO!ndO!odO!vxO!xyO!zzO!|{O#O|O#S}O#U!OO#X!QO#Y!QO#[!RO#c!TO#f!WO#j!XO#l!YO#q!ZO#tlO$jqO$zQO${QO%PRO%QVO%f[O%g]O%j^O%m_O%s`O%vaO%xbO~OT!aO]!aO_!bOf!iO!V!kO!d!mO$u![O$v!]O$w!^O$x!_O$y!_O$z!`O${!`O$|!aO$}!aO%O!aO~Oh%TXi%TXj%TXk%TXl%TXm%TXp%TXw%TXx%TX!s%TX#^%TX$j%TX$m%TX%V%TX!O%TX!R%TX!S%TX%W%TX!W%TX![%TX}%TX#V%TXq%TX!j%TX~P$_OdsOfXO!VYO!ZZO!fdO!mdO!ndO!odO$zQO${QO%PRO%QVO%f[O%g]O%j^O%m_O%s`O%vaO%xbO~Ow%SXx%SX#^%SX$j%SX$m%SX%V%SX~Oh!pOi!qOj!oOk!oOl!rOm!sOp!tO!s%SX~P(`OT!zOl-dOs-rO|vO~P'ROT!}Ol-dOs-rO!W#OO~P'ROT#RO_#SOl-dOs-rO![#TO~P'RO%h#WO%i#YO~O%k#ZO%l#YO~O!Z#]O%n#^O%r#`O~O!Z#]O%t#aO%u#`O~O!Z#]O%i#`O%w#cO~O!Z#]O%l#`O%y#eO~OT$tX]$tX_$tXf$tXh$tXi$tXj$tXk$tXl$tXm$tXp$tXw$tX!V$tX!d$tX$u$tX$v$tX$w$tX$x$tX$y$tX$z$tX${$tX$|$tX$}$tX%O$tX!O$tX!R$tX!S$tX~O%f[O%g]O%j^O%m_O%s`O%vaO%xbOx$tX!s$tX#^$tX$j$tX$m$tX%V$tX%W$tX!W$tX![$tX}$tX#V$tXq$tX!j$tX~P+uOw#jOx$sX!s$sX#^$sX$j$sX$m$sX%V$sX~Ol-dOs-rO~P'RO#^#mO$j#oO$m#oO~O%QVO~O!R#tO#l!YO#q!ZO#tlO~OltO~P'ROT#yO_#zO%QVOxtP~OT$OOl-dOs-rO}$PO~P'ROx$RO!s$WO%V$SO#^!tX$j!tX$m!tX~OT$OOl-dOs-rO#^!}X$j!}X$m!}X~P'ROl-dOs-rO#^#RX$j#RX$m#RX~P'RO!d$^O!m$^O%QVO~OT$hO~P'RO!S$jO#j$kO#l$lO~Ox$mO~OT${O_${Ol-dOs-rO!O$}O~P'ROl-dOs-rOx%QO~P'RO%e%SO~O_!bOf!iO!V!kO!d!mOT`a]`ah`ai`aj`ak`al`am`ap`aw`ax`a!s`a#^`a$j`a$m`a$u`a$v`a$w`a$x`a$y`a$z`a${`a$|`a$}`a%O`a%V`a!O`a!R`a!S`a%W`a!W`a![`a}`a#V`aq`a!j`a~Ok%XO~Ol%XO~P'ROl-dO~P'ROh-fOi-gOj-eOk-eOl-nOm-oOp-sO!O%SX!R%SX!S%SX%W%SX!W%SX![%SX}%SX#V%SX!j%SX~P(`O%W%ZOw%RX!O%RX!R%RX!S%RX!W%RXx%RX~Ow%^O!O%]O!R%bO!S%aO~O!O%]O~Ow%eO!R%bO!S%aO!W%_X~O!W%iO~Ow%jOx%lO!R%bO!S%aO![%YX~O![%pO~O![%qO~O%h#WO%i%sO~O%k#ZO%l%sO~OT%vOl-dOs-rO|vO~P'RO!Z#]O%n#^O%r%yO~O!Z#]O%t#aO%u%yO~O!Z#]O%i%yO%w#cO~O!Z#]O%l%yO%y#eO~OT!la]!la_!laf!lah!lai!laj!lak!lal!lam!lap!law!lax!la!V!la!d!la!s!la#^!la$j!la$m!la$u!la$v!la$w!la$x!la$y!la$z!la${!la$|!la$}!la%O!la%V!la!O!la!R!la!S!la%W!la!W!la![!la}!la#V!laq!la!j!la~P#vOw&OOx$sa!s$sa#^$sa$j$sa$m$sa%V$sa~P$_OT&QOltOsuOx$sa!s$sa#^$sa$j$sa$m$sa%V$sa~P'ROw&OOx$sa!s$sa#^$sa$j$sa$m$sa%V$sa~OPhOTeOltOsuO|vO}!PO!vxO!xyO!zzO!|{O#O|O#S}O#U!OO#X!QO#Y!QO#[!RO#^$_X$j$_X$m$_X~P'RO#^#mO$j&VO$m&VO~O!d&WOf%{X$j%{X#V%{X#^%{X$m%{X#U%{X~Of!iO$j&YO~Ohcaicajcakcalcamcapcawcaxca!sca#^ca$jca$mca%Vca!Oca!Rca!Sca%Wca!Wca![ca}ca#Vcaqca!jca~P$_Opnawnaxna#^na$jna$mna%Vna~Oh!pOi!qOj!oOk!oOl!rOm!sO!sna~PDTO%V&[Ow%UXx%UX~O%QVOw%UXx%UX~Ow&_OxtX~Ox&aO~Ow%jO#^%YX$j%YX$m%YX!O%YXx%YX![%YX!j%YX%V%YX~OT-mOl-dOs-rO|vO~P'RO%V$SO#^Sa$jSa$mSa~Ow&jO#^%[X$j%[X$m%[Xk%[X~P$_Ow&mO}&lO#^#Ra$j#Ra$m#Ra~O#V&nO#^#Ta$j#Ta$m#Ta~O!d$^O!m$^O#U&pO%QVO~O#U&pO~Ow&rO#^&OX$j&OX$m&OX~Ow&tO#^%zX$j%zX$m%zXx%zX~Ow&xOk&QX~P$_Ok&{O~OPhOTeOltOsuO|vO}!PO!vxO!xyO!zzO!|{O#O|O#S}O#U!OO#X!QO#Y!QO#[!RO$j'QO~P'ROq'UO#g'SO#h'TOP#eaT#ead#eaf#eal#eap#eas#ea|#ea}#ea!R#ea!S#ea!V#ea!Z#ea!f#ea!m#ea!n#ea!o#ea!v#ea!x#ea!z#ea!|#ea#O#ea#S#ea#U#ea#X#ea#Y#ea#[#ea#c#ea#f#ea#j#ea#l#ea#q#ea#t#ea$g#ea$j#ea$z#ea${#ea%P#ea%Q#ea%f#ea%g#ea%j#ea%m#ea%s#ea%v#ea%x#ea$i#ea$m#ea~Ow'VO#V'XOx&RX~Of'ZO~Of!iOx$mO~OT!aO]!aO_!bOf!iO!V!kO!d!mO$w!^O$x!_O$y!_O$z!`O${!`O$|!aO$}!aO%O!aOhUiiUijUikUilUimUipUiwUixUi!sUi#^Ui$jUi$mUi$uUi%VUi!OUi!RUi!SUi%WUi!WUi![Ui}Ui#VUiqUi!jUi~O$v!]O~PNtO$vUi~PNtOT!aO]!aO_!bOf!iO!V!kO!d!mO$z!`O${!`O$|!aO$}!aO%O!aOhUiiUijUikUilUimUipUiwUixUi!sUi#^Ui$jUi$mUi$uUi$vUi$wUi%VUi!OUi!RUi!SUi%WUi!WUi![Ui}Ui#VUiqUi!jUi~O$x!_O$y!_O~P!#oO$xUi$yUi~P!#oO_!bOf!iO!V!kO!d!mOhUiiUijUikUilUimUipUiwUixUi!sUi#^Ui$jUi$mUi$uUi$vUi$wUi$xUi$yUi$zUi${Ui%VUi!OUi!RUi!SUi%WUi!WUi![Ui}Ui#VUiqUi!jUi~OT!aO]!aO$|!aO$}!aO%O!aO~P!&mOTUi]Ui$|Ui$}Ui%OUi~P!&mO!R%bO!S%aOw%bX!O%bX~O%V'`O%W'`O~P+uOw'bO!O%aX~O!O'dO~Ow'eOx'gO!W%dX~Ol-dOs-rOw'eOx'hO!W%dX~P'RO!W'jO~Oj!oOk!oOl!rOm!sOhgipgiwgixgi!sgi#^gi$jgi$mgi%Vgi~Oi!qO~P!+`Oigi~P!+`Oh-fOi-gOj-eOk-eOl-nOm-oO~Oq'lO~P!,iOT'qOl-dOs-rO!O'rO~P'ROw'sO!O'rO~O!O'uO~O!S'wO~Ow'sO!O'xO!R%bO!S%aO~P$_Oh-fOi-gOj-eOk-eOl-nOm-oO!Ona!Rna!Sna%Wna!Wna![na}na#Vnaqna!jna~PDTOT'qOl-dOs-rO!W%_a~P'ROw'{O!W%_a~O!W'|O~Ow'{O!R%bO!S%aO!W%_a~P$_OT(QOl-dOs-rO![%Ya#^%Ya$j%Ya$m%Ya!O%Yax%Ya!j%Ya%V%Ya~P'ROw(RO![%Ya#^%Ya$j%Ya$m%Ya!O%Yax%Ya!j%Ya%V%Ya~O![(UO~Ow(RO!R%bO!S%aO![%Ya~P$_Ow(XO!R%bO!S%aO![%`a~P$_Ow([Ox%oX![%oX!j%oX~Ox(_O![(aO!j(bO~OT&QOltOsuOx$si!s$si#^$si$j$si$m$si%V$si~P'ROw(cOx$si!s$si#^$si$j$si$m$si%V$si~O!d&WOf%{a$j%{a#V%{a#^%{a$m%{a#U%{a~O$j(hO~OT#yO_#zO%QVO~Ow&_Oxta~OltOsuO~P'ROw(RO#^%Ya$j%Ya$m%Ya!O%Yax%Ya![%Ya!j%Ya%V%Ya~P$_Ow(mO#^$sX$j$sX$m$sX%V$sX~O%V$SO#^Si$jSi$mSi~O#^%[a$j%[a$m%[ak%[a~P'ROw(pO#^%[a$j%[a$m%[ak%[a~OT(tOf(vO%QVO~O#U(wO~O%QVO#^&Oa$j&Oa$m&Oa~Ow(yO#^&Oa$j&Oa$m&Oa~Ol-dOs-rO#^%za$j%za$m%zax%za~P'ROw(|O#^%za$j%za$m%zax%za~Oq)QO#a)POP#_iT#_id#_if#_il#_ip#_is#_i|#_i}#_i!R#_i!S#_i!V#_i!Z#_i!f#_i!m#_i!n#_i!o#_i!v#_i!x#_i!z#_i!|#_i#O#_i#S#_i#U#_i#X#_i#Y#_i#[#_i#c#_i#f#_i#j#_i#l#_i#q#_i#t#_i$g#_i$j#_i$z#_i${#_i%P#_i%Q#_i%f#_i%g#_i%j#_i%m#_i%s#_i%v#_i%x#_i$i#_i$m#_i~Oq)ROP#biT#bid#bif#bil#bip#bis#bi|#bi}#bi!R#bi!S#bi!V#bi!Z#bi!f#bi!m#bi!n#bi!o#bi!v#bi!x#bi!z#bi!|#bi#O#bi#S#bi#U#bi#X#bi#Y#bi#[#bi#c#bi#f#bi#j#bi#l#bi#q#bi#t#bi$g#bi$j#bi$z#bi${#bi%P#bi%Q#bi%f#bi%g#bi%j#bi%m#bi%s#bi%v#bi%x#bi$i#bi$m#bi~OT)TOk&Qa~P'ROw)UOk&Qa~Ow)UOk&Qa~P$_Ok)YO~O$h)]O~Oq)`O#g'SO#h)_OP#eiT#eid#eif#eil#eip#eis#ei|#ei}#ei!R#ei!S#ei!V#ei!Z#ei!f#ei!m#ei!n#ei!o#ei!v#ei!x#ei!z#ei!|#ei#O#ei#S#ei#U#ei#X#ei#Y#ei#[#ei#c#ei#f#ei#j#ei#l#ei#q#ei#t#ei$g#ei$j#ei$z#ei${#ei%P#ei%Q#ei%f#ei%g#ei%j#ei%m#ei%s#ei%v#ei%x#ei$i#ei$m#ei~Ol-dOs-rOx$mO~P'ROl-dOs-rOx&Ra~P'ROw)fOx&Ra~OT)jO_)kO!O)nO$|)lO%QVO~Ox$mO&U)pO~OT${O_${Ol-dOs-rO!O%aa~P'ROw)vO!O%aa~Ol-dOs-rOx)yO!W%da~P'ROw)zO!W%da~Ol-dOs-rOw)zOx)}O!W%da~P'ROl-dOs-rOw)zO!W%da~P'ROw)zOx)}O!W%da~Oj-eOk-eOl-nOm-oOhgipgiwgi!Ogi!Rgi!Sgi%Wgi!Wgixgi![gi#^gi$jgi$mgi}gi#Vgiqgi!jgi%Vgi~Oi-gO~P!GhOigi~P!GhOT'qOl-dOs-rO!O*SO~P'ROk*UO~Ow*WO!O*SO~O!O*XO~OT'qOl-dOs-rO!W%_i~P'ROw*YO!W%_i~O!W*ZO~OT(QOl-dOs-rO![%Yi#^%Yi$j%Yi$m%Yi!O%Yix%Yi!j%Yi%V%Yi~P'ROw*^O!R%bO!S%aO![%`i~Ow*aO![%Yi#^%Yi$j%Yi$m%Yi!O%Yix%Yi!j%Yi%V%Yi~O![*bO~O_*dOl-dOs-rO![%`i~P'ROw*^O![%`i~O![*fO~OT*hOl-dOs-rOx%oa![%oa!j%oa~P'ROw*iOx%oa![%oa!j%oa~O!Z#]O%q*lO![!kX~O![*nO~Ox(_O![*oO~OT&QOltOsuOx$sq!s$sq#^$sq$j$sq$m$sq%V$sq~P'ROw$Wix$Wi!s$Wi#^$Wi$j$Wi$m$Wi%V$Wi~P$_OT&QOltOsuO~P'ROT&QOl-dOs-rO#^$sa$j$sa$m$sa%V$sa~P'ROw*pO#^$sa$j$sa$m$sa%V$sa~Ow#ya#^#ya$j#ya$m#yak#ya~P$_O#^%[i$j%[i$m%[ik%[i~P'ROw*sO#^#Rq$j#Rq$m#Rq~Ow*tO#V*vO#^%}X$j%}X$m%}X!O%}X~OT*xOf(vO%QVO~O%QVO#^&Oi$j&Oi$m&Oi~Ol-dOs-rO#^%zi$j%zi$m%zix%zi~P'ROq*|O#a)POP#_qT#_qd#_qf#_ql#_qp#_qs#_q|#_q}#_q!R#_q!S#_q!V#_q!Z#_q!f#_q!m#_q!n#_q!o#_q!v#_q!x#_q!z#_q!|#_q#O#_q#S#_q#U#_q#X#_q#Y#_q#[#_q#c#_q#f#_q#j#_q#l#_q#q#_q#t#_q$g#_q$j#_q$z#_q${#_q%P#_q%Q#_q%f#_q%g#_q%j#_q%m#_q%s#_q%v#_q%x#_q$i#_q$m#_q~Ok$baw$ba~P$_OT)TOk&Qi~P'ROw+TOk&Qi~OPhOTeOltOp!SOsuO|vO}!PO!R!VO!S!UO!vxO!xyO!zzO!|{O#O|O#S}O#U!OO#X!QO#Y!QO#[!RO#c!TO#f!WO#j!XO#l!YO#q!ZO#tlO~P'ROw+_Ox$mO#V+_O~O#h+`OP#eqT#eqd#eqf#eql#eqp#eqs#eq|#eq}#eq!R#eq!S#eq!V#eq!Z#eq!f#eq!m#eq!n#eq!o#eq!v#eq!x#eq!z#eq!|#eq#O#eq#S#eq#U#eq#X#eq#Y#eq#[#eq#c#eq#f#eq#j#eq#l#eq#q#eq#t#eq$g#eq$j#eq$z#eq${#eq%P#eq%Q#eq%f#eq%g#eq%j#eq%m#eq%s#eq%v#eq%x#eq$i#eq$m#eq~O#V+aOw$dax$da~Ol-dOs-rOx&Ri~P'ROw+cOx&Ri~Ox$RO%V+eOw&TX!O&TX~O%QVOw&TX!O&TX~Ow+iO!O&SX~O!O+kO~OT${O_${Ol-dOs-rO!O%ai~P'ROx+nOw#|a!W#|a~Ol-dOs-rOx+oOw#|a!W#|a~P'ROl-dOs-rOx)yO!W%di~P'ROw+rO!W%di~Ol-dOs-rOw+rO!W%di~P'ROw+rOx+uO!W%di~Ow#xi!O#xi!W#xi~P$_OT'qOl-dOs-rO~P'ROk+wO~OT'qOl-dOs-rO!O+xO~P'ROT'qOl-dOs-rO!W%_q~P'ROw#wi![#wi#^#wi$j#wi$m#wi!O#wix#wi!j#wi%V#wi~P$_OT(QOl-dOs-rO~P'RO_*dOl-dOs-rO![%`q~P'ROw+yO![%`q~O![+zO~OT(QOl-dOs-rO![%Yq#^%Yq$j%Yq$m%Yq!O%Yqx%Yq!j%Yq%V%Yq~P'ROx+{O~OT*hOl-dOs-rOx%oi![%oi!j%oi~P'ROw,QOx%oi![%oi!j%oi~O!Z#]O%q*lO![!ka~OT&QOl-dOs-rO#^$si$j$si$m$si%V$si~P'ROw,SO#^$si$j$si$m$si%V$si~O%QVO#^%}a$j%}a$m%}a!O%}a~Ow,VO#^%}a$j%}a$m%}a!O%}a~O!O,YO~Ok$biw$bi~P$_OT)TO~P'ROT)TOk&Qq~P'ROq,]OP#dyT#dyd#dyf#dyl#dyp#dys#dy|#dy}#dy!R#dy!S#dy!V#dy!Z#dy!f#dy!m#dy!n#dy!o#dy!v#dy!x#dy!z#dy!|#dy#O#dy#S#dy#U#dy#X#dy#Y#dy#[#dy#c#dy#f#dy#j#dy#l#dy#q#dy#t#dy$g#dy$j#dy$z#dy${#dy%P#dy%Q#dy%f#dy%g#dy%j#dy%m#dy%s#dy%v#dy%x#dy$i#dy$m#dy~OPhOTeOltOp!SOsuO|vO}!PO!R!VO!S!UO!vxO!xyO!zzO!|{O#O|O#S}O#U!OO#X!QO#Y!QO#[!RO#c!TO#f!WO#j!XO#l!YO#q!ZO#tlO$i,aO$m,aO~P'RO#h,bOP#eyT#eyd#eyf#eyl#eyp#eys#ey|#ey}#ey!R#ey!S#ey!V#ey!Z#ey!f#ey!m#ey!n#ey!o#ey!v#ey!x#ey!z#ey!|#ey#O#ey#S#ey#U#ey#X#ey#Y#ey#[#ey#c#ey#f#ey#j#ey#l#ey#q#ey#t#ey$g#ey$j#ey$z#ey${#ey%P#ey%Q#ey%f#ey%g#ey%j#ey%m#ey%s#ey%v#ey%x#ey$i#ey$m#ey~Ol-dOs-rOx&Rq~P'ROw,fOx&Rq~O%V+eOw&Ta!O&Ta~OT)jO_)kO$|)lO%QVO!O&Sa~Ow,jO!O&Sa~OT${O_${Ol-dOs-rO~P'ROl-dOs-rOx,lOw#|i!W#|i~P'ROl-dOs-rOw#|i!W#|i~P'ROx,lOw#|i!W#|i~Ol-dOs-rOx)yO~P'ROl-dOs-rOx)yO!W%dq~P'ROw,oO!W%dq~Ol-dOs-rOw,oO!W%dq~P'ROp,rO!R%bO!S%aO!O%Zq!W%Zq![%Zqw%Zq~P!,iO_*dOl-dOs-rO![%`y~P'ROw#zi![#zi~P$_O_*dOl-dOs-rO~P'ROT*hOl-dOs-rO~P'ROT*hOl-dOs-rOx%oq![%oq!j%oq~P'ROT&QOl-dOs-rO#^$sq$j$sq$m$sq%V$sq~P'RO#V,vOw$]a#^$]a$j$]a$m$]a!O$]a~O%QVO#^%}i$j%}i$m%}i!O%}i~Ow,xO#^%}i$j%}i$m%}i!O%}i~Oq,{OP#d!RT#d!Rd#d!Rf#d!Rl#d!Rp#d!Rs#d!R|#d!R}#d!R!R#d!R!S#d!R!V#d!R!Z#d!R!f#d!R!m#d!R!n#d!R!o#d!R!v#d!R!x#d!R!z#d!R!|#d!R#O#d!R#S#d!R#U#d!R#X#d!R#Y#d!R#[#d!R#c#d!R#f#d!R#j#d!R#l#d!R#q#d!R#t#d!R$g#d!R$j#d!R$z#d!R${#d!R%P#d!R%Q#d!R%f#d!R%g#d!R%j#d!R%m#d!R%s#d!R%v#d!R%x#d!R$i#d!R$m#d!R~Ol-dOs-rOx&Ry~P'ROT)jO_)kO$|)lO%QVO!O&Si~Ol-dOs-rOw#|q!W#|q~P'ROx-ROw#|q!W#|q~Ol-dOs-rOx)yO!W%dy~P'ROw-SO!W%dy~Ol-dOs-WO~P'ROp,rO!R%bO!S%aO!O%Zy!W%Zy![%Zyw%Zy~P!,iO%QVO#^%}q$j%}q$m%}q!O%}q~Ow-[O#^%}q$j%}q$m%}q!O%}q~OT)jO_)kO$|)lO%QVO~Ol-dOs-rOw#|y!W#|y~P'ROl-dOs-rOx)yO!W%d!R~P'ROw-_O!W%d!R~Op%^X!O%^X!R%^X!S%^X!W%^X![%^Xw%^X~P!,iOp,rO!R%bO!S%aO!O%]a!W%]a![%]aw%]a~O%QVO#^%}y$j%}y$m%}y!O%}y~Ol-dOs-rOx)yO!W%d!Z~P'ROx-bO~Ow*pO#^$sa$j$sa$m$sa%V$sa~P$_OT&QOl-dOs-rO~P'ROk-iO~Ol-iO~P'ROx-jO~Oq-kO~P!,iO%g%j%v%x%f!Z%n%t%w%y%m%s%m%Q~", - goto: "!-g&UPPPP&VP&_)p*V*m+U+n,XP,sP&_-a-a&_P&_P0rPPPPPP0r3bPP3bP5n5w:zPP:};];`PPP&_&_PP;l&_PP&_&_PP&_&_&_&_;p<d&_P<gP<j<j@PP@e&_PPP@i@o&VP&V&VP&VP&VP&VP&VP&V&V&VP&VPP&VPP&VP@uP@|ASP@|P@|@|PPP@|PB{PCUC[CbB{P@|ChPCoCuC{DXDkDqD{EREoEuE{FRF]FcFiFoFuF{G_GiGoGuG{HVH]HcHiHoHyIPIZIaPPPPPPPPPIjIrI{JVJbPPPPPPPPPPPPNw! a!%o!({PP!)T!)c!)l!*b!*X!*k!*q!*t!*w!*z!+S!+pPPPPPPPPPP!+s!+vPPPPPPPPP!+|!,Y!,f!,l!,u!,x!-O!-U!-[!-_]iOr#m$m)]+Z'odOSXYZehrstvx|}!R!S!T!U!X!c!d!e!f!g!h!i!k!o!p!q!s!t!z!}#R#S#]#j#m$O$P$R$T$W$h$j$k$m${%Q%X%[%^%a%e%j%l%v&O&Q&]&a&j&l&m&t&x&{'S'V'a'b'e'g'h'l'q's'w'{(Q(R(X([(c(e(m(p(|)P)T)U)Y)])f)p)v)y)z)}*T*U*W*Y*]*^*a*d*h*i*p*r*s*z+S+T+Z+b+c+f+m+n+o+q+r+u+w+y+{+},P,Q,S,f,h,l,o,r-R-S-_-b-d-e-f-g-i-j-k-l-m-o-sw!cP#i#v$X$g%c%h%n%o&b&z(d(o)S*R*[+R+|-hy!dP#i#v$X$g$s%c%h%n%o&b&z(d(o)S*R*[+R+|-h{!eP#i#v$X$g$s$t%c%h%n%o&b&z(d(o)S*R*[+R+|-h}!fP#i#v$X$g$s$t$u%c%h%n%o&b&z(d(o)S*R*[+R+|-h!P!gP#i#v$X$g$s$t$u$v%c%h%n%o&b&z(d(o)S*R*[+R+|-h!R!hP#i#v$X$g$s$t$u$v$w%c%h%n%o&b&z(d(o)S*R*[+R+|-h!V!hP!n#i#v$X$g$s$t$u$v$w$x%c%h%n%o&b&z(d(o)S*R*[+R+|-h'oSOSXYZehrstvx|}!R!S!T!U!X!c!d!e!f!g!h!i!k!o!p!q!s!t!z!}#R#S#]#j#m$O$P$R$T$W$h$j$k$m${%Q%X%[%^%a%e%j%l%v&O&Q&]&a&j&l&m&t&x&{'S'V'a'b'e'g'h'l'q's'w'{(Q(R(X([(c(e(m(p(|)P)T)U)Y)])f)p)v)y)z)}*T*U*W*Y*]*^*a*d*h*i*p*r*s*z+S+T+Z+b+c+f+m+n+o+q+r+u+w+y+{+},P,Q,S,f,h,l,o,r-R-S-_-b-d-e-f-g-i-j-k-l-m-o-s&ZUOXYZhrtv|}!R!S!T!X!i!k!o!p!q!s!t#]#j#m$P$R$T$W$k$m${%Q%X%[%^%e%j%l%v&O&]&a&l&m&t&{'S'V'a'b'e'g'h'l's'{(R(X([(c(e(m(|)P)Y)])f)p)v)y)z)}*T*U*W*Y*]*^*a*h*i*p*s*z+Z+b+c+f+m+n+o+q+r+u+w+y+{+},P,Q,S,f,h,l,o,r-R-S-_-b-d-e-f-g-i-j-k-l-o-s%eWOXYZhrv|}!R!S!T!X!i!k#]#j#m$P$R$T$W$k$m${%Q%[%^%e%j%l%v&O&]&a&l&m&t&{'S'V'a'b'e'g'h'l's'{(R(X([(c(e(m(|)P)Y)])f)p)v)y)z)}*T*W*Y*]*^*a*h*i*p*s*z+Z+b+c+f+m+n+o+q+r+u+y+{+},P,Q,S,f,h,l,o-R-S-_-j-k-lQ#|uQ-`-WR-p-r'fdOSXYZehrstvx|}!R!S!T!U!X!c!d!e!f!g!h!k!o!p!q!s!t!z!}#R#S#]#j#m$O$P$R$T$W$h$j$k$m${%Q%X%[%^%a%e%j%l%v&O&Q&]&a&j&l&m&t&x&{'S'V'a'e'g'h'l'q's'w'{(Q(R(X([(c(e(m(p(|)P)T)U)Y)])f)p)y)z)}*T*U*W*Y*]*^*a*d*h*i*p*r*s*z+S+T+Z+b+c+f+n+o+q+r+u+w+y+{+},P,Q,S,f,h,l,o,r-R-S-_-b-d-e-f-g-i-j-k-l-m-o-sW#pl!O!P$_W#xu&_-W-rQ$a!QQ$q!YQ$r!ZW$z!i'b)v+mS&^#y#zQ'O$lQ(f&WQ(t&nU(u&p(v(wU(x&r(y*yQ)h'XW)i'Z+i,j-PS+h)j)kY,U*t,V,w,x-[Q,X*vQ,c+_Q,e+aR-Z,vR&]#xi!wXY!S!T%^%e's'{)P*T*W*YR%[!vQ!{XQ%w#]Q&f$TR&i$WT-V,r-b!U!jP!n#i#v$X$g$s$t$u$v$w$x%c%h%n%o&b&z(d(o)S*R*[+R+|-hQ&Z#qR'^$rR'a$zR%T!m'ncOSXYZehrstvx|}!R!S!T!U!X!c!d!e!f!g!h!i!k!o!p!q!s!t!z!}#R#S#]#j#m$O$P$R$T$W$h$j$k$m${%Q%X%[%^%a%e%j%l%v&O&Q&]&a&j&l&m&t&x&{'S'V'a'b'e'g'h'l'q's'w'{(Q(R(X([(c(e(m(p(|)P)T)U)Y)])f)p)v)y)z)}*T*U*W*Y*]*^*a*d*h*i*p*r*s*z+S+T+Z+b+c+f+m+n+o+q+r+u+w+y+{+},P,Q,S,f,h,l,o,r-R-S-_-b-d-e-f-g-i-j-k-l-m-o-sT#gc#hS#^_#_S#a`#bS#ca#dS#eb#fT*l(_*mT(`%w(bQ$VwR+g)iX$Tw$U$V&hZkOr$m)]+ZXoOr)]+ZQ$n!WQ&v$eQ&w$fQ'Y$pQ']$rQ)Z&}Q)a'SQ)c'TQ)d'UQ)q'[Q)s'^Q*})PQ+P)QQ+Q)RQ+U)XS+W)[)rQ+[)_Q+])`Q+^)bQ,Z*|Q,[+OQ,^+VQ,_+XQ,d+`Q,z,]Q,|,bQ,},cR-],{WoOr)]+ZR#snQ'[$qR)['OQ+f)iR,h+gQ)r'[R+X)[ZmOnr)]+ZQrOR#urQ&`#{R(k&`S%k#Q#}S(S%k(VT(V%n&bQ%_!yQ%f!|W't%_%f'y'}Q'y%cR'}%hQ&k$XR(q&kQ(Y%oQ*_(TT*e(Y*_Q'c$|R)w'cS'f%P%QY){'f)|+s,p-TU)|'g'h'iU+s)}*O*PS,p+t+uR-T,qQ#X]R%r#XQ#[^R%t#[Q#__R%x#_Q(]%uS*j(]*kR*k(^Q*m(_R,R*mQ#b`R%z#bQ#daR%{#dQ#fbR%|#fQ#hcR%}#hQ#kfQ&P#iW&S#k&P(n*qQ(n&eR*q-hQ$UwS&g$U&hR&h$VQ&u$cR(}&uQ&X#pR(g&XQ$_!PR&o$_Q*u(uS,W*u,yR,y,XQ&s$aR(z&sQ#njR&U#nQ+Z)]R,`+ZQ)O&vR*{)OQ&y$gS)V&y)WR)W&zQ'R$nR)^'RQ'W$oS)g'W+dR+d)hQ+j)mR,k+jWnOr)]+ZR#rnSqOrT+Y)]+ZWpOr)]+ZR'P$mYjOr$m)]+ZR&T#m[wOr#m$m)]+ZR&f$T&YPOXYZhrtv|}!R!S!T!X!i!k!o!p!q!s!t#]#j#m$P$R$T$W$k$m${%Q%X%[%^%e%j%l%v&O&]&a&l&m&t&{'S'V'a'b'e'g'h'l's'{(R(X([(c(e(m(|)P)Y)])f)p)v)y)z)}*T*U*W*Y*]*^*a*h*i*p*s*z+Z+b+c+f+m+n+o+q+r+u+w+y+{+},P,Q,S,f,h,l,o,r-R-S-_-b-d-e-f-g-i-j-k-l-o-sQ!nSQ#ieQ#vsU$Xx%a'wS$g!U$jQ$s!cQ$t!dQ$u!eQ$v!fQ$w!gQ$x!hQ%c!zQ%h!}Q%n#RQ%o#SQ&b$OQ&z$hQ(d&QU(o&j(p*rW)S&x)U+S+TQ*R'qQ*[(QQ+R)TQ+|*dR-h-mQ!yXQ!|YQ$e!SQ$f!T^'p%^%e's'{*T*W*YR+O)P[fOr#m$m)]+Zh!vXY!S!T%^%e's'{)P*T*W*YQ#QZQ#lhS#}v|Q$[}W$c!R$W&{)YS$o!X$kW$y!i'b)v+mQ%P!kQ%u#]`&R#j&O(c(e(m*p,S-lQ&c$PQ&d$RQ&e$TQ'_${Q'i%QQ'o%[W(P%j(R*]*aQ(T%lQ(^%vQ(i&]S(l&a-jQ(r&lQ(s&mU({&t(|*zQ)b'SY)e'V)f+b+c,fQ)t'a^)x'e)z+q+r,o-S-_Q*O'gQ*P'hS*Q'l-kW*c(X*^+y+}W*g([*i,P,QQ+l)pQ+p)yQ+t)}Q,O*hQ,T*sQ,g+fQ,m+nQ,n+oQ,q+uQ,u+{Q-O,hQ-Q,lR-^-RhTOr#j#m$m&O&a'l(c(e)]+Z$z!uXYZhv|}!R!S!T!X!i!k#]$P$R$T$W$k${%Q%[%^%e%j%l%v&]&l&m&t&{'S'V'a'b'e'g'h's'{(R(X([(m(|)P)Y)f)p)v)y)z)}*T*W*Y*]*^*a*h*i*p*s*z+b+c+f+m+n+o+q+r+u+y+{+},P,Q,S,f,h,l,o-R-S-_-j-k-lQ#wtW%U!o!s-e-oQ%V!pQ%W!qQ%Y!tQ%d-dS'k%X-iQ'm-fQ'n-gQ+v*UQ,t+wS-U,r-bR-q-sU#{u-W-rR(j&_[gOr#m$m)]+ZX!xX#]$T$WQ#VZQ$QvR$Z|Q%`!yQ%g!|Q%m#QQ'_$yQ'z%cQ(O%hQ(W%nQ(Z%oQ*`(TQ,s+vQ-Y,tR-a-XQ$YxQ'v%aR*V'wQ-X,rR-c-bR#PYR#UZR%O!iQ$|!iV)u'b)v+m!V!lP!n#i#v$X$g$s$t$u$v$w$x%c%h%n%o&b&z(d(o)S*R*[+R+|-hR%R!kR%w#]Q(a%wR*o(bQ$d!RQ&i$WQ)X&{R+V)YQ#qlQ$]!OQ$`!PR&q$_Q(t&pR*x(wQ(t&pQ*w(vR*x(wR$b!QXpOr)]+ZQ$i!UR&|$jQ$p!XR&}$kR)o'ZQ)m'ZV,i+i,j-P", - nodeNames: "⚠ print Comment Script AssignStatement * BinaryExpression BitOp BitOp BitOp BitOp ArithOp ArithOp @ ArithOp ** UnaryExpression ArithOp BitOp AwaitExpression await ParenthesizedExpression ( BinaryExpression or and CompareOp in not is UnaryExpression ConditionalExpression if else LambdaExpression lambda ParamList VariableName AssignOp , : NamedExpression AssignOp YieldExpression yield from ) TupleExpression ComprehensionExpression async for LambdaExpression ArrayExpression [ ] ArrayComprehensionExpression DictionaryExpression { } DictionaryComprehensionExpression SetExpression SetComprehensionExpression CallExpression ArgList AssignOp MemberExpression . PropertyName Number String FormatString FormatReplacement FormatConversion FormatSpec ContinuedString Ellipsis None Boolean TypeDef AssignOp UpdateStatement UpdateOp ExpressionStatement DeleteStatement del PassStatement pass BreakStatement break ContinueStatement continue ReturnStatement return YieldStatement PrintStatement RaiseStatement raise ImportStatement import as ScopeStatement global nonlocal AssertStatement assert StatementGroup ; IfStatement Body elif WhileStatement while ForStatement TryStatement try except finally WithStatement with FunctionDefinition def ParamList AssignOp TypeDef ClassDefinition class DecoratedStatement Decorator At", - maxTerm: 236, - context: trackIndent, - nodeProps: [ - [NodeProp.group, -14,4,80,82,83,85,87,89,91,93,94,95,97,100,103,"Statement Statement",-22,6,16,19,21,37,47,48,52,55,56,59,60,61,62,65,68,69,70,74,75,76,77,"Expression",-9,105,107,110,112,113,117,119,124,126,"Statement"] - ], - skippedNodes: [0,2], - repeatNodeCount: 32, - tokenData: "&AaMgR!^OX$}XY!#xY[$}[]!#x]p$}pq!#xqr!&Srs!)yst!C{tu$}uv$+}vw$.awx$/mxy$Lgyz$Mmz{$Ns{|%#c|}%$o}!O%%u!O!P%([!P!Q%3b!Q!R%6Q!R![%:S![!]%EO!]!^%Gb!^!_%Hh!_!`%KW!`!a%Ld!a!b$}!b!c& P!c!d&!_!d!e&$P!e!h&!_!h!i&.R!i!t&!_!t!u&7g!u!w&!_!w!x&,a!x!}&!_!}#O&9q#O#P!%b#P#Q&:w#Q#R&;}#R#S&!_#S#T$}#T#U&!_#U#V&$P#V#Y&!_#Y#Z&.R#Z#f&!_#f#g&7g#g#i&!_#i#j&,a#j#o&!_#o#p&=Z#p#q&>P#q#r&?]#r#s&@Z#s$g$}$g~&!_<r%`Z%q7[%hS%kW%n`%tp%w!b%y#tOr$}rs&Rsw$}wxFSx#O$}#O#P! n#P#o$}#o#p!#U#p#q$}#q#r!!S#r~$}9[&^Z%q7[%hS%n`%w!bOr'PrsCxsw'Pwx(Px#O'P#O#P>v#P#o'P#o#pCU#p#q'P#q#r?[#r~'P9['^Z%q7[%hS%kW%n`%w!bOr'Prs&Rsw'Pwx(Px#O'P#O#P>v#P#o'P#o#pCU#p#q'P#q#r?[#r~'P8z(WZ%q7[%kWOr(yrs)wsw(ywx;bx#O(y#O#P2V#P#o(y#o#p7n#p#q(y#q#r2k#r~(y8z)UZ%q7[%hS%kW%w!bOr(yrs)wsw(ywx(Px#O(y#O#P2V#P#o(y#o#p7n#p#q(y#q#r2k#r~(y8z*QZ%q7[%hS%w!bOr(yrs*ssw(ywx(Px#O(y#O#P2V#P#o(y#o#p7n#p#q(y#q#r2k#r~(y8z*|Z%q7[%hS%w!bOr(yrs+osw(ywx(Px#O(y#O#P2V#P#o(y#o#p7n#p#q(y#q#r2k#r~(y8r+xX%q7[%hS%w!bOw+owx,ex#O+o#O#P.V#P#o+o#o#p0^#p#q+o#q#r.k#r~+o8r,jX%q7[Ow+owx-Vx#O+o#O#P.V#P#o+o#o#p0^#p#q+o#q#r.k#r~+o8r-[X%q7[Ow+owx-wx#O+o#O#P.V#P#o+o#o#p0^#p#q+o#q#r.k#r~+o7[-|R%q7[O#o-w#p#q-w#r~-w8r.[T%q7[O#o+o#o#p.k#p#q+o#q#r.k#r~+o!f.rV%hS%w!bOw.kwx/Xx#O.k#O#P0W#P#o.k#o#p0^#p~.k!f/[VOw.kwx/qx#O.k#O#P0W#P#o.k#o#p0^#p~.k!f/tUOw.kx#O.k#O#P0W#P#o.k#o#p0^#p~.k!f0ZPO~.k!f0cV%hSOw0xwx1^x#O0x#O#P2P#P#o0x#o#p.k#p~0xS0}T%hSOw0xwx1^x#O0x#O#P2P#P~0xS1aTOw0xwx1px#O0x#O#P2P#P~0xS1sSOw0xx#O0x#O#P2P#P~0xS2SPO~0x8z2[T%q7[O#o(y#o#p2k#p#q(y#q#r2k#r~(y!n2tX%hS%kW%w!bOr2krs3asw2kwx4wx#O2k#O#P7h#P#o2k#o#p7n#p~2k!n3hX%hS%w!bOr2krs4Tsw2kwx4wx#O2k#O#P7h#P#o2k#o#p7n#p~2k!n4[X%hS%w!bOr2krs.ksw2kwx4wx#O2k#O#P7h#P#o2k#o#p7n#p~2k!n4|X%kWOr2krs3asw2kwx5ix#O2k#O#P7h#P#o2k#o#p7n#p~2k!n5nX%kWOr2krs3asw2kwx6Zx#O2k#O#P7h#P#o2k#o#p7n#p~2kW6`T%kWOr6Zrs6os#O6Z#O#P7b#P~6ZW6rTOr6Zrs7Rs#O6Z#O#P7b#P~6ZW7USOr6Zs#O6Z#O#P7b#P~6ZW7ePO~6Z!n7kPO~2k!n7uX%hS%kWOr8brs9Osw8bwx:Ux#O8b#O#P;[#P#o8b#o#p2k#p~8b[8iV%hS%kWOr8brs9Osw8bwx:Ux#O8b#O#P;[#P~8b[9TV%hSOr8brs9jsw8bwx:Ux#O8b#O#P;[#P~8b[9oV%hSOr8brs0xsw8bwx:Ux#O8b#O#P;[#P~8b[:ZV%kWOr8brs9Osw8bwx:px#O8b#O#P;[#P~8b[:uV%kWOr8brs9Osw8bwx6Zx#O8b#O#P;[#P~8b[;_PO~8b8z;iZ%q7[%kWOr(yrs)wsw(ywx<[x#O(y#O#P2V#P#o(y#o#p7n#p#q(y#q#r2k#r~(y7d<cX%q7[%kWOr<[rs=Os#O<[#O#P>b#P#o<[#o#p6Z#p#q<[#q#r6Z#r~<[7d=TX%q7[Or<[rs=ps#O<[#O#P>b#P#o<[#o#p6Z#p#q<[#q#r6Z#r~<[7d=uX%q7[Or<[rs-ws#O<[#O#P>b#P#o<[#o#p6Z#p#q<[#q#r6Z#r~<[7d>gT%q7[O#o<[#o#p6Z#p#q<[#q#r6Z#r~<[9[>{T%q7[O#o'P#o#p?[#p#q'P#q#r?[#r~'P#O?gX%hS%kW%n`%w!bOr?[rs@Ssw?[wx4wx#O?[#O#PCO#P#o?[#o#pCU#p~?[#O@]X%hS%n`%w!bOr?[rs@xsw?[wx4wx#O?[#O#PCO#P#o?[#o#pCU#p~?[#OARX%hS%n`%w!bOr?[rsAnsw?[wx4wx#O?[#O#PCO#P#o?[#o#pCU#p~?[!vAwV%hS%n`%w!bOwAnwx/Xx#OAn#O#PB^#P#oAn#o#pBd#p~An!vBaPO~An!vBiV%hSOw0xwx1^x#O0x#O#P2P#P#o0x#o#pAn#p~0x#OCRPO~?[#OC]X%hS%kWOr8brs9Osw8bwx:Ux#O8b#O#P;[#P#o8b#o#p?[#p~8b9[DTZ%q7[%hS%n`%w!bOr'PrsDvsw'Pwx(Px#O'P#O#P>v#P#o'P#o#pCU#p#q'P#q#r?[#r~'P9SERX%q7[%hS%n`%w!bOwDvwx,ex#ODv#O#PEn#P#oDv#o#pBd#p#qDv#q#rAn#r~Dv9SEsT%q7[O#oDv#o#pAn#p#qDv#q#rAn#r~Dv<bF_Z%q7[%kW%tp%y#tOrGQrs)wswGQwxM^x#OGQ#O#PHS#P#oGQ#o#pLj#p#qGQ#q#rHh#r~GQ<bGaZ%q7[%hS%kW%tp%w!b%y#tOrGQrs)wswGQwxFSx#OGQ#O#PHS#P#oGQ#o#pLj#p#qGQ#q#rHh#r~GQ<bHXT%q7[O#oGQ#o#pHh#p#qGQ#q#rHh#r~GQ&UHuX%hS%kW%tp%w!b%y#tOrHhrs3aswHhwxIbx#OHh#O#PLd#P#oHh#o#pLj#p~Hh&UIkX%kW%tp%y#tOrHhrs3aswHhwxJWx#OHh#O#PLd#P#oHh#o#pLj#p~Hh&UJaX%kW%tp%y#tOrHhrs3aswHhwxJ|x#OHh#O#PLd#P#oHh#o#pLj#p~Hh$nKVX%kW%tp%y#tOrJ|rs6oswJ|wxJ|x#OJ|#O#PKr#P#oJ|#o#pKx#p~J|$nKuPO~J|$nK}V%kWOr6Zrs6os#O6Z#O#P7b#P#o6Z#o#pJ|#p~6Z&ULgPO~Hh&ULqX%hS%kWOr8brs9Osw8bwx:Ux#O8b#O#P;[#P#o8b#o#pHh#p~8b<bMiZ%q7[%kW%tp%y#tOrGQrs)wswGQwxN[x#OGQ#O#PHS#P#oGQ#o#pLj#p#qGQ#q#rHh#r~GQ:zNgZ%q7[%kW%tp%y#tOrN[rs=OswN[wxN[x#ON[#O#P! Y#P#oN[#o#pKx#p#qN[#q#rJ|#r~N[:z! _T%q7[O#oN[#o#pJ|#p#qN[#q#rJ|#r~N[<r! sT%q7[O#o$}#o#p!!S#p#q$}#q#r!!S#r~$}&f!!cX%hS%kW%n`%tp%w!b%y#tOr!!Srs@Ssw!!SwxIbx#O!!S#O#P!#O#P#o!!S#o#p!#U#p~!!S&f!#RPO~!!S&f!#]X%hS%kWOr8brs9Osw8bwx:Ux#O8b#O#P;[#P#o8b#o#p!!S#p~8bMg!$]a%q7[%hS%kW$o1s%n`%tp%w!b%y#tOX$}XY!#xY[$}[]!#x]p$}pq!#xqr$}rs&Rsw$}wxFSx#O$}#O#P!%b#P#o$}#o#p!#U#p#q$}#q#r!!S#r~$}Mg!%gX%q7[OY$}YZ!#xZ]$}]^!#x^#o$}#o#p!!S#p#q$}#q#r!!S#r~$}<u!&eb%q7[%hS%kW%n`%tp%w!b%y#tOr$}rs&Rsw$}wxFSx!_$}!_!`!'m!`#O$}#O#P! n#P#T$}#T#U!(s#U#f$}#f#g!(s#g#h!(s#h#o$}#o#p!#U#p#q$}#q#r!!S#r~$}<u!(QZjR%q7[%hS%kW%n`%tp%w!b%y#tOr$}rs&Rsw$}wxFSx#O$}#O#P! n#P#o$}#o#p!#U#p#q$}#q#r!!S#r~$}<u!)WZ!jR%q7[%hS%kW%n`%tp%w!b%y#tOr$}rs&Rsw$}wxFSx#O$}#O#P! n#P#o$}#o#p!#U#p#q$}#q#r!!S#r~$}G{!*Y_%up%q7[%hS%f,X%n`%w!bOY!+XYZ'PZ]!+X]^'P^r!+Xrs!BPsw!+Xwx!-gx#O!+X#O#P!>e#P#o!+X#o#p!@}#p#q!+X#q#r!>y#r~!+XDe!+h_%q7[%hS%kW%f,X%n`%w!bOY!+XYZ'PZ]!+X]^'P^r!+Xrs!,gsw!+Xwx!-gx#O!+X#O#P!>e#P#o!+X#o#p!@}#p#q!+X#q#r!>y#r~!+XDe!,tZ%q7[%hS%f,X%n`%w!bOr'PrsCxsw'Pwx(Px#O'P#O#P>v#P#o'P#o#pCU#p#q'P#q#r?[#r~'PDT!-p_%q7[%kW%f,XOY!.oYZ(yZ]!.o]^(y^r!.ors!/{sw!.owx!;Rx#O!.o#O#P!0y#P#o!.o#o#p!6m#p#q!.o#q#r!1_#r~!.oDT!.|_%q7[%hS%kW%f,X%w!bOY!.oYZ(yZ]!.o]^(y^r!.ors!/{sw!.owx!-gx#O!.o#O#P!0y#P#o!.o#o#p!6m#p#q!.o#q#r!1_#r~!.oDT!0WZ%q7[%hS%f,X%w!bOr(yrs*ssw(ywx(Px#O(y#O#P2V#P#o(y#o#p7n#p#q(y#q#r2k#r~(yDT!1OT%q7[O#o!.o#o#p!1_#p#q!.o#q#r!1_#r~!.o-w!1j]%hS%kW%f,X%w!bOY!1_YZ2kZ]!1_]^2k^r!1_rs!2csw!1_wx!3Xx#O!1_#O#P!6g#P#o!1_#o#p!6m#p~!1_-w!2lX%hS%f,X%w!bOr2krs4Tsw2kwx4wx#O2k#O#P7h#P#o2k#o#p7n#p~2k-w!3`]%kW%f,XOY!1_YZ2kZ]!1_]^2k^r!1_rs!2csw!1_wx!4Xx#O!1_#O#P!6g#P#o!1_#o#p!6m#p~!1_-w!4`]%kW%f,XOY!1_YZ2kZ]!1_]^2k^r!1_rs!2csw!1_wx!5Xx#O!1_#O#P!6g#P#o!1_#o#p!6m#p~!1_,a!5`X%kW%f,XOY!5XYZ6ZZ]!5X]^6Z^r!5Xrs!5{s#O!5X#O#P!6a#P~!5X,a!6QT%f,XOr6Zrs7Rs#O6Z#O#P7b#P~6Z,a!6dPO~!5X-w!6jPO~!1_-w!6v]%hS%kW%f,XOY!7oYZ8bZ]!7o]^8b^r!7ors!8ksw!7owx!9Xx#O!7o#O#P!:{#P#o!7o#o#p!1_#p~!7o,e!7xZ%hS%kW%f,XOY!7oYZ8bZ]!7o]^8b^r!7ors!8ksw!7owx!9Xx#O!7o#O#P!:{#P~!7o,e!8rV%hS%f,XOr8brs9jsw8bwx:Ux#O8b#O#P;[#P~8b,e!9`Z%kW%f,XOY!7oYZ8bZ]!7o]^8b^r!7ors!8ksw!7owx!:Rx#O!7o#O#P!:{#P~!7o,e!:YZ%kW%f,XOY!7oYZ8bZ]!7o]^8b^r!7ors!8ksw!7owx!5Xx#O!7o#O#P!:{#P~!7o,e!;OPO~!7oDT!;[_%q7[%kW%f,XOY!.oYZ(yZ]!.o]^(y^r!.ors!/{sw!.owx!<Zx#O!.o#O#P!0y#P#o!.o#o#p!6m#p#q!.o#q#r!1_#r~!.oBm!<d]%q7[%kW%f,XOY!<ZYZ<[Z]!<Z]^<[^r!<Zrs!=]s#O!<Z#O#P!>P#P#o!<Z#o#p!5X#p#q!<Z#q#r!5X#r~!<ZBm!=dX%q7[%f,XOr<[rs=ps#O<[#O#P>b#P#o<[#o#p6Z#p#q<[#q#r6Z#r~<[Bm!>UT%q7[O#o!<Z#o#p!5X#p#q!<Z#q#r!5X#r~!<ZDe!>jT%q7[O#o!+X#o#p!>y#p#q!+X#q#r!>y#r~!+X.X!?W]%hS%kW%f,X%n`%w!bOY!>yYZ?[Z]!>y]^?[^r!>yrs!@Psw!>ywx!3Xx#O!>y#O#P!@w#P#o!>y#o#p!@}#p~!>y.X!@[X%hS%f,X%n`%w!bOr?[rs@xsw?[wx4wx#O?[#O#PCO#P#o?[#o#pCU#p~?[.X!@zPO~!>y.X!AW]%hS%kW%f,XOY!7oYZ8bZ]!7o]^8b^r!7ors!8ksw!7owx!9Xx#O!7o#O#P!:{#P#o!7o#o#p!>y#p~!7oGZ!B^Z%q7[%hS%f,X%n`%w!bOr'Prs!CPsw'Pwx(Px#O'P#O#P>v#P#o'P#o#pCU#p#q'P#q#r?[#r~'PGZ!C`X%l#|%q7[%hS%j,X%n`%w!bOwDvwx,ex#ODv#O#PEn#P#oDv#o#pBd#p#qDv#q#rAn#r~DvMg!D`_Q1s%q7[%hS%kW%n`%tp%w!b%y#tOY!C{YZ$}Z]!C{]^$}^r!C{rs!E_sw!C{wx#Hqx#O!C{#O#P$(i#P#o!C{#o#p$*{#p#q!C{#q#r$)]#r~!C{JP!El_Q1s%q7[%hS%n`%w!bOY!FkYZ'PZ]!Fk]^'P^r!Fkrs#Eksw!Fkwx!Gyx#O!Fk#O#P#=u#P#o!Fk#o#p#Di#p#q!Fk#q#r#>i#r~!FkJP!Fz_Q1s%q7[%hS%kW%n`%w!bOY!FkYZ'PZ]!Fk]^'P^r!Fkrs!E_sw!Fkwx!Gyx#O!Fk#O#P#=u#P#o!Fk#o#p#Di#p#q!Fk#q#r#>i#r~!FkIo!HS_Q1s%q7[%kWOY!IRYZ(yZ]!IR]^(y^r!IRrs!J_sw!IRwx#8wx#O!IR#O#P#*R#P#o!IR#o#p#2}#p#q!IR#q#r#*u#r~!IRIo!I`_Q1s%q7[%hS%kW%w!bOY!IRYZ(yZ]!IR]^(y^r!IRrs!J_sw!IRwx!Gyx#O!IR#O#P#*R#P#o!IR#o#p#2}#p#q!IR#q#r#*u#r~!IRIo!Jj_Q1s%q7[%hS%w!bOY!IRYZ(yZ]!IR]^(y^r!IRrs!Kisw!IRwx!Gyx#O!IR#O#P#*R#P#o!IR#o#p#2}#p#q!IR#q#r#*u#r~!IRIo!Kt_Q1s%q7[%hS%w!bOY!IRYZ(yZ]!IR]^(y^r!IRrs!Lssw!IRwx!Gyx#O!IR#O#P#*R#P#o!IR#o#p#2}#p#q!IR#q#r#*u#r~!IRIg!MO]Q1s%q7[%hS%w!bOY!LsYZ+oZ]!Ls]^+o^w!Lswx!Mwx#O!Ls#O#P#!y#P#o!Ls#o#p#&m#p#q!Ls#q#r##m#r~!LsIg!NO]Q1s%q7[OY!LsYZ+oZ]!Ls]^+o^w!Lswx!Nwx#O!Ls#O#P#!y#P#o!Ls#o#p#&m#p#q!Ls#q#r##m#r~!LsIg# O]Q1s%q7[OY!LsYZ+oZ]!Ls]^+o^w!Lswx# wx#O!Ls#O#P#!y#P#o!Ls#o#p#&m#p#q!Ls#q#r##m#r~!LsHP#!OXQ1s%q7[OY# wYZ-wZ]# w]^-w^#o# w#o#p#!k#p#q# w#q#r#!k#r~# w1s#!pRQ1sOY#!kZ]#!k^~#!kIg##QXQ1s%q7[OY!LsYZ+oZ]!Ls]^+o^#o!Ls#o#p##m#p#q!Ls#q#r##m#r~!Ls3Z##vZQ1s%hS%w!bOY##mYZ.kZ]##m]^.k^w##mwx#$ix#O##m#O#P#&X#P#o##m#o#p#&m#p~##m3Z#$nZQ1sOY##mYZ.kZ]##m]^.k^w##mwx#%ax#O##m#O#P#&X#P#o##m#o#p#&m#p~##m3Z#%fZQ1sOY##mYZ.kZ]##m]^.k^w##mwx#!kx#O##m#O#P#&X#P#o##m#o#p#&m#p~##m3Z#&^TQ1sOY##mYZ.kZ]##m]^.k^~##m3Z#&tZQ1s%hSOY#'gYZ0xZ]#'g]^0x^w#'gwx#(Zx#O#'g#O#P#)m#P#o#'g#o#p##m#p~#'g1w#'nXQ1s%hSOY#'gYZ0xZ]#'g]^0x^w#'gwx#(Zx#O#'g#O#P#)m#P~#'g1w#(`XQ1sOY#'gYZ0xZ]#'g]^0x^w#'gwx#({x#O#'g#O#P#)m#P~#'g1w#)QXQ1sOY#'gYZ0xZ]#'g]^0x^w#'gwx#!kx#O#'g#O#P#)m#P~#'g1w#)rTQ1sOY#'gYZ0xZ]#'g]^0x^~#'gIo#*YXQ1s%q7[OY!IRYZ(yZ]!IR]^(y^#o!IR#o#p#*u#p#q!IR#q#r#*u#r~!IR3c#+Q]Q1s%hS%kW%w!bOY#*uYZ2kZ]#*u]^2k^r#*urs#+ysw#*uwx#-}x#O#*u#O#P#2i#P#o#*u#o#p#2}#p~#*u3c#,S]Q1s%hS%w!bOY#*uYZ2kZ]#*u]^2k^r#*urs#,{sw#*uwx#-}x#O#*u#O#P#2i#P#o#*u#o#p#2}#p~#*u3c#-U]Q1s%hS%w!bOY#*uYZ2kZ]#*u]^2k^r#*urs##msw#*uwx#-}x#O#*u#O#P#2i#P#o#*u#o#p#2}#p~#*u3c#.U]Q1s%kWOY#*uYZ2kZ]#*u]^2k^r#*urs#+ysw#*uwx#.}x#O#*u#O#P#2i#P#o#*u#o#p#2}#p~#*u3c#/U]Q1s%kWOY#*uYZ2kZ]#*u]^2k^r#*urs#+ysw#*uwx#/}x#O#*u#O#P#2i#P#o#*u#o#p#2}#p~#*u1{#0UXQ1s%kWOY#/}YZ6ZZ]#/}]^6Z^r#/}rs#0qs#O#/}#O#P#2T#P~#/}1{#0vXQ1sOY#/}YZ6ZZ]#/}]^6Z^r#/}rs#1cs#O#/}#O#P#2T#P~#/}1{#1hXQ1sOY#/}YZ6ZZ]#/}]^6Z^r#/}rs#!ks#O#/}#O#P#2T#P~#/}1{#2YTQ1sOY#/}YZ6ZZ]#/}]^6Z^~#/}3c#2nTQ1sOY#*uYZ2kZ]#*u]^2k^~#*u3c#3W]Q1s%hS%kWOY#4PYZ8bZ]#4P]^8b^r#4Prs#4{sw#4Pwx#6ox#O#4P#O#P#8c#P#o#4P#o#p#*u#p~#4P2P#4YZQ1s%hS%kWOY#4PYZ8bZ]#4P]^8b^r#4Prs#4{sw#4Pwx#6ox#O#4P#O#P#8c#P~#4P2P#5SZQ1s%hSOY#4PYZ8bZ]#4P]^8b^r#4Prs#5usw#4Pwx#6ox#O#4P#O#P#8c#P~#4P2P#5|ZQ1s%hSOY#4PYZ8bZ]#4P]^8b^r#4Prs#'gsw#4Pwx#6ox#O#4P#O#P#8c#P~#4P2P#6vZQ1s%kWOY#4PYZ8bZ]#4P]^8b^r#4Prs#4{sw#4Pwx#7ix#O#4P#O#P#8c#P~#4P2P#7pZQ1s%kWOY#4PYZ8bZ]#4P]^8b^r#4Prs#4{sw#4Pwx#/}x#O#4P#O#P#8c#P~#4P2P#8hTQ1sOY#4PYZ8bZ]#4P]^8b^~#4PIo#9Q_Q1s%q7[%kWOY!IRYZ(yZ]!IR]^(y^r!IRrs!J_sw!IRwx#:Px#O!IR#O#P#*R#P#o!IR#o#p#2}#p#q!IR#q#r#*u#r~!IRHX#:Y]Q1s%q7[%kWOY#:PYZ<[Z]#:P]^<[^r#:Prs#;Rs#O#:P#O#P#=R#P#o#:P#o#p#/}#p#q#:P#q#r#/}#r~#:PHX#;Y]Q1s%q7[OY#:PYZ<[Z]#:P]^<[^r#:Prs#<Rs#O#:P#O#P#=R#P#o#:P#o#p#/}#p#q#:P#q#r#/}#r~#:PHX#<Y]Q1s%q7[OY#:PYZ<[Z]#:P]^<[^r#:Prs# ws#O#:P#O#P#=R#P#o#:P#o#p#/}#p#q#:P#q#r#/}#r~#:PHX#=YXQ1s%q7[OY#:PYZ<[Z]#:P]^<[^#o#:P#o#p#/}#p#q#:P#q#r#/}#r~#:PJP#=|XQ1s%q7[OY!FkYZ'PZ]!Fk]^'P^#o!Fk#o#p#>i#p#q!Fk#q#r#>i#r~!Fk3s#>v]Q1s%hS%kW%n`%w!bOY#>iYZ?[Z]#>i]^?[^r#>irs#?osw#>iwx#-}x#O#>i#O#P#DT#P#o#>i#o#p#Di#p~#>i3s#?z]Q1s%hS%n`%w!bOY#>iYZ?[Z]#>i]^?[^r#>irs#@ssw#>iwx#-}x#O#>i#O#P#DT#P#o#>i#o#p#Di#p~#>i3s#AO]Q1s%hS%n`%w!bOY#>iYZ?[Z]#>i]^?[^r#>irs#Awsw#>iwx#-}x#O#>i#O#P#DT#P#o#>i#o#p#Di#p~#>i3k#BSZQ1s%hS%n`%w!bOY#AwYZAnZ]#Aw]^An^w#Awwx#$ix#O#Aw#O#P#Bu#P#o#Aw#o#p#CZ#p~#Aw3k#BzTQ1sOY#AwYZAnZ]#Aw]^An^~#Aw3k#CbZQ1s%hSOY#'gYZ0xZ]#'g]^0x^w#'gwx#(Zx#O#'g#O#P#)m#P#o#'g#o#p#Aw#p~#'g3s#DYTQ1sOY#>iYZ?[Z]#>i]^?[^~#>i3s#Dr]Q1s%hS%kWOY#4PYZ8bZ]#4P]^8b^r#4Prs#4{sw#4Pwx#6ox#O#4P#O#P#8c#P#o#4P#o#p#>i#p~#4PJP#Ex_Q1s%q7[%hS%n`%w!bOY!FkYZ'PZ]!Fk]^'P^r!Fkrs#Fwsw!Fkwx!Gyx#O!Fk#O#P#=u#P#o!Fk#o#p#Di#p#q!Fk#q#r#>i#r~!FkIw#GU]Q1s%q7[%hS%n`%w!bOY#FwYZDvZ]#Fw]^Dv^w#Fwwx!Mwx#O#Fw#O#P#G}#P#o#Fw#o#p#CZ#p#q#Fw#q#r#Aw#r~#FwIw#HUXQ1s%q7[OY#FwYZDvZ]#Fw]^Dv^#o#Fw#o#p#Aw#p#q#Fw#q#r#Aw#r~#FwMV#IO_Q1s%q7[%kW%tp%y#tOY#I}YZGQZ]#I}]^GQ^r#I}rs!J_sw#I}wx$%]x#O#I}#O#P#K_#P#o#I}#o#p$$Z#p#q#I}#q#r#LR#r~#I}MV#J`_Q1s%q7[%hS%kW%tp%w!b%y#tOY#I}YZGQZ]#I}]^GQ^r#I}rs!J_sw#I}wx#Hqx#O#I}#O#P#K_#P#o#I}#o#p$$Z#p#q#I}#q#r#LR#r~#I}MV#KfXQ1s%q7[OY#I}YZGQZ]#I}]^GQ^#o#I}#o#p#LR#p#q#I}#q#r#LR#r~#I}6y#Lb]Q1s%hS%kW%tp%w!b%y#tOY#LRYZHhZ]#LR]^Hh^r#LRrs#+ysw#LRwx#MZx#O#LR#O#P$#u#P#o#LR#o#p$$Z#p~#LR6y#Mf]Q1s%kW%tp%y#tOY#LRYZHhZ]#LR]^Hh^r#LRrs#+ysw#LRwx#N_x#O#LR#O#P$#u#P#o#LR#o#p$$Z#p~#LR6y#Nj]Q1s%kW%tp%y#tOY#LRYZHhZ]#LR]^Hh^r#LRrs#+ysw#LRwx$ cx#O#LR#O#P$#u#P#o#LR#o#p$$Z#p~#LR5c$ n]Q1s%kW%tp%y#tOY$ cYZJ|Z]$ c]^J|^r$ crs#0qsw$ cwx$ cx#O$ c#O#P$!g#P#o$ c#o#p$!{#p~$ c5c$!lTQ1sOY$ cYZJ|Z]$ c]^J|^~$ c5c$#SZQ1s%kWOY#/}YZ6ZZ]#/}]^6Z^r#/}rs#0qs#O#/}#O#P#2T#P#o#/}#o#p$ c#p~#/}6y$#zTQ1sOY#LRYZHhZ]#LR]^Hh^~#LR6y$$d]Q1s%hS%kWOY#4PYZ8bZ]#4P]^8b^r#4Prs#4{sw#4Pwx#6ox#O#4P#O#P#8c#P#o#4P#o#p#LR#p~#4PMV$%j_Q1s%q7[%kW%tp%y#tOY#I}YZGQZ]#I}]^GQ^r#I}rs!J_sw#I}wx$&ix#O#I}#O#P#K_#P#o#I}#o#p$$Z#p#q#I}#q#r#LR#r~#I}Ko$&v_Q1s%q7[%kW%tp%y#tOY$&iYZN[Z]$&i]^N[^r$&irs#;Rsw$&iwx$&ix#O$&i#O#P$'u#P#o$&i#o#p$!{#p#q$&i#q#r$ c#r~$&iKo$'|XQ1s%q7[OY$&iYZN[Z]$&i]^N[^#o$&i#o#p$ c#p#q$&i#q#r$ c#r~$&iMg$(pXQ1s%q7[OY!C{YZ$}Z]!C{]^$}^#o!C{#o#p$)]#p#q!C{#q#r$)]#r~!C{7Z$)n]Q1s%hS%kW%n`%tp%w!b%y#tOY$)]YZ!!SZ]$)]]^!!S^r$)]rs#?osw$)]wx#MZx#O$)]#O#P$*g#P#o$)]#o#p$*{#p~$)]7Z$*lTQ1sOY$)]YZ!!SZ]$)]]^!!S^~$)]7Z$+U]Q1s%hS%kWOY#4PYZ8bZ]#4P]^8b^r#4Prs#4{sw#4Pwx#6ox#O#4P#O#P#8c#P#o#4P#o#p$)]#p~#4PGz$,b]$}Q%q7[%hS%kW%n`%tp%w!b%y#tOr$}rs&Rsw$}wxFSx!_$}!_!`$-Z!`#O$}#O#P! n#P#o$}#o#p!#U#p#q$}#q#r!!S#r~$}Gz$-nZ!s,W%q7[%hS%kW%n`%tp%w!b%y#tOr$}rs&Rsw$}wxFSx#O$}#O#P! n#P#o$}#o#p!#U#p#q$}#q#r!!S#r~$}Gz$.t]$wQ%q7[%hS%kW%n`%tp%w!b%y#tOr$}rs&Rsw$}wxFSx!_$}!_!`$-Z!`#O$}#O#P! n#P#o$}#o#p!#U#p#q$}#q#r!!S#r~$}G{$/|_%r`%q7[%kW%f,X%tp%y#tOY$0{YZGQZ]$0{]^GQ^r$0{rs$2]sw$0{wx$Jex#O$0{#O#P$Fw#P#o$0{#o#p$Ic#p#q$0{#q#r$G]#r~$0{Gk$1^_%q7[%hS%kW%f,X%tp%w!b%y#tOY$0{YZGQZ]$0{]^GQ^r$0{rs$2]sw$0{wx$Ewx#O$0{#O#P$Fw#P#o$0{#o#p$Ic#p#q$0{#q#r$G]#r~$0{DT$2h_%q7[%hS%f,X%w!bOY$3gYZ(yZ]$3g]^(y^r$3grs$Basw$3gwx$4sx#O$3g#O#P$5o#P#o$3g#o#p$={#p#q$3g#q#r$6T#r~$3gDT$3t_%q7[%hS%kW%f,X%w!bOY$3gYZ(yZ]$3g]^(y^r$3grs$2]sw$3gwx$4sx#O$3g#O#P$5o#P#o$3g#o#p$={#p#q$3g#q#r$6T#r~$3gDT$4|Z%q7[%kW%f,XOr(yrs)wsw(ywx;bx#O(y#O#P2V#P#o(y#o#p7n#p#q(y#q#r2k#r~(yDT$5tT%q7[O#o$3g#o#p$6T#p#q$3g#q#r$6T#r~$3g-w$6`]%hS%kW%f,X%w!bOY$6TYZ2kZ]$6T]^2k^r$6Trs$7Xsw$6Twx$=Rx#O$6T#O#P$=u#P#o$6T#o#p$={#p~$6T-w$7b]%hS%f,X%w!bOY$6TYZ2kZ]$6T]^2k^r$6Trs$8Zsw$6Twx$=Rx#O$6T#O#P$=u#P#o$6T#o#p$={#p~$6T-w$8d]%hS%f,X%w!bOY$6TYZ2kZ]$6T]^2k^r$6Trs$9]sw$6Twx$=Rx#O$6T#O#P$=u#P#o$6T#o#p$={#p~$6T-o$9fZ%hS%f,X%w!bOY$9]YZ.kZ]$9]]^.k^w$9]wx$:Xx#O$9]#O#P$:s#P#o$9]#o#p$:y#p~$9]-o$:^V%f,XOw.kwx/qx#O.k#O#P0W#P#o.k#o#p0^#p~.k-o$:vPO~$9]-o$;QZ%hS%f,XOY$;sYZ0xZ]$;s]^0x^w$;swx$<gx#O$;s#O#P$<{#P#o$;s#o#p$9]#p~$;s,]$;zX%hS%f,XOY$;sYZ0xZ]$;s]^0x^w$;swx$<gx#O$;s#O#P$<{#P~$;s,]$<lT%f,XOw0xwx1px#O0x#O#P2P#P~0x,]$=OPO~$;s-w$=YX%kW%f,XOr2krs3asw2kwx5ix#O2k#O#P7h#P#o2k#o#p7n#p~2k-w$=xPO~$6T-w$>U]%hS%kW%f,XOY$>}YZ8bZ]$>}]^8b^r$>}rs$?ysw$>}wx$Amx#O$>}#O#P$BZ#P#o$>}#o#p$6T#p~$>},e$?WZ%hS%kW%f,XOY$>}YZ8bZ]$>}]^8b^r$>}rs$?ysw$>}wx$Amx#O$>}#O#P$BZ#P~$>},e$@QZ%hS%f,XOY$>}YZ8bZ]$>}]^8b^r$>}rs$@ssw$>}wx$Amx#O$>}#O#P$BZ#P~$>},e$@zZ%hS%f,XOY$>}YZ8bZ]$>}]^8b^r$>}rs$;ssw$>}wx$Amx#O$>}#O#P$BZ#P~$>},e$AtV%kW%f,XOr8brs9Osw8bwx:px#O8b#O#P;[#P~8b,e$B^PO~$>}DT$Bl_%q7[%hS%f,X%w!bOY$3gYZ(yZ]$3g]^(y^r$3grs$Cksw$3gwx$4sx#O$3g#O#P$5o#P#o$3g#o#p$={#p#q$3g#q#r$6T#r~$3gC{$Cv]%q7[%hS%f,X%w!bOY$CkYZ+oZ]$Ck]^+o^w$Ckwx$Dox#O$Ck#O#P$Ec#P#o$Ck#o#p$:y#p#q$Ck#q#r$9]#r~$CkC{$DvX%q7[%f,XOw+owx-Vx#O+o#O#P.V#P#o+o#o#p0^#p#q+o#q#r.k#r~+oC{$EhT%q7[O#o$Ck#o#p$9]#p#q$Ck#q#r$9]#r~$CkGk$FUZ%q7[%kW%f,X%tp%y#tOrGQrs)wswGQwxM^x#OGQ#O#PHS#P#oGQ#o#pLj#p#qGQ#q#rHh#r~GQGk$F|T%q7[O#o$0{#o#p$G]#p#q$0{#q#r$G]#r~$0{1_$Gl]%hS%kW%f,X%tp%w!b%y#tOY$G]YZHhZ]$G]]^Hh^r$G]rs$7Xsw$G]wx$Hex#O$G]#O#P$I]#P#o$G]#o#p$Ic#p~$G]1_$HpX%kW%f,X%tp%y#tOrHhrs3aswHhwxJWx#OHh#O#PLd#P#oHh#o#pLj#p~Hh1_$I`PO~$G]1_$Il]%hS%kW%f,XOY$>}YZ8bZ]$>}]^8b^r$>}rs$?ysw$>}wx$Amx#O$>}#O#P$BZ#P#o$>}#o#p$G]#p~$>}Gk$JrZ%q7[%kW%f,X%tp%y#tOrGQrs)wswGQwx$Kex#OGQ#O#PHS#P#oGQ#o#pLj#p#qGQ#q#rHh#r~GQGk$KtZ%i!f%q7[%kW%g,X%tp%y#tOrN[rs=OswN[wxN[x#ON[#O#P! Y#P#oN[#o#pKx#p#qN[#q#rJ|#r~N[G{$LzZf,X%q7[%hS%kW%n`%tp%w!b%y#tOr$}rs&Rsw$}wxFSx#O$}#O#P! n#P#o$}#o#p!#U#p#q$}#q#r!!S#r~$}<u$NQZ!OR%q7[%hS%kW%n`%tp%w!b%y#tOr$}rs&Rsw$}wxFSx#O$}#O#P! n#P#o$}#o#p!#U#p#q$}#q#r!!S#r~$}G{% W_T,X%q7[%hS%kW%n`%tp%w!b%y#tOr$}rs&Rsw$}wxFSxz$}z{%!V{!_$}!_!`$-Z!`#O$}#O#P! n#P#o$}#o#p!#U#p#q$}#q#r!!S#r~$}G{%!j]_R%q7[%hS%kW%n`%tp%w!b%y#tOr$}rs&Rsw$}wxFSx!_$}!_!`$-Z!`#O$}#O#P! n#P#o$}#o#p!#U#p#q$}#q#r!!S#r~$}G{%#v]$z,X%q7[%hS%kW%n`%tp%w!b%y#tOr$}rs&Rsw$}wxFSx!_$}!_!`$-Z!`#O$}#O#P! n#P#o$}#o#p!#U#p#q$}#q#r!!S#r~$}<u%%SZwR%q7[%hS%kW%n`%tp%w!b%y#tOr$}rs&Rsw$}wxFSx#O$}#O#P! n#P#o$}#o#p!#U#p#q$}#q#r!!S#r~$}Mg%&Y^${,X%q7[%hS%kW%n`%tp%w!b%y#tOr$}rs&Rsw$}wxFSx!_$}!_!`$-Z!`!a%'U!a#O$}#O#P! n#P#o$}#o#p!#U#p#q$}#q#r!!S#r~$}B^%'iZ&U&j%q7[%hS%kW%n`%tp%w!b%y#tOr$}rs&Rsw$}wxFSx#O$}#O#P! n#P#o$}#o#p!#U#p#q$}#q#r!!S#r~$}G{%(o_!dQ%q7[%hS%kW%n`%tp%w!b%y#tOr$}rs&Rsw$}wxFSx!O$}!O!P%)n!P!Q$}!Q![%,O![#O$}#O#P! n#P#o$}#o#p!#U#p#q$}#q#r!!S#r~$}G{%*P]%q7[%hS%kW%n`%tp%w!b%y#tOr$}rs&Rsw$}wxFSx!O$}!O!P%*x!P#O$}#O#P! n#P#o$}#o#p!#U#p#q$}#q#r!!S#r~$}G{%+]Z!m,X%q7[%hS%kW%n`%tp%w!b%y#tOr$}rs&Rsw$}wxFSx#O$}#O#P! n#P#o$}#o#p!#U#p#q$}#q#r!!S#r~$}Gy%,cg!f,V%q7[%hS%kW%n`%tp%w!b%y#tOr$}rs&Rsw$}wxFSx!Q$}!Q![%,O![!g$}!g!h%-z!h!l$}!l!m%2[!m#O$}#O#P! n#P#R$}#R#S%,O#S#X$}#X#Y%-z#Y#^$}#^#_%2[#_#o$}#o#p!#U#p#q$}#q#r!!S#r~$}Gy%.]a%q7[%hS%kW%n`%tp%w!b%y#tOr$}rs&Rsw$}wxFSx{$}{|%/b|}$}}!O%/b!O!Q$}!Q![%0l![#O$}#O#P! n#P#o$}#o#p!#U#p#q$}#q#r!!S#r~$}Gy%/s]%q7[%hS%kW%n`%tp%w!b%y#tOr$}rs&Rsw$}wxFSx!Q$}!Q![%0l![#O$}#O#P! n#P#o$}#o#p!#U#p#q$}#q#r!!S#r~$}Gy%1Pc!f,V%q7[%hS%kW%n`%tp%w!b%y#tOr$}rs&Rsw$}wxFSx!Q$}!Q![%0l![!l$}!l!m%2[!m#O$}#O#P! n#P#R$}#R#S%0l#S#^$}#^#_%2[#_#o$}#o#p!#U#p#q$}#q#r!!S#r~$}Gy%2oZ!f,V%q7[%hS%kW%n`%tp%w!b%y#tOr$}rs&Rsw$}wxFSx#O$}#O#P! n#P#o$}#o#p!#U#p#q$}#q#r!!S#r~$}G{%3u_$|R%q7[%hS%kW%n`%tp%w!b%y#tOr$}rs&Rsw$}wxFSx!P$}!P!Q%4t!Q!_$}!_!`$-Z!`#O$}#O#P! n#P#o$}#o#p!#U#p#q$}#q#r!!S#r~$}Gz%5X]%OQ%q7[%hS%kW%n`%tp%w!b%y#tOr$}rs&Rsw$}wxFSx!_$}!_!`$-Z!`#O$}#O#P! n#P#o$}#o#p!#U#p#q$}#q#r!!S#r~$}Gy%6eu!f,V%q7[%hS%kW%n`%tp%w!b%y#tOr$}rs&Rsw$}wxFSx!O$}!O!P%8x!P!Q$}!Q![%:S![!d$}!d!e%<U!e!g$}!g!h%-z!h!l$}!l!m%2[!m!q$}!q!r%?O!r!z$}!z!{%Ar!{#O$}#O#P! n#P#R$}#R#S%:S#S#U$}#U#V%<U#V#X$}#X#Y%-z#Y#^$}#^#_%2[#_#c$}#c#d%?O#d#l$}#l#m%Ar#m#o$}#o#p!#U#p#q$}#q#r!!S#r~$}Gy%9Z]%q7[%hS%kW%n`%tp%w!b%y#tOr$}rs&Rsw$}wxFSx!Q$}!Q![%,O![#O$}#O#P! n#P#o$}#o#p!#U#p#q$}#q#r!!S#r~$}Gy%:gi!f,V%q7[%hS%kW%n`%tp%w!b%y#tOr$}rs&Rsw$}wxFSx!O$}!O!P%8x!P!Q$}!Q![%:S![!g$}!g!h%-z!h!l$}!l!m%2[!m#O$}#O#P! n#P#R$}#R#S%:S#S#X$}#X#Y%-z#Y#^$}#^#_%2[#_#o$}#o#p!#U#p#q$}#q#r!!S#r~$}Gy%<g`%q7[%hS%kW%n`%tp%w!b%y#tOr$}rs&Rsw$}wxFSx!Q$}!Q!R%=i!R!S%=i!S#O$}#O#P! n#P#R$}#R#S%=i#S#o$}#o#p!#U#p#q$}#q#r!!S#r~$}Gy%=|`!f,V%q7[%hS%kW%n`%tp%w!b%y#tOr$}rs&Rsw$}wxFSx!Q$}!Q!R%=i!R!S%=i!S#O$}#O#P! n#P#R$}#R#S%=i#S#o$}#o#p!#U#p#q$}#q#r!!S#r~$}Gy%?a_%q7[%hS%kW%n`%tp%w!b%y#tOr$}rs&Rsw$}wxFSx!Q$}!Q!Y%@`!Y#O$}#O#P! n#P#R$}#R#S%@`#S#o$}#o#p!#U#p#q$}#q#r!!S#r~$}Gy%@s_!f,V%q7[%hS%kW%n`%tp%w!b%y#tOr$}rs&Rsw$}wxFSx!Q$}!Q!Y%@`!Y#O$}#O#P! n#P#R$}#R#S%@`#S#o$}#o#p!#U#p#q$}#q#r!!S#r~$}Gy%BTc%q7[%hS%kW%n`%tp%w!b%y#tOr$}rs&Rsw$}wxFSx!Q$}!Q![%C`![!c$}!c!i%C`!i#O$}#O#P! n#P#R$}#R#S%C`#S#T$}#T#Z%C`#Z#o$}#o#p!#U#p#q$}#q#r!!S#r~$}Gy%Csc!f,V%q7[%hS%kW%n`%tp%w!b%y#tOr$}rs&Rsw$}wxFSx!Q$}!Q![%C`![!c$}!c!i%C`!i#O$}#O#P! n#P#R$}#R#S%C`#S#T$}#T#Z%C`#Z#o$}#o#p!#U#p#q$}#q#r!!S#r~$}Mg%Ec]x1s%q7[%hS%kW%n`%tp%w!b%y#tOr$}rs&Rsw$}wxFSx!_$}!_!`%F[!`#O$}#O#P! n#P#o$}#o#p!#U#p#q$}#q#r!!S#r~$}<u%FoZ%WR%q7[%hS%kW%n`%tp%w!b%y#tOr$}rs&Rsw$}wxFSx#O$}#O#P! n#P#o$}#o#p!#U#p#q$}#q#r!!S#r~$}G{%GuZ#^,X%q7[%hS%kW%n`%tp%w!b%y#tOr$}rs&Rsw$}wxFSx#O$}#O#P! n#P#o$}#o#p!#U#p#q$}#q#r!!S#r~$}G{%H{_jR%q7[%hS%kW%n`%tp%w!b%y#tOr$}rs&Rsw$}wxFSx!^$}!^!_%Iz!_!`!'m!`!a!'m!a#O$}#O#P! n#P#o$}#o#p!#U#p#q$}#q#r!!S#r~$}Gz%J_]$xQ%q7[%hS%kW%n`%tp%w!b%y#tOr$}rs&Rsw$}wxFSx!_$}!_!`$-Z!`#O$}#O#P! n#P#o$}#o#p!#U#p#q$}#q#r!!S#r~$}G{%Kk]%V,X%q7[%hS%kW%n`%tp%w!b%y#tOr$}rs&Rsw$}wxFSx!_$}!_!`!'m!`#O$}#O#P! n#P#o$}#o#p!#U#p#q$}#q#r!!S#r~$}G{%Lw^jR%q7[%hS%kW%n`%tp%w!b%y#tOr$}rs&Rsw$}wxFSx!_$}!_!`!'m!`!a%Ms!a#O$}#O#P! n#P#o$}#o#p!#U#p#q$}#q#r!!S#r~$}Gz%NW]$yQ%q7[%hS%kW%n`%tp%w!b%y#tOr$}rs&Rsw$}wxFSx!_$}!_!`$-Z!`#O$}#O#P! n#P#o$}#o#p!#U#p#q$}#q#r!!S#r~$}G{& f]]Q#tP%q7[%hS%kW%n`%tp%w!b%y#tOr$}rs&Rsw$}wxFSx!_$}!_!`$-Z!`#O$}#O#P! n#P#o$}#o#p!#U#p#q$}#q#r!!S#r~$}Mg&!tc%q7[%hS%kW%e&j%n`%tp%w!b%y#t%Q,XOr$}rs&Rsw$}wxFSx!Q$}!Q![&!_![!c$}!c!}&!_!}#O$}#O#P! n#P#R$}#R#S&!_#S#T$}#T#o&!_#o#p!#U#p#q$}#q#r!!S#r$g$}$g~&!_Mg&$fg%q7[%hS%kW%e&j%n`%tp%w!b%y#t%Q,XOr$}rs&%}sw$}wx&)Tx!Q$}!Q![&!_![!c$}!c!t&!_!t!u&,a!u!}&!_!}#O$}#O#P! n#P#R$}#R#S&!_#S#T$}#T#f&!_#f#g&,a#g#o&!_#o#p!#U#p#q$}#q#r!!S#r$g$}$g~&!_De&&[_%q7[%hS%f,X%n`%w!bOY!+XYZ'PZ]!+X]^'P^r!+Xrs&'Zsw!+Xwx!-gx#O!+X#O#P!>e#P#o!+X#o#p!@}#p#q!+X#q#r!>y#r~!+XDe&'hZ%q7[%hS%f,X%n`%w!bOr'Prs&(Zsw'Pwx(Px#O'P#O#P>v#P#o'P#o#pCU#p#q'P#q#r?[#r~'PD]&(hX%q7[%hS%j,X%n`%w!bOwDvwx,ex#ODv#O#PEn#P#oDv#o#pBd#p#qDv#q#rAn#r~DvGk&)b_%q7[%kW%f,X%tp%y#tOY$0{YZGQZ]$0{]^GQ^r$0{rs$2]sw$0{wx&*ax#O$0{#O#P$Fw#P#o$0{#o#p$Ic#p#q$0{#q#r$G]#r~$0{Gk&*nZ%q7[%kW%f,X%tp%y#tOrGQrs)wswGQwx&+ax#OGQ#O#PHS#P#oGQ#o#pLj#p#qGQ#q#rHh#r~GQFT&+nZ%q7[%kW%g,X%tp%y#tOrN[rs=OswN[wxN[x#ON[#O#P! Y#P#oN[#o#pKx#p#qN[#q#rJ|#r~N[Mg&,vc%q7[%hS%kW%e&j%n`%tp%w!b%y#t%Q,XOr$}rs&%}sw$}wx&)Tx!Q$}!Q![&!_![!c$}!c!}&!_!}#O$}#O#P! n#P#R$}#R#S&!_#S#T$}#T#o&!_#o#p!#U#p#q$}#q#r!!S#r$g$}$g~&!_Mg&.hg%q7[%hS%kW%e&j%n`%tp%w!b%y#t%Q,XOr$}rs&0Psw$}wx&2wx!Q$}!Q![&!_![!c$}!c!t&!_!t!u&5u!u!}&!_!}#O$}#O#P! n#P#R$}#R#S&!_#S#T$}#T#f&!_#f#g&5u#g#o&!_#o#p!#U#p#q$}#q#r!!S#r$g$}$g~&!_De&0^Z%q7[%hS%n`%w!b%s,XOr'Prs&1Psw'Pwx(Px#O'P#O#P>v#P#o'P#o#pCU#p#q'P#q#r?[#r~'PDe&1[Z%q7[%hS%n`%w!bOr'Prs&1}sw'Pwx(Px#O'P#O#P>v#P#o'P#o#pCU#p#q'P#q#r?[#r~'PD]&2[X%q7[%hS%x,X%n`%w!bOwDvwx,ex#ODv#O#PEn#P#oDv#o#pBd#p#qDv#q#rAn#r~DvGk&3UZ%q7[%kW%tp%y#t%m,XOrGQrs)wswGQwx&3wx#OGQ#O#PHS#P#oGQ#o#pLj#p#qGQ#q#rHh#r~GQGk&4SZ%q7[%kW%tp%y#tOrGQrs)wswGQwx&4ux#OGQ#O#PHS#P#oGQ#o#pLj#p#qGQ#q#rHh#r~GQFT&5SZ%q7[%kW%v,X%tp%y#tOrN[rs=OswN[wxN[x#ON[#O#P! Y#P#oN[#o#pKx#p#qN[#q#rJ|#r~N[Mg&6[c%q7[%hS%kW%e&j%n`%tp%w!b%y#t%Q,XOr$}rs&0Psw$}wx&2wx!Q$}!Q![&!_![!c$}!c!}&!_!}#O$}#O#P! n#P#R$}#R#S&!_#S#T$}#T#o&!_#o#p!#U#p#q$}#q#r!!S#r$g$}$g~&!_Mg&7|k%q7[%hS%kW%e&j%n`%tp%w!b%y#t%Q,XOr$}rs&%}sw$}wx&)Tx!Q$}!Q![&!_![!c$}!c!h&!_!h!i&5u!i!t&!_!t!u&,a!u!}&!_!}#O$}#O#P! n#P#R$}#R#S&!_#S#T$}#T#U&!_#U#V&,a#V#Y&!_#Y#Z&5u#Z#o&!_#o#p!#U#p#q$}#q#r!!S#r$g$}$g~&!_G{&:UZ!V,X%q7[%hS%kW%n`%tp%w!b%y#tOr$}rs&Rsw$}wxFSx#O$}#O#P! n#P#o$}#o#p!#U#p#q$}#q#r!!S#r~$}<u&;[Z!WR%q7[%hS%kW%n`%tp%w!b%y#tOr$}rs&Rsw$}wxFSx#O$}#O#P! n#P#o$}#o#p!#U#p#q$}#q#r!!S#r~$}Gz&<b]$vQ%q7[%hS%kW%n`%tp%w!b%y#tOr$}rs&Rsw$}wxFSx!_$}!_!`$-Z!`#O$}#O#P! n#P#o$}#o#p!#U#p#q$}#q#r!!S#r~$}Gy&=dX%hS%kW!ZGmOr8brs9Osw8bwx:Ux#O8b#O#P;[#P#o8b#o#p!!S#p~8bGz&>d]$uQ%q7[%hS%kW%n`%tp%w!b%y#tOr$}rs&Rsw$}wxFSx!_$}!_!`$-Z!`#O$}#O#P! n#P#o$}#o#p!#U#p#q$}#q#r!!S#r~$}<u&?nX![7_%hS%kW%n`%tp%w!b%y#tOr!!Srs@Ssw!!SwxIbx#O!!S#O#P!#O#P#o!!S#o#p!#U#p~!!SGy&@nZ%P,V%q7[%hS%kW%n`%tp%w!b%y#tOr$}rs&Rsw$}wxFSx#O$}#O#P! n#P#o$}#o#p!#U#p#q$}#q#r!!S#r~$}", - tokenizers: [legacyPrint, indentation, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, newlines], - topRules: {"Script":[0,3]}, - specialized: [{term: 186, get: value => spec_identifier[value] || -1}], - tokenPrec: 6584 - }); - - function indentBody(context, node) { - let base = context.lineIndent(node.from); - let line = context.lineAt(context.pos, -1), to = line.from + line.text.length; - // Don't consider blank, deindented lines at the end of the - // block part of the block - if (!/\S/.test(line.text) && - context.node.to < to + 100 && - !/\S/.test(context.state.sliceDoc(to, context.node.to)) && - context.lineIndent(context.pos, -1) <= base) - return null; - // A normally deindenting keyword that appears at a higher - // indentation than the block should probably be handled by the next - // level - if (/^\s*(else:|elif |except |finally:)/.test(context.textAfter) && context.lineIndent(context.pos, -1) > base) - return null; - return base + context.unit; - } - /** - A language provider based on the [Lezer Python - parser](https://github.com/lezer-parser/python), extended with - highlighting and indentation information. - */ - const pythonLanguage = /*@__PURE__*/LRLanguage.define({ - parser: /*@__PURE__*/parser.configure({ - props: [ - /*@__PURE__*/indentNodeProp.add({ - Body: context => { var _a; return (_a = indentBody(context, context.node)) !== null && _a !== void 0 ? _a : context.continue(); }, - IfStatement: cx => /^\s*(else:|elif )/.test(cx.textAfter) ? cx.baseIndent : cx.continue(), - TryStatement: cx => /^\s*(except |finally:)/.test(cx.textAfter) ? cx.baseIndent : cx.continue(), - "TupleExpression ComprehensionExpression ParamList ArgList ParenthesizedExpression": /*@__PURE__*/delimitedIndent({ closing: ")" }), - "DictionaryExpression DictionaryComprehensionExpression SetExpression SetComprehensionExpression": /*@__PURE__*/delimitedIndent({ closing: "}" }), - "ArrayExpression ArrayComprehensionExpression": /*@__PURE__*/delimitedIndent({ closing: "]" }), - Script: context => { - if (context.pos + /\s*/.exec(context.textAfter)[0].length >= context.node.to) { - let endBody = null; - for (let cur = context.node, to = cur.to;;) { - cur = cur.lastChild; - if (!cur || cur.to != to) - break; - if (cur.type.name == "Body") - endBody = cur; - } - if (endBody) { - let bodyIndent = indentBody(context, endBody); - if (bodyIndent != null) - return bodyIndent; - } - } - return context.continue(); - } - }), - /*@__PURE__*/foldNodeProp.add({ - "ArrayExpression DictionaryExpression": foldInside$1, - Body: (node, state) => ({ from: node.from + 1, to: node.to - (node.to == state.doc.length ? 0 : 1) }) - }), - /*@__PURE__*/styleTags({ - "async \"*\" \"**\" FormatConversion FormatSpec": tags.modifier, - "for while if elif else try except finally return raise break continue with pass assert await yield": tags.controlKeyword, - "in not and or is del": tags.operatorKeyword, - "from def class global nonlocal lambda": tags.definitionKeyword, - import: tags.moduleKeyword, - "with as print": tags.keyword, - Boolean: tags.bool, - None: tags.null, - VariableName: tags.variableName, - "CallExpression/VariableName": /*@__PURE__*/tags.function(tags.variableName), - "FunctionDefinition/VariableName": /*@__PURE__*/tags.function(/*@__PURE__*/tags.definition(tags.variableName)), - "ClassDefinition/VariableName": /*@__PURE__*/tags.definition(tags.className), - PropertyName: tags.propertyName, - "CallExpression/MemberExpression/PropertyName": /*@__PURE__*/tags.function(tags.propertyName), - Comment: tags.lineComment, - Number: tags.number, - String: tags.string, - FormatString: /*@__PURE__*/tags.special(tags.string), - UpdateOp: tags.updateOperator, - ArithOp: tags.arithmeticOperator, - BitOp: tags.bitwiseOperator, - CompareOp: tags.compareOperator, - AssignOp: tags.definitionOperator, - Ellipsis: tags.punctuation, - At: tags.meta, - "( )": tags.paren, - "[ ]": tags.squareBracket, - "{ }": tags.brace, - ".": tags.derefOperator, - ", ;": tags.separator - }) - ], - }), - languageData: { - closeBrackets: { brackets: ["(", "[", "{", "'", '"', "'''", '"""'] }, - commentTokens: { line: "#" }, - indentOnInput: /^\s*([\}\]\)]|else:|elif |except |finally:)$/ - } - }); - /** - Python language support. - */ - function python() { - return new LanguageSupport(pythonLanguage); - } - - // Using https://github.com/one-dark/vscode-one-dark-theme/ as reference for the colors - const chalky = "#e5c07b", coral = "#e06c75", cyan = "#56b6c2", invalid = "#ffffff", ivory = "#abb2bf", stone = "#7d8799", // Brightened compared to original to increase contrast - malibu = "#61afef", sage = "#98c379", whiskey = "#d19a66", violet = "#c678dd", darkBackground = "#21252b", highlightBackground = "#2c313a", background = "#282c34", tooltipBackground = "#353a42", selection = "#3E4451", cursor = "#528bff"; - /** - The editor theme styles for One Dark. - */ - const oneDarkTheme = /*@__PURE__*/EditorView.theme({ - "&": { - color: ivory, - backgroundColor: background - }, - ".cm-content": { - caretColor: cursor - }, - "&.cm-focused .cm-cursor": { borderLeftColor: cursor }, - "&.cm-focused .cm-selectionBackground, .cm-selectionBackground, .cm-content ::selection": { backgroundColor: selection }, - ".cm-panels": { backgroundColor: darkBackground, color: ivory }, - ".cm-panels.cm-panels-top": { borderBottom: "2px solid black" }, - ".cm-panels.cm-panels-bottom": { borderTop: "2px solid black" }, - ".cm-searchMatch": { - backgroundColor: "#72a1ff59", - outline: "1px solid #457dff" - }, - ".cm-searchMatch.cm-searchMatch-selected": { - backgroundColor: "#6199ff2f" - }, - ".cm-activeLine": { backgroundColor: highlightBackground }, - ".cm-selectionMatch": { backgroundColor: "#aafe661a" }, - "&.cm-focused .cm-matchingBracket, &.cm-focused .cm-nonmatchingBracket": { - backgroundColor: "#bad0f847", - outline: "1px solid #515a6b" - }, - ".cm-gutters": { - backgroundColor: background, - color: stone, - border: "none" - }, - ".cm-activeLineGutter": { - backgroundColor: highlightBackground - }, - ".cm-foldPlaceholder": { - backgroundColor: "transparent", - border: "none", - color: "#ddd" - }, - ".cm-tooltip": { - border: "none", - backgroundColor: tooltipBackground - }, - ".cm-tooltip .cm-tooltip-arrow:before": { - borderTopColor: "transparent", - borderBottomColor: "transparent" - }, - ".cm-tooltip .cm-tooltip-arrow:after": { - borderTopColor: tooltipBackground, - borderBottomColor: tooltipBackground - }, - ".cm-tooltip-autocomplete": { - "& > ul > li[aria-selected]": { - backgroundColor: highlightBackground, - color: ivory - } - } - }, { dark: true }); - /** - The highlighting style for code in the One Dark theme. - */ - /*@__PURE__*/HighlightStyle.define([ - { tag: tags.keyword, - color: violet }, - { tag: [tags.name, tags.deleted, tags.character, tags.propertyName, tags.macroName], - color: coral }, - { tag: [/*@__PURE__*/tags.function(tags.variableName), tags.labelName], - color: malibu }, - { tag: [tags.color, /*@__PURE__*/tags.constant(tags.name), /*@__PURE__*/tags.standard(tags.name)], - color: whiskey }, - { tag: [/*@__PURE__*/tags.definition(tags.name), tags.separator], - color: ivory }, - { tag: [tags.typeName, tags.className, tags.number, tags.changed, tags.annotation, tags.modifier, tags.self, tags.namespace], - color: chalky }, - { tag: [tags.operator, tags.operatorKeyword, tags.url, tags.escape, tags.regexp, tags.link, /*@__PURE__*/tags.special(tags.string)], - color: cyan }, - { tag: [tags.meta, tags.comment], - color: stone }, - { tag: tags.strong, - fontWeight: "bold" }, - { tag: tags.emphasis, - fontStyle: "italic" }, - { tag: tags.strikethrough, - textDecoration: "line-through" }, - { tag: tags.link, - color: stone, - textDecoration: "underline" }, - { tag: tags.heading, - fontWeight: "bold", - color: coral }, - { tag: [tags.atom, tags.bool, /*@__PURE__*/tags.special(tags.variableName)], - color: whiskey }, - { tag: [tags.processingInstruction, tags.string, tags.inserted], - color: sage }, - { tag: tags.invalid, - color: invalid }, - ]); - - const logger$7 = getLogger('py-repl'); - function createCmdHandler(el) { - // Creates a codemirror cmd handler that calls the el.evaluate when an event - // triggers that specific cmd - return () => { - void el.evaluate(); - return true; - }; - } - let initialTheme; - function getEditorTheme(el) { - return initialTheme || (initialTheme = el.getAttribute('theme')); - } - class PyRepl extends BaseEvalElement { - editor; - editorNode; - constructor() { - super(); - // add an extra div where we can attach the codemirror editor - this.editorNode = document.createElement('div'); - addClasses(this.editorNode, ['editor-box']); - this.shadow.appendChild(this.wrapper); - } - connectedCallback() { - this.checkId(); - this.code = htmlDecode(this.innerHTML); - this.innerHTML = ''; - const languageConf = new Compartment(); - const extensions = [ - basicSetup, - languageConf.of(python()), - keymap.of([ - ...defaultKeymap, - { key: 'Ctrl-Enter', run: createCmdHandler(this) }, - { key: 'Shift-Enter', run: createCmdHandler(this) }, - ]), - ]; - if (getEditorTheme(this) === 'dark') { - extensions.push(oneDarkTheme); - } - this.editor = new EditorView({ - state: EditorState.create({ - doc: this.code.trim(), - extensions, - }), - parent: this.editorNode, - }); - const mainDiv = document.createElement('div'); - addClasses(mainDiv, ['py-repl-box']); - // Styles that we use to hide the labels whilst also keeping it accessible for screen readers - const labelStyle = 'overflow:hidden; display:block; width:1px; height:1px'; - // Code editor Label - this.editorNode.id = 'code-editor'; - const editorLabel = document.createElement('label'); - editorLabel.innerHTML = 'Python Script Area'; - editorLabel.setAttribute('style', labelStyle); - editorLabel.htmlFor = 'code-editor'; - mainDiv.append(editorLabel); - // add Editor to main PyScript div - mainDiv.appendChild(this.editorNode); - // Play Button - this.btnRun = document.createElement('button'); - this.btnRun.id = 'btnRun'; - this.btnRun.innerHTML = - '<svg id="" class="svelte-fa svelte-ps5qeg" style="height:20px;width:20px;vertical-align:-.125em;transform-origin:center;overflow:visible;color:green" viewBox="0 0 384 512" aria-hidden="true" role="img" xmlns="http://www.w3.org/2000/svg"><g transform="translate(192 256)" transform-origin="96 0"><g transform="translate(0,0) scale(1,1)"><path d="M361 215C375.3 223.8 384 239.3 384 256C384 272.7 375.3 288.2 361 296.1L73.03 472.1C58.21 482 39.66 482.4 24.52 473.9C9.377 465.4 0 449.4 0 432V80C0 62.64 9.377 46.63 24.52 38.13C39.66 29.64 58.21 29.99 73.03 39.04L361 215z" fill="currentColor" transform="translate(-192 -256)"></path></g></g></svg>'; - addClasses(this.btnRun, ['absolute', 'repl-play-button']); - // Play Button Label - const btnLabel = document.createElement('label'); - btnLabel.innerHTML = 'Python Script Run Button'; - btnLabel.setAttribute('style', labelStyle); - btnLabel.htmlFor = 'btnRun'; - this.editorNode.appendChild(btnLabel); - this.editorNode.appendChild(this.btnRun); - this.btnRun.addEventListener('click', () => { - void this.evaluate(); - }); - if (!this.id) { - logger$7.warn("WARNING: <py-repl> defined without an id. <py-repl> should always have an id, otherwise multiple <py-repl> in the same page will not work!"); - } - if (!this.hasAttribute('exec-id')) { - this.setAttribute('exec-id', '1'); - } - if (!this.hasAttribute('root')) { - this.setAttribute('root', this.id); - } - if (this.hasAttribute('output')) { - this.errorElement = this.outputElement = document.getElementById(this.getAttribute('output')); - } - else { - if (this.hasAttribute('std-out')) { - this.outputElement = document.getElementById(this.getAttribute('std-out')); - } - else { - // In this case neither output or std-out have been provided so we need - // to create a new output div to output to - this.outputElement = document.createElement('div'); - this.outputElement.classList.add('output'); - this.outputElement.hidden = true; - this.outputElement.id = this.id + '-' + this.getAttribute('exec-id'); - // add the output div id if there's not output pre-defined - mainDiv.appendChild(this.outputElement); - } - this.errorElement = this.hasAttribute('std-err') - ? document.getElementById(this.getAttribute('std-err')) - : this.outputElement; - } - this.appendChild(mainDiv); - this.editor.focus(); - logger$7.debug(`element ${this.id} successfully connected`); - } - addToOutput(s) { - this.outputElement.innerHTML += '<div>' + s + '</div>'; - this.outputElement.hidden = false; - } - preEvaluate() { - this.setOutputMode("replace"); - if (!this.appendOutput) { - this.outputElement.innerHTML = ''; - } - } - postEvaluate() { - this.outputElement.hidden = false; - this.outputElement.style.display = 'block'; - if (this.hasAttribute('auto-generate')) { - const allPyRepls = document.querySelectorAll(`py-repl[root='${this.getAttribute('root')}'][exec-id]`); - const lastRepl = allPyRepls[allPyRepls.length - 1]; - const lastExecId = lastRepl.getAttribute('exec-id'); - const nextExecId = parseInt(lastExecId) + 1; - const newPyRepl = document.createElement('py-repl'); - newPyRepl.setAttribute('root', this.getAttribute('root')); - newPyRepl.id = this.getAttribute('root') + '-' + nextExecId.toString(); - if (this.hasAttribute('auto-generate')) { - newPyRepl.setAttribute('auto-generate', ''); - this.removeAttribute('auto-generate'); - } - if (this.hasAttribute('output-mode')) { - newPyRepl.setAttribute('output-mode', this.getAttribute('output-mode')); - } - const addReplAttribute = (attribute) => { - if (this.hasAttribute(attribute)) { - newPyRepl.setAttribute(attribute, this.getAttribute(attribute)); - } - }; - addReplAttribute('output'); - addReplAttribute('std-out'); - addReplAttribute('std-err'); - newPyRepl.setAttribute('exec-id', nextExecId.toString()); - this.parentElement.appendChild(newPyRepl); - } - } - getSourceFromElement() { - return this.editor.state.doc.toString(); - } - } - - const logger$6 = getLogger('py-box'); - class PyBox extends HTMLElement { - shadow; - wrapper; - theme; - widths; - constructor() { - super(); - // attach shadow so we can preserve the element original innerHtml content - this.shadow = this.attachShadow({ mode: 'open' }); - this.wrapper = document.createElement('slot'); - this.shadow.appendChild(this.wrapper); - } - connectedCallback() { - const mainDiv = document.createElement('div'); - addClasses(mainDiv, ['py-box']); - // Hack: for some reason when moving children, the editor box duplicates children - // meaning that we end up with 2 editors, if there's a <py-repl> inside the <py-box> - // so, if we have more than 2 children with the cm-editor class, we remove one of them - while (this.childNodes.length > 0) { - if (this.firstChild.nodeName == 'PY-REPL') { - // in this case we need to remove the child and create a new one from scratch - const replDiv = document.createElement('div'); - // we need to put the new repl inside a div so that if the repl has auto-generate true - // it can replicate itself inside that constrained div - replDiv.appendChild(this.firstChild.cloneNode()); - mainDiv.appendChild(replDiv); - this.firstChild.remove(); - } - else { - if (this.firstChild.nodeName != '#text') { - mainDiv.appendChild(this.firstChild); - } - else { - this.firstChild.remove(); - } - } - } - // now we need to set widths - this.widths = []; - if (this.hasAttribute('widths')) { - for (const w of this.getAttribute('widths').split(';')) { - if (w.includes('/')) - this.widths.push(w.split('/')[0]); - else - this.widths.push(w); - } - } - else { - this.widths = Array(mainDiv.children.length).fill('1 1 0'); - } - this.widths.forEach((width, index) => { - const node = mainDiv.childNodes[index]; - node.style.flex = width; - addClasses(node, ['py-box-child']); - }); - this.appendChild(mainDiv); - logger$6.info('py-box connected'); - } - } - - const logger$5 = getLogger('py-button'); - class PyButton extends BaseEvalElement { - widths; - label; - class; - defaultClass; - mount_name; - constructor() { - super(); - this.defaultClass = ['py-button']; - if (this.hasAttribute('label')) { - this.label = this.getAttribute('label'); - } - // Styling does the same thing as class in normal HTML. Using the name "class" makes the style to malfunction - if (this.hasAttribute('styling')) { - const klass = this.getAttribute('styling').trim(); - if (klass === '') { - this.class = this.defaultClass; - } - else { - // trim each element to remove unnecessary spaces which makes the button style to malfunction - this.class = klass - .split(' ') - .map(x => x.trim()) - .filter(x => x !== ''); - } - } - else { - this.class = this.defaultClass; - } - } - connectedCallback() { - this.checkId(); - this.code = htmlDecode(this.innerHTML); - this.mount_name = this.id.split('-').join('_'); - this.innerHTML = ''; - const mainDiv = document.createElement('button'); - mainDiv.innerHTML = this.label; - addClasses(mainDiv, this.class); - mainDiv.id = this.id; - this.id = `${this.id}-container`; - this.appendChild(mainDiv); - this.code = this.code.split('self').join(this.mount_name); - let registrationCode = `from pyodide.ffi import create_proxy`; - registrationCode += `\n${this.mount_name} = Element("${mainDiv.id}")`; - if (this.code.includes('def on_focus')) { - this.code = this.code.replace('def on_focus', `def on_focus_${this.mount_name}`); - registrationCode += `\n${this.mount_name}.element.addEventListener('focus', create_proxy(on_focus_${this.mount_name}))`; - } - if (this.code.includes('def on_click')) { - this.code = this.code.replace('def on_click', `def on_click_${this.mount_name}`); - registrationCode += `\n${this.mount_name}.element.addEventListener('click', create_proxy(on_click_${this.mount_name}))`; - } - // now that we appended and the element is attached, lets connect with the event handlers - // defined for this widget - this.runAfterRuntimeInitialized(async () => { - await this.eval(this.code); - await this.eval(registrationCode); - logger$5.debug('registered handlers'); - }); - logger$5.debug('py-button connected'); - } - } - - class PyTitle extends BaseEvalElement { - widths; - label; - mount_name; - constructor() { - super(); - } - connectedCallback() { - this.label = htmlDecode(this.innerHTML); - this.mount_name = this.id.split('-').join('_'); - this.innerHTML = ''; - const mainDiv = document.createElement('div'); - const divContent = document.createElement('h1'); - addClasses(mainDiv, ['py-title']); - divContent.innerHTML = this.label; - mainDiv.id = this.id; - this.id = `${this.id}-container`; - mainDiv.appendChild(divContent); - this.appendChild(mainDiv); - } - } - - const logger$4 = getLogger('py-inputbox'); - class PyInputBox extends BaseEvalElement { - widths; - label; - mount_name; - constructor() { - super(); - if (this.hasAttribute('label')) { - this.label = this.getAttribute('label'); - } - } - connectedCallback() { - this.checkId(); - this.code = htmlDecode(this.innerHTML); - this.mount_name = this.id.split('-').join('_'); - this.innerHTML = ''; - const mainDiv = document.createElement('input'); - mainDiv.type = 'text'; - addClasses(mainDiv, ['py-input']); - mainDiv.id = this.id; - this.id = `${this.id}-container`; - this.appendChild(mainDiv); - // now that we appended and the element is attached, lets connect with the event handlers - // defined for this widget - this.appendChild(mainDiv); - this.code = this.code.split('self').join(this.mount_name); - let registrationCode = `from pyodide.ffi import create_proxy`; - registrationCode += `\n${this.mount_name} = Element("${mainDiv.id}")`; - if (this.code.includes('def on_keypress')) { - this.code = this.code.replace('def on_keypress', `def on_keypress_${this.mount_name}`); - registrationCode += `\n${this.mount_name}.element.addEventListener('keypress', create_proxy(on_keypress_${this.mount_name}))`; - } - // TODO: For now we delay execution to allow pyodide to load but in the future this - // should really wait for it to load.. - this.runAfterRuntimeInitialized(async () => { - await this.eval(this.code); - await this.eval(registrationCode); - logger$4.debug('registered handlers'); - }); - } - } - - /* - These were taken from main.js because some of our components call - runAfterRuntimeInitialized immediately when we are creating the custom - element, this was causing tests to fail since runAfterRuntimeInitialized - expects the runtime to have been loaded before being called. - - This function is now called from within the `runtime.initialize`. Once - the runtime finished initializing, then we will create the custom elements - so they are rendered in the page and we will always have a runtime available. - - Ideally, this would live under utils.js, but importing all the components in - the utils.js file was causing jest to fail with weird errors such as: - "ReferenceError: Cannot access 'BaseEvalElement' before initialization" coming - from the PyScript class. - - */ - function createCustomElements() { - /* eslint-disable @typescript-eslint/no-unused-vars */ - customElements.define('py-repl', PyRepl); - customElements.define('py-box', PyBox); - customElements.define('py-title', PyTitle); - customElements.define('py-register-widget', PyWidget); - customElements.define('py-inputbox', PyInputBox); - customElements.define('py-button', PyButton); - /* eslint-enable @typescript-eslint/no-unused-vars */ - } - - const logger$3 = getLogger('pyscript/runtime'); - const version = "<<VERSION>>"; - let loader$1; - globalLoader.subscribe(value => { - loader$1 = value; - }); - let initializers_; - initializers.subscribe((value) => { - initializers_ = value; - }); - let postInitializers_; - postInitializers.subscribe((value) => { - postInitializers_ = value; - }); - let scriptsQueue_; - scriptsQueue.subscribe((value) => { - scriptsQueue_ = value; - }); - let appConfig_$1 = { - autoclose_loader: true - }; - appConfig.subscribe((value) => { - if (value) { - appConfig_$1 = value; - } - }); - /* - Runtime class is a super class that all different runtimes must respect - and adhere to. - - Currently, the only runtime available is Pyodide as indicated by the - `RuntimeInterpreter` type above. This serves as a Union of types of - different runtimes/interpreters which will be added in near future. - - The class has abstract methods available which each runtime is supposed - to implement. - - Methods available handle loading of the interpreter, initialization, - running code, loading and installation of packages, loading from files etc. - - For an example implementation, refer to the `PyodideRuntime` class - in `pyodide.ts` - */ - class Runtime extends Object { - /** - * initializes the page which involves loading of runtime, - * as well as evaluating all the code inside <py-script> tags - * along with initializers and postInitializers - * */ - async initialize() { - loader$1?.log('Loading runtime...'); - await this.loadInterpreter(); - const newEnv = { - id: 'default', - runtime: this, - state: 'loading', - }; - runtimeLoaded.set(this); - // Inject the loader into the runtime namespace - // eslint-disable-next-line - this.globals.set('pyscript_loader', loader$1); - loader$1?.log('Runtime created...'); - loadedEnvironments.update(environments => ({ - ...environments, - [newEnv['id']]: newEnv, - })); - // now we call all initializers before we actually executed all page scripts - loader$1?.log('Initializing components...'); - for (const initializer of initializers_) { - await initializer(); - } - loader$1?.log('Initializing scripts...'); - for (const script of scriptsQueue_) { - void script.evaluate(); - } - scriptsQueue.set([]); - // now we call all post initializers AFTER we actually executed all page scripts - loader$1?.log('Running post initializers...'); - // Finally create the custom elements for pyscript such as pybutton - createCustomElements(); - if (appConfig_$1 && appConfig_$1.autoclose_loader) { - loader$1?.close(); - } - for (const initializer of postInitializers_) { - await initializer(); - } - // NOTE: this message is used by integration tests to know that - // pyscript initialization has complete. If you change it, you need to - // change it also in tests/integration/support.py - logger$3.info('PyScript page fully initialized'); - } - } - - var pyscript = "import asyncio\nimport base64\nimport io\nimport sys\nimport time\nfrom textwrap import dedent\n\nimport micropip # noqa: F401\nfrom js import console, document\n\nloop = asyncio.get_event_loop()\n\nMIME_METHODS = {\n \"__repr__\": \"text/plain\",\n \"_repr_html_\": \"text/html\",\n \"_repr_markdown_\": \"text/markdown\",\n \"_repr_svg_\": \"image/svg+xml\",\n \"_repr_png_\": \"image/png\",\n \"_repr_pdf_\": \"application/pdf\",\n \"_repr_jpeg_\": \"image/jpeg\",\n \"_repr_latex\": \"text/latex\",\n \"_repr_json_\": \"application/json\",\n \"_repr_javascript_\": \"application/javascript\",\n \"savefig\": \"image/png\",\n}\n\n\ndef render_image(mime, value, meta):\n data = f\"data:{mime};charset=utf-8;base64,{value}\"\n attrs = \" \".join(['{k}=\"{v}\"' for k, v in meta.items()])\n return f'<img src=\"{data}\" {attrs}</img>'\n\n\ndef identity(value, meta):\n return value\n\n\nMIME_RENDERERS = {\n \"text/plain\": identity,\n \"text/html\": identity,\n \"image/png\": lambda value, meta: render_image(\"image/png\", value, meta),\n \"image/jpeg\": lambda value, meta: render_image(\"image/jpeg\", value, meta),\n \"image/svg+xml\": identity,\n \"application/json\": identity,\n \"application/javascript\": lambda value, meta: f\"<script>{value}</script>\",\n}\n\n\ndef eval_formatter(obj, print_method):\n \"\"\"\n Evaluates a formatter method.\n \"\"\"\n if print_method == \"__repr__\":\n return repr(obj)\n elif hasattr(obj, print_method):\n if print_method == \"savefig\":\n buf = io.BytesIO()\n obj.savefig(buf, format=\"png\")\n buf.seek(0)\n return base64.b64encode(buf.read()).decode(\"utf-8\")\n return getattr(obj, print_method)()\n elif print_method == \"_repr_mimebundle_\":\n return {}, {}\n return None\n\n\ndef format_mime(obj):\n \"\"\"\n Formats object using _repr_x_ methods.\n \"\"\"\n if isinstance(obj, str):\n return obj, \"text/plain\"\n\n mimebundle = eval_formatter(obj, \"_repr_mimebundle_\")\n if isinstance(mimebundle, tuple):\n format_dict, _ = mimebundle\n else:\n format_dict = mimebundle\n\n output, not_available = None, []\n for method, mime_type in reversed(MIME_METHODS.items()):\n if mime_type in format_dict:\n output = format_dict[mime_type]\n else:\n output = eval_formatter(obj, method)\n\n if output is None:\n continue\n elif mime_type not in MIME_RENDERERS:\n not_available.append(mime_type)\n continue\n break\n if output is None:\n if not_available:\n console.warn(\n f\"Rendered object requested unavailable MIME renderers: {not_available}\"\n )\n output = repr(output)\n mime_type = \"text/plain\"\n elif isinstance(output, tuple):\n output, meta = output\n else:\n meta = {}\n return MIME_RENDERERS[mime_type](output, meta), mime_type\n\n\nclass PyScript:\n loop = loop\n\n @staticmethod\n def run_until_complete(f):\n _ = loop.run_until_complete(f)\n\n @staticmethod\n def write(element_id, value, append=False, exec_id=0):\n \"\"\"Writes value to the element with id \"element_id\"\"\"\n Element(element_id).write(value=value, append=append)\n console.warn(\n dedent(\n \"\"\"PyScript Deprecation Warning: PyScript.write is\n marked as deprecated and will be removed sometime soon. Please, use\n Element(<id>).write instead.\"\"\"\n )\n )\n\n\nclass Element:\n def __init__(self, element_id, element=None):\n self._id = element_id\n self._element = element\n\n @property\n def id(self):\n return self._id\n\n @property\n def element(self):\n \"\"\"Return the dom element\"\"\"\n if not self._element:\n self._element = document.querySelector(f\"#{self._id}\")\n return self._element\n\n @property\n def value(self):\n return self.element.value\n\n @property\n def innerHtml(self):\n return self.element.innerHtml\n\n def write(self, value, append=False):\n out_element_id = self.id\n\n html, mime_type = format_mime(value)\n if html == \"\\n\":\n return\n\n if append:\n child = document.createElement(\"div\")\n exec_id = self.element.childElementCount + 1\n out_element_id = child.id = f\"{self.id}-{exec_id}\"\n self.element.appendChild(child)\n\n out_element = document.querySelector(f\"#{out_element_id}\")\n\n if mime_type in (\"application/javascript\", \"text/html\"):\n script_element = document.createRange().createContextualFragment(html)\n out_element.appendChild(script_element)\n else:\n out_element.innerHTML = html\n\n def clear(self):\n if hasattr(self.element, \"value\"):\n self.element.value = \"\"\n else:\n self.write(\"\", append=False)\n\n def select(self, query, from_content=False):\n el = self.element\n if from_content:\n el = el.content\n\n _el = el.querySelector(query)\n if _el:\n return Element(_el.id, _el)\n else:\n console.warn(f\"WARNING: can't find element matching query {query}\")\n\n def clone(self, new_id=None, to=None):\n if new_id is None:\n new_id = self.element.id\n\n clone = self.element.cloneNode(True)\n clone.id = new_id\n\n if to:\n to.element.appendChild(clone)\n\n # Inject it into the DOM\n self.element.after(clone)\n\n return Element(clone.id, clone)\n\n def remove_class(self, classname):\n if isinstance(classname, list):\n for cl in classname:\n self.remove_class(cl)\n else:\n self.element.classList.remove(classname)\n\n def add_class(self, classname):\n self.element.classList.add(classname)\n\n\ndef add_classes(element, class_list):\n for klass in class_list.split(\" \"):\n element.classList.add(klass)\n\n\ndef create(what, id_=None, classes=\"\"):\n element = document.createElement(what)\n if id_:\n element.id = id_\n add_classes(element, classes)\n return Element(id_, element)\n\n\nclass PyWidgetTheme:\n def __init__(self, main_style_classes):\n self.main_style_classes = main_style_classes\n\n def theme_it(self, widget):\n for klass in self.main_style_classes.split(\" \"):\n widget.classList.add(klass)\n\n\nclass PyItemTemplate(Element):\n label_fields = None\n\n def __init__(self, data, labels=None, state_key=None, parent=None):\n self.data = data\n\n self.register_parent(parent)\n\n if not labels:\n labels = list(self.data.keys())\n self.labels = labels\n\n self.state_key = state_key\n\n super().__init__(self._id)\n\n def register_parent(self, parent):\n self._parent = parent\n if parent:\n self._id = f\"{self._parent._id}-c-{len(self._parent._children)}\"\n self.data[\"id\"] = self._id\n else:\n self._id = None\n\n def create(self):\n new_child = create(\"div\", self._id, \"py-li-element\")\n new_child._element.innerHTML = dedent(\n f\"\"\"\n <label id=\"{self._id}\" for=\"flex items-center p-2 \">\n <input class=\"mr-2\" type=\"checkbox\" class=\"task-check\">\n <p>{self.render_content()}</p>\n </label>\n \"\"\"\n )\n return new_child\n\n def on_click(self, evt):\n pass\n\n def pre_append(self):\n pass\n\n def post_append(self):\n self.element.click = self.on_click\n self.element.onclick = self.on_click\n\n self._post_append()\n\n def _post_append(self):\n pass\n\n def strike(self, value, extra=None):\n if value:\n self.add_class(\"line-through\")\n else:\n self.remove_class(\"line-through\")\n\n def render_content(self):\n return \" - \".join([self.data[f] for f in self.labels])\n\n\nclass PyListTemplate:\n theme = PyWidgetTheme(\"py-li-element\")\n item_class = PyItemTemplate\n\n def __init__(self, parent):\n self.parent = parent\n self._children = []\n self._id = self.parent.id\n\n @property\n def children(self):\n return self._children\n\n @property\n def data(self):\n return [c.data for c in self._children]\n\n def render_children(self):\n binds = {}\n for i, c in enumerate(self._children):\n txt = c.element.innerHTML\n rnd = str(time.time()).replace(\".\", \"\")[-5:]\n new_id = f\"{c.element.id}-{i}-{rnd}\"\n binds[new_id] = c.element.id\n txt = txt.replace(\">\", f\" id='{new_id}'>\")\n print(txt)\n\n def foo(evt):\n evtEl = evt.srcElement\n srcEl = Element(binds[evtEl.id])\n srcEl.element.onclick()\n evtEl.classList = srcEl.element.classList\n\n for new_id in binds:\n Element(new_id).element.onclick = foo\n\n def connect(self):\n self.md = main_div = document.createElement(\"div\")\n main_div.id = self._id + \"-list-tasks-container\"\n\n if self.theme:\n self.theme.theme_it(main_div)\n\n self.parent.appendChild(main_div)\n\n def add(self, *args, **kws):\n if not isinstance(args[0], self.item_class):\n child = self.item_class(*args, **kws)\n else:\n child = args[0]\n child.register_parent(self)\n return self._add(child)\n\n def _add(self, child_elem):\n self.pre_child_append(child_elem)\n child_elem.pre_append()\n self._children.append(child_elem)\n self.md.appendChild(child_elem.create().element)\n child_elem.post_append()\n self.child_appended(child_elem)\n return child_elem\n\n def pre_child_append(self, child):\n pass\n\n def child_appended(self, child):\n \"\"\"Overwrite me to define logic\"\"\"\n pass\n\n\nclass OutputCtxManager:\n def __init__(self, out=None, output_to_console=True, append=True):\n self._out = out\n self._prev = out\n self.output_to_console = output_to_console\n self._append = append\n\n def change(self, out=None, output_to_console=True, append=True):\n self._prev = self._out\n self._out = out\n self.output_to_console = output_to_console\n self._append = append\n\n def revert(self):\n self._out = self._prev\n\n def write(self, value):\n if self._out:\n Element(self._out).write(value, self._append)\n\n if self.output_to_console:\n console.info(value)\n\n\nclass OutputManager:\n def __init__(self, out=None, err=None, output_to_console=True, append=True):\n sys.stdout = self._out_manager = OutputCtxManager(\n out=out, output_to_console=output_to_console, append=append\n )\n sys.stderr = self._err_manager = OutputCtxManager(\n out=err, output_to_console=output_to_console, append=append\n )\n self.output_to_console = output_to_console\n self._append = append\n\n def change(self, out=None, err=None, output_to_console=True, append=True):\n self._out_manager.change(\n out=out, output_to_console=output_to_console, append=append\n )\n sys.stdout = self._out_manager\n self._err_manager.change(\n out=err, output_to_console=output_to_console, append=append\n )\n sys.stderr = self._err_manager\n self.output_to_console = output_to_console\n self._append = append\n\n def revert(self):\n self._out_manager.revert()\n self._err_manager.revert()\n sys.stdout = self._out_manager\n sys.stderr = self._err_manager\n\n\npyscript = PyScript()\noutput_manager = OutputManager()\n"; - - const logger$2 = getLogger('pyscript/pyodide'); - class PyodideRuntime extends Runtime { - src; - name; - lang; - interpreter; - globals; - constructor(src = 'https://cdn.jsdelivr.net/pyodide/v0.21.2/full/pyodide.js', name = 'pyodide-default', lang = 'python') { - logger$2.info('Runtime config:', { name, lang, src }); - super(); - this.src = src; - this.name = name; - this.lang = lang; - } - /** - * Although `loadPyodide` is used below, - * notice that it is not imported i.e. - * import { loadPyodide } from 'pyodide'; - * is not used at the top of this file. - * - * This is because, if it's used, loadPyodide - * behaves mischievously i.e. it tries to load - * `pyodide.asm.js` and `pyodide_py.tar` but - * with paths that are wrong such as: - * - * http://127.0.0.1:8080/build/pyodide_py.tar - * which results in a 404 since `build` doesn't - * contain these files and is clearly the wrong - * path. - */ - async loadInterpreter() { - logger$2.info('Loading pyodide'); - // eslint-disable-next-line - // @ts-ignore - this.interpreter = await loadPyodide({ - stdout: console.log, - stderr: console.log, - fullStdLib: false, - }); - this.globals = this.interpreter.globals; - // XXX: ideally, we should load micropip only if we actually need it - await this.loadPackage('micropip'); - logger$2.info('importing pyscript.py'); - await this.run(pyscript); - logger$2.info('pyodide loaded and initialized'); - } - async run(code) { - return await this.interpreter.runPythonAsync(code); - } - registerJsModule(name, module) { - this.interpreter.registerJsModule(name, module); - } - async loadPackage(names) { - logger$2.info(`pyodide.loadPackage: ${names.toString()}`); - await this.interpreter.loadPackage(names, logger$2.info.bind(logger$2), logger$2.info.bind(logger$2)); - } - async installPackage(package_name) { - if (package_name.length > 0) { - logger$2.info(`micropip install ${package_name.toString()}`); - const micropip = this.globals.get('micropip'); - await micropip.install(package_name); - micropip.destroy(); - } - } - async loadFromFile(path) { - const filename = getLastPath(path); - await this.run(` - from pyodide.http import pyfetch - from js import console - - try: - response = await pyfetch("${path}") - except Exception as err: - console.warn("PyScript: Access to local files (using 'paths:' in py-env) is not available when directly opening a HTML file; you must use a webserver to serve the additional files. See https://github.com/pyscript/pyscript/issues/257#issuecomment-1119595062 on starting a simple webserver with Python.") - raise(err) - content = await response.bytes() - with open("${filename}", "wb") as f: - f.write(content) - `); - } - } - - // Subscriber used to connect to the first available runtime (can be pyodide or others) - let runtimeSpec; - runtimeLoaded.subscribe(value => { - runtimeSpec = value; - }); - let appConfig_; - appConfig.subscribe(value => { - appConfig_ = value; - }); - const logger$1 = getLogger('py-config'); - /** - * Configures general metadata about the PyScript application such - * as a list of runtimes, name, version, closing the loader - * automatically, etc. - * - * Also initializes the different runtimes passed. If no runtime is passed, - * the default runtime based on Pyodide is used. - */ - class PyConfig extends BaseEvalElement { - widths; - label; - mount_name; - details; - operation; - values; - constructor() { - super(); - } - extractFromSrc(configType) { - if (this.hasAttribute('src')) { - logger$1.info('config set from src attribute'); - return validateConfig(readTextFromPath(this.getAttribute('src')), configType); - } - return {}; - } - extractFromInline(configType) { - if (this.innerHTML !== '') { - this.code = this.innerHTML; - this.innerHTML = ''; - logger$1.info('config set from inline'); - return validateConfig(this.code, configType); - } - return {}; - } - injectMetadata() { - this.values.pyscript = { - "version": version, - "time": new Date().toISOString() - }; - } - connectedCallback() { - const configType = this.hasAttribute("type") ? this.getAttribute("type") : "toml"; - let srcConfig = this.extractFromSrc(configType); - const inlineConfig = this.extractFromInline(configType); - // first make config from src whole if it is partial - srcConfig = mergeConfig(srcConfig, defaultConfig$1); - // then merge inline config and config from src - this.values = mergeConfig(inlineConfig, srcConfig); - this.injectMetadata(); - appConfig.set(this.values); - logger$1.info('config set:', this.values); - addInitializer(this.loadPackages); - addInitializer(this.loadPaths); - this.loadRuntimes(); - } - log(msg) { - const newLog = document.createElement('p'); - newLog.innerText = msg; - this.details.appendChild(newLog); - } - close() { - this.remove(); - } - loadPackages = async () => { - const env = appConfig_.packages; - logger$1.info("Loading env: ", env); - await runtimeSpec.installPackage(env); - }; - loadPaths = async () => { - const paths = appConfig_.paths; - logger$1.info("Paths to load: ", paths); - for (const singleFile of paths) { - logger$1.info(` loading path: ${singleFile}`); - try { - await runtimeSpec.loadFromFile(singleFile); - } - catch (e) { - //Should we still export full error contents to console? - handleFetchError(e, singleFile); - } - } - logger$1.info("All paths loaded"); - }; - loadRuntimes() { - logger$1.info('Initializing runtimes'); - for (const runtime of this.values.runtimes) { - const runtimeObj = new PyodideRuntime(runtime.src, runtime.name, runtime.lang); - const script = document.createElement('script'); // create a script DOM node - script.src = runtimeObj.src; // set its src to the provided URL - script.addEventListener('load', () => { - void runtimeObj.initialize(); - }); - document.head.appendChild(script); - } - } - } - - const logger = getLogger('pyscript/main'); - /* eslint-disable @typescript-eslint/no-unused-vars */ - customElements.define('py-script', PyScript); - customElements.define('py-loader', PyLoader); - customElements.define('py-config', PyConfig); - customElements.define('py-env', PyEnv); - /* eslint-disable @typescript-eslint/no-unused-vars */ - // As first thing, loop for application configs - logger.info('checking for py-config'); - const config = document.querySelector('py-config'); - if (!config) { - const loader = document.createElement('py-config'); - document.body.append(loader); - } - // add loader to the page body - logger.info('add py-loader'); - const loader = document.createElement('py-loader'); - document.body.append(loader); - globalLoader.set(loader); - -})(); +})({}); //# sourceMappingURL=pyscript.js.map diff --git a/examples/02_image_filter/resources/pyscript_bootstrap_templates-0.1.0-py3-none-any.whl b/examples/02_image_filter/resources/pyscript_bootstrap_templates-0.1.0-py3-none-any.whl index 7d580e9..19acf2b 100644 Binary files a/examples/02_image_filter/resources/pyscript_bootstrap_templates-0.1.0-py3-none-any.whl and b/examples/02_image_filter/resources/pyscript_bootstrap_templates-0.1.0-py3-none-any.whl differ diff --git a/examples/02_image_filter/resources/pyscript_bootstrap_templates-0.2.0-py3-none-any.whl b/examples/02_image_filter/resources/pyscript_bootstrap_templates-0.2.0-py3-none-any.whl new file mode 100644 index 0000000..e1a2da0 Binary files /dev/null and b/examples/02_image_filter/resources/pyscript_bootstrap_templates-0.2.0-py3-none-any.whl differ diff --git a/examples/02_image_filter/serviceWorker.js b/examples/02_image_filter/serviceWorker.js index 2b267dd..8dedfd2 100644 --- a/examples/02_image_filter/serviceWorker.js +++ b/examples/02_image_filter/serviceWorker.js @@ -1,5 +1,5 @@ -const pwa_version = "02_image_filter_202210161638" +const pwa_version = "02_image_filter_202306031006" const assets = ["./index.html", "./main.py", "./resources/bootstrap.css", @@ -7,7 +7,7 @@ const assets = ["./index.html", "./resources/pyscript.css", "./resources/pyscript.js", "./resources/pyscript.py", - "./resources/pyscript_bootstrap_templates-0.1.0-py3-none-any.whl", + "./resources/pyscript_bootstrap_templates-0.2.0-py3-none-any.whl", "./resources/pwa.js", "./site.js", ] diff --git a/examples/03_numpy_grid_demo/config.json b/examples/03_numpy_grid_demo/config.json index eadc7b6..589b78e 100644 --- a/examples/03_numpy_grid_demo/config.json +++ b/examples/03_numpy_grid_demo/config.json @@ -10,7 +10,7 @@ "pyscript_py_url": "https://pyscript.net/latest/pyscript.py", "bootstrap_css_url": "https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css", "bootstrap_js_url": "https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js", - "pyscript_bootstrap_templates_wheel_url": "../dist/pyscript_bootstrap_templates-0.1.0-py3-none-any.whl", + "pyscript_bootstrap_templates_wheel_url": "../dist/pyscript_bootstrap_templates-0.2.0-py3-none-any.whl", "pwa_bg_color": "#000000", "pwa_theme_color": "#ffffff" } \ No newline at end of file diff --git a/examples/03_numpy_grid_demo/index.html b/examples/03_numpy_grid_demo/index.html index 4ec1945..0beedcb 100644 --- a/examples/03_numpy_grid_demo/index.html +++ b/examples/03_numpy_grid_demo/index.html @@ -19,9 +19,11 @@ <body style="width: 100%; height: 100%"> <py-config type="json"> { - "autoclose_loader": true, + "splashscreen": { + "autoclose": true + }, "packages": [ - "./resources/pyscript_bootstrap_templates-0.1.0-py3-none-any.whl", + "./resources/pyscript_bootstrap_templates-0.2.0-py3-none-any.whl", "numpy" ], "paths": [] diff --git a/examples/03_numpy_grid_demo/resources/pyscript.css b/examples/03_numpy_grid_demo/resources/pyscript.css index be94299..10a1f1c 100644 --- a/examples/03_numpy_grid_demo/resources/pyscript.css +++ b/examples/03_numpy_grid_demo/resources/pyscript.css @@ -1,9 +1,35 @@ -:not(:defined) { - display: none +/* py-config - not a component */ +py-config { + display: none; +} +/* py-{el} - components not defined */ +py-script:not(:defined) { + display: none; } -html{ - font-family: ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, "Noto Sans", sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji"; +py-repl:not(:defined) { + display: none; +} + +py-title:not(:defined) { + display: none; +} + +py-inputbox:not(:defined) { + display: none; +} + +py-button:not(:defined) { + display: none; +} + +py-box:not(:defined) { + display: none; +} + +html { + font-family: ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', + Arial, 'Noto Sans', sans-serif, 'Apple Color Emoji', 'Segoe UI Emoji', 'Segoe UI Symbol', 'Noto Color Emoji'; line-height: 1.5; } @@ -24,6 +50,7 @@ html{ border-right: 4px solid rgba(255, 255, 255, 0); animation: spinner 0.6s linear infinite; } + @keyframes spinner { to { transform: rotate(360deg); @@ -81,27 +108,68 @@ html{ right: 5%; } -.py-box{ +/* Pop-up second layer end */ +.alert-banner { + position: relative; + padding: 0.5rem 1.5rem 0.5rem 0.5rem; + margin: 5px 0; +} + +.alert-banner p { + margin: 0; +} + +.py-error { + background-color: #ffe9e8; + border: solid; + border-color: #f0625f; + color: #9d041c; +} + +.py-warning { + background-color: rgb(255, 244, 229); + border: solid; + border-color: #ffa016; + color: #794700; +} + +.alert-banner.py-error > #alert-close-button { + color: #9d041c; +} + +.alert-banner.py-warning > #alert-close-button { + color: #794700; +} + +#alert-close-button { + position: absolute; + right: 0.5rem; + top: 0.5rem; + cursor: pointer; + background: transparent; + border: none; +} + +.py-box { display: flex; flex-direction: row; justify-content: flex-start; } -.py-box div.py-box-child * -{ +.py-box div.py-box-child * { max-width: 100%; } -.py-repl-box{ +.py-repl-box { flex-direction: column; } -.editor-box{ +.py-repl-editor { --tw-border-opacity: 1; border-color: rgba(209, 213, 219, var(--tw-border-opacity)); border-width: 1px; position: relative; - --tw-ring-inset: var(--tw-empty,/*!*/ /*!*/); + --tw-ring-inset: var(--tw-empty, /*!*/ /*!*/); --tw-ring-offset-width: 0px; --tw-ring-offset-color: #fff; --tw-ring-color: rgba(59, 130, 246, 0.5); @@ -113,14 +181,14 @@ html{ box-sizing: border-box; border-width: 1px; border-style: solid; - border-color: rgb(209, 213, 219) + border-color: rgb(209, 213, 219); } -.editor-box:hover button{ +.editor-box:hover button { opacity: 1; } -.repl-play-button{ +.py-repl-run-button { opacity: 0; bottom: 0.25rem; right: 0.25rem; @@ -154,65 +222,64 @@ html{ border: 0; } -.repl-play-button:hover{ +.py-repl-run-button:hover { opacity: 1; } -.py-title{ +.py-title { text-transform: uppercase; text-align: center; } -.py-title h1{ +.py-title h1 { font-weight: 700; font-size: 1.875rem; } -.py-input{ +.py-input { padding: 0.5rem; --tw-border-opacity: 1; border-color: rgba(209, 213, 219, var(--tw-border-opacity)); border-width: 1px; - border-radius: 0.25rem; + border-radius: 0.25rem; margin-right: 0.75rem; border-style: solid; width: auto; } -.py-box input.py-input{ +.py-box input.py-input { width: -webkit-fill-available; } -.central-content{ +.central-content { max-width: 20rem; margin-left: auto; margin-right: auto; } input { - text-rendering: auto; - color: -internal-light-dark(black, white); - letter-spacing: normal; - word-spacing: normal; - line-height: normal; - text-transform: none; - text-indent: 0px; - text-shadow: none; - display: inline-block; - text-align: start; - appearance: auto; - -webkit-rtl-ordering: logical; - cursor: text; - background-color: -internal-light-dark(rgb(255, 255, 255), rgb(59, 59, 59)); - margin: 0em; - padding: 1px 2px; - border-width: 2px; - border-style: inset; - border-color: -internal-light-dark(rgb(118, 118, 118), rgb(133, 133, 133)); - border-image: initial; + text-rendering: auto; + color: -internal-light-dark(black, white); + letter-spacing: normal; + word-spacing: normal; + line-height: normal; + text-transform: none; + text-indent: 0px; + text-shadow: none; + display: inline-block; + text-align: start; + appearance: auto; + -webkit-rtl-ordering: logical; + background-color: -internal-light-dark(rgb(255, 255, 255), rgb(59, 59, 59)); + margin: 0em; + padding: 1px 2px; + border-width: 2px; + border-style: inset; + border-color: -internal-light-dark(rgb(118, 118, 118), rgb(133, 133, 133)); + border-image: initial; } -.py-button{ +.py-button { --tw-text-opacity: 1; color: rgba(255, 255, 255, var(--tw-text-opacity)); padding: 0.5rem; @@ -222,17 +289,22 @@ input { border-color: rgba(37, 99, 235, var(--tw-border-opacity)); border-width: 1px; border-radius: 0.25rem; + cursor: pointer; } -.py-li-element p{ +.py-li-element p { margin: 5px; } -.py-li-element p{ +.py-li-element p { display: inline; } -button, input, optgroup, select, textarea { +button, +input, +optgroup, +select, +textarea { font-family: inherit; font-size: 100%; line-height: 1.15; @@ -242,3 +314,19 @@ button, input, optgroup, select, textarea { .line-through { text-decoration: line-through; } + +/* ===== py-terminal plugin ===== */ +/* XXX: it would be nice if these rules were stored in e.g. pyterminal.css and + bundled together at build time (by rollup?) */ + +.py-terminal { + min-height: 10em; + background-color: black; + color: white; + padding: 0.5rem; + overflow: auto; +} + +.py-terminal-hidden { + display: none; +} diff --git a/examples/03_numpy_grid_demo/resources/pyscript.js b/examples/03_numpy_grid_demo/resources/pyscript.js index e9b92a0..4bc0b89 100644 --- a/examples/03_numpy_grid_demo/resources/pyscript.js +++ b/examples/03_numpy_grid_demo/resources/pyscript.js @@ -1,4167 +1,28471 @@ -(function () { - 'use strict'; +var pyscript = (function (exports) { + 'use strict'; - function noop() { } - function safe_not_equal(a, b) { - return a != a ? b == b : a !== b || ((a && typeof a === 'object') || typeof a === 'function'); + var parser$2 = /* + * Generated by PEG.js 0.10.0. + * + * http://pegjs.org/ + */ + (function() { + + function peg$subclass(child, parent) { + function ctor() { this.constructor = child; } + ctor.prototype = parent.prototype; + child.prototype = new ctor(); } - Promise.resolve(); - const subscriber_queue = []; - /** - * Create a `Writable` store that allows both updating and reading by subscription. - * @param {*=}value initial value - * @param {StartStopNotifier=}start start and stop notifications for subscriptions - */ - function writable(value, start = noop) { - let stop; - const subscribers = new Set(); - function set(new_value) { - if (safe_not_equal(value, new_value)) { - value = new_value; - if (stop) { // store is ready - const run_queue = !subscriber_queue.length; - for (const subscriber of subscribers) { - subscriber[1](); - subscriber_queue.push(subscriber, value); - } - if (run_queue) { - for (let i = 0; i < subscriber_queue.length; i += 2) { - subscriber_queue[i][0](subscriber_queue[i + 1]); - } - subscriber_queue.length = 0; - } - } + function peg$SyntaxError(message, expected, found, location) { + this.message = message; + this.expected = expected; + this.found = found; + this.location = location; + this.name = "SyntaxError"; + + if (typeof Error.captureStackTrace === "function") { + Error.captureStackTrace(this, peg$SyntaxError); + } + } + + peg$subclass(peg$SyntaxError, Error); + + peg$SyntaxError.buildMessage = function(expected, found) { + var DESCRIBE_EXPECTATION_FNS = { + literal: function(expectation) { + return "\"" + literalEscape(expectation.text) + "\""; + }, + + "class": function(expectation) { + var escapedParts = "", + i; + + for (i = 0; i < expectation.parts.length; i++) { + escapedParts += expectation.parts[i] instanceof Array + ? classEscape(expectation.parts[i][0]) + "-" + classEscape(expectation.parts[i][1]) + : classEscape(expectation.parts[i]); + } + + return "[" + (expectation.inverted ? "^" : "") + escapedParts + "]"; + }, + + any: function(expectation) { + return "any character"; + }, + + end: function(expectation) { + return "end of input"; + }, + + other: function(expectation) { + return expectation.description; } + }; + + function hex(ch) { + return ch.charCodeAt(0).toString(16).toUpperCase(); + } + + function literalEscape(s) { + return s + .replace(/\\/g, '\\\\') + .replace(/"/g, '\\"') + .replace(/\0/g, '\\0') + .replace(/\t/g, '\\t') + .replace(/\n/g, '\\n') + .replace(/\r/g, '\\r') + .replace(/[\x00-\x0F]/g, function(ch) { return '\\x0' + hex(ch); }) + .replace(/[\x10-\x1F\x7F-\x9F]/g, function(ch) { return '\\x' + hex(ch); }); + } + + function classEscape(s) { + return s + .replace(/\\/g, '\\\\') + .replace(/\]/g, '\\]') + .replace(/\^/g, '\\^') + .replace(/-/g, '\\-') + .replace(/\0/g, '\\0') + .replace(/\t/g, '\\t') + .replace(/\n/g, '\\n') + .replace(/\r/g, '\\r') + .replace(/[\x00-\x0F]/g, function(ch) { return '\\x0' + hex(ch); }) + .replace(/[\x10-\x1F\x7F-\x9F]/g, function(ch) { return '\\x' + hex(ch); }); + } + + function describeExpectation(expectation) { + return DESCRIBE_EXPECTATION_FNS[expectation.type](expectation); + } + + function describeExpected(expected) { + var descriptions = new Array(expected.length), + i, j; + + for (i = 0; i < expected.length; i++) { + descriptions[i] = describeExpectation(expected[i]); } - function update(fn) { - set(fn(value)); - } - function subscribe(run, invalidate = noop) { - const subscriber = [run, invalidate]; - subscribers.add(subscriber); - if (subscribers.size === 1) { - stop = start(set) || noop; + + descriptions.sort(); + + if (descriptions.length > 0) { + for (i = 1, j = 1; i < descriptions.length; i++) { + if (descriptions[i - 1] !== descriptions[i]) { + descriptions[j] = descriptions[i]; + j++; } - run(value); - return () => { - subscribers.delete(subscriber); - if (subscribers.size === 0) { - stop(); - stop = null; - } - }; + } + descriptions.length = j; } - return { set, update, subscribe }; - } - /* Very simple logger interface. + switch (descriptions.length) { + case 1: + return descriptions[0]; - Each module is expected to create its own logger by doing e.g.: + case 2: + return descriptions[0] + " or " + descriptions[1]; - const logger = getLogger('my-prefix'); - - and then use it instead of console: - - logger.info('hello', 'world'); - logger.warn('...'); - logger.error('...'); - - The logger automatically adds the prefix "[my-prefix]" to all logs; so e.g., the - above call would print: - - [my-prefix] hello world - - logger.log is intentionally omitted. The idea is that PyScript should not - write anything to console.log, to leave it free for the user. - - Currently, the logger does not to anything more than that. In the future, - we might want to add additional features such as the ability to - enable/disable logs on a global or per-module basis. - */ - const _cache = new Map(); - function getLogger(prefix) { - let logger = _cache.get(prefix); - if (logger === undefined) { - logger = _makeLogger(prefix); - _cache.set(prefix, logger); + default: + return descriptions.slice(0, -1).join(", ") + + ", or " + + descriptions[descriptions.length - 1]; } - return logger; - } - function _makeLogger(prefix) { - prefix = "[" + prefix + "] "; - function make(level) { - const out_fn = console[level].bind(console); - function fn(fmt, ...args) { - out_fn(prefix + fmt, ...args); - } - return fn; - } - // 'log' is intentionally omitted - const debug = make('debug'); - const info = make('info'); - const warn = make('warn'); - const error = make('error'); - return { debug, info, warn, error }; - } + } - /* - A store for Runtime which can encompass any - runtime, but currently only has Pyodide as its offering. - */ - const runtimeLoaded = writable(); - const loadedEnvironments = writable({}); - const scriptsQueue = writable([]); - const initializers = writable([]); - const postInitializers = writable([]); - const globalLoader = writable(); - const appConfig = writable(); - const addToScriptsQueue = (script) => { - scriptsQueue.update(scriptsQueue => [...scriptsQueue, script]); - }; - const addInitializer = (initializer) => { - initializers.update(initializers => [...initializers, initializer]); - }; - const addPostInitializer = (initializer) => { - postInitializers.update(postInitializers => [...postInitializers, initializer]); + function describeFound(found) { + return found ? "\"" + literalEscape(found) + "\"" : "end of input"; + } + + return "Expected " + describeExpected(expected) + " but " + describeFound(found) + " found."; }; - // taken from https://github.com/Gin-Quin/fast-toml - let e = "", t$1 = 0; - function i$2(e, t = 0) { - let i; - for (; (i = e[t++]) && (" " == i || "\t" == i || "\r" == i);) - ; - return t - 1; - } - function n(e) { - switch (e[0]) { - case void 0: - return ""; - case '"': - return (function (e) { - let t, i = 0, n = ""; - for (; (t = e.indexOf("\\", i) + 1);) { - switch (((n += e.slice(i, t - 1)), e[t])) { - case "\\": - n += "\\"; - break; - case '"': - n += '"'; - break; - case "\r": - "\n" == e[t + 1] && t++; - case "\n": - break; - case "b": - n += "\b"; - break; - case "t": - n += "\t"; - break; - case "n": - n += "\n"; - break; - case "f": - n += "\f"; - break; - case "r": - n += "\r"; - break; - case "u": - (n += String.fromCharCode(parseInt(e.substr(t + 1, 4), 16))), (t += 4); - break; - case "U": - (n += String.fromCharCode(parseInt(e.substr(t + 1, 8), 16))), (t += 8); - break; - default: - throw r(e[t]); - } - i = t + 1; + function peg$parse(input, options) { + options = options !== void 0 ? options : {}; + + var peg$FAILED = {}, + + peg$startRuleFunctions = { Expressions: peg$parseExpressions }, + peg$startRuleFunction = peg$parseExpressions, + + peg$c0 = function() { + return g_root; + }, + peg$c1 = function(path) { + g_context = findContext(g_root, true, path); + }, + peg$c2 = function(path) { + g_context = findContext(g_root, false, path); + }, + peg$c3 = function(keyValue) { + checkTableKey(g_context.table, keyValue[0]); + g_context.table[keyValue[0]] = keyValue[1]; + }, + peg$c4 = peg$otherExpectation("Newline"), + peg$c5 = "\n", + peg$c6 = peg$literalExpectation("\n", false), + peg$c7 = "\r\n", + peg$c8 = peg$literalExpectation("\r\n", false), + peg$c9 = peg$otherExpectation("Whitespace"), + peg$c10 = /^[ \t]/, + peg$c11 = peg$classExpectation([" ", "\t"], false, false), + peg$c12 = peg$otherExpectation("Comment"), + peg$c13 = "#", + peg$c14 = peg$literalExpectation("#", false), + peg$c15 = peg$anyExpectation(), + peg$c16 = "=", + peg$c17 = peg$literalExpectation("=", false), + peg$c18 = function(key, value) { + return [key, value.value]; + }, + peg$c19 = function() { + return text(); + }, + peg$c20 = peg$otherExpectation("[a-z], [A-Z], [0-9], \"-\", \"_\""), + peg$c21 = /^[a-zA-Z0-9\-_]/, + peg$c22 = peg$classExpectation([["a", "z"], ["A", "Z"], ["0", "9"], "-", "_"], false, false), + peg$c23 = function(chars) { + return chars.join(''); + }, + peg$c24 = peg$otherExpectation("DoubleQuote"), + peg$c25 = "\"", + peg$c26 = peg$literalExpectation("\"", false), + peg$c27 = peg$otherExpectation("SingleQuote"), + peg$c28 = "'", + peg$c29 = peg$literalExpectation("'", false), + peg$c30 = peg$otherExpectation("ThreeDoubleQuotes"), + peg$c31 = "\"\"\"", + peg$c32 = peg$literalExpectation("\"\"\"", false), + peg$c33 = peg$otherExpectation("ThreeSingleQuotes"), + peg$c34 = "'''", + peg$c35 = peg$literalExpectation("'''", false), + peg$c36 = function(chars) { + return { + type: 'String', + value: chars.join('') + }; + }, + peg$c37 = peg$otherExpectation("NormalCharacter"), + peg$c38 = /^[^\0-\x1F"\\]/, + peg$c39 = peg$classExpectation([["\0", "\x1F"], "\"", "\\"], true, false), + peg$c40 = "u", + peg$c41 = peg$literalExpectation("u", false), + peg$c42 = "U", + peg$c43 = peg$literalExpectation("U", false), + peg$c44 = function() { + var s = text(); + if (s.length <= 2) { + return unescape(s[1]); + } + return fromCodePoint(parseInt(s.substr(2), 16)); + }, + peg$c45 = peg$otherExpectation("\"b\", \"f\", \"n\", \"r\", \"t\""), + peg$c46 = /^[bfnrt]/, + peg$c47 = peg$classExpectation(["b", "f", "n", "r", "t"], false, false), + peg$c48 = peg$otherExpectation("Backslash"), + peg$c49 = "\\", + peg$c50 = peg$literalExpectation("\\", false), + peg$c51 = peg$otherExpectation("FourHexadecimalDigits"), + peg$c52 = peg$otherExpectation("EightHexadecimalDigits"), + peg$c53 = /^[0-9A-Fa-f]/, + peg$c54 = peg$classExpectation([["0", "9"], ["A", "F"], ["a", "f"]], false, false), + peg$c55 = function() { + var s = text(); + return { + type: 'String', + value: s.substr(1, s.length - 2) + }; + }, + peg$c56 = /^[^\0-\x08\n-\x1F']/, + peg$c57 = peg$classExpectation([["\0", "\b"], ["\n", "\x1F"], "'"], true, false), + peg$c58 = function(chars) { + return { + type: 'String', + value: chars.join('').replace(/\\\r?\n(?:\r?\n|[ \t])*/g, '') + }; + }, + peg$c59 = /^[^\0-\x1F\\]/, + peg$c60 = peg$classExpectation([["\0", "\x1F"], "\\"], true, false), + peg$c61 = peg$otherExpectation("AnyCharacter"), + peg$c62 = /^[^\0-\x08\n-\x1F]/, + peg$c63 = peg$classExpectation([["\0", "\b"], ["\n", "\x1F"]], true, false), + peg$c64 = "true", + peg$c65 = peg$literalExpectation("true", false), + peg$c66 = function() { + return { + type: 'Boolean', + value: true + }; + }, + peg$c67 = "false", + peg$c68 = peg$literalExpectation("false", false), + peg$c69 = function() { + return { + type: 'Boolean', + value: false + }; + }, + peg$c70 = function() { + // A double-precision 64-bit floating-point number in IEEE 754 standard. + var s = text(); + var number = parseFloat(s.replace(/_/g, '')); + if (!isFiniteNumber(number)) { + error(s + 'is not a 64-bit floating-point number.'); + } + return { + type: 'Float', + value: number + }; + }, + peg$c71 = ".", + peg$c72 = peg$literalExpectation(".", false), + peg$c73 = "_", + peg$c74 = peg$literalExpectation("_", false), + peg$c75 = "e", + peg$c76 = peg$literalExpectation("e", false), + peg$c77 = "E", + peg$c78 = peg$literalExpectation("E", false), + peg$c79 = function() { + // Be careful of JavaScript limits: + // 1) Number.MAX_SAFE_INTEGER = 9007199254740991 + // 2) Number.MIN_SAFE_INTEGER = -9007199254740991 + var s = text(); + var number = s.replace(/_/g, ''); + // Check if it is a 64-bit signed integer. + var invalid = false; + if (number[0] === '-') { + var minInt = '-9223372036854775808'; + if (number.length > minInt.length || + (number.length === minInt.length && number > minInt)) { + invalid = true; } - return n + e.slice(i); - })(e.slice(1, -1)); - case "'": - return e.slice(1, -1); - case "0": - case "1": - case "2": - case "3": - case "4": - case "5": - case "6": - case "7": - case "8": - case "9": - case "+": - case "-": - case ".": - let t = e; - if ((-1 != t.indexOf("_") && (t = t.replace(/_/g, "")), !isNaN(t))) - return +t; - if ("-" == e[4] && "-" == e[7]) { - let t = new Date(e); - if ("Invalid Date" != t.toString()) - return t; - } - else if (":" == e[2] && ":" == e[5] && e.length >= 7) { - let t = new Date("0000-01-01T" + e + "Z"); - if ("Invalid Date" != t.toString()) - return t; - } - return e; - } - switch (e) { - case "true": - return !0; - case "false": - return !1; - case "nan": - case "NaN": - return !1; - case "null": - return null; - case "inf": - case "+inf": - case "Infinity": - case "+Infinity": - return 1 / 0; - case "-inf": - case "-Infinity": - return -1 / 0; - } - return e; - } - function r(i) { - let n = (function () { - let i = e[t$1], n = t$1; - "\n" == i && n--; - let r = 1, s = e.lastIndexOf("\n", n), a = e.indexOf("\n", n); - -1 == a && (a = 1 / 0); - ("," != i && "\n" != i) || (n = s + 1); - if (-1 == s) - return { line: r, column: n + 1, position: n, lineContent: e.slice(0, a).trim() }; - const c = n - s + 1, o = e.slice(s + 1, a).trim(); - r++; - for (; -1 != (s = e.lastIndexOf("\n", s - 1));) - r++; - return { line: r, column: c, position: n, lineContent: o }; - })(), r = String(n.line); - return (i += "\n" + r + " | " + n.lineContent + "\n"), (i += " ".repeat(r.length + n.column + 2) + "^"), SyntaxError(i); - } - function s(e, i = 0, n = !1) { - let a, c = e[i], o = c, f = c, l = !0, u = !1; - switch (c) { - case '"': - case "'": - if (((a = i + 1), n && e[i + 1] == c && e[i + 2] == c ? ((f = c + c + c), (a += 2)) : (u = !0), "'" == c)) - a = e.indexOf(f, a) + 1; - else - for (; (a = e.indexOf(f, a) + 1);) { - let t = !0, i = a - 1; - for (; "\\" == e[--i];) - t = !t; - if (t) - break; + } else { + if (number[0] === '+') { + number = number.substr(1); } - if (!a) - throw r("Missing " + f + " closer"); - if (c != f) - a += 2; - else if (u) { - let n = e.indexOf("\n", i + 1) + 1; - if (n && n < a) - throw ((t$1 = n - 2), r("Forbidden end-of-line character in single-line string")); - } - return a; - case "(": - f = ")"; - break; - case "{": - f = "}"; - break; - case "[": - f = "]"; - break; - case "<": - f = ">"; - break; - default: - l = !1; - } - let h = 0; - for (; (c = e[++i]);) - if (c == f) { - if (0 == h) - return i + 1; - h--; - } - else if ('"' == c || "'" == c) { - i = s(e, i, n) - 1; - } - else - l && c == o && h++; - throw r("Missing " + f); - } - function a(e) { - "string" != typeof e && (e = String(e)); - let t, i, n = -1, a = "", c = []; - for (; (i = e[++n]);) - switch (i) { - case ".": - if (!a) - throw r('Unexpected "."'); - c.push(a), (a = ""); - continue; - case '"': - case "'": - if (((t = s(e, n)), t == n + 2)) - throw r("Empty string key"); - (a += e.slice(n + 1, t - 1)), (n = t - 1); - continue; - default: - a += i; - } - return a && c.push(a), c; - } - function c(e, t = []) { - const i = t.pop(); - for (let i of t) { - if ("object" != typeof e) { - throw r('["' + t.slice(0, t.indexOf(i) + 1).join('"].["') + '"]' + " must be an object"); - } - void 0 === e[i] && (e[i] = {}), (e = e[i]) instanceof Array && (e = e[e.length - 1]); - } - return [e, i]; - } - class o { - root; - data; - inlineScopeList; - constructor() { - this.root = {}; - this.data = this.root; - this.inlineScopeList = []; - } - get isRoot() { - return this.data == this.root; - } - set(e, t) { - let [i, n] = c(this.data, a(e)); - if ("string" == typeof i) - throw "Wtf the scope is a string. Please report the bug"; - if (n in i) - throw r(`Re-writing the key '${e}'`); - return (i[n] = t), t; - } - push(e) { - if (!(this.data instanceof Array)) { - if (!this.isRoot) - throw r("Missing key"); - (this.data = Object.assign([], this.data)), (this.root = this.data); - } - return this.data.push(e), this; - } - use(e) { - return ((this.data = (function (e, t = []) { - for (let i of t) { - //if (void 0 === e) e = lastData[lastElt] = {}; - //else - if ("object" != typeof e) { - throw r('["' + t.slice(0, t.indexOf(i) + 1).join('"].["') + '"]' + " must be an object"); + var maxInt = '9223372036854775807'; + if (number.length > maxInt.length || + (number.length === maxInt.length && number > maxInt)) { + invalid = true; } - void 0 === e[i] && (e[i] = {}), (e = e[i]) instanceof Array && (e = e[e.length - 1]); - } - return e; - })(this.root, a(e))), - this); + } + if (invalid) { + error(s + ' is not a 64-bit signed integer.'); + } + number = parseInt(number, 10); + if (!isFiniteNumber(number)) { + error(s + ' is not a 64-bit signed integer.'); + } + return { + type: 'Integer', + value: number + }; + }, + peg$c80 = "+", + peg$c81 = peg$literalExpectation("+", false), + peg$c82 = "-", + peg$c83 = peg$literalExpectation("-", false), + peg$c84 = /^[1-9]/, + peg$c85 = peg$classExpectation([["1", "9"]], false, false), + peg$c86 = /^[0-9]/, + peg$c87 = peg$classExpectation([["0", "9"]], false, false), + peg$c88 = "T", + peg$c89 = peg$literalExpectation("T", false), + peg$c90 = function() { + var s = text(); + var date = new Date(s); + if (!isFiniteNumber(date.getTime())) { + error('Date-time ' + s + ' is invalid. It does not conform to RFC 3339 or this is a browser-specific problem.'); + } + return { + type: 'DateTime', + value: date + }; + }, + peg$c91 = peg$otherExpectation("FullDate (YYYY-mm-dd)"), + peg$c92 = ":", + peg$c93 = peg$literalExpectation(":", false), + peg$c94 = peg$otherExpectation("Hour (HH)"), + peg$c95 = peg$otherExpectation("Minute (MM)"), + peg$c96 = peg$otherExpectation("Second (SS)"), + peg$c97 = peg$otherExpectation("TimeOffset (Z or +/-HH:MM)"), + peg$c98 = "Z", + peg$c99 = peg$literalExpectation("Z", false), + peg$c100 = "[", + peg$c101 = peg$literalExpectation("[", false), + peg$c102 = ",", + peg$c103 = peg$literalExpectation(",", false), + peg$c104 = "]", + peg$c105 = peg$literalExpectation("]", false), + peg$c106 = function(values) { + var o = { + type: 'Array', + value: values ? values[0] : [] + }; + for (var i = 0, arr = o.value, l = arr.length; i < l; i++) { + arr[i] = arr[i].value; + } + return o; + }, + peg$c107 = function(value, opt) { + var array = [value]; + if (opt) { + var type = value.type; + for (var i = 0, arr = opt[3], l = arr.length; i < l; i++) { + if (type !== arr[i].type) { + error(stringify(arr[i].value) + ' should be of type "' + type + + '".'); + } + array.push(arr[i]); + } + } + return array; + }, + peg$c108 = "{", + peg$c109 = peg$literalExpectation("{", false), + peg$c110 = "}", + peg$c111 = peg$literalExpectation("}", false), + peg$c112 = function(opt) { + var table = {}; + if (opt) { + table[opt[0][0]] = opt[0][1]; + for (var i = 0, arr = opt[1], l = arr.length; i < l; i++) { + var kv = arr[i][3]; + checkTableKey(table, kv[0]); + table[kv[0]] = kv[1]; + } + } + return { + type: 'InlineTable', + value: table + }; + }, + peg$c113 = function(path) { + return path; + }, + peg$c114 = function(key, arr) { + var path = [key]; + for (var i = 0, l = arr.length; i < l; i++) { + path.push(arr[i][3]); + } + return path; + }, + + peg$currPos = 0, + peg$savedPos = 0, + peg$posDetailsCache = [{ line: 1, column: 1 }], + peg$maxFailPos = 0, + peg$maxFailExpected = [], + peg$silentFails = 0, + + peg$result; + + if ("startRule" in options) { + if (!(options.startRule in peg$startRuleFunctions)) { + throw new Error("Can't start parsing from rule \"" + options.startRule + "\"."); } - useArray(e) { - let [t, i] = c(this.root, a(e)); - return (this.data = {}), void 0 === t[i] && (t[i] = []), t[i].push(this.data), this; - } - enter(e, t) { - return this.inlineScopeList.push(this.data), this.set(e, t), (this.data = t), this; - } - enterArray(e) { - return this.inlineScopeList.push(this.data), this.push(e), (this.data = e), this; - } - exit() { - return (this.data = this.inlineScopeList.pop()), this; - } - } - function f(a) { - "string" != typeof a && (a = String(a)); - const c = new o(), f = []; - (e = a), (t$1 = 0); - let l, u, h = "", d = "", p = e[0], w = !0; - const g = () => { - if (((h = h.trimEnd()), w)) - h && c.push(n(h)); - else { - if (!h) - throw r("Expected key before ="); - if (!d) - throw r("Expected value after ="); - c.set(h, n(d.trimEnd())); + + peg$startRuleFunction = peg$startRuleFunctions[options.startRule]; + } + + function text() { + return input.substring(peg$savedPos, peg$currPos); + } + + function error(message, location) { + location = location !== void 0 ? location : peg$computeLocation(peg$savedPos, peg$currPos); + + throw peg$buildSimpleError(message, location); + } + + function peg$literalExpectation(text, ignoreCase) { + return { type: "literal", text: text, ignoreCase: ignoreCase }; + } + + function peg$classExpectation(parts, inverted, ignoreCase) { + return { type: "class", parts: parts, inverted: inverted, ignoreCase: ignoreCase }; + } + + function peg$anyExpectation() { + return { type: "any" }; + } + + function peg$endExpectation() { + return { type: "end" }; + } + + function peg$otherExpectation(description) { + return { type: "other", description: description }; + } + + function peg$computePosDetails(pos) { + var details = peg$posDetailsCache[pos], p; + + if (details) { + return details; + } else { + p = pos - 1; + while (!peg$posDetailsCache[p]) { + p--; + } + + details = peg$posDetailsCache[p]; + details = { + line: details.line, + column: details.column + }; + + while (p < pos) { + if (input.charCodeAt(p) === 10) { + details.line++; + details.column = 1; + } else { + details.column++; } - (h = ""), (d = ""), (w = !0); + + p++; + } + + peg$posDetailsCache[pos] = details; + return details; + } + } + + function peg$computeLocation(startPos, endPos) { + var startPosDetails = peg$computePosDetails(startPos), + endPosDetails = peg$computePosDetails(endPos); + + return { + start: { + offset: startPos, + line: startPosDetails.line, + column: startPosDetails.column + }, + end: { + offset: endPos, + line: endPosDetails.line, + column: endPosDetails.column + } }; - do { - switch (p) { - case " ": - w ? h && (h += p) : d && (d += p); - case "\t": - case "\r": - continue; - case "#": - (t$1 = e.indexOf("\n", t$1 + 1) - 1), -2 == t$1 && (t$1 = 1 / 0); - continue; - case '"': - case "'": - if (!w && d) { - d += p; - continue; - } - let n = e[t$1 + 1] == p && e[t$1 + 2] == p; - if (((l = s(e, t$1, !0)), w)) { - if (h) - throw r("Unexpected " + p); - (h += n ? e.slice(t$1 + 2, l - 2) : e.slice(t$1, l)), (t$1 = l); - } - else - (d = e.slice(t$1, l)), (t$1 = l), n && ((d = d.slice(2, -2)), "\n" == d[1] ? (d = d[0] + d.slice(2)) : "\r" == d[1] && "\n" == d[2] && (d = d[0] + d.slice(3))); - if (((t$1 = i$2(e, t$1)), (p = e[t$1]), p && "," != p && "\n" != p && "#" != p && "}" != p && "]" != p && "=" != p)) - throw r("Unexpected character after end of string"); - t$1--; - continue; - case "\n": - case ",": - case void 0: - g(); - continue; - case "[": - case "{": - if (((u = "[" == p ? "]" : "}"), w && !f.length)) { - if (h) - throw r("Unexpected " + p); - if (((l = s(e, t$1)), "[" == p && "[" == e[t$1 + 1])) { - if ("]" != e[l - 2]) - throw r("Missing ]]"); - c.useArray(e.slice(t$1 + 2, l - 2)); - } - else - c.use(e.slice(t$1 + 1, l - 1)); - t$1 = l; - } - else if (w) { - if (h) - throw r("Unexpected " + p); - c.enterArray("[" == p ? [] : {}), f.push(u); - } - else { - if (d) - throw r("Unexpected " + p); - c.enter(h.trimEnd(), "[" == p ? [] : {}), f.push(u), (h = ""), (w = !0); - } - continue; - case "]": - case "}": - if ((h && g(), f.pop() != p)) - throw r("Unexpected " + p); - if ((c.exit(), (t$1 = i$2(e, t$1 + 1)), (p = e[t$1]), p && "," != p && "\n" != p && "#" != p && "}" != p && "]" != p)) - throw r("Unexpected character after end of scope"); - t$1--; - continue; - case "=": - if (!w) - throw r("Unexpected " + p); - if (!h) - throw r("Missing key before " + p); - w = !1; - continue; - default: - w ? (h += p) : (d += p); - } - } while ((p = e[++t$1]) || h); - if (f.length) - throw r("Missing " + f.pop()); - return c.root; - } - function h() { - let e = ""; - for (let t of arguments) - e += "string" == typeof t ? t : t[0]; - return f(e); - } - const toml = ((h.parse = f), - h); + } - const allKeys = { - "string": ["name", "description", "version", "type", "author_name", "author_email", "license"], - "number": ["schema_version"], - "boolean": ["autoclose_loader"], - "array": ["runtimes", "packages", "paths", "plugins"] - }; - const defaultConfig$1 = { - "schema_version": 1, - "type": "app", - "autoclose_loader": true, - "runtimes": [{ - "src": "https://cdn.jsdelivr.net/pyodide/v0.21.2/full/pyodide.js", - "name": "pyodide-0.21.2", - "lang": "python" - }], - "packages": [], - "paths": [], - "plugins": [] - }; - function addClasses(element, classes) { - for (const entry of classes) { - element.classList.add(entry); + function peg$fail(expected) { + if (peg$currPos < peg$maxFailPos) { return; } + + if (peg$currPos > peg$maxFailPos) { + peg$maxFailPos = peg$currPos; + peg$maxFailExpected = []; } - } - function removeClasses(element, classes) { - for (const entry of classes) { - element.classList.remove(entry); + + peg$maxFailExpected.push(expected); + } + + function peg$buildSimpleError(message, location) { + return new peg$SyntaxError(message, null, null, location); + } + + function peg$buildStructuredError(expected, found, location) { + return new peg$SyntaxError( + peg$SyntaxError.buildMessage(expected, found), + expected, + found, + location + ); + } + + function peg$parseExpressions() { + var s0, s1, s2, s3, s4, s5, s6, s7; + + s0 = peg$currPos; + s1 = []; + s2 = peg$parseWhitespace(); + if (s2 === peg$FAILED) { + s2 = peg$parseNewline(); + if (s2 === peg$FAILED) { + s2 = peg$parseComment(); + } } - } - function getLastPath(str) { - return str.split('\\').pop().split('/').pop(); - } - function escape(str) { - return str.replace(/</g, "<").replace(/>/g, ">"); - } - function htmlDecode(input) { - const doc = new DOMParser().parseFromString(ltrim(escape(input)), 'text/html'); - return doc.documentElement.textContent; - } - function ltrim(code) { - const lines = code.split('\n'); - if (lines.length == 0) - return code; - const lengths = lines - .filter(line => line.trim().length != 0) - .map(line => { - const [prefix] = line.match(/^\s*/); - return prefix.length; - }); - const k = Math.min(...lengths); - return k != 0 ? lines.map(line => line.substring(k)).join('\n') - : code; - } - function guidGenerator() { - const S4 = function () { - return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1); + while (s2 !== peg$FAILED) { + s1.push(s2); + s2 = peg$parseWhitespace(); + if (s2 === peg$FAILED) { + s2 = peg$parseNewline(); + if (s2 === peg$FAILED) { + s2 = peg$parseComment(); + } + } + } + if (s1 !== peg$FAILED) { + s2 = peg$currPos; + s3 = peg$parseExpression(); + if (s3 !== peg$FAILED) { + s4 = []; + s5 = peg$parseWhitespace(); + if (s5 === peg$FAILED) { + s5 = peg$parseComment(); + } + while (s5 !== peg$FAILED) { + s4.push(s5); + s5 = peg$parseWhitespace(); + if (s5 === peg$FAILED) { + s5 = peg$parseComment(); + } + } + if (s4 !== peg$FAILED) { + s5 = peg$currPos; + s6 = peg$parseNewline(); + if (s6 !== peg$FAILED) { + s7 = peg$parseExpressions(); + if (s7 !== peg$FAILED) { + s6 = [s6, s7]; + s5 = s6; + } else { + peg$currPos = s5; + s5 = peg$FAILED; + } + } else { + peg$currPos = s5; + s5 = peg$FAILED; + } + if (s5 === peg$FAILED) { + s5 = null; + } + if (s5 !== peg$FAILED) { + s3 = [s3, s4, s5]; + s2 = s3; + } else { + peg$currPos = s2; + s2 = peg$FAILED; + } + } else { + peg$currPos = s2; + s2 = peg$FAILED; + } + } else { + peg$currPos = s2; + s2 = peg$FAILED; + } + if (s2 === peg$FAILED) { + s2 = null; + } + if (s2 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c0(); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + + return s0; + } + + function peg$parseExpression() { + var s0, s1; + + s0 = peg$currPos; + s1 = peg$parseTableArrayHeader(); + if (s1 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c1(s1); + } + s0 = s1; + if (s0 === peg$FAILED) { + s0 = peg$currPos; + s1 = peg$parseTableHeader(); + if (s1 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c2(s1); + } + s0 = s1; + if (s0 === peg$FAILED) { + s0 = peg$currPos; + s1 = peg$parseKeyValue(); + if (s1 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c3(s1); + } + s0 = s1; + } + } + + return s0; + } + + function peg$parseNewline() { + var s0; + + peg$silentFails++; + if (input.charCodeAt(peg$currPos) === 10) { + s0 = peg$c5; + peg$currPos++; + } else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c6); } + } + if (s0 === peg$FAILED) { + if (input.substr(peg$currPos, 2) === peg$c7) { + s0 = peg$c7; + peg$currPos += 2; + } else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c8); } + } + } + peg$silentFails--; + if (s0 === peg$FAILED) { + if (peg$silentFails === 0) { peg$fail(peg$c4); } + } + + return s0; + } + + function peg$parseWhitespace() { + var s0; + + peg$silentFails++; + if (peg$c10.test(input.charAt(peg$currPos))) { + s0 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c11); } + } + peg$silentFails--; + if (s0 === peg$FAILED) { + if (peg$silentFails === 0) { peg$fail(peg$c9); } + } + + return s0; + } + + function peg$parseComment() { + var s0, s1, s2, s3, s4, s5; + + peg$silentFails++; + s0 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 35) { + s1 = peg$c13; + peg$currPos++; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c14); } + } + if (s1 !== peg$FAILED) { + s2 = []; + s3 = peg$currPos; + s4 = peg$currPos; + peg$silentFails++; + s5 = peg$parseNewline(); + peg$silentFails--; + if (s5 === peg$FAILED) { + s4 = void 0; + } else { + peg$currPos = s4; + s4 = peg$FAILED; + } + if (s4 !== peg$FAILED) { + if (input.length > peg$currPos) { + s5 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s5 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c15); } + } + if (s5 !== peg$FAILED) { + s4 = [s4, s5]; + s3 = s4; + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + while (s3 !== peg$FAILED) { + s2.push(s3); + s3 = peg$currPos; + s4 = peg$currPos; + peg$silentFails++; + s5 = peg$parseNewline(); + peg$silentFails--; + if (s5 === peg$FAILED) { + s4 = void 0; + } else { + peg$currPos = s4; + s4 = peg$FAILED; + } + if (s4 !== peg$FAILED) { + if (input.length > peg$currPos) { + s5 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s5 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c15); } + } + if (s5 !== peg$FAILED) { + s4 = [s4, s5]; + s3 = s4; + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } + if (s2 !== peg$FAILED) { + s1 = [s1, s2]; + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + peg$silentFails--; + if (s0 === peg$FAILED) { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c12); } + } + + return s0; + } + + function peg$parseKeyValue() { + var s0, s1, s2, s3, s4, s5; + + s0 = peg$currPos; + s1 = peg$parseKey(); + if (s1 !== peg$FAILED) { + s2 = []; + s3 = peg$parseWhitespace(); + while (s3 !== peg$FAILED) { + s2.push(s3); + s3 = peg$parseWhitespace(); + } + if (s2 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 61) { + s3 = peg$c16; + peg$currPos++; + } else { + s3 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c17); } + } + if (s3 !== peg$FAILED) { + s4 = []; + s5 = peg$parseWhitespace(); + while (s5 !== peg$FAILED) { + s4.push(s5); + s5 = peg$parseWhitespace(); + } + if (s4 !== peg$FAILED) { + s5 = peg$parseValue(); + if (s5 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c18(s1, s5); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + + return s0; + } + + function peg$parseKey() { + var s0; + + s0 = peg$parseBareKey(); + if (s0 === peg$FAILED) { + s0 = peg$parseQuotedKey(); + } + + return s0; + } + + function peg$parseBareKey() { + var s0, s1, s2; + + s0 = peg$currPos; + s1 = []; + s2 = peg$parseBareKeyCharacter(); + if (s2 !== peg$FAILED) { + while (s2 !== peg$FAILED) { + s1.push(s2); + s2 = peg$parseBareKeyCharacter(); + } + } else { + s1 = peg$FAILED; + } + if (s1 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c19(); + } + s0 = s1; + + return s0; + } + + function peg$parseBareKeyCharacter() { + var s0; + + peg$silentFails++; + if (peg$c21.test(input.charAt(peg$currPos))) { + s0 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c22); } + } + peg$silentFails--; + if (s0 === peg$FAILED) { + if (peg$silentFails === 0) { peg$fail(peg$c20); } + } + + return s0; + } + + function peg$parseQuotedKey() { + var s0, s1, s2, s3; + + s0 = peg$currPos; + s1 = peg$parseDoubleQuote(); + if (s1 !== peg$FAILED) { + s2 = []; + s3 = peg$parseBasicCharacter(); + if (s3 !== peg$FAILED) { + while (s3 !== peg$FAILED) { + s2.push(s3); + s3 = peg$parseBasicCharacter(); + } + } else { + s2 = peg$FAILED; + } + if (s2 !== peg$FAILED) { + s3 = peg$parseDoubleQuote(); + if (s3 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c23(s2); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + + return s0; + } + + function peg$parseDoubleQuote() { + var s0; + + peg$silentFails++; + if (input.charCodeAt(peg$currPos) === 34) { + s0 = peg$c25; + peg$currPos++; + } else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c26); } + } + peg$silentFails--; + if (s0 === peg$FAILED) { + if (peg$silentFails === 0) { peg$fail(peg$c24); } + } + + return s0; + } + + function peg$parseSingleQuote() { + var s0; + + peg$silentFails++; + if (input.charCodeAt(peg$currPos) === 39) { + s0 = peg$c28; + peg$currPos++; + } else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c29); } + } + peg$silentFails--; + if (s0 === peg$FAILED) { + if (peg$silentFails === 0) { peg$fail(peg$c27); } + } + + return s0; + } + + function peg$parseThreeDoubleQuotes() { + var s0; + + peg$silentFails++; + if (input.substr(peg$currPos, 3) === peg$c31) { + s0 = peg$c31; + peg$currPos += 3; + } else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c32); } + } + peg$silentFails--; + if (s0 === peg$FAILED) { + if (peg$silentFails === 0) { peg$fail(peg$c30); } + } + + return s0; + } + + function peg$parseThreeSingleQuotes() { + var s0; + + peg$silentFails++; + if (input.substr(peg$currPos, 3) === peg$c34) { + s0 = peg$c34; + peg$currPos += 3; + } else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c35); } + } + peg$silentFails--; + if (s0 === peg$FAILED) { + if (peg$silentFails === 0) { peg$fail(peg$c33); } + } + + return s0; + } + + function peg$parseValue() { + var s0; + + s0 = peg$parseString(); + if (s0 === peg$FAILED) { + s0 = peg$parseBoolean(); + if (s0 === peg$FAILED) { + s0 = peg$parseDateTime(); + if (s0 === peg$FAILED) { + s0 = peg$parseFloat(); + if (s0 === peg$FAILED) { + s0 = peg$parseInteger(); + if (s0 === peg$FAILED) { + s0 = peg$parseArray(); + if (s0 === peg$FAILED) { + s0 = peg$parseInlineTable(); + } + } + } + } + } + } + + return s0; + } + + function peg$parseString() { + var s0; + + s0 = peg$parseMultilineBasicString(); + if (s0 === peg$FAILED) { + s0 = peg$parseBasicString(); + if (s0 === peg$FAILED) { + s0 = peg$parseMultilineLiteralString(); + if (s0 === peg$FAILED) { + s0 = peg$parseLiteralString(); + } + } + } + + return s0; + } + + function peg$parseBasicString() { + var s0, s1, s2, s3; + + s0 = peg$currPos; + s1 = peg$parseDoubleQuote(); + if (s1 !== peg$FAILED) { + s2 = []; + s3 = peg$parseBasicCharacter(); + while (s3 !== peg$FAILED) { + s2.push(s3); + s3 = peg$parseBasicCharacter(); + } + if (s2 !== peg$FAILED) { + s3 = peg$parseDoubleQuote(); + if (s3 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c36(s2); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + + return s0; + } + + function peg$parseBasicCharacter() { + var s0; + + s0 = peg$parseNormalCharacter(); + if (s0 === peg$FAILED) { + s0 = peg$parseEscapedCharacter(); + } + + return s0; + } + + function peg$parseNormalCharacter() { + var s0, s1, s2; + + peg$silentFails++; + s0 = peg$currPos; + s1 = peg$currPos; + peg$silentFails++; + s2 = peg$parseNewline(); + peg$silentFails--; + if (s2 === peg$FAILED) { + s1 = void 0; + } else { + peg$currPos = s1; + s1 = peg$FAILED; + } + if (s1 !== peg$FAILED) { + if (peg$c38.test(input.charAt(peg$currPos))) { + s2 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c39); } + } + if (s2 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c19(); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + peg$silentFails--; + if (s0 === peg$FAILED) { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c37); } + } + + return s0; + } + + function peg$parseEscapedCharacter() { + var s0, s1, s2, s3, s4; + + s0 = peg$currPos; + s1 = peg$parseBackslash(); + if (s1 !== peg$FAILED) { + s2 = peg$parseControlCharacter(); + if (s2 === peg$FAILED) { + s2 = peg$parseDoubleQuote(); + if (s2 === peg$FAILED) { + s2 = peg$parseBackslash(); + if (s2 === peg$FAILED) { + s2 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 117) { + s3 = peg$c40; + peg$currPos++; + } else { + s3 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c41); } + } + if (s3 !== peg$FAILED) { + s4 = peg$parseFourHexadecimalDigits(); + if (s4 !== peg$FAILED) { + s3 = [s3, s4]; + s2 = s3; + } else { + peg$currPos = s2; + s2 = peg$FAILED; + } + } else { + peg$currPos = s2; + s2 = peg$FAILED; + } + if (s2 === peg$FAILED) { + s2 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 85) { + s3 = peg$c42; + peg$currPos++; + } else { + s3 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c43); } + } + if (s3 !== peg$FAILED) { + s4 = peg$parseEightHexadecimalDigits(); + if (s4 !== peg$FAILED) { + s3 = [s3, s4]; + s2 = s3; + } else { + peg$currPos = s2; + s2 = peg$FAILED; + } + } else { + peg$currPos = s2; + s2 = peg$FAILED; + } + } + } + } + } + if (s2 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c44(); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + + return s0; + } + + function peg$parseControlCharacter() { + var s0; + + peg$silentFails++; + if (peg$c46.test(input.charAt(peg$currPos))) { + s0 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c47); } + } + peg$silentFails--; + if (s0 === peg$FAILED) { + if (peg$silentFails === 0) { peg$fail(peg$c45); } + } + + return s0; + } + + function peg$parseBackslash() { + var s0; + + peg$silentFails++; + if (input.charCodeAt(peg$currPos) === 92) { + s0 = peg$c49; + peg$currPos++; + } else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c50); } + } + peg$silentFails--; + if (s0 === peg$FAILED) { + if (peg$silentFails === 0) { peg$fail(peg$c48); } + } + + return s0; + } + + function peg$parseFourHexadecimalDigits() { + var s0, s1, s2, s3, s4; + + peg$silentFails++; + s0 = peg$currPos; + s1 = peg$parseHexDigit(); + if (s1 !== peg$FAILED) { + s2 = peg$parseHexDigit(); + if (s2 !== peg$FAILED) { + s3 = peg$parseHexDigit(); + if (s3 !== peg$FAILED) { + s4 = peg$parseHexDigit(); + if (s4 !== peg$FAILED) { + s1 = [s1, s2, s3, s4]; + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + peg$silentFails--; + if (s0 === peg$FAILED) { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c51); } + } + + return s0; + } + + function peg$parseEightHexadecimalDigits() { + var s0, s1, s2, s3, s4, s5, s6, s7, s8; + + peg$silentFails++; + s0 = peg$currPos; + s1 = peg$parseHexDigit(); + if (s1 !== peg$FAILED) { + s2 = peg$parseHexDigit(); + if (s2 !== peg$FAILED) { + s3 = peg$parseHexDigit(); + if (s3 !== peg$FAILED) { + s4 = peg$parseHexDigit(); + if (s4 !== peg$FAILED) { + s5 = peg$parseHexDigit(); + if (s5 !== peg$FAILED) { + s6 = peg$parseHexDigit(); + if (s6 !== peg$FAILED) { + s7 = peg$parseHexDigit(); + if (s7 !== peg$FAILED) { + s8 = peg$parseHexDigit(); + if (s8 !== peg$FAILED) { + s1 = [s1, s2, s3, s4, s5, s6, s7, s8]; + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + peg$silentFails--; + if (s0 === peg$FAILED) { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c52); } + } + + return s0; + } + + function peg$parseHexDigit() { + var s0; + + if (peg$c53.test(input.charAt(peg$currPos))) { + s0 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c54); } + } + + return s0; + } + + function peg$parseLiteralString() { + var s0, s1, s2, s3; + + s0 = peg$currPos; + s1 = peg$parseSingleQuote(); + if (s1 !== peg$FAILED) { + s2 = []; + s3 = peg$parseLiteralCharacter(); + while (s3 !== peg$FAILED) { + s2.push(s3); + s3 = peg$parseLiteralCharacter(); + } + if (s2 !== peg$FAILED) { + s3 = peg$parseSingleQuote(); + if (s3 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c55(); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + + return s0; + } + + function peg$parseLiteralCharacter() { + var s0, s1, s2; + + peg$silentFails++; + s0 = peg$currPos; + s1 = peg$currPos; + peg$silentFails++; + s2 = peg$parseNewline(); + peg$silentFails--; + if (s2 === peg$FAILED) { + s1 = void 0; + } else { + peg$currPos = s1; + s1 = peg$FAILED; + } + if (s1 !== peg$FAILED) { + if (peg$c56.test(input.charAt(peg$currPos))) { + s2 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c57); } + } + if (s2 !== peg$FAILED) { + s1 = [s1, s2]; + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + peg$silentFails--; + if (s0 === peg$FAILED) { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c37); } + } + + return s0; + } + + function peg$parseMultilineBasicString() { + var s0, s1, s2, s3, s4; + + s0 = peg$currPos; + s1 = peg$parseThreeDoubleQuotes(); + if (s1 !== peg$FAILED) { + s2 = peg$parseNewline(); + if (s2 === peg$FAILED) { + s2 = null; + } + if (s2 !== peg$FAILED) { + s3 = []; + s4 = peg$parseMultilineBasicText(); + while (s4 !== peg$FAILED) { + s3.push(s4); + s4 = peg$parseMultilineBasicText(); + } + if (s3 !== peg$FAILED) { + s4 = peg$parseThreeDoubleQuotes(); + if (s4 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c58(s3); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + + return s0; + } + + function peg$parseMultilineBasicText() { + var s0, s1, s2; + + s0 = peg$parseMultilineBasicCharacter(); + if (s0 === peg$FAILED) { + s0 = peg$currPos; + s1 = peg$parseBackslash(); + if (s1 !== peg$FAILED) { + s2 = peg$parseNewline(); + if (s2 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c19(); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + if (s0 === peg$FAILED) { + s0 = peg$parseNewline(); + } + } + + return s0; + } + + function peg$parseMultilineBasicCharacter() { + var s0, s1, s2; + + s0 = peg$currPos; + s1 = peg$currPos; + peg$silentFails++; + s2 = peg$parseThreeDoubleQuotes(); + peg$silentFails--; + if (s2 === peg$FAILED) { + s1 = void 0; + } else { + peg$currPos = s1; + s1 = peg$FAILED; + } + if (s1 !== peg$FAILED) { + s2 = peg$parseMultilineNormalCharacter(); + if (s2 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c19(); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + if (s0 === peg$FAILED) { + s0 = peg$parseEscapedCharacter(); + } + + return s0; + } + + function peg$parseMultilineNormalCharacter() { + var s0, s1, s2; + + peg$silentFails++; + s0 = peg$currPos; + s1 = peg$currPos; + peg$silentFails++; + s2 = peg$parseNewline(); + peg$silentFails--; + if (s2 === peg$FAILED) { + s1 = void 0; + } else { + peg$currPos = s1; + s1 = peg$FAILED; + } + if (s1 !== peg$FAILED) { + if (peg$c59.test(input.charAt(peg$currPos))) { + s2 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c60); } + } + if (s2 !== peg$FAILED) { + s1 = [s1, s2]; + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + peg$silentFails--; + if (s0 === peg$FAILED) { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c37); } + } + + return s0; + } + + function peg$parseMultilineLiteralString() { + var s0, s1, s2, s3, s4; + + s0 = peg$currPos; + s1 = peg$parseThreeSingleQuotes(); + if (s1 !== peg$FAILED) { + s2 = peg$parseNewline(); + if (s2 === peg$FAILED) { + s2 = null; + } + if (s2 !== peg$FAILED) { + s3 = []; + s4 = peg$parseMultilineLiteralText(); + while (s4 !== peg$FAILED) { + s3.push(s4); + s4 = peg$parseMultilineLiteralText(); + } + if (s3 !== peg$FAILED) { + s4 = peg$parseThreeSingleQuotes(); + if (s4 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c36(s3); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + + return s0; + } + + function peg$parseMultilineLiteralText() { + var s0, s1, s2; + + s0 = peg$currPos; + s1 = peg$currPos; + peg$silentFails++; + if (input.substr(peg$currPos, 3) === peg$c34) { + s2 = peg$c34; + peg$currPos += 3; + } else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c35); } + } + peg$silentFails--; + if (s2 === peg$FAILED) { + s1 = void 0; + } else { + peg$currPos = s1; + s1 = peg$FAILED; + } + if (s1 !== peg$FAILED) { + s2 = peg$parseMultilineLiteralCharacter(); + if (s2 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c19(); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + if (s0 === peg$FAILED) { + s0 = peg$parseNewline(); + } + + return s0; + } + + function peg$parseMultilineLiteralCharacter() { + var s0, s1, s2; + + peg$silentFails++; + s0 = peg$currPos; + s1 = peg$currPos; + peg$silentFails++; + s2 = peg$parseNewline(); + peg$silentFails--; + if (s2 === peg$FAILED) { + s1 = void 0; + } else { + peg$currPos = s1; + s1 = peg$FAILED; + } + if (s1 !== peg$FAILED) { + if (peg$c62.test(input.charAt(peg$currPos))) { + s2 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c63); } + } + if (s2 !== peg$FAILED) { + s1 = [s1, s2]; + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + peg$silentFails--; + if (s0 === peg$FAILED) { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c61); } + } + + return s0; + } + + function peg$parseBoolean() { + var s0, s1; + + s0 = peg$currPos; + if (input.substr(peg$currPos, 4) === peg$c64) { + s1 = peg$c64; + peg$currPos += 4; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c65); } + } + if (s1 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c66(); + } + s0 = s1; + if (s0 === peg$FAILED) { + s0 = peg$currPos; + if (input.substr(peg$currPos, 5) === peg$c67) { + s1 = peg$c67; + peg$currPos += 5; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c68); } + } + if (s1 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c69(); + } + s0 = s1; + } + + return s0; + } + + function peg$parseFloat() { + var s0, s1, s2, s3, s4; + + s0 = peg$currPos; + s1 = peg$parseInteger(); + if (s1 !== peg$FAILED) { + s2 = peg$currPos; + s3 = peg$parseFraction(); + if (s3 !== peg$FAILED) { + s4 = peg$parseExponent(); + if (s4 === peg$FAILED) { + s4 = null; + } + if (s4 !== peg$FAILED) { + s3 = [s3, s4]; + s2 = s3; + } else { + peg$currPos = s2; + s2 = peg$FAILED; + } + } else { + peg$currPos = s2; + s2 = peg$FAILED; + } + if (s2 === peg$FAILED) { + s2 = peg$parseExponent(); + } + if (s2 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c70(); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + + return s0; + } + + function peg$parseFraction() { + var s0, s1, s2, s3, s4, s5, s6; + + s0 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 46) { + s1 = peg$c71; + peg$currPos++; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c72); } + } + if (s1 !== peg$FAILED) { + s2 = peg$parseDigit(); + if (s2 !== peg$FAILED) { + s3 = []; + s4 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 95) { + s5 = peg$c73; + peg$currPos++; + } else { + s5 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c74); } + } + if (s5 === peg$FAILED) { + s5 = null; + } + if (s5 !== peg$FAILED) { + s6 = peg$parseDigit(); + if (s6 !== peg$FAILED) { + s5 = [s5, s6]; + s4 = s5; + } else { + peg$currPos = s4; + s4 = peg$FAILED; + } + } else { + peg$currPos = s4; + s4 = peg$FAILED; + } + while (s4 !== peg$FAILED) { + s3.push(s4); + s4 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 95) { + s5 = peg$c73; + peg$currPos++; + } else { + s5 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c74); } + } + if (s5 === peg$FAILED) { + s5 = null; + } + if (s5 !== peg$FAILED) { + s6 = peg$parseDigit(); + if (s6 !== peg$FAILED) { + s5 = [s5, s6]; + s4 = s5; + } else { + peg$currPos = s4; + s4 = peg$FAILED; + } + } else { + peg$currPos = s4; + s4 = peg$FAILED; + } + } + if (s3 !== peg$FAILED) { + s1 = [s1, s2, s3]; + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + + return s0; + } + + function peg$parseExponent() { + var s0, s1, s2; + + s0 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 101) { + s1 = peg$c75; + peg$currPos++; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c76); } + } + if (s1 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 69) { + s1 = peg$c77; + peg$currPos++; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c78); } + } + } + if (s1 !== peg$FAILED) { + s2 = peg$parseInteger(); + if (s2 !== peg$FAILED) { + s1 = [s1, s2]; + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + + return s0; + } + + function peg$parseInteger() { + var s0, s1, s2; + + s0 = peg$currPos; + s1 = peg$parseSign(); + if (s1 === peg$FAILED) { + s1 = null; + } + if (s1 !== peg$FAILED) { + s2 = peg$parseIntDigits(); + if (s2 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c79(); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + + return s0; + } + + function peg$parseSign() { + var s0; + + if (input.charCodeAt(peg$currPos) === 43) { + s0 = peg$c80; + peg$currPos++; + } else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c81); } + } + if (s0 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 45) { + s0 = peg$c82; + peg$currPos++; + } else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c83); } + } + } + + return s0; + } + + function peg$parseIntDigits() { + var s0, s1, s2, s3, s4, s5; + + s0 = peg$currPos; + s1 = peg$parseDigit_1to9(); + if (s1 !== peg$FAILED) { + s2 = []; + s3 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 95) { + s4 = peg$c73; + peg$currPos++; + } else { + s4 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c74); } + } + if (s4 === peg$FAILED) { + s4 = null; + } + if (s4 !== peg$FAILED) { + s5 = peg$parseDigit(); + if (s5 !== peg$FAILED) { + s4 = [s4, s5]; + s3 = s4; + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + if (s3 !== peg$FAILED) { + while (s3 !== peg$FAILED) { + s2.push(s3); + s3 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 95) { + s4 = peg$c73; + peg$currPos++; + } else { + s4 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c74); } + } + if (s4 === peg$FAILED) { + s4 = null; + } + if (s4 !== peg$FAILED) { + s5 = peg$parseDigit(); + if (s5 !== peg$FAILED) { + s4 = [s4, s5]; + s3 = s4; + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } + } else { + s2 = peg$FAILED; + } + if (s2 !== peg$FAILED) { + s1 = [s1, s2]; + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + if (s0 === peg$FAILED) { + s0 = peg$parseDigit(); + } + + return s0; + } + + function peg$parseDigit_1to9() { + var s0; + + if (peg$c84.test(input.charAt(peg$currPos))) { + s0 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c85); } + } + + return s0; + } + + function peg$parseDigit() { + var s0; + + if (peg$c86.test(input.charAt(peg$currPos))) { + s0 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c87); } + } + + return s0; + } + + function peg$parseDateTime() { + var s0, s1, s2, s3; + + s0 = peg$currPos; + s1 = peg$parseFullDate(); + if (s1 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 84) { + s2 = peg$c88; + peg$currPos++; + } else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c89); } + } + if (s2 !== peg$FAILED) { + s3 = peg$parseFullTime(); + if (s3 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c90(); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + + return s0; + } + + function peg$parseFullDate() { + var s0, s1, s2, s3, s4, s5; + + peg$silentFails++; + s0 = peg$currPos; + s1 = peg$parseYear(); + if (s1 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 45) { + s2 = peg$c82; + peg$currPos++; + } else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c83); } + } + if (s2 !== peg$FAILED) { + s3 = peg$parseMonth(); + if (s3 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 45) { + s4 = peg$c82; + peg$currPos++; + } else { + s4 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c83); } + } + if (s4 !== peg$FAILED) { + s5 = peg$parseMDay(); + if (s5 !== peg$FAILED) { + s1 = [s1, s2, s3, s4, s5]; + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + peg$silentFails--; + if (s0 === peg$FAILED) { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c91); } + } + + return s0; + } + + function peg$parseYear() { + var s0, s1, s2, s3, s4; + + s0 = peg$currPos; + s1 = peg$parseDigit(); + if (s1 !== peg$FAILED) { + s2 = peg$parseDigit(); + if (s2 !== peg$FAILED) { + s3 = peg$parseDigit(); + if (s3 !== peg$FAILED) { + s4 = peg$parseDigit(); + if (s4 !== peg$FAILED) { + s1 = [s1, s2, s3, s4]; + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + + return s0; + } + + function peg$parseMonth() { + var s0, s1, s2; + + s0 = peg$currPos; + s1 = peg$parseDigit(); + if (s1 !== peg$FAILED) { + s2 = peg$parseDigit(); + if (s2 !== peg$FAILED) { + s1 = [s1, s2]; + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + + return s0; + } + + function peg$parseMDay() { + var s0, s1, s2; + + s0 = peg$currPos; + s1 = peg$parseDigit(); + if (s1 !== peg$FAILED) { + s2 = peg$parseDigit(); + if (s2 !== peg$FAILED) { + s1 = [s1, s2]; + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + + return s0; + } + + function peg$parseFullTime() { + var s0, s1, s2; + + s0 = peg$currPos; + s1 = peg$parseTime(); + if (s1 !== peg$FAILED) { + s2 = peg$parseTimeOffset(); + if (s2 !== peg$FAILED) { + s1 = [s1, s2]; + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + + return s0; + } + + function peg$parseTime() { + var s0, s1, s2, s3, s4, s5, s6; + + s0 = peg$currPos; + s1 = peg$parseHour(); + if (s1 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 58) { + s2 = peg$c92; + peg$currPos++; + } else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c93); } + } + if (s2 !== peg$FAILED) { + s3 = peg$parseMinute(); + if (s3 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 58) { + s4 = peg$c92; + peg$currPos++; + } else { + s4 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c93); } + } + if (s4 !== peg$FAILED) { + s5 = peg$parseSecond(); + if (s5 !== peg$FAILED) { + s6 = peg$parseSecondFraction(); + if (s6 === peg$FAILED) { + s6 = null; + } + if (s6 !== peg$FAILED) { + s1 = [s1, s2, s3, s4, s5, s6]; + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + + return s0; + } + + function peg$parseHour() { + var s0, s1, s2; + + peg$silentFails++; + s0 = peg$currPos; + s1 = peg$parseDigit(); + if (s1 !== peg$FAILED) { + s2 = peg$parseDigit(); + if (s2 !== peg$FAILED) { + s1 = [s1, s2]; + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + peg$silentFails--; + if (s0 === peg$FAILED) { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c94); } + } + + return s0; + } + + function peg$parseMinute() { + var s0, s1, s2; + + peg$silentFails++; + s0 = peg$currPos; + s1 = peg$parseDigit(); + if (s1 !== peg$FAILED) { + s2 = peg$parseDigit(); + if (s2 !== peg$FAILED) { + s1 = [s1, s2]; + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + peg$silentFails--; + if (s0 === peg$FAILED) { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c95); } + } + + return s0; + } + + function peg$parseSecond() { + var s0, s1, s2; + + peg$silentFails++; + s0 = peg$currPos; + s1 = peg$parseDigit(); + if (s1 !== peg$FAILED) { + s2 = peg$parseDigit(); + if (s2 !== peg$FAILED) { + s1 = [s1, s2]; + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + peg$silentFails--; + if (s0 === peg$FAILED) { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c96); } + } + + return s0; + } + + function peg$parseSecondFraction() { + var s0, s1, s2, s3; + + s0 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 46) { + s1 = peg$c71; + peg$currPos++; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c72); } + } + if (s1 !== peg$FAILED) { + s2 = []; + s3 = peg$parseDigit(); + if (s3 !== peg$FAILED) { + while (s3 !== peg$FAILED) { + s2.push(s3); + s3 = peg$parseDigit(); + } + } else { + s2 = peg$FAILED; + } + if (s2 !== peg$FAILED) { + s1 = [s1, s2]; + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + + return s0; + } + + function peg$parseTimeOffset() { + var s0, s1, s2, s3, s4; + + peg$silentFails++; + if (input.charCodeAt(peg$currPos) === 90) { + s0 = peg$c98; + peg$currPos++; + } else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c99); } + } + if (s0 === peg$FAILED) { + s0 = peg$currPos; + s1 = peg$parseSign(); + if (s1 !== peg$FAILED) { + s2 = peg$parseHour(); + if (s2 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 58) { + s3 = peg$c92; + peg$currPos++; + } else { + s3 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c93); } + } + if (s3 !== peg$FAILED) { + s4 = peg$parseMinute(); + if (s4 !== peg$FAILED) { + s1 = [s1, s2, s3, s4]; + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + peg$silentFails--; + if (s0 === peg$FAILED) { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c97); } + } + + return s0; + } + + function peg$parseArray() { + var s0, s1, s2, s3, s4, s5, s6, s7, s8, s9; + + s0 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 91) { + s1 = peg$c100; + peg$currPos++; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c101); } + } + if (s1 !== peg$FAILED) { + s2 = []; + s3 = peg$parseArraySpace(); + while (s3 !== peg$FAILED) { + s2.push(s3); + s3 = peg$parseArraySpace(); + } + if (s2 !== peg$FAILED) { + s3 = peg$currPos; + s4 = peg$parseArrayValue(); + if (s4 !== peg$FAILED) { + s5 = []; + s6 = peg$parseArraySpace(); + while (s6 !== peg$FAILED) { + s5.push(s6); + s6 = peg$parseArraySpace(); + } + if (s5 !== peg$FAILED) { + s6 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 44) { + s7 = peg$c102; + peg$currPos++; + } else { + s7 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c103); } + } + if (s7 !== peg$FAILED) { + s8 = []; + s9 = peg$parseArraySpace(); + while (s9 !== peg$FAILED) { + s8.push(s9); + s9 = peg$parseArraySpace(); + } + if (s8 !== peg$FAILED) { + s7 = [s7, s8]; + s6 = s7; + } else { + peg$currPos = s6; + s6 = peg$FAILED; + } + } else { + peg$currPos = s6; + s6 = peg$FAILED; + } + if (s6 === peg$FAILED) { + s6 = null; + } + if (s6 !== peg$FAILED) { + s4 = [s4, s5, s6]; + s3 = s4; + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + if (s3 === peg$FAILED) { + s3 = null; + } + if (s3 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 93) { + s4 = peg$c104; + peg$currPos++; + } else { + s4 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c105); } + } + if (s4 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c106(s3); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + + return s0; + } + + function peg$parseArrayValue() { + var s0, s1, s2, s3, s4, s5, s6; + + s0 = peg$currPos; + s1 = peg$parseValue(); + if (s1 !== peg$FAILED) { + s2 = peg$currPos; + s3 = []; + s4 = peg$parseArraySpace(); + while (s4 !== peg$FAILED) { + s3.push(s4); + s4 = peg$parseArraySpace(); + } + if (s3 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 44) { + s4 = peg$c102; + peg$currPos++; + } else { + s4 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c103); } + } + if (s4 !== peg$FAILED) { + s5 = []; + s6 = peg$parseArraySpace(); + while (s6 !== peg$FAILED) { + s5.push(s6); + s6 = peg$parseArraySpace(); + } + if (s5 !== peg$FAILED) { + s6 = peg$parseArrayValue(); + if (s6 !== peg$FAILED) { + s3 = [s3, s4, s5, s6]; + s2 = s3; + } else { + peg$currPos = s2; + s2 = peg$FAILED; + } + } else { + peg$currPos = s2; + s2 = peg$FAILED; + } + } else { + peg$currPos = s2; + s2 = peg$FAILED; + } + } else { + peg$currPos = s2; + s2 = peg$FAILED; + } + if (s2 === peg$FAILED) { + s2 = null; + } + if (s2 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c107(s1, s2); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + + return s0; + } + + function peg$parseArraySpace() { + var s0; + + s0 = peg$parseWhitespace(); + if (s0 === peg$FAILED) { + s0 = peg$parseNewline(); + if (s0 === peg$FAILED) { + s0 = peg$parseComment(); + } + } + + return s0; + } + + function peg$parseInlineTable() { + var s0, s1, s2, s3, s4, s5, s6, s7, s8, s9, s10; + + s0 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 123) { + s1 = peg$c108; + peg$currPos++; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c109); } + } + if (s1 !== peg$FAILED) { + s2 = []; + s3 = peg$parseWhitespace(); + while (s3 !== peg$FAILED) { + s2.push(s3); + s3 = peg$parseWhitespace(); + } + if (s2 !== peg$FAILED) { + s3 = peg$currPos; + s4 = peg$parseKeyValue(); + if (s4 !== peg$FAILED) { + s5 = []; + s6 = peg$currPos; + s7 = []; + s8 = peg$parseWhitespace(); + while (s8 !== peg$FAILED) { + s7.push(s8); + s8 = peg$parseWhitespace(); + } + if (s7 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 44) { + s8 = peg$c102; + peg$currPos++; + } else { + s8 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c103); } + } + if (s8 !== peg$FAILED) { + s9 = []; + s10 = peg$parseWhitespace(); + while (s10 !== peg$FAILED) { + s9.push(s10); + s10 = peg$parseWhitespace(); + } + if (s9 !== peg$FAILED) { + s10 = peg$parseKeyValue(); + if (s10 !== peg$FAILED) { + s7 = [s7, s8, s9, s10]; + s6 = s7; + } else { + peg$currPos = s6; + s6 = peg$FAILED; + } + } else { + peg$currPos = s6; + s6 = peg$FAILED; + } + } else { + peg$currPos = s6; + s6 = peg$FAILED; + } + } else { + peg$currPos = s6; + s6 = peg$FAILED; + } + while (s6 !== peg$FAILED) { + s5.push(s6); + s6 = peg$currPos; + s7 = []; + s8 = peg$parseWhitespace(); + while (s8 !== peg$FAILED) { + s7.push(s8); + s8 = peg$parseWhitespace(); + } + if (s7 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 44) { + s8 = peg$c102; + peg$currPos++; + } else { + s8 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c103); } + } + if (s8 !== peg$FAILED) { + s9 = []; + s10 = peg$parseWhitespace(); + while (s10 !== peg$FAILED) { + s9.push(s10); + s10 = peg$parseWhitespace(); + } + if (s9 !== peg$FAILED) { + s10 = peg$parseKeyValue(); + if (s10 !== peg$FAILED) { + s7 = [s7, s8, s9, s10]; + s6 = s7; + } else { + peg$currPos = s6; + s6 = peg$FAILED; + } + } else { + peg$currPos = s6; + s6 = peg$FAILED; + } + } else { + peg$currPos = s6; + s6 = peg$FAILED; + } + } else { + peg$currPos = s6; + s6 = peg$FAILED; + } + } + if (s5 !== peg$FAILED) { + s6 = []; + s7 = peg$parseWhitespace(); + while (s7 !== peg$FAILED) { + s6.push(s7); + s7 = peg$parseWhitespace(); + } + if (s6 !== peg$FAILED) { + s4 = [s4, s5, s6]; + s3 = s4; + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + if (s3 === peg$FAILED) { + s3 = null; + } + if (s3 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 125) { + s4 = peg$c110; + peg$currPos++; + } else { + s4 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c111); } + } + if (s4 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c112(s3); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + + return s0; + } + + function peg$parseTableArrayHeader() { + var s0, s1, s2, s3; + + s0 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 91) { + s1 = peg$c100; + peg$currPos++; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c101); } + } + if (s1 !== peg$FAILED) { + s2 = peg$parseTableHeader(); + if (s2 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 93) { + s3 = peg$c104; + peg$currPos++; + } else { + s3 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c105); } + } + if (s3 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c113(s2); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + + return s0; + } + + function peg$parseTableHeader() { + var s0, s1, s2, s3, s4, s5, s6, s7, s8, s9; + + s0 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 91) { + s1 = peg$c100; + peg$currPos++; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c101); } + } + if (s1 !== peg$FAILED) { + s2 = []; + s3 = peg$parseWhitespace(); + while (s3 !== peg$FAILED) { + s2.push(s3); + s3 = peg$parseWhitespace(); + } + if (s2 !== peg$FAILED) { + s3 = peg$parseKey(); + if (s3 !== peg$FAILED) { + s4 = []; + s5 = peg$currPos; + s6 = []; + s7 = peg$parseWhitespace(); + while (s7 !== peg$FAILED) { + s6.push(s7); + s7 = peg$parseWhitespace(); + } + if (s6 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 46) { + s7 = peg$c71; + peg$currPos++; + } else { + s7 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c72); } + } + if (s7 !== peg$FAILED) { + s8 = []; + s9 = peg$parseWhitespace(); + while (s9 !== peg$FAILED) { + s8.push(s9); + s9 = peg$parseWhitespace(); + } + if (s8 !== peg$FAILED) { + s9 = peg$parseKey(); + if (s9 !== peg$FAILED) { + s6 = [s6, s7, s8, s9]; + s5 = s6; + } else { + peg$currPos = s5; + s5 = peg$FAILED; + } + } else { + peg$currPos = s5; + s5 = peg$FAILED; + } + } else { + peg$currPos = s5; + s5 = peg$FAILED; + } + } else { + peg$currPos = s5; + s5 = peg$FAILED; + } + while (s5 !== peg$FAILED) { + s4.push(s5); + s5 = peg$currPos; + s6 = []; + s7 = peg$parseWhitespace(); + while (s7 !== peg$FAILED) { + s6.push(s7); + s7 = peg$parseWhitespace(); + } + if (s6 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 46) { + s7 = peg$c71; + peg$currPos++; + } else { + s7 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c72); } + } + if (s7 !== peg$FAILED) { + s8 = []; + s9 = peg$parseWhitespace(); + while (s9 !== peg$FAILED) { + s8.push(s9); + s9 = peg$parseWhitespace(); + } + if (s8 !== peg$FAILED) { + s9 = peg$parseKey(); + if (s9 !== peg$FAILED) { + s6 = [s6, s7, s8, s9]; + s5 = s6; + } else { + peg$currPos = s5; + s5 = peg$FAILED; + } + } else { + peg$currPos = s5; + s5 = peg$FAILED; + } + } else { + peg$currPos = s5; + s5 = peg$FAILED; + } + } else { + peg$currPos = s5; + s5 = peg$FAILED; + } + } + if (s4 !== peg$FAILED) { + s5 = []; + s6 = peg$parseWhitespace(); + while (s6 !== peg$FAILED) { + s5.push(s6); + s6 = peg$parseWhitespace(); + } + if (s5 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 93) { + s6 = peg$c104; + peg$currPos++; + } else { + s6 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c105); } + } + if (s6 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c114(s3, s4); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + + return s0; + } + + + var genMsgRedefined, isFiniteNumber, isArray, hasOwnProperty, stringify, + unescape, fromCodePoint, checkTableKey, findContext; + + genMsgRedefined = function (key) { + return ('Value for ' + key + ' should not be redefined in the same table.'); }; - return S4() + S4() + '-' + S4() + '-' + S4() + '-' + S4() + '-' + S4() + S4() + S4(); + + isFiniteNumber = Number.isFinite || function (n) { + return typeof n === 'number' && isFinite(n); + }; + + isArray = Array.isArray || function (obj) { + return Object.prototype.toString.call(obj) === '[object Array]'; + }; + + hasOwnProperty = function (obj, key) { + return Object.prototype.hasOwnProperty.call(obj, key); + }; + + stringify = typeof JSON === 'object' && JSON ? JSON.stringify : function (o) { + return '"' + String(o).replace(/[\x00-\x1F"\\]/g, function (c) { + switch (c) { + case '"': case '\\': return '\\' + c; + case '\t': return '\\t'; + case '\n': return '\\n'; + case '\r': return '\\r'; + case '\b': return '\\b'; + case '\f': return '\\f'; + default: + var hex = c.charCodeAt(0).toString(16); + return '\\u' + '0000'.substr(hex.length) + hex; + } + }) + '"'; + }; + + unescape = function (c) { + switch (c) { + case '"': case '\\': return c; + case 't': return '\t'; + case 'n': return '\n'; + case 'r': return '\r'; + case 'b': return '\b'; + case 'f': return '\f'; + default: error(stringify(c) + ' cannot be escaped.'); + } + }; + + fromCodePoint = function (codepoint) { + if (!isFiniteNumber(codepoint) || codepoint < 0 || codepoint > 0x10FFFF) { + error('U+' + codepoint.toString(16) + + ' is not a valid Unicode code point.'); + } + if (String.fromCodePoint) { + return String.fromCodePoint(codepoint); + } + // See: punnycode.ucs2.encode from https://github.com/bestiejs/punycode.js + var c = ''; + if (codepoint > 0xFFFF) { + codepoint -= 0x10000; + c += String.fromCharCode((codepoint >>> 10) & 0x3FF | 0xD800); + codepoint = 0xDC00 | codepoint & 0x3FF; + } + c += String.fromCharCode(codepoint); + return c; + }; + + checkTableKey = function (table, k) { + if (hasOwnProperty(table, k)) { + error(genMsgRedefined(stringify(k))); + } + }; + + findContext = function (table, isTableArray, path) { + var s = ''; + for (var i = 0, l = path.length; i < l; i++) { + var k = path[i]; + s += (s ? '.' : '') + stringify(k); + if (!hasOwnProperty(table, k)) { + if (isTableArray && i + 1 === l) { + var t = {}; + table[k] = [t]; + table = t; + g_table_arrays[s] = true; + } else { + table = table[k] = {}; + g_tables[s] = true; + } + } else { + if (isTableArray) { + if (isArray(table[k])) { + if (!g_table_arrays[s]) { + error(genMsgRedefined(s)); + } + if (i + 1 === l) { + var t = {}; + table[k].push(t); + table = t; + } else { + s += '.' + stringify(table[k].length - 1); + table = table[k][table[k].length-1]; + } + } else { + if (!g_tables[s]) { + error(genMsgRedefined(s)); + } + table = table[k]; + } + } else { + if (isArray(table[k])) { + if (!g_table_arrays[s] || i + 1 === l) { + error(genMsgRedefined(s)); + } + s += '.' + stringify(table[k].length - 1); + table = table[k][table[k].length-1]; + } else { + if (!g_tables[s]) { + error(genMsgRedefined(s)); + } + table = table[k]; + } + } + } + } + if (isTableArray) { + if (!g_table_arrays[s]) { + error(genMsgRedefined(s)); + } + } else { + if (g_defined_tables[s] || g_table_arrays[s]) { + error(genMsgRedefined(s)); + } + g_defined_tables[s] = true; + } + return { + table: table, + path: path + }; + }; + + var g_root = {}; // TOML table + var g_context = { // current context + table: g_root, + path: [] + }; + var g_tables = {}; // paths to tables + var g_defined_tables = {}; // paths to tables directly defined + var g_table_arrays = {}; // paths to table arrays + + + peg$result = peg$startRuleFunction(); + + if (peg$result !== peg$FAILED && peg$currPos === input.length) { + return peg$result; + } else { + if (peg$result !== peg$FAILED && peg$currPos < input.length) { + peg$fail(peg$endExpectation()); + } + + throw peg$buildStructuredError( + peg$maxFailExpected, + peg$maxFailPos < input.length ? input.charAt(peg$maxFailPos) : null, + peg$maxFailPos < input.length + ? peg$computeLocation(peg$maxFailPos, peg$maxFailPos + 1) + : peg$computeLocation(peg$maxFailPos, peg$maxFailPos) + ); + } } - /* - * Display a page-wide error message to show that something has gone wrong with - * PyScript or Pyodide during loading. Probably not be used for issues that occur within - * Python scripts, since stderr can be routed to somewhere in the DOM - */ - function showError(msg) { - const warning = document.createElement('div'); - warning.style.backgroundColor = 'LightCoral'; - warning.style.alignContent = 'center'; - warning.style.margin = '4px'; - warning.style.padding = '4px'; - warning.innerHTML = msg; - document.body.prepend(warning); + + return { + SyntaxError: peg$SyntaxError, + parse: peg$parse + }; + })(); + + function subclass(child, parent) { + function ctor() { + this.constructor = child; } - function handleFetchError(e, singleFile) { - //Should we still export full error contents to console? - console.warn(`Caught an error in loadPaths:\r\n ${e.toString()}`); - let errorContent; - if (e.message.includes('TypeError: Failed to fetch')) { - errorContent = `<p>PyScript: Access to local files - (using "Paths:" in <py-env>) + ctor.prototype = parent.prototype; + child.prototype = new ctor(); + } + + function TomlSyntaxError(message, offset, line, column) { + this.message = message; + this.offset = offset; + this.line = line; + this.column = column; + } + + subclass(TomlSyntaxError, SyntaxError); + + var parser$1 = parser$2; + var toml = { + parse: function (src) { + try { + return parser$1.parse(src); + } catch (err) { + if (err instanceof parser$1.SyntaxError) { + err.line = err.location.start.line; + err.column = err.location.start.column; + err.offset = err.location.start.offset; + throw new TomlSyntaxError( + err.message, + err.location.start.offset, + err.location.start.line, + err.location.start.column); + } else { + throw err; + } + } + }, + SyntaxError: TomlSyntaxError + }; + + var toml_1 = toml; + + /* Very simple logger interface. + + Each module is expected to create its own logger by doing e.g.: + + const logger = getLogger('my-prefix'); + + and then use it instead of console: + + logger.info('hello', 'world'); + logger.warn('...'); + logger.error('...'); + + The logger automatically adds the prefix "[my-prefix]" to all logs. + E.g., the above call would print: + + [my-prefix] hello world + + logger.log is intentionally omitted. The idea is that PyScript should not + write anything to console.log, to leave it free for the user. + + Currently, the logger does not to anything more than that. In the future, + we might want to add additional features such as the ability to + enable/disable logs on a global or per-module basis. + */ + const _cache = new Map(); + function getLogger(prefix) { + let logger = _cache.get(prefix); + if (logger === undefined) { + logger = _makeLogger(prefix); + _cache.set(prefix, logger); + } + return logger; + } + function _makeLogger(prefix) { + prefix = `[${prefix}] `; + function make(level) { + const out_fn = console[level].bind(console); + function fn(fmt, ...args) { + out_fn(prefix + fmt, ...args); + } + return fn; + } + // 'log' is intentionally omitted + const debug = make('debug'); + const info = make('info'); + const warn = make('warn'); + const error = make('error'); + return { debug, info, warn, error }; + } + + /** + * @fileoverview Version of pyscript + * The version is based on calver which contains YEAR.MONTH.DAY.MODIFIER. + * The Modifier can be an optional text tag, such as "dev", "rc", etc. + * + * We are adding this file because we can't add version in main.js due to + * circular imports. + */ + const version = '2022.12.1.dev'; + + const CLOSEBUTTON = `<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 16 16' fill="currentColor" width="12px"><path d='M.293.293a1 1 0 011.414 0L8 6.586 14.293.293a1 1 0 111.414 1.414L9.414 8l6.293 6.293a1 1 0 01-1.414 1.414L8 9.414l-6.293 6.293a1 1 0 01-1.414-1.414L6.586 8 .293 1.707a1 1 0 010-1.414z'/></svg>`; + /* + These error codes are used to identify the type of error that occurred. + The convention is: + * PY0 - errors that occur when fetching + * PY1 - errors that occur in config + * Py2 - errors that occur in plugins + * PY9 - Deprecation errors + */ + var ErrorCode; + (function (ErrorCode) { + ErrorCode["GENERIC"] = "PY0000"; + ErrorCode["FETCH_ERROR"] = "PY0001"; + ErrorCode["FETCH_NAME_ERROR"] = "PY0002"; + // Currently these are created depending on error code received from fetching + ErrorCode["FETCH_UNAUTHORIZED_ERROR"] = "PY0401"; + ErrorCode["FETCH_FORBIDDEN_ERROR"] = "PY0403"; + ErrorCode["FETCH_NOT_FOUND_ERROR"] = "PY0404"; + ErrorCode["FETCH_SERVER_ERROR"] = "PY0500"; + ErrorCode["FETCH_UNAVAILABLE_ERROR"] = "PY0503"; + ErrorCode["BAD_CONFIG"] = "PY1000"; + ErrorCode["MICROPIP_INSTALL_ERROR"] = "PY1001"; + ErrorCode["BAD_PLUGIN_FILE_EXTENSION"] = "PY2000"; + ErrorCode["NO_DEFAULT_EXPORT"] = "PY2001"; + ErrorCode["TOP_LEVEL_AWAIT"] = "PY9000"; + })(ErrorCode || (ErrorCode = {})); + class UserError extends Error { + constructor(errorCode, message, t = 'text') { + super(message); + this.errorCode = errorCode; + this.name = 'UserError'; + this.messageType = t; + this.message = `(${errorCode}): ${message}`; + } + } + class FetchError extends UserError { + constructor(errorCode, message) { + super(errorCode, message); + this.name = 'FetchError'; + } + } + class InstallError extends UserError { + constructor(errorCode, message) { + super(errorCode, message); + this.name = 'InstallError'; + } + } + function _createAlertBanner(message, level = 'error', messageType = 'text', logMessage = true) { + // eslint-disable-next-line @typescript-eslint/restrict-template-expressions + switch (`log-${level}-${logMessage}`) { + case 'log-error-true': + console.error(message); + break; + case 'log-warning-true': + console.warn(message); + break; + } + const banner = document.createElement('div'); + banner.className = `alert-banner py-${level}`; + if (messageType === 'html') { + banner.innerHTML = message; + } + else { + banner.textContent = message; + } + if (level === 'warning') { + const closeButton = document.createElement('button'); + closeButton.id = 'alert-close-button'; + closeButton.addEventListener('click', () => { + banner.remove(); + }); + closeButton.innerHTML = CLOSEBUTTON; + banner.appendChild(closeButton); + } + document.body.prepend(banner); + } + + function escape(str) { + return str.replace(/</g, '<').replace(/>/g, '>'); + } + function htmlDecode(input) { + const doc = new DOMParser().parseFromString(ltrim(escape(input)), 'text/html'); + return doc.documentElement.textContent; + } + function ltrim(code) { + const lines = code.split('\n'); + if (lines.length == 0) + return code; + const lengths = lines + .filter(line => line.trim().length != 0) + .map(line => { + return line.match(/^\s*/)?.pop()?.length; + }); + const k = Math.min(...lengths); + return k != 0 ? lines.map(line => line.substring(k)).join('\n') : code; + } + let _uniqueIdCounter = 0; + function ensureUniqueId(el) { + if (el.id === '') + el.id = `py-internal-${_uniqueIdCounter++}`; + } + function showWarning(msg, messageType = 'text') { + _createAlertBanner(msg, 'warning', messageType); + } + function readTextFromPath(path) { + const request = new XMLHttpRequest(); + request.open('GET', path, false); + request.send(); + const returnValue = request.responseText; + return returnValue; + } + function globalExport(name, obj) { + // attach the given object to the global object, so that it is globally + // visible everywhere. Should be used very sparingly! + globalThis[name] = obj; + } + function getAttribute(el, attr) { + if (el.hasAttribute(attr)) { + const value = el.getAttribute(attr); + if (value) { + return value; + } + } + return null; + } + function joinPaths(parts, separator = '/') { + const res = parts + .map(function (part) { + return part.trim().replace(/(^[/]*|[/]*$)/g, ''); + }) + .filter(p => p !== '') + .join(separator || '/'); + if (parts[0].startsWith('/')) { + return '/' + res; + } + return res; + } + function createDeprecationWarning(msg, elementName) { + createSingularWarning(msg, elementName); + } + /** Adds a warning banner with content {msg} at the top of the page if + * and only if no banner containing the {sentinelText} already exists. + * If sentinelText is null, the full text of {msg} is used instead + * + * @param msg {string} The full text content of the warning banner to be displayed + * @param sentinelText {string} [null] The text to match against existing warning banners. + * If null, the full text of 'msg' is used instead. + */ + function createSingularWarning(msg, sentinelText = null) { + const banners = document.getElementsByClassName('alert-banner py-warning'); + let bannerCount = 0; + for (const banner of banners) { + if (banner.innerHTML.includes(sentinelText ? sentinelText : msg)) { + bannerCount++; + } + } + if (bannerCount == 0) { + _createAlertBanner(msg, 'warning'); + } + } + /** + * @returns A new asynchronous lock + * @private + */ + function createLock() { + // This is a promise that is resolved when the lock is open, not resolved when lock is held. + let _lock = Promise.resolve(); + /** + * Acquire the async lock + * @returns A zero argument function that releases the lock. + * @private + */ + async function acquireLock() { + const old_lock = _lock; + let releaseLock; + _lock = new Promise(resolve => (releaseLock = resolve)); + await old_lock; + return releaseLock; + } + return acquireLock; + } + + const logger$b = getLogger('py-config'); + const allKeys = { + string: ['name', 'description', 'version', 'type', 'author_name', 'author_email', 'license'], + number: ['schema_version'], + array: ['runtimes', 'interpreters', 'packages', 'fetch', 'plugins'], + }; + const defaultConfig$1 = { + schema_version: 1, + type: 'app', + interpreters: [ + { + src: 'https://cdn.jsdelivr.net/pyodide/v0.22.1/full/pyodide.js', + name: 'pyodide-0.22.1', + lang: 'python', + }, + ], + // This is for backward compatibility, we need to remove it in the future + runtimes: [], + packages: [], + fetch: [], + plugins: [], + }; + function loadConfigFromElement(el) { + let srcConfig; + let inlineConfig; + if (el === null) { + srcConfig = {}; + inlineConfig = {}; + } + else { + const configType = getAttribute(el, 'type') || 'toml'; + srcConfig = extractFromSrc(el, configType); + inlineConfig = extractFromInline(el, configType); + } + srcConfig = mergeConfig(srcConfig, defaultConfig$1); + const result = mergeConfig(inlineConfig, srcConfig); + result.pyscript = { + version, + time: new Date().toISOString(), + }; + return result; + } + function extractFromSrc(el, configType) { + const src = getAttribute(el, 'src'); + if (src) { + logger$b.info('loading ', src); + return validateConfig(readTextFromPath(src), configType); + } + return {}; + } + function extractFromInline(el, configType) { + if (el.innerHTML !== '') { + logger$b.info('loading <py-config> content'); + return validateConfig(htmlDecode(el.innerHTML), configType); + } + return {}; + } + function fillUserData(inputConfig, resultConfig) { + for (const key in inputConfig) { + // fill in all extra keys ignored by the validator + if (!(key in defaultConfig$1)) { + resultConfig[key] = inputConfig[key]; + } + } + return resultConfig; + } + function mergeConfig(inlineConfig, externalConfig) { + if (Object.keys(inlineConfig).length === 0 && Object.keys(externalConfig).length === 0) { + return defaultConfig$1; + } + else if (Object.keys(inlineConfig).length === 0) { + return externalConfig; + } + else if (Object.keys(externalConfig).length === 0) { + return inlineConfig; + } + else { + let merged = {}; + for (const keyType in allKeys) { + const keys = allKeys[keyType]; + keys.forEach(function (item) { + if (keyType === 'boolean') { + merged[item] = + typeof inlineConfig[item] !== 'undefined' ? inlineConfig[item] : externalConfig[item]; + } + else { + merged[item] = inlineConfig[item] || externalConfig[item]; + } + }); + } + // fill extra keys from external first + // they will be overridden by inline if extra keys also clash + merged = fillUserData(externalConfig, merged); + merged = fillUserData(inlineConfig, merged); + return merged; + } + } + function parseConfig(configText, configType = 'toml') { + if (configType === 'toml') { + // TOML parser is soft and can parse even JSON strings, this additional check prevents it. + if (configText.trim()[0] === '{') { + throw new UserError(ErrorCode.BAD_CONFIG, `The config supplied: ${configText} is an invalid TOML and cannot be parsed`); + } + try { + return toml_1.parse(configText); + } + catch (err) { + const errMessage = err.toString(); + throw new UserError(ErrorCode.BAD_CONFIG, `The config supplied: ${configText} is an invalid TOML and cannot be parsed: ${errMessage}`); + } + } + else if (configType === 'json') { + try { + return JSON.parse(configText); + } + catch (err) { + const errMessage = err.toString(); + throw new UserError(ErrorCode.BAD_CONFIG, `The config supplied: ${configText} is an invalid JSON and cannot be parsed: ${errMessage}`); + } + } + else { + throw new UserError(ErrorCode.BAD_CONFIG, `The type of config supplied '${configType}' is not supported, supported values are ["toml", "json"]`); + } + } + function validateConfig(configText, configType = 'toml') { + const config = parseConfig(configText, configType); + const finalConfig = {}; + for (const keyType in allKeys) { + const keys = allKeys[keyType]; + keys.forEach(function (item) { + if (validateParamInConfig(item, keyType, config)) { + if (item === 'interpreters') { + finalConfig[item] = []; + const interpreters = config[item]; + interpreters.forEach(function (eachInterpreter) { + const interpreterConfig = {}; + for (const eachInterpreterParam in eachInterpreter) { + if (validateParamInConfig(eachInterpreterParam, 'string', eachInterpreter)) { + interpreterConfig[eachInterpreterParam] = eachInterpreter[eachInterpreterParam]; + } + } + finalConfig[item].push(interpreterConfig); + }); + } + else if (item === 'runtimes') { + // This code is a bit of a mess, but it's used for backwards + // compatibility with the old runtimes config. It should be + // removed when we remove support for the old config. + // We also need the warning here since we are pushing + // runtimes to `interpreter` and we can't show the warning + // in main.js + createDeprecationWarning('The configuration option `config.runtimes` is deprecated. ' + + 'Please use `config.interpreters` instead.', ''); + finalConfig['interpreters'] = []; + const interpreters = config[item]; + interpreters.forEach(function (eachInterpreter) { + const interpreterConfig = {}; + for (const eachInterpreterParam in eachInterpreter) { + if (validateParamInConfig(eachInterpreterParam, 'string', eachInterpreter)) { + interpreterConfig[eachInterpreterParam] = eachInterpreter[eachInterpreterParam]; + } + } + finalConfig['interpreters'].push(interpreterConfig); + }); + } + else if (item === 'fetch') { + finalConfig[item] = []; + const fetchList = config[item]; + fetchList.forEach(function (eachFetch) { + const eachFetchConfig = {}; + for (const eachFetchConfigParam in eachFetch) { + const targetType = eachFetchConfigParam === 'files' ? 'array' : 'string'; + if (validateParamInConfig(eachFetchConfigParam, targetType, eachFetch)) { + eachFetchConfig[eachFetchConfigParam] = eachFetch[eachFetchConfigParam]; + } + } + finalConfig[item].push(eachFetchConfig); + }); + } + else { + finalConfig[item] = config[item]; + } + } + }); + } + return fillUserData(config, finalConfig); + } + function validateParamInConfig(paramName, paramType, config) { + if (paramName in config) { + return paramType === 'array' ? Array.isArray(config[paramName]) : typeof config[paramName] === paramType; + } + return false; + } + + /** + * This is a fetch wrapper that handles any non 200 responses and throws a + * FetchError with the right ErrorCode. This is useful because our FetchError + * will automatically create an alert banner. + * + * @param url - URL to fetch + * @param options - options to pass to fetch + * @returns Response + */ + async function robustFetch(url, options) { + let response; + // Note: We need to wrap fetch into a try/catch block because fetch + // throws a TypeError if the URL is invalid such as http://blah.blah + try { + response = await fetch(url, options); + } + catch (err) { + const error = err; + let errMsg; + if (url.startsWith('http')) { + errMsg = + `Fetching from URL ${url} failed with error ` + + `'${error.message}'. Are your filename and path correct?`; + } + else { + errMsg = `PyScript: Access to local files + (using "Paths:" in <py-config>) is not available when directly opening a HTML file; you must use a webserver to serve the additional files. See <a style="text-decoration: underline;" href="https://github.com/pyscript/pyscript/issues/257#issuecomment-1119595062">this reference</a> - on starting a simple webserver with Python.</p>`; - } - else if (e.message.includes('404')) { - errorContent = - `<p>PyScript: Loading from file <u>` + - singleFile + - `</u> failed with error 404 (File not Found). Are your filename and path are correct?</p>`; - } - else { - errorContent = '<p>PyScript encountered an error while loading from file: ' + e.message + '</p>'; - } - showError(errorContent); - } - function readTextFromPath(path) { - const request = new XMLHttpRequest(); - request.open("GET", path, false); - request.send(); - const returnValue = request.responseText; - return returnValue; - } - function fillUserData(inputConfig, resultConfig) { - for (const key in inputConfig) { - // fill in all extra keys ignored by the validator - if (!(key in defaultConfig$1)) { - resultConfig[key] = inputConfig[key]; - } - } - return resultConfig; - } - function mergeConfig(inlineConfig, externalConfig) { - if (Object.keys(inlineConfig).length === 0 && Object.keys(externalConfig).length === 0) { - return defaultConfig$1; - } - else if (Object.keys(inlineConfig).length === 0) { - return externalConfig; - } - else if (Object.keys(externalConfig).length === 0) { - return inlineConfig; - } - else { - let merged = {}; - for (const keyType in allKeys) { - const keys = allKeys[keyType]; - keys.forEach(function (item) { - if (keyType === "boolean") { - merged[item] = (typeof inlineConfig[item] !== "undefined") ? inlineConfig[item] : externalConfig[item]; - } - else { - merged[item] = inlineConfig[item] || externalConfig[item]; - } - }); - } - // fill extra keys from external first - // they will be overridden by inline if extra keys also clash - merged = fillUserData(externalConfig, merged); - merged = fillUserData(inlineConfig, merged); - return merged; - } - } - function parseConfig(configText, configType = "toml") { - let config; - if (configType === "toml") { - try { - // TOML parser is soft and can parse even JSON strings, this additional check prevents it. - if (configText.trim()[0] === "{") { - const errMessage = `config supplied: ${configText} is an invalid TOML and cannot be parsed`; - showError(`<p>${errMessage}</p>`); - throw Error(errMessage); - } - config = toml.parse(configText); - } - catch (err) { - const errMessage = err.toString(); - showError(`<p>config supplied: ${configText} is an invalid TOML and cannot be parsed: ${errMessage}</p>`); - throw err; - } - } - else if (configType === "json") { - try { - config = JSON.parse(configText); - } - catch (err) { - const errMessage = err.toString(); - showError(`<p>config supplied: ${configText} is an invalid JSON and cannot be parsed: ${errMessage}</p>`); - throw err; - } - } - else { - showError(`<p>type of config supplied is: ${configType}, supported values are ["toml", "json"].</p>`); - } - return config; - } - function validateConfig(configText, configType = "toml") { - const config = parseConfig(configText, configType); - const finalConfig = {}; - for (const keyType in allKeys) { - const keys = allKeys[keyType]; - keys.forEach(function (item) { - if (validateParamInConfig(item, keyType, config)) { - if (item === "runtimes") { - finalConfig[item] = []; - const runtimes = config[item]; - runtimes.forEach(function (eachRuntime) { - const runtimeConfig = {}; - for (const eachRuntimeParam in eachRuntime) { - if (validateParamInConfig(eachRuntimeParam, "string", eachRuntime)) { - runtimeConfig[eachRuntimeParam] = eachRuntime[eachRuntimeParam]; - } - } - finalConfig[item].push(runtimeConfig); - }); - } - else { - finalConfig[item] = config[item]; - } - } - }); - } - return fillUserData(config, finalConfig); - } - function validateParamInConfig(paramName, paramType, config) { - if (paramName in config) { - return paramType === "array" ? Array.isArray(config[paramName]) : typeof config[paramName] === paramType; - } - return false; - } + on starting a simple webserver with Python. + `; + } + throw new FetchError(ErrorCode.FETCH_ERROR, errMsg); + } + // Note that response.ok is true for 200-299 responses + if (!response.ok) { + const errorMsg = `Fetching from URL ${url} failed with error ${response.status} (${response.statusText}). Are your filename and path correct?`; + switch (response.status) { + case 404: + throw new FetchError(ErrorCode.FETCH_NOT_FOUND_ERROR, errorMsg); + case 401: + throw new FetchError(ErrorCode.FETCH_UNAUTHORIZED_ERROR, errorMsg); + case 403: + throw new FetchError(ErrorCode.FETCH_FORBIDDEN_ERROR, errorMsg); + case 500: + throw new FetchError(ErrorCode.FETCH_SERVER_ERROR, errorMsg); + case 503: + throw new FetchError(ErrorCode.FETCH_UNAVAILABLE_ERROR, errorMsg); + default: + throw new FetchError(ErrorCode.FETCH_ERROR, errorMsg); + } + } + return response; + } - const logger$b = getLogger('pyscript/base'); - // Global `Runtime` that implements the generic runtimes API - let runtime$2; - let Element; - runtimeLoaded.subscribe(value => { - runtime$2 = value; - }); - class BaseEvalElement extends HTMLElement { - shadow; - wrapper; - code; - source; - btnConfig; - btnRun; - outputElement; - errorElement; - theme; - appendOutput; - constructor() { - super(); - // attach shadow so we can preserve the element original innerHtml content - this.shadow = this.attachShadow({ mode: 'open' }); - this.wrapper = document.createElement('slot'); - this.shadow.appendChild(this.wrapper); - this.setOutputMode("append"); - } - addToOutput(s) { - this.outputElement.innerHTML += '<div>' + s + '</div>'; - this.outputElement.hidden = false; - } - setOutputMode(defaultMode = "append") { - const mode = this.hasAttribute('output-mode') ? this.getAttribute('output-mode') : defaultMode; - switch (mode) { - case "append": - this.appendOutput = true; - break; - case "replace": - this.appendOutput = false; - break; - default: - logger$b.warn(`${this.id}: custom output-modes are currently not implemented`); - } - } - // subclasses should overwrite this method to define custom logic - // before code gets evaluated - preEvaluate() { - return null; - } - // subclasses should overwrite this method to define custom logic - // after code has been evaluated - postEvaluate() { - return null; - } - checkId() { - if (!this.id) - this.id = 'py-' + guidGenerator(); - } - getSourceFromElement() { - return ''; - } - async getSourceFromFile(s) { - const response = await fetch(s); - this.code = await response.text(); - return this.code; - } - async _register_esm(runtime) { - const imports = {}; - const nodes = document.querySelectorAll("script[type='importmap']"); - const importmaps = []; - nodes.forEach(node => { - let importmap; - try { - importmap = JSON.parse(node.textContent); - if (importmap?.imports == null) - return; - importmaps.push(importmap); - } - catch { - return; - } - }); - for (const importmap of importmaps) { - for (const [name, url] of Object.entries(importmap.imports)) { - if (typeof name != 'string' || typeof url != 'string') - continue; - try { - // XXX: pyodide doesn't like Module(), failing with - // "can't read 'name' of undefined" at import time - imports[name] = { ...(await import(url)) }; - } - catch { - logger$b.error(`failed to fetch '${url}' for '${name}'`); - } - } - } - runtime.registerJsModule('esm', imports); - } - async evaluate() { - this.preEvaluate(); - let source; - let output; - try { - source = this.source ? await this.getSourceFromFile(this.source) - : this.getSourceFromElement(); - this._register_esm(runtime$2); - await runtime$2.run(`output_manager.change(out="${this.outputElement.id}", err="${this.errorElement.id}", append=${this.appendOutput ? 'True' : 'False'})`); - output = await runtime$2.run(source); - if (output !== undefined) { - if (Element === undefined) { - Element = runtime$2.globals.get('Element'); - } - const out = Element(this.outputElement.id); - out.write.callKwargs(output, { append: this.appendOutput }); - this.outputElement.hidden = false; - this.outputElement.style.display = 'block'; - } - await runtime$2.run(`output_manager.revert()`); - // check if this REPL contains errors, delete them and remove error classes - const errorElements = document.querySelectorAll(`div[id^='${this.errorElement.id}'][error]`); - if (errorElements.length > 0) { - errorElements.forEach(errorElement => { - errorElement.classList.add('hidden'); - if (this.hasAttribute('std-err')) { - this.errorElement.hidden = true; - this.errorElement.style.removeProperty('display'); - } - }); - } - removeClasses(this.errorElement, ['bg-red-200', 'p-2']); - this.postEvaluate(); - } - catch (err) { - logger$b.error(err); - try { - if (Element === undefined) { - Element = runtime$2.globals.get('Element'); - } - const out = Element(this.errorElement.id); - addClasses(this.errorElement, ['bg-red-200', 'p-2']); - out.write.callKwargs(err.toString(), { append: this.appendOutput }); - if (this.errorElement.children.length === 0) { - this.errorElement.setAttribute('error', ''); - } - else { - this.errorElement.children[this.errorElement.children.length - 1].setAttribute('error', ''); - } - this.errorElement.hidden = false; - this.errorElement.style.display = 'block'; - this.errorElement.style.visibility = 'visible'; - } - catch (internalErr) { - logger$b.error("Unnable to write error to error element in page."); - } - } - } // end evaluate - async eval(source) { - try { - const output = await runtime$2.run(source); - if (output !== undefined) { - logger$b.info(output); - } - } - catch (err) { - logger$b.error(err); - } - } // end eval - runAfterRuntimeInitialized(callback) { - runtimeLoaded.subscribe(value => { - if ('run' in value) { - setTimeout(() => { - void callback(); - }, 100); - } - }); - } - } - function createWidget(name, code, klass) { - class CustomWidget extends HTMLElement { - shadow; - wrapper; - name = name; - klass = klass; - code = code; - proxy; - proxyClass; - constructor() { - super(); - // attach shadow so we can preserve the element original innerHtml content - this.shadow = this.attachShadow({ mode: 'open' }); - this.wrapper = document.createElement('slot'); - this.shadow.appendChild(this.wrapper); - } - connectedCallback() { - // TODO: we are calling with a 2secs delay to allow pyodide to load - // ideally we can just wait for it to load and then run. To do - // so we need to replace using the promise and actually using - // the interpreter after it loads completely - // setTimeout(() => { - // void (async () => { - // await this.eval(this.code); - // this.proxy = this.proxyClass(this); - // console.log('proxy', this.proxy); - // this.proxy.connect(); - // this.registerWidget(); - // })(); - // }, 2000); - runtimeLoaded.subscribe(value => { - if ('run' in value) { - runtime$2 = value; - setTimeout(() => { - void (async () => { - await this.eval(this.code); - this.proxy = this.proxyClass(this); - this.proxy.connect(); - this.registerWidget(); - })(); - }, 1000); - } - }); - } - registerWidget() { - logger$b.info('new widget registered:', this.name); - runtime$2.globals.set(this.id, this.proxy); - } - async eval(source) { - try { - const output = await runtime$2.run(source); - this.proxyClass = runtime$2.globals.get(this.klass); - if (output !== undefined) { - logger$b.info('CustomWidget.eval: ', output); - } - } - catch (err) { - logger$b.error('CustomWidget.eval: ', err); - } - } - } - customElements.define(name, CustomWidget); - } - class PyWidget extends HTMLElement { - shadow; - name; - klass; - outputElement; - errorElement; - wrapper; - theme; - source; - code; - constructor() { - super(); - // attach shadow so we can preserve the element original innerHtml content - this.shadow = this.attachShadow({ mode: 'open' }); - this.wrapper = document.createElement('slot'); - this.shadow.appendChild(this.wrapper); - this.addAttributes('src', 'name', 'klass'); - } - addAttributes(...attrs) { - for (const each of attrs) { - const property = each === "src" ? "source" : each; - if (this.hasAttribute(each)) { - this[property] = this.getAttribute(each); - } - } - } - async connectedCallback() { - if (this.id === undefined) { - throw new ReferenceError(`No id specified for component. Components must have an explicit id. Please use id="" to specify your component id.`); - } - const mainDiv = document.createElement('div'); - mainDiv.id = this.id + '-main'; - this.appendChild(mainDiv); - logger$b.debug('PyWidget: reading source', this.source); - this.code = await this.getSourceFromFile(this.source); - createWidget(this.name, this.code, this.klass); - } - initOutErr() { - if (this.hasAttribute('output')) { - this.errorElement = this.outputElement = document.getElementById(this.getAttribute('output')); - // in this case, the default output-mode is append, if hasn't been specified - if (!this.hasAttribute('output-mode')) { - this.setAttribute('output-mode', 'append'); - } - } - else { - if (this.hasAttribute('std-out')) { - this.outputElement = document.getElementById(this.getAttribute('std-out')); - } - else { - // In this case neither output or std-out have been provided so we need - // to create a new output div to output to - this.outputElement = document.createElement('div'); - this.outputElement.classList.add('output'); - this.outputElement.hidden = true; - this.outputElement.id = this.id + '-' + this.getAttribute('exec-id'); - } - if (this.hasAttribute('std-err')) { - this.errorElement = document.getElementById(this.getAttribute('std-err')); - } - else { - this.errorElement = this.outputElement; - } - } - } - async getSourceFromFile(s) { - const response = await fetch(s); - return await response.text(); - } - async eval(source) { - try { - const output = await runtime$2.run(source); - if (output !== undefined) { - logger$b.info('PyWidget.eval: ', output); - } - } - catch (err) { - logger$b.error('PyWidget.eval: ', err); - } - } - } + const logger$a = getLogger('pyscript/pyodide'); + /* + RemoteInterpreter class is responsible to process requests from the + `InterpreterClient` class -- these can be requests for installation of + a package, executing code, etc. - const logger$a = getLogger('py-script'); - // Premise used to connect to the first available runtime (can be pyodide or others) - let runtime$1; - runtimeLoaded.subscribe(value => { - runtime$1 = value; - }); - loadedEnvironments.subscribe(value => { - }); - class PyScript extends BaseEvalElement { - constructor() { - super(); - // add an extra div where we can attach the codemirror editor - this.shadow.appendChild(this.wrapper); - } - connectedCallback() { - this.checkId(); - this.code = htmlDecode(this.innerHTML); - this.innerHTML = ''; - const mainDiv = document.createElement('div'); - addClasses(mainDiv, ['output']); - // add Editor to main PyScript div - if (this.hasAttribute('output')) { - this.errorElement = this.outputElement = document.getElementById(this.getAttribute('output')); - // in this case, the default output-mode is append, if hasn't been specified - if (!this.hasAttribute('output-mode')) { - this.setAttribute('output-mode', 'append'); - } - } - else { - if (this.hasAttribute('std-out')) { - this.outputElement = document.getElementById(this.getAttribute('std-out')); - } - else { - // In this case neither output or std-out have been provided so we need - // to create a new output div to output to - // Let's check if we have an id first and create one if not - this.outputElement = document.createElement('div'); - const exec_id = this.getAttribute('exec-id'); - this.outputElement.id = this.id + (exec_id ? '-' + exec_id : ''); - // add the output div id if there's not output pre-defined - mainDiv.appendChild(this.outputElement); - } - if (this.hasAttribute('std-err')) { - this.errorElement = document.getElementById(this.getAttribute('std-err')); - } - else { - this.errorElement = this.outputElement; - } - } - this.appendChild(mainDiv); - addToScriptsQueue(this); - if (this.hasAttribute('src')) { - this.source = this.getAttribute('src'); - } - } - async _register_esm(runtime) { - for (const node of document.querySelectorAll("script[type='importmap']")) { - const importmap = (() => { - try { - return JSON.parse(node.textContent); - } - catch { - return null; - } - })(); - if (importmap?.imports == null) - continue; - for (const [name, url] of Object.entries(importmap.imports)) { - if (typeof name != 'string' || typeof url != 'string') - continue; - let exports; - try { - // XXX: pyodide doesn't like Module(), failing with - // "can't read 'name' of undefined" at import time - exports = { ...(await import(url)) }; - } - catch { - logger$a.warn(`failed to fetch '${url}' for '${name}'`); - continue; - } - runtime.registerJsModule(name, exports); - } - } - } - getSourceFromElement() { - return htmlDecode(this.code); - } - } - /** Defines all possible py-on* and their corresponding event types */ - const pyAttributeToEvent = new Map([ - // Leaving pys-onClick and pys-onKeyDown for backward compatibility - ["pys-onClick", "click"], - ["pys-onKeyDown", "keydown"], - ["py-onClick", "click"], - ["py-onKeyDown", "keydown"], - // Window Events - ["py-afterprint", "afterprint"], - ["py-beforeprint", "beforeprint"], - ["py-beforeunload", "beforeunload"], - ["py-error", "error"], - ["py-hashchange", "hashchange"], - ["py-load", "load"], - ["py-message", "message"], - ["py-offline", "offline"], - ["py-online", "online"], - ["py-pagehide", "pagehide"], - ["py-pageshow", "pageshow"], - ["py-popstate", "popstate"], - ["py-resize", "resize"], - ["py-storage", "storage"], - ["py-unload", "unload"], - // Form Events - ["py-blur", "blur"], - ["py-change", "change"], - ["py-contextmenu", "contextmenu"], - ["py-focus", "focus"], - ["py-input", "input"], - ["py-invalid", "invalid"], - ["py-reset", "reset"], - ["py-search", "search"], - ["py-select", "select"], - ["py-submit", "submit"], - // Keyboard Events - ["py-keydown", "keydown"], - ["py-keypress", "keypress"], - ["py-keyup", "keyup"], - // Mouse Events - ["py-click", "click"], - ["py-dblclick", "dblclick"], - ["py-mousedown", "mousedown"], - ["py-mousemove", "mousemove"], - ["py-mouseout", "mouseout"], - ["py-mouseover", "mouseover"], - ["py-mouseup", "mouseup"], - ["py-mousewheel", "mousewheel"], - ["py-wheel", "wheel"], - // Drag Events - ["py-drag", "drag"], - ["py-dragend", "dragend"], - ["py-dragenter", "dragenter"], - ["py-dragleave", "dragleave"], - ["py-dragover", "dragover"], - ["py-dragstart", "dragstart"], - ["py-drop", "drop"], - ["py-scroll", "scroll"], - // Clipboard Events - ["py-copy", "copy"], - ["py-cut", "cut"], - ["py-paste", "paste"], - // Media Events - ["py-abort", "abort"], - ["py-canplay", "canplay"], - ["py-canplaythrough", "canplaythrough"], - ["py-cuechange", "cuechange"], - ["py-durationchange", "durationchange"], - ["py-emptied", "emptied"], - ["py-ended", "ended"], - ["py-loadeddata", "loadeddata"], - ["py-loadedmetadata", "loadedmetadata"], - ["py-loadstart", "loadstart"], - ["py-pause", "pause"], - ["py-play", "play"], - ["py-playing", "playing"], - ["py-progress", "progress"], - ["py-ratechange", "ratechange"], - ["py-seeked", "seeked"], - ["py-seeking", "seeking"], - ["py-stalled", "stalled"], - ["py-suspend", "suspend"], - ["py-timeupdate", "timeupdate"], - ["py-volumechange", "volumechange"], - ["py-waiting", "waiting"], - // Misc Events - ["py-toggle", "toggle"], - ]); - /** Initialize all elements with py-* handlers attributes */ - async function initHandlers() { - logger$a.debug('Initializing py-* event handlers...'); - for (const pyAttribute of pyAttributeToEvent.keys()) { - await createElementsWithEventListeners(runtime$1, pyAttribute); - } - } - /** Initializes an element with the given py-on* attribute and its handler */ - async function createElementsWithEventListeners(runtime, pyAttribute) { - const matches = document.querySelectorAll(`[${pyAttribute}]`); - for (const el of matches) { - if (el.id.length === 0) { - throw new TypeError(`<${el.tagName.toLowerCase()}> must have an id attribute, when using the ${pyAttribute} attribute`); - } - const handlerCode = el.getAttribute(pyAttribute); - const event = pyAttributeToEvent.get(pyAttribute); - if (pyAttribute === 'pys-onClick' || pyAttribute === 'pys-onKeyDown') { - console.warn("Use of pys-onClick and pys-onKeyDown attributes is deprecated in favor of py-onClick() and py-onKeyDown(). pys-on* attributes will be deprecated in a future version of PyScript."); - const source = ` + Currently, the only interpreter available is Pyodide as indicated by the + `InterpreterInterface` type above. This serves as a Union of types of + different interpreters which will be added in near future. + + Methods available handle loading of the interpreter, initialization, + running code, loading and installation of packages, loading from files etc. + + The class will be turned `abstract` in future, to support more runtimes + such as MicroPython. + */ + class RemoteInterpreter extends Object { + constructor(src = 'https://cdn.jsdelivr.net/pyodide/v0.22.1/full/pyodide.js') { + super(); + this.src = src; + } + /** + * loads the interface for the interpreter and saves an instance of it + * in the `this.interface` property along with calling of other + * additional convenience functions. + * */ + /** + * Although `loadPyodide` is used below, + * notice that it is not imported i.e. + * import { loadPyodide } from 'pyodide'; + * is not used at the top of this file. + * + * This is because, if it's used, loadPyodide + * behaves mischievously i.e. it tries to load + * `pyodide.asm.js` and `pyodide_py.tar` but + * with paths that are wrong such as: + * + * http://127.0.0.1:8080/build/pyodide_py.tar + * which results in a 404 since `build` doesn't + * contain these files and is clearly the wrong + * path. + */ + async loadInterpreter(config, stdio) { + this.interface = await loadPyodide({ + stdout: (msg) => { + stdio.stdout_writeline(msg); + }, + stderr: (msg) => { + stdio.stderr_writeline(msg); + }, + fullStdLib: false, + }); + // TODO: Remove this once `runtimes` is removed! + this.interpreter = this.interface; + this.globals = this.interface.globals; + if (config.packages) { + logger$a.info('Found packages in configuration to install. Loading micropip...'); + await this.loadPackage('micropip'); + } + logger$a.info('pyodide loaded and initialized'); + await this.run('print("Python initialization complete")'); + } + /* eslint-disable */ + async run(code) { + /** + * eslint wants `await` keyword to be used i.e. + * { result: await this.interface.runPython(code) } + * However, `await` is not a no-op (no-operation) i.e. + * `await 42` is NOT the same as `42` i.e. if the awaited + * thing is not a promise, it is wrapped inside a promise and + * that promise is awaited. Thus, it changes the execution order. + * See https://stackoverflow.com/questions/55262996/does-awaiting-a-non-promise-have-any-detectable-effect + * Thus, `eslint` is disabled for this block / snippet. + */ + /** + * The output of `runPython` is wrapped inside an object + * since an object is not thennable and avoids return of + * a coroutine directly. This is so we do not `await` the results + * of the underlying python execution, even if it's an + * awaitable object (Future, Task, etc.) + */ + return { result: this.interface.runPython(code) }; + } + /* eslint-enable */ + /** + * delegates the registration of JS modules to + * the underlying interface. + * */ + registerJsModule(name, module) { + this.interface.registerJsModule(name, module); + } + /** + * delegates the loading of packages to + * the underlying interface. + * */ + async loadPackage(names) { + logger$a.info(`pyodide.loadPackage: ${names.toString()}`); + // the new way in v0.22.1 is to pass it as a dict of options i.e. + // { messageCallback: logger.info.bind(logger), errorCallback: logger.info.bind(logger) } + // but one of our tests tries to use a locally downloaded older version of pyodide + // for which the signature of `loadPackage` accepts the above params as args i.e. + // the call uses `logger.info.bind(logger), logger.info.bind(logger)`. + const pyodide_version = (await this.run("import sys; sys.modules['pyodide'].__version__")).result.toString(); + if (pyodide_version.startsWith('0.22')) { + await this.interface.loadPackage(names, { + messageCallback: logger$a.info.bind(logger$a), + errorCallback: logger$a.info.bind(logger$a), + }); + } + else { + await this.interface.loadPackage(names, logger$a.info.bind(logger$a), logger$a.info.bind(logger$a)); + } + } + /** + * delegates the installation of packages + * (using a package manager, which can be specific to + * the interface) to the underlying interface. + * + * For Pyodide, we use `micropip` + * */ + async installPackage(package_name) { + if (package_name.length > 0) { + logger$a.info(`micropip install ${package_name.toString()}`); + const micropip = this.interface.pyimport('micropip'); + try { + await micropip.install(package_name); + micropip.destroy(); + } + catch (e) { + let exceptionMessage = `Unable to install package(s) '` + package_name + `'.`; + // If we can't fetch `package_name` micropip.install throws a huge + // Python traceback in `e.message` this logic is to handle the + // error and throw a more sensible error message instead of the + // huge traceback. + if (e.message.includes("Can't find a pure Python 3 wheel")) { + exceptionMessage += + ` Reason: Can't find a pure Python 3 Wheel for package(s) '` + + package_name + + `'. See: https://pyodide.org/en/stable/usage/faq.html#micropip-can-t-find-a-pure-python-wheel ` + + `for more information.`; + } + else if (e.message.includes("Can't fetch metadata")) { + exceptionMessage += + ' Unable to find package in PyPI. ' + + 'Please make sure you have entered a correct package name.'; + } + else { + exceptionMessage += + ` Reason: ${e.message}. Please open an issue at ` + + `https://github.com/pyscript/pyscript/issues/new if you require help or ` + + `you think it's a bug.`; + } + logger$a.error(e); + throw new InstallError(ErrorCode.MICROPIP_INSTALL_ERROR, exceptionMessage); + } + } + } + /** + * + * @param path : the path in the filesystem + * @param fetch_path : the path to be fetched + * + * Given a file available at `fetch_path` URL (eg: + * `http://dummy.com/hi.py`), the function downloads the file and saves it + * to the `path` (eg: `a/b/c/foo.py`) on the FS. + * + * Example usage: await loadFromFile(`a/b/c/foo.py`, + * `http://dummy.com/hi.py`) + * + * Write content of `http://dummy.com/hi.py` to `a/b/c/foo.py` + * + * NOTE: The `path` parameter expects to have the `filename` in it i.e. + * `a/b/c/foo.py` is valid while `a/b/c` (i.e. only the folders) are + * incorrect. + * + * The path will be resolved relative to the current working directory, + * which is initially `/home/pyodide`. So by default `a/b.py` will be placed + * in `/home/pyodide/a/b.py`, `../a/b.py` will be placed into `/home/a/b.py` + * and `/a/b.py` will be placed into `/a/b.py`. + */ + async loadFromFile(path, fetch_path) { + // eslint-disable-next-line @typescript-eslint/ban-ts-comment + // @ts-ignore + path = this.interface._module.PATH_FS.resolve(path); + // eslint-disable-next-line @typescript-eslint/ban-ts-comment + // @ts-ignore + const dir = this.interface._module.PATH.dirname(path); + this.interface.FS.mkdirTree(dir); + // `robustFetch` checks for failures in getting a response + const response = await robustFetch(fetch_path); + const buffer = await response.arrayBuffer(); + const data = new Uint8Array(buffer); + this.interface.FS.writeFile(path, data, { canOwn: true }); + } + /** + * delegates clearing importlib's module path + * caches to the underlying interface + */ + invalidate_module_path_cache() { + const importlib = this.interface.pyimport('importlib'); + importlib.invalidate_caches(); + } + } + + const logger$9 = getLogger('pyscript/interpreter'); + /* + InterpreterClient class is responsible to request code execution + (among other things) from a `RemoteInterpreter` + */ + class InterpreterClient extends Object { + constructor(config, stdio) { + super(); + this.config = config; + this._remote = new RemoteInterpreter(this.config.interpreters[0].src); + this.stdio = stdio; + } + /** + * initializes the remote interpreter, which further loads the underlying + * interface. + * */ + async initializeRemote() { + await this._remote.loadInterpreter(this.config, this.stdio); + this.globals = this._remote.globals; + } + /** + * delegates the code to be run to the underlying interface of + * the remote interpreter. + * Python exceptions are turned into JS exceptions. + * */ + async run(code) { + return await this._remote.run(code); + } + /** + * Same as run, but Python exceptions are not propagated: instead, they + * are logged to the console. + * + * This is a bad API and should be killed/refactored/changed eventually, + * but for now we have code which relies on it. + * */ + async runButDontRaise(code) { + let result; + try { + result = (await this.run(code)).result; + } + catch (error) { + logger$9.error('Error:', error); + } + return result; + } + } + + const logger$8 = getLogger('plugin'); + class Plugin { + /** Validate the configuration of the plugin and handle default values. + * + * Individual plugins are expected to check that the config keys/sections + * which are relevant to them contains valid values, and to raise an error + * if they contains unknown keys. + * + * This is also a good place where set default values for those keys which + * are not specified by the user. + * + * This hook should **NOT** contain expensive operations, else it delays + * the download of the python interpreter which is initiated later. + */ + configure(config) { } + /** The preliminary initialization phase is complete and we are about to + * download and launch the Python interpreter. + * + * We can assume that the page is already shown to the user and that the + * DOM content has been loaded. This is a good place where to add tags to + * the DOM, if needed. + * + * This hook should **NOT** contain expensive operations, else it delays + * the download of the python interpreter which is initiated later. + */ + beforeLaunch(config) { } + /** The Python interpreter has been launched, the virtualenv has been + * installed and we are ready to execute user code. + * + * The <py-script> tags will be executed after this hook. + */ + afterSetup(interpreter) { } + /** The source of a <py-script>> tag has been fetched, and we're about + * to evaluate that source using the provided interpreter. + * + * @param options.interpreter The Interpreter object that will be used to evaluated the Python source code + * @param options.src {string} The Python source code to be evaluated + * @param options.pyScriptTag The <py-script> HTML tag that originated the evaluation + */ + beforePyScriptExec(options) { } + /** The Python in a <py-script> has just been evaluated, but control + * has not been ceded back to the JavaScript event loop yet + * + * @param options.interpreter The Interpreter object that will be used to evaluated the Python source code + * @param options.src {string} The Python source code to be evaluated + * @param options.pyScriptTag The <py-script> HTML tag that originated the evaluation + * @param options.result The returned result of evaluating the Python (if any) + */ + afterPyScriptExec(options) { } + /** Startup complete. The interpreter is initialized and ready, user + * scripts have been executed: the main initialization logic ends here and + * the page is ready to accept user interactions. + */ + afterStartup(interpreter) { } + /** Called when an UserError is raised + */ + onUserError(error) { } + } + class PluginManager { + constructor() { + this._plugins = []; + this._pythonPlugins = []; + } + add(...plugins) { + for (const p of plugins) + this._plugins.push(p); + } + addPythonPlugin(plugin) { + this._pythonPlugins.push(plugin); + } + configure(config) { + for (const p of this._plugins) + p.configure?.(config); + for (const p of this._pythonPlugins) + p.configure?.(config); + } + beforeLaunch(config) { + for (const p of this._plugins) { + try { + p?.beforeLaunch?.(config); + } + catch (e) { + logger$8.error(`Error while calling beforeLaunch hook of plugin ${p.constructor.name}`, e); + } + } + } + afterSetup(interpreter) { + for (const p of this._plugins) { + try { + p.afterSetup?.(interpreter); + } + catch (e) { + logger$8.error(`Error while calling afterSetup hook of plugin ${p.constructor.name}`, e); + } + } + for (const p of this._pythonPlugins) + p.afterSetup?.(interpreter); + } + afterStartup(interpreter) { + for (const p of this._plugins) + p.afterStartup?.(interpreter); + for (const p of this._pythonPlugins) + p.afterStartup?.(interpreter); + } + beforePyScriptExec(options) { + for (const p of this._plugins) + p.beforePyScriptExec?.(options); + for (const p of this._pythonPlugins) + p.beforePyScriptExec?.callKwargs(options); + } + afterPyScriptExec(options) { + for (const p of this._plugins) + p.afterPyScriptExec?.(options); + for (const p of this._pythonPlugins) + p.afterPyScriptExec?.callKwargs(options); + } + onUserError(error) { + for (const p of this._plugins) + p.onUserError?.(error); + for (const p of this._pythonPlugins) + p.onUserError?.(error); + } + } + /** + * Defines a new CustomElement (via customElement.defines) with `tag`, + * where the new CustomElement is a proxy that delegates the logic to + * pyPluginClass. + * + * @param tag - tag that will be used to define the new CustomElement (i.e: "py-script") + * @param pyPluginClass - class that will be used to create instance to be + * used as CustomElement logic handler. Any DOM event + * received by the newly created CustomElement will be + * delegated to that instance. + */ + function define_custom_element(tag, pyPluginClass) { + logger$8.info(`creating plugin: ${tag}`); + class ProxyCustomElement extends HTMLElement { + constructor() { + logger$8.debug(`creating ${tag} plugin instance`); + super(); + this.shadow = this.attachShadow({ mode: 'open' }); + this.wrapper = document.createElement('slot'); + this.shadow.appendChild(this.wrapper); + this.originalInnerHTML = this.innerHTML; + this.pyPluginInstance = pyPluginClass(this); + } + connectedCallback() { + const innerHTML = this.pyPluginInstance.connect(); + if (typeof innerHTML === 'string') + this.innerHTML = innerHTML; + } + } + customElements.define(tag, ProxyCustomElement); + } + + const logger$7 = getLogger('pyexec'); + async function pyExec(interpreter, pysrc, outElem) { + //This is pyscript.py + const pyscript_py = interpreter._remote.interface.pyimport('pyscript'); + ensureUniqueId(outElem); + pyscript_py.set_current_display_target(outElem.id); + try { + try { + if (pyscript_py.uses_top_level_await(pysrc)) { + throw new UserError(ErrorCode.TOP_LEVEL_AWAIT, 'The use of top-level "await", "async for", and ' + + '"async with" has been removed.' + + '\nPlease write a coroutine containing ' + + 'your code and schedule it using asyncio.ensure_future() or similar.' + + '\nSee https://docs.pyscript.net/latest/guides/asyncio.html for more information.'); + } + return await interpreter.run(pysrc); + } + catch (err) { + // XXX: currently we display exceptions in the same position as + // the output. But we probably need a better way to do that, + // e.g. allowing plugins to intercept exceptions and display them + // in a configurable way. + displayPyException(err, outElem); + return { result: undefined }; + } + } + finally { + pyscript_py.set_current_display_target(undefined); + pyscript_py.destroy(); + } + } + /** + * Javascript API to call the python display() function + * + * Expected usage: + * pyDisplay(interpreter, obj); + * pyDisplay(interpreter, obj, { target: targetID }); + */ + function pyDisplay(interpreter, obj, kwargs) { + const display = interpreter.globals.get('display'); + if (kwargs === undefined) + display(obj); + else { + display.callKwargs(obj, kwargs); + } + } + function displayPyException(err, errElem) { + //addClasses(errElem, ['py-error']) + const pre = document.createElement('pre'); + pre.className = 'py-error'; + if (err.name === 'PythonError') { + // err.message contains the python-level traceback (i.e. a string + // starting with: "Traceback (most recent call last) ..." + logger$7.error('Python exception:\n' + err.message); + pre.innerText = err.message; + } + else { + // this is very likely a normal JS exception. The best we can do is to + // display it as is. + logger$7.error('Non-python exception:\n' + err); + pre.innerText = err; + } + errElem.appendChild(pre); + } + + const logger$6 = getLogger('py-script'); + function make_PyScript(interpreter, app) { + class PyScript extends HTMLElement { + async connectedCallback() { + /** + * Since connectedCallback is async, multiple py-script tags can be executed in + * an order which is not particularly sequential. The locking mechanism here ensures + * a sequential execution of multiple py-script tags present in one page. + * + * Concurrent access to the multiple py-script tags is thus avoided. + */ + let releaseLock; + try { + releaseLock = await app.tagExecutionLock(); + ensureUniqueId(this); + // Save innerHTML information in srcCode so we can access it later + // once we clean innerHTML (which is required since we don't want + // source code to be rendered on the screen) + this.srcCode = this.innerHTML; + const pySrc = await this.getPySrc(); + this.innerHTML = ''; + app.plugins.beforePyScriptExec({ interpreter: interpreter, src: pySrc, pyScriptTag: this }); + const result = (await pyExec(interpreter, pySrc, this)).result; + app.plugins.afterPyScriptExec({ + interpreter: interpreter, + src: pySrc, + pyScriptTag: this, + result: result, + }); + } + finally { + releaseLock(); + } + } + async getPySrc() { + if (this.hasAttribute('src')) { + const url = this.getAttribute('src'); + try { + const response = await robustFetch(url); + return await response.text(); + } + catch (e) { + _createAlertBanner(e.message); + this.innerHTML = ''; + throw e; + } + } + else { + return htmlDecode(this.srcCode); + } + } + } + return PyScript; + } + /** Defines all possible py-on* and their corresponding event types */ + const pyAttributeToEvent = new Map([ + // Leaving pys-onClick and pys-onKeyDown for backward compatibility + ['pys-onClick', 'click'], + ['pys-onKeyDown', 'keydown'], + ['py-onClick', 'click'], + ['py-onKeyDown', 'keydown'], + // Window Events + ['py-afterprint', 'afterprint'], + ['py-beforeprint', 'beforeprint'], + ['py-beforeunload', 'beforeunload'], + ['py-error', 'error'], + ['py-hashchange', 'hashchange'], + ['py-load', 'load'], + ['py-message', 'message'], + ['py-offline', 'offline'], + ['py-online', 'online'], + ['py-pagehide', 'pagehide'], + ['py-pageshow', 'pageshow'], + ['py-popstate', 'popstate'], + ['py-resize', 'resize'], + ['py-storage', 'storage'], + ['py-unload', 'unload'], + // Form Events + ['py-blur', 'blur'], + ['py-change', 'change'], + ['py-contextmenu', 'contextmenu'], + ['py-focus', 'focus'], + ['py-input', 'input'], + ['py-invalid', 'invalid'], + ['py-reset', 'reset'], + ['py-search', 'search'], + ['py-select', 'select'], + ['py-submit', 'submit'], + // Keyboard Events + ['py-keydown', 'keydown'], + ['py-keypress', 'keypress'], + ['py-keyup', 'keyup'], + // Mouse Events + ['py-click', 'click'], + ['py-dblclick', 'dblclick'], + ['py-mousedown', 'mousedown'], + ['py-mousemove', 'mousemove'], + ['py-mouseout', 'mouseout'], + ['py-mouseover', 'mouseover'], + ['py-mouseup', 'mouseup'], + ['py-mousewheel', 'mousewheel'], + ['py-wheel', 'wheel'], + // Drag Events + ['py-drag', 'drag'], + ['py-dragend', 'dragend'], + ['py-dragenter', 'dragenter'], + ['py-dragleave', 'dragleave'], + ['py-dragover', 'dragover'], + ['py-dragstart', 'dragstart'], + ['py-drop', 'drop'], + ['py-scroll', 'scroll'], + // Clipboard Events + ['py-copy', 'copy'], + ['py-cut', 'cut'], + ['py-paste', 'paste'], + // Media Events + ['py-abort', 'abort'], + ['py-canplay', 'canplay'], + ['py-canplaythrough', 'canplaythrough'], + ['py-cuechange', 'cuechange'], + ['py-durationchange', 'durationchange'], + ['py-emptied', 'emptied'], + ['py-ended', 'ended'], + ['py-loadeddata', 'loadeddata'], + ['py-loadedmetadata', 'loadedmetadata'], + ['py-loadstart', 'loadstart'], + ['py-pause', 'pause'], + ['py-play', 'play'], + ['py-playing', 'playing'], + ['py-progress', 'progress'], + ['py-ratechange', 'ratechange'], + ['py-seeked', 'seeked'], + ['py-seeking', 'seeking'], + ['py-stalled', 'stalled'], + ['py-suspend', 'suspend'], + ['py-timeupdate', 'timeupdate'], + ['py-volumechange', 'volumechange'], + ['py-waiting', 'waiting'], + // Misc Events + ['py-toggle', 'toggle'], + ]); + /** Initialize all elements with py-* handlers attributes */ + function initHandlers(interpreter) { + logger$6.debug('Initializing py-* event handlers...'); + for (const pyAttribute of pyAttributeToEvent.keys()) { + createElementsWithEventListeners(interpreter, pyAttribute); + } + } + /** Initializes an element with the given py-on* attribute and its handler */ + function createElementsWithEventListeners(interpreter, pyAttribute) { + const matches = document.querySelectorAll(`[${pyAttribute}]`); + for (const el of matches) { + // If the element doesn't have an id, let's add one automatically! + if (el.id.length === 0) { + ensureUniqueId(el); + } + const handlerCode = el.getAttribute(pyAttribute); + const event = pyAttributeToEvent.get(pyAttribute); + if (pyAttribute === 'pys-onClick' || pyAttribute === 'pys-onKeyDown') { + const msg = `The attribute 'pys-onClick' and 'pys-onKeyDown' are deprecated. Please 'py-click="myFunction()"' ` + + ` or 'py-keydown="myFunction()"' instead.`; + createDeprecationWarning(msg, msg); + const source = ` from pyodide.ffi import create_proxy Element("${el.id}").element.addEventListener("${event}", create_proxy(${handlerCode})) `; - await runtime.run(source); - } - else { - el.addEventListener(event, () => { - (async () => { await runtime.run(handlerCode); })(); - }); - } - // TODO: Should we actually map handlers in JS instead of Python? - // el.onclick = (evt: any) => { - // console.log("click"); - // new Promise((resolve, reject) => { - // setTimeout(() => { - // console.log('Inside') - // }, 300); - // }).then(() => { - // console.log("resolved") - // }); - // // let handlerCode = el.getAttribute('py-onClick'); - // // pyodide.runPython(handlerCode); - // } - } - } - /** Mount all elements with attribute py-mount into the Python namespace */ - async function mountElements() { - const matches = document.querySelectorAll('[py-mount]'); - logger$a.info(`py-mount: found ${matches.length} elements`); - let source = ''; - for (const el of matches) { - const mountName = el.getAttribute('py-mount') || el.id.split('-').join('_'); - source += `\n${mountName} = Element("${el.id}")`; - } - await runtime$1.run(source); - } - addInitializer(mountElements); - addPostInitializer(initHandlers); - - /*! js-yaml 4.1.0 https://github.com/nodeca/js-yaml @license MIT */ - function isNothing(subject) { - return (typeof subject === 'undefined') || (subject === null); - } - - - function isObject(subject) { - return (typeof subject === 'object') && (subject !== null); - } - - - function toArray(sequence) { - if (Array.isArray(sequence)) return sequence; - else if (isNothing(sequence)) return []; - - return [ sequence ]; - } - - - function extend$1(target, source) { - var index, length, key, sourceKeys; - - if (source) { - sourceKeys = Object.keys(source); - - for (index = 0, length = sourceKeys.length; index < length; index += 1) { - key = sourceKeys[index]; - target[key] = source[key]; - } + // We meed to run the source code in a try/catch block, because + // the source code may contain a syntax error, which will cause + // the splashscreen to not be removed. + try { + interpreter.run(source); + } + catch (e) { + logger$6.error(e.message); + } + } + else { + el.addEventListener(event, () => { + void (async () => { + try { + await interpreter.run(handlerCode); + } + catch (err) { + displayPyException(err, el.parentElement); + } + })(); + }); + } + // TODO: Should we actually map handlers in JS instead of Python? + // el.onclick = (evt: any) => { + // console.log("click"); + // new Promise((resolve, reject) => { + // setTimeout(() => { + // console.log('Inside') + // }, 300); + // }).then(() => { + // console.log("resolved") + // }); + // // let handlerCode = el.getAttribute('py-onClick'); + // // pyodide.runPython(handlerCode); + // } } + } + /** Mount all elements with attribute py-mount into the Python namespace */ + async function mountElements(interpreter) { + const matches = document.querySelectorAll('[py-mount]'); + logger$6.info(`py-mount: found ${matches.length} elements`); + let source = ''; + for (const el of matches) { + const mountName = el.getAttribute('py-mount') || el.id.split('-').join('_'); + source += `\n${mountName} = Element("${el.id}")`; + } + await interpreter.run(source); + } + function calculatePaths(fetch_cfg) { + const fetchPaths = []; + const paths = []; + fetch_cfg.forEach(function (each_fetch_cfg) { + const from = each_fetch_cfg.from || ''; + const to_folder = each_fetch_cfg.to_folder || '.'; + const to_file = each_fetch_cfg.to_file; + const files = each_fetch_cfg.files; + if (files !== undefined) { + if (to_file !== undefined) { + throw new UserError(ErrorCode.BAD_CONFIG, `Cannot use 'to_file' and 'files' parameters together!`); + } + for (const each_f of files) { + const each_fetch_path = joinPaths([from, each_f]); + fetchPaths.push(each_fetch_path); + const each_path = joinPaths([to_folder, each_f]); + paths.push(each_path); + } + } + else { + fetchPaths.push(from); + const filename = to_file || from.split('/').pop(); + if (filename === '') { + throw new UserError(ErrorCode.BAD_CONFIG, `Couldn't determine the filename from the path ${from}, please supply 'to_file' parameter.`); + } + else { + paths.push(joinPaths([to_folder, filename])); + } + } + }); + return [paths, fetchPaths]; + } + + /** + The data structure for documents. @nonabstract + */ + class Text { + /** + @internal + */ + constructor() { } + /** + Get the line description around the given position. + */ + lineAt(pos) { + if (pos < 0 || pos > this.length) + throw new RangeError(`Invalid position ${pos} in document of length ${this.length}`); + return this.lineInner(pos, false, 1, 0); + } + /** + Get the description for the given (1-based) line number. + */ + line(n) { + if (n < 1 || n > this.lines) + throw new RangeError(`Invalid line number ${n} in ${this.lines}-line document`); + return this.lineInner(n, true, 1, 0); + } + /** + Replace a range of the text with the given content. + */ + replace(from, to, text) { + let parts = []; + this.decompose(0, from, parts, 2 /* Open.To */); + if (text.length) + text.decompose(0, text.length, parts, 1 /* Open.From */ | 2 /* Open.To */); + this.decompose(to, this.length, parts, 1 /* Open.From */); + return TextNode.from(parts, this.length - (to - from) + text.length); + } + /** + Append another document to this one. + */ + append(other) { + return this.replace(this.length, this.length, other); + } + /** + Retrieve the text between the given points. + */ + slice(from, to = this.length) { + let parts = []; + this.decompose(from, to, parts, 0); + return TextNode.from(parts, to - from); + } + /** + Test whether this text is equal to another instance. + */ + eq(other) { + if (other == this) + return true; + if (other.length != this.length || other.lines != this.lines) + return false; + let start = this.scanIdentical(other, 1), end = this.length - this.scanIdentical(other, -1); + let a = new RawTextCursor(this), b = new RawTextCursor(other); + for (let skip = start, pos = start;;) { + a.next(skip); + b.next(skip); + skip = 0; + if (a.lineBreak != b.lineBreak || a.done != b.done || a.value != b.value) + return false; + pos += a.value.length; + if (a.done || pos >= end) + return true; + } + } + /** + Iterate over the text. When `dir` is `-1`, iteration happens + from end to start. This will return lines and the breaks between + them as separate strings. + */ + iter(dir = 1) { return new RawTextCursor(this, dir); } + /** + Iterate over a range of the text. When `from` > `to`, the + iterator will run in reverse. + */ + iterRange(from, to = this.length) { return new PartialTextCursor(this, from, to); } + /** + Return a cursor that iterates over the given range of lines, + _without_ returning the line breaks between, and yielding empty + strings for empty lines. + + When `from` and `to` are given, they should be 1-based line numbers. + */ + iterLines(from, to) { + let inner; + if (from == null) { + inner = this.iter(); + } + else { + if (to == null) + to = this.lines + 1; + let start = this.line(from).from; + inner = this.iterRange(start, Math.max(start, to == this.lines + 1 ? this.length : to <= 1 ? 0 : this.line(to - 1).to)); + } + return new LineCursor(inner); + } + /** + @internal + */ + toString() { return this.sliceString(0); } + /** + Convert the document to an array of lines (which can be + deserialized again via [`Text.of`](https://codemirror.net/6/docs/ref/#state.Text^of)). + */ + toJSON() { + let lines = []; + this.flatten(lines); + return lines; + } + /** + Create a `Text` instance for the given array of lines. + */ + static of(text) { + if (text.length == 0) + throw new RangeError("A document must have at least one line"); + if (text.length == 1 && !text[0]) + return Text.empty; + return text.length <= 32 /* Tree.Branch */ ? new TextLeaf(text) : TextNode.from(TextLeaf.split(text, [])); + } + } + // Leaves store an array of line strings. There are always line breaks + // between these strings. Leaves are limited in size and have to be + // contained in TextNode instances for bigger documents. + class TextLeaf extends Text { + constructor(text, length = textLength(text)) { + super(); + this.text = text; + this.length = length; + } + get lines() { return this.text.length; } + get children() { return null; } + lineInner(target, isLine, line, offset) { + for (let i = 0;; i++) { + let string = this.text[i], end = offset + string.length; + if ((isLine ? line : end) >= target) + return new Line(offset, end, line, string); + offset = end + 1; + line++; + } + } + decompose(from, to, target, open) { + let text = from <= 0 && to >= this.length ? this + : new TextLeaf(sliceText(this.text, from, to), Math.min(to, this.length) - Math.max(0, from)); + if (open & 1 /* Open.From */) { + let prev = target.pop(); + let joined = appendText(text.text, prev.text.slice(), 0, text.length); + if (joined.length <= 32 /* Tree.Branch */) { + target.push(new TextLeaf(joined, prev.length + text.length)); + } + else { + let mid = joined.length >> 1; + target.push(new TextLeaf(joined.slice(0, mid)), new TextLeaf(joined.slice(mid))); + } + } + else { + target.push(text); + } + } + replace(from, to, text) { + if (!(text instanceof TextLeaf)) + return super.replace(from, to, text); + let lines = appendText(this.text, appendText(text.text, sliceText(this.text, 0, from)), to); + let newLen = this.length + text.length - (to - from); + if (lines.length <= 32 /* Tree.Branch */) + return new TextLeaf(lines, newLen); + return TextNode.from(TextLeaf.split(lines, []), newLen); + } + sliceString(from, to = this.length, lineSep = "\n") { + let result = ""; + for (let pos = 0, i = 0; pos <= to && i < this.text.length; i++) { + let line = this.text[i], end = pos + line.length; + if (pos > from && i) + result += lineSep; + if (from < end && to > pos) + result += line.slice(Math.max(0, from - pos), to - pos); + pos = end + 1; + } + return result; + } + flatten(target) { + for (let line of this.text) + target.push(line); + } + scanIdentical() { return 0; } + static split(text, target) { + let part = [], len = -1; + for (let line of text) { + part.push(line); + len += line.length + 1; + if (part.length == 32 /* Tree.Branch */) { + target.push(new TextLeaf(part, len)); + part = []; + len = -1; + } + } + if (len > -1) + target.push(new TextLeaf(part, len)); + return target; + } + } + // Nodes provide the tree structure of the `Text` type. They store a + // number of other nodes or leaves, taking care to balance themselves + // on changes. There are implied line breaks _between_ the children of + // a node (but not before the first or after the last child). + class TextNode extends Text { + constructor(children, length) { + super(); + this.children = children; + this.length = length; + this.lines = 0; + for (let child of children) + this.lines += child.lines; + } + lineInner(target, isLine, line, offset) { + for (let i = 0;; i++) { + let child = this.children[i], end = offset + child.length, endLine = line + child.lines - 1; + if ((isLine ? endLine : end) >= target) + return child.lineInner(target, isLine, line, offset); + offset = end + 1; + line = endLine + 1; + } + } + decompose(from, to, target, open) { + for (let i = 0, pos = 0; pos <= to && i < this.children.length; i++) { + let child = this.children[i], end = pos + child.length; + if (from <= end && to >= pos) { + let childOpen = open & ((pos <= from ? 1 /* Open.From */ : 0) | (end >= to ? 2 /* Open.To */ : 0)); + if (pos >= from && end <= to && !childOpen) + target.push(child); + else + child.decompose(from - pos, to - pos, target, childOpen); + } + pos = end + 1; + } + } + replace(from, to, text) { + if (text.lines < this.lines) + for (let i = 0, pos = 0; i < this.children.length; i++) { + let child = this.children[i], end = pos + child.length; + // Fast path: if the change only affects one child and the + // child's size remains in the acceptable range, only update + // that child + if (from >= pos && to <= end) { + let updated = child.replace(from - pos, to - pos, text); + let totalLines = this.lines - child.lines + updated.lines; + if (updated.lines < (totalLines >> (5 /* Tree.BranchShift */ - 1)) && + updated.lines > (totalLines >> (5 /* Tree.BranchShift */ + 1))) { + let copy = this.children.slice(); + copy[i] = updated; + return new TextNode(copy, this.length - (to - from) + text.length); + } + return super.replace(pos, end, updated); + } + pos = end + 1; + } + return super.replace(from, to, text); + } + sliceString(from, to = this.length, lineSep = "\n") { + let result = ""; + for (let i = 0, pos = 0; i < this.children.length && pos <= to; i++) { + let child = this.children[i], end = pos + child.length; + if (pos > from && i) + result += lineSep; + if (from < end && to > pos) + result += child.sliceString(from - pos, to - pos, lineSep); + pos = end + 1; + } + return result; + } + flatten(target) { + for (let child of this.children) + child.flatten(target); + } + scanIdentical(other, dir) { + if (!(other instanceof TextNode)) + return 0; + let length = 0; + let [iA, iB, eA, eB] = dir > 0 ? [0, 0, this.children.length, other.children.length] + : [this.children.length - 1, other.children.length - 1, -1, -1]; + for (;; iA += dir, iB += dir) { + if (iA == eA || iB == eB) + return length; + let chA = this.children[iA], chB = other.children[iB]; + if (chA != chB) + return length + chA.scanIdentical(chB, dir); + length += chA.length + 1; + } + } + static from(children, length = children.reduce((l, ch) => l + ch.length + 1, -1)) { + let lines = 0; + for (let ch of children) + lines += ch.lines; + if (lines < 32 /* Tree.Branch */) { + let flat = []; + for (let ch of children) + ch.flatten(flat); + return new TextLeaf(flat, length); + } + let chunk = Math.max(32 /* Tree.Branch */, lines >> 5 /* Tree.BranchShift */), maxChunk = chunk << 1, minChunk = chunk >> 1; + let chunked = [], currentLines = 0, currentLen = -1, currentChunk = []; + function add(child) { + let last; + if (child.lines > maxChunk && child instanceof TextNode) { + for (let node of child.children) + add(node); + } + else if (child.lines > minChunk && (currentLines > minChunk || !currentLines)) { + flush(); + chunked.push(child); + } + else if (child instanceof TextLeaf && currentLines && + (last = currentChunk[currentChunk.length - 1]) instanceof TextLeaf && + child.lines + last.lines <= 32 /* Tree.Branch */) { + currentLines += child.lines; + currentLen += child.length + 1; + currentChunk[currentChunk.length - 1] = new TextLeaf(last.text.concat(child.text), last.length + 1 + child.length); + } + else { + if (currentLines + child.lines > chunk) + flush(); + currentLines += child.lines; + currentLen += child.length + 1; + currentChunk.push(child); + } + } + function flush() { + if (currentLines == 0) + return; + chunked.push(currentChunk.length == 1 ? currentChunk[0] : TextNode.from(currentChunk, currentLen)); + currentLen = -1; + currentLines = currentChunk.length = 0; + } + for (let child of children) + add(child); + flush(); + return chunked.length == 1 ? chunked[0] : new TextNode(chunked, length); + } + } + Text.empty = /*@__PURE__*/new TextLeaf([""], 0); + function textLength(text) { + let length = -1; + for (let line of text) + length += line.length + 1; + return length; + } + function appendText(text, target, from = 0, to = 1e9) { + for (let pos = 0, i = 0, first = true; i < text.length && pos <= to; i++) { + let line = text[i], end = pos + line.length; + if (end >= from) { + if (end > to) + line = line.slice(0, to - pos); + if (pos < from) + line = line.slice(from - pos); + if (first) { + target[target.length - 1] += line; + first = false; + } + else + target.push(line); + } + pos = end + 1; + } return target; - } - - - function repeat(string, count) { - var result = '', cycle; - - for (cycle = 0; cycle < count; cycle += 1) { - result += string; + } + function sliceText(text, from, to) { + return appendText(text, [""], from, to); + } + class RawTextCursor { + constructor(text, dir = 1) { + this.dir = dir; + this.done = false; + this.lineBreak = false; + this.value = ""; + this.nodes = [text]; + this.offsets = [dir > 0 ? 1 : (text instanceof TextLeaf ? text.text.length : text.children.length) << 1]; } - - return result; - } - - - function isNegativeZero(number) { - return (number === 0) && (Number.NEGATIVE_INFINITY === 1 / number); - } - - - var isNothing_1 = isNothing; - var isObject_1 = isObject; - var toArray_1 = toArray; - var repeat_1 = repeat; - var isNegativeZero_1 = isNegativeZero; - var extend_1 = extend$1; - - var common = { - isNothing: isNothing_1, - isObject: isObject_1, - toArray: toArray_1, - repeat: repeat_1, - isNegativeZero: isNegativeZero_1, - extend: extend_1 - }; - - // YAML error class. http://stackoverflow.com/questions/8458984 - - - function formatError(exception, compact) { - var where = '', message = exception.reason || '(unknown reason)'; - - if (!exception.mark) return message; - - if (exception.mark.name) { - where += 'in "' + exception.mark.name + '" '; - } - - where += '(' + (exception.mark.line + 1) + ':' + (exception.mark.column + 1) + ')'; - - if (!compact && exception.mark.snippet) { - where += '\n\n' + exception.mark.snippet; - } - - return message + ' ' + where; - } - - - function YAMLException$1(reason, mark) { - // Super constructor - Error.call(this); - - this.name = 'YAMLException'; - this.reason = reason; - this.mark = mark; - this.message = formatError(this, false); - - // Include stack trace in error object - if (Error.captureStackTrace) { - // Chrome and NodeJS - Error.captureStackTrace(this, this.constructor); - } else { - // FF, IE 10+ and Safari 6+. Fallback for others - this.stack = (new Error()).stack || ''; - } - } - - - // Inherit from Error - YAMLException$1.prototype = Object.create(Error.prototype); - YAMLException$1.prototype.constructor = YAMLException$1; - - - YAMLException$1.prototype.toString = function toString(compact) { - return this.name + ': ' + formatError(this, compact); - }; - - - var exception = YAMLException$1; - - // get snippet for a single line, respecting maxLength - function getLine(buffer, lineStart, lineEnd, position, maxLineLength) { - var head = ''; - var tail = ''; - var maxHalfLength = Math.floor(maxLineLength / 2) - 1; - - if (position - lineStart > maxHalfLength) { - head = ' ... '; - lineStart = position - maxHalfLength + head.length; - } - - if (lineEnd - position > maxHalfLength) { - tail = ' ...'; - lineEnd = position + maxHalfLength - tail.length; - } - - return { - str: head + buffer.slice(lineStart, lineEnd).replace(/\t/g, '→') + tail, - pos: position - lineStart + head.length // relative position - }; - } - - - function padStart(string, max) { - return common.repeat(' ', max - string.length) + string; - } - - - function makeSnippet(mark, options) { - options = Object.create(options || null); - - if (!mark.buffer) return null; - - if (!options.maxLength) options.maxLength = 79; - if (typeof options.indent !== 'number') options.indent = 1; - if (typeof options.linesBefore !== 'number') options.linesBefore = 3; - if (typeof options.linesAfter !== 'number') options.linesAfter = 2; - - var re = /\r?\n|\r|\0/g; - var lineStarts = [ 0 ]; - var lineEnds = []; - var match; - var foundLineNo = -1; - - while ((match = re.exec(mark.buffer))) { - lineEnds.push(match.index); - lineStarts.push(match.index + match[0].length); - - if (mark.position <= match.index && foundLineNo < 0) { - foundLineNo = lineStarts.length - 2; - } - } - - if (foundLineNo < 0) foundLineNo = lineStarts.length - 1; - - var result = '', i, line; - var lineNoLength = Math.min(mark.line + options.linesAfter, lineEnds.length).toString().length; - var maxLineLength = options.maxLength - (options.indent + lineNoLength + 3); - - for (i = 1; i <= options.linesBefore; i++) { - if (foundLineNo - i < 0) break; - line = getLine( - mark.buffer, - lineStarts[foundLineNo - i], - lineEnds[foundLineNo - i], - mark.position - (lineStarts[foundLineNo] - lineStarts[foundLineNo - i]), - maxLineLength - ); - result = common.repeat(' ', options.indent) + padStart((mark.line - i + 1).toString(), lineNoLength) + - ' | ' + line.str + '\n' + result; - } - - line = getLine(mark.buffer, lineStarts[foundLineNo], lineEnds[foundLineNo], mark.position, maxLineLength); - result += common.repeat(' ', options.indent) + padStart((mark.line + 1).toString(), lineNoLength) + - ' | ' + line.str + '\n'; - result += common.repeat('-', options.indent + lineNoLength + 3 + line.pos) + '^' + '\n'; - - for (i = 1; i <= options.linesAfter; i++) { - if (foundLineNo + i >= lineEnds.length) break; - line = getLine( - mark.buffer, - lineStarts[foundLineNo + i], - lineEnds[foundLineNo + i], - mark.position - (lineStarts[foundLineNo] - lineStarts[foundLineNo + i]), - maxLineLength - ); - result += common.repeat(' ', options.indent) + padStart((mark.line + i + 1).toString(), lineNoLength) + - ' | ' + line.str + '\n'; - } - - return result.replace(/\n$/, ''); - } - - - var snippet = makeSnippet; - - var TYPE_CONSTRUCTOR_OPTIONS = [ - 'kind', - 'multi', - 'resolve', - 'construct', - 'instanceOf', - 'predicate', - 'represent', - 'representName', - 'defaultStyle', - 'styleAliases' - ]; - - var YAML_NODE_KINDS = [ - 'scalar', - 'sequence', - 'mapping' - ]; - - function compileStyleAliases(map) { - var result = {}; - - if (map !== null) { - Object.keys(map).forEach(function (style) { - map[style].forEach(function (alias) { - result[String(alias)] = style; - }); - }); - } - - return result; - } - - function Type$1(tag, options) { - options = options || {}; - - Object.keys(options).forEach(function (name) { - if (TYPE_CONSTRUCTOR_OPTIONS.indexOf(name) === -1) { - throw new exception('Unknown option "' + name + '" is met in definition of "' + tag + '" YAML type.'); - } - }); - - // TODO: Add tag format check. - this.options = options; // keep original options in case user wants to extend this type later - this.tag = tag; - this.kind = options['kind'] || null; - this.resolve = options['resolve'] || function () { return true; }; - this.construct = options['construct'] || function (data) { return data; }; - this.instanceOf = options['instanceOf'] || null; - this.predicate = options['predicate'] || null; - this.represent = options['represent'] || null; - this.representName = options['representName'] || null; - this.defaultStyle = options['defaultStyle'] || null; - this.multi = options['multi'] || false; - this.styleAliases = compileStyleAliases(options['styleAliases'] || null); - - if (YAML_NODE_KINDS.indexOf(this.kind) === -1) { - throw new exception('Unknown kind "' + this.kind + '" is specified for "' + tag + '" YAML type.'); - } - } - - var type = Type$1; - - /*eslint-disable max-len*/ - - - - - - function compileList(schema, name) { - var result = []; - - schema[name].forEach(function (currentType) { - var newIndex = result.length; - - result.forEach(function (previousType, previousIndex) { - if (previousType.tag === currentType.tag && - previousType.kind === currentType.kind && - previousType.multi === currentType.multi) { - - newIndex = previousIndex; + nextInner(skip, dir) { + this.done = this.lineBreak = false; + for (;;) { + let last = this.nodes.length - 1; + let top = this.nodes[last], offsetValue = this.offsets[last], offset = offsetValue >> 1; + let size = top instanceof TextLeaf ? top.text.length : top.children.length; + if (offset == (dir > 0 ? size : 0)) { + if (last == 0) { + this.done = true; + this.value = ""; + return this; + } + if (dir > 0) + this.offsets[last - 1]++; + this.nodes.pop(); + this.offsets.pop(); + } + else if ((offsetValue & 1) == (dir > 0 ? 0 : 1)) { + this.offsets[last] += dir; + if (skip == 0) { + this.lineBreak = true; + this.value = "\n"; + return this; + } + skip--; + } + else if (top instanceof TextLeaf) { + // Move to the next string + let next = top.text[offset + (dir < 0 ? -1 : 0)]; + this.offsets[last] += dir; + if (next.length > Math.max(0, skip)) { + this.value = skip == 0 ? next : dir > 0 ? next.slice(skip) : next.slice(0, next.length - skip); + return this; + } + skip -= next.length; + } + else { + let next = top.children[offset + (dir < 0 ? -1 : 0)]; + if (skip > next.length) { + skip -= next.length; + this.offsets[last] += dir; + } + else { + if (dir < 0) + this.offsets[last]--; + this.nodes.push(next); + this.offsets.push(dir > 0 ? 1 : (next instanceof TextLeaf ? next.text.length : next.children.length) << 1); + } + } } - }); - - result[newIndex] = currentType; - }); - - return result; - } - - - function compileMap(/* lists... */) { - var result = { - scalar: {}, - sequence: {}, - mapping: {}, - fallback: {}, - multi: { - scalar: [], - sequence: [], - mapping: [], - fallback: [] - } - }, index, length; - - function collectType(type) { - if (type.multi) { - result.multi[type.kind].push(type); - result.multi['fallback'].push(type); - } else { - result[type.kind][type.tag] = result['fallback'][type.tag] = type; - } } - - for (index = 0, length = arguments.length; index < length; index += 1) { - arguments[index].forEach(collectType); - } - return result; - } - - - function Schema$1(definition) { - return this.extend(definition); - } - - - Schema$1.prototype.extend = function extend(definition) { - var implicit = []; - var explicit = []; - - if (definition instanceof type) { - // Schema.extend(type) - explicit.push(definition); - - } else if (Array.isArray(definition)) { - // Schema.extend([ type1, type2, ... ]) - explicit = explicit.concat(definition); - - } else if (definition && (Array.isArray(definition.implicit) || Array.isArray(definition.explicit))) { - // Schema.extend({ explicit: [ type1, type2, ... ], implicit: [ type1, type2, ... ] }) - if (definition.implicit) implicit = implicit.concat(definition.implicit); - if (definition.explicit) explicit = explicit.concat(definition.explicit); - - } else { - throw new exception('Schema.extend argument should be a Type, [ Type ], ' + - 'or a schema definition ({ implicit: [...], explicit: [...] })'); - } - - implicit.forEach(function (type$1) { - if (!(type$1 instanceof type)) { - throw new exception('Specified list of YAML types (or a single Type object) contains a non-Type object.'); - } - - if (type$1.loadKind && type$1.loadKind !== 'scalar') { - throw new exception('There is a non-scalar type in the implicit list of a schema. Implicit resolving of such types is not supported.'); - } - - if (type$1.multi) { - throw new exception('There is a multi type in the implicit list of a schema. Multi tags can only be listed as explicit.'); - } - }); - - explicit.forEach(function (type$1) { - if (!(type$1 instanceof type)) { - throw new exception('Specified list of YAML types (or a single Type object) contains a non-Type object.'); - } - }); - - var result = Object.create(Schema$1.prototype); - - result.implicit = (this.implicit || []).concat(implicit); - result.explicit = (this.explicit || []).concat(explicit); - - result.compiledImplicit = compileList(result, 'implicit'); - result.compiledExplicit = compileList(result, 'explicit'); - result.compiledTypeMap = compileMap(result.compiledImplicit, result.compiledExplicit); - - return result; - }; - - - var schema = Schema$1; - - var str = new type('tag:yaml.org,2002:str', { - kind: 'scalar', - construct: function (data) { return data !== null ? data : ''; } - }); - - var seq = new type('tag:yaml.org,2002:seq', { - kind: 'sequence', - construct: function (data) { return data !== null ? data : []; } - }); - - var map = new type('tag:yaml.org,2002:map', { - kind: 'mapping', - construct: function (data) { return data !== null ? data : {}; } - }); - - var failsafe = new schema({ - explicit: [ - str, - seq, - map - ] - }); - - function resolveYamlNull(data) { - if (data === null) return true; - - var max = data.length; - - return (max === 1 && data === '~') || - (max === 4 && (data === 'null' || data === 'Null' || data === 'NULL')); - } - - function constructYamlNull() { - return null; - } - - function isNull(object) { - return object === null; - } - - var _null = new type('tag:yaml.org,2002:null', { - kind: 'scalar', - resolve: resolveYamlNull, - construct: constructYamlNull, - predicate: isNull, - represent: { - canonical: function () { return '~'; }, - lowercase: function () { return 'null'; }, - uppercase: function () { return 'NULL'; }, - camelcase: function () { return 'Null'; }, - empty: function () { return ''; } - }, - defaultStyle: 'lowercase' - }); - - function resolveYamlBoolean(data) { - if (data === null) return false; - - var max = data.length; - - return (max === 4 && (data === 'true' || data === 'True' || data === 'TRUE')) || - (max === 5 && (data === 'false' || data === 'False' || data === 'FALSE')); - } - - function constructYamlBoolean(data) { - return data === 'true' || - data === 'True' || - data === 'TRUE'; - } - - function isBoolean(object) { - return Object.prototype.toString.call(object) === '[object Boolean]'; - } - - var bool = new type('tag:yaml.org,2002:bool', { - kind: 'scalar', - resolve: resolveYamlBoolean, - construct: constructYamlBoolean, - predicate: isBoolean, - represent: { - lowercase: function (object) { return object ? 'true' : 'false'; }, - uppercase: function (object) { return object ? 'TRUE' : 'FALSE'; }, - camelcase: function (object) { return object ? 'True' : 'False'; } - }, - defaultStyle: 'lowercase' - }); - - function isHexCode(c) { - return ((0x30/* 0 */ <= c) && (c <= 0x39/* 9 */)) || - ((0x41/* A */ <= c) && (c <= 0x46/* F */)) || - ((0x61/* a */ <= c) && (c <= 0x66/* f */)); - } - - function isOctCode(c) { - return ((0x30/* 0 */ <= c) && (c <= 0x37/* 7 */)); - } - - function isDecCode(c) { - return ((0x30/* 0 */ <= c) && (c <= 0x39/* 9 */)); - } - - function resolveYamlInteger(data) { - if (data === null) return false; - - var max = data.length, - index = 0, - hasDigits = false, - ch; - - if (!max) return false; - - ch = data[index]; - - // sign - if (ch === '-' || ch === '+') { - ch = data[++index]; - } - - if (ch === '0') { - // 0 - if (index + 1 === max) return true; - ch = data[++index]; - - // base 2, base 8, base 16 - - if (ch === 'b') { - // base 2 - index++; - - for (; index < max; index++) { - ch = data[index]; - if (ch === '_') continue; - if (ch !== '0' && ch !== '1') return false; - hasDigits = true; + next(skip = 0) { + if (skip < 0) { + this.nextInner(-skip, (-this.dir)); + skip = this.value.length; } - return hasDigits && ch !== '_'; - } - - - if (ch === 'x') { - // base 16 - index++; - - for (; index < max; index++) { - ch = data[index]; - if (ch === '_') continue; - if (!isHexCode(data.charCodeAt(index))) return false; - hasDigits = true; + return this.nextInner(skip, this.dir); + } + } + class PartialTextCursor { + constructor(text, start, end) { + this.value = ""; + this.done = false; + this.cursor = new RawTextCursor(text, start > end ? -1 : 1); + this.pos = start > end ? text.length : 0; + this.from = Math.min(start, end); + this.to = Math.max(start, end); + } + nextInner(skip, dir) { + if (dir < 0 ? this.pos <= this.from : this.pos >= this.to) { + this.value = ""; + this.done = true; + return this; } - return hasDigits && ch !== '_'; - } - - - if (ch === 'o') { - // base 8 - index++; - - for (; index < max; index++) { - ch = data[index]; - if (ch === '_') continue; - if (!isOctCode(data.charCodeAt(index))) return false; - hasDigits = true; + skip += Math.max(0, dir < 0 ? this.pos - this.to : this.from - this.pos); + let limit = dir < 0 ? this.pos - this.from : this.to - this.pos; + if (skip > limit) + skip = limit; + limit -= skip; + let { value } = this.cursor.next(skip); + this.pos += (value.length + skip) * dir; + this.value = value.length <= limit ? value : dir < 0 ? value.slice(value.length - limit) : value.slice(0, limit); + this.done = !this.value; + return this; + } + next(skip = 0) { + if (skip < 0) + skip = Math.max(skip, this.from - this.pos); + else if (skip > 0) + skip = Math.min(skip, this.to - this.pos); + return this.nextInner(skip, this.cursor.dir); + } + get lineBreak() { return this.cursor.lineBreak && this.value != ""; } + } + class LineCursor { + constructor(inner) { + this.inner = inner; + this.afterBreak = true; + this.value = ""; + this.done = false; + } + next(skip = 0) { + let { done, lineBreak, value } = this.inner.next(skip); + if (done) { + this.done = true; + this.value = ""; } - return hasDigits && ch !== '_'; - } + else if (lineBreak) { + if (this.afterBreak) { + this.value = ""; + } + else { + this.afterBreak = true; + this.next(); + } + } + else { + this.value = value; + this.afterBreak = false; + } + return this; } - - // base 10 (except 0) - - // value should not start with `_`; - if (ch === '_') return false; - - for (; index < max; index++) { - ch = data[index]; - if (ch === '_') continue; - if (!isDecCode(data.charCodeAt(index))) { - return false; - } - hasDigits = true; + get lineBreak() { return false; } + } + if (typeof Symbol != "undefined") { + Text.prototype[Symbol.iterator] = function () { return this.iter(); }; + RawTextCursor.prototype[Symbol.iterator] = PartialTextCursor.prototype[Symbol.iterator] = + LineCursor.prototype[Symbol.iterator] = function () { return this; }; + } + /** + This type describes a line in the document. It is created + on-demand when lines are [queried](https://codemirror.net/6/docs/ref/#state.Text.lineAt). + */ + class Line { + /** + @internal + */ + constructor( + /** + The position of the start of the line. + */ + from, + /** + The position at the end of the line (_before_ the line break, + or at the end of document for the last line). + */ + to, + /** + This line's line number (1-based). + */ + number, + /** + The line's content. + */ + text) { + this.from = from; + this.to = to; + this.number = number; + this.text = text; } + /** + The length of the line (not including any line break after it). + */ + get length() { return this.to - this.from; } + } - // Should have digits and should not end with `_` - if (!hasDigits || ch === '_') return false; - - return true; - } - - function constructYamlInteger(data) { - var value = data, sign = 1, ch; - - if (value.indexOf('_') !== -1) { - value = value.replace(/_/g, ''); - } - - ch = value[0]; - - if (ch === '-' || ch === '+') { - if (ch === '-') sign = -1; - value = value.slice(1); - ch = value[0]; - } - - if (value === '0') return 0; - - if (ch === '0') { - if (value[1] === 'b') return sign * parseInt(value.slice(2), 2); - if (value[1] === 'x') return sign * parseInt(value.slice(2), 16); - if (value[1] === 'o') return sign * parseInt(value.slice(2), 8); - } - - return sign * parseInt(value, 10); - } - - function isInteger(object) { - return (Object.prototype.toString.call(object)) === '[object Number]' && - (object % 1 === 0 && !common.isNegativeZero(object)); - } - - var int = new type('tag:yaml.org,2002:int', { - kind: 'scalar', - resolve: resolveYamlInteger, - construct: constructYamlInteger, - predicate: isInteger, - represent: { - binary: function (obj) { return obj >= 0 ? '0b' + obj.toString(2) : '-0b' + obj.toString(2).slice(1); }, - octal: function (obj) { return obj >= 0 ? '0o' + obj.toString(8) : '-0o' + obj.toString(8).slice(1); }, - decimal: function (obj) { return obj.toString(10); }, - /* eslint-disable max-len */ - hexadecimal: function (obj) { return obj >= 0 ? '0x' + obj.toString(16).toUpperCase() : '-0x' + obj.toString(16).toUpperCase().slice(1); } - }, - defaultStyle: 'decimal', - styleAliases: { - binary: [ 2, 'bin' ], - octal: [ 8, 'oct' ], - decimal: [ 10, 'dec' ], - hexadecimal: [ 16, 'hex' ] - } - }); - - var YAML_FLOAT_PATTERN = new RegExp( - // 2.5e4, 2.5 and integers - '^(?:[-+]?(?:[0-9][0-9_]*)(?:\\.[0-9_]*)?(?:[eE][-+]?[0-9]+)?' + - // .2e4, .2 - // special case, seems not from spec - '|\\.[0-9_]+(?:[eE][-+]?[0-9]+)?' + - // .inf - '|[-+]?\\.(?:inf|Inf|INF)' + - // .nan - '|\\.(?:nan|NaN|NAN))$'); - - function resolveYamlFloat(data) { - if (data === null) return false; - - if (!YAML_FLOAT_PATTERN.test(data) || - // Quick hack to not allow integers end with `_` - // Probably should update regexp & check speed - data[data.length - 1] === '_') { - return false; - } - - return true; - } - - function constructYamlFloat(data) { - var value, sign; - - value = data.replace(/_/g, '').toLowerCase(); - sign = value[0] === '-' ? -1 : 1; - - if ('+-'.indexOf(value[0]) >= 0) { - value = value.slice(1); - } - - if (value === '.inf') { - return (sign === 1) ? Number.POSITIVE_INFINITY : Number.NEGATIVE_INFINITY; - - } else if (value === '.nan') { - return NaN; - } - return sign * parseFloat(value, 10); - } - - - var SCIENTIFIC_WITHOUT_DOT = /^[-+]?[0-9]+e/; - - function representYamlFloat(object, style) { - var res; - - if (isNaN(object)) { - switch (style) { - case 'lowercase': return '.nan'; - case 'uppercase': return '.NAN'; - case 'camelcase': return '.NaN'; - } - } else if (Number.POSITIVE_INFINITY === object) { - switch (style) { - case 'lowercase': return '.inf'; - case 'uppercase': return '.INF'; - case 'camelcase': return '.Inf'; - } - } else if (Number.NEGATIVE_INFINITY === object) { - switch (style) { - case 'lowercase': return '-.inf'; - case 'uppercase': return '-.INF'; - case 'camelcase': return '-.Inf'; - } - } else if (common.isNegativeZero(object)) { - return '-0.0'; - } - - res = object.toString(10); - - // JS stringifier can build scientific format without dots: 5e-100, - // while YAML requres dot: 5.e-100. Fix it with simple hack - - return SCIENTIFIC_WITHOUT_DOT.test(res) ? res.replace('e', '.e') : res; - } - - function isFloat(object) { - return (Object.prototype.toString.call(object) === '[object Number]') && - (object % 1 !== 0 || common.isNegativeZero(object)); - } - - var float = new type('tag:yaml.org,2002:float', { - kind: 'scalar', - resolve: resolveYamlFloat, - construct: constructYamlFloat, - predicate: isFloat, - represent: representYamlFloat, - defaultStyle: 'lowercase' - }); - - var json = failsafe.extend({ - implicit: [ - _null, - bool, - int, - float - ] - }); - - var core = json; - - var YAML_DATE_REGEXP = new RegExp( - '^([0-9][0-9][0-9][0-9])' + // [1] year - '-([0-9][0-9])' + // [2] month - '-([0-9][0-9])$'); // [3] day - - var YAML_TIMESTAMP_REGEXP = new RegExp( - '^([0-9][0-9][0-9][0-9])' + // [1] year - '-([0-9][0-9]?)' + // [2] month - '-([0-9][0-9]?)' + // [3] day - '(?:[Tt]|[ \\t]+)' + // ... - '([0-9][0-9]?)' + // [4] hour - ':([0-9][0-9])' + // [5] minute - ':([0-9][0-9])' + // [6] second - '(?:\\.([0-9]*))?' + // [7] fraction - '(?:[ \\t]*(Z|([-+])([0-9][0-9]?)' + // [8] tz [9] tz_sign [10] tz_hour - '(?::([0-9][0-9]))?))?$'); // [11] tz_minute - - function resolveYamlTimestamp(data) { - if (data === null) return false; - if (YAML_DATE_REGEXP.exec(data) !== null) return true; - if (YAML_TIMESTAMP_REGEXP.exec(data) !== null) return true; + // Compressed representation of the Grapheme_Cluster_Break=Extend + // information from + // http://www.unicode.org/Public/13.0.0/ucd/auxiliary/GraphemeBreakProperty.txt. + // Each pair of elements represents a range, as an offet from the + // previous range and a length. Numbers are in base-36, with the empty + // string being a shorthand for 1. + let extend = /*@__PURE__*/"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(s => s ? parseInt(s, 36) : 1); + // Convert offsets into absolute values + for (let i = 1; i < extend.length; i++) + extend[i] += extend[i - 1]; + function isExtendingChar(code) { + for (let i = 1; i < extend.length; i += 2) + if (extend[i] > code) + return extend[i - 1] <= code; return false; - } - - function constructYamlTimestamp(data) { - var match, year, month, day, hour, minute, second, fraction = 0, - delta = null, tz_hour, tz_minute, date; - - match = YAML_DATE_REGEXP.exec(data); - if (match === null) match = YAML_TIMESTAMP_REGEXP.exec(data); - - if (match === null) throw new Error('Date resolve error'); - - // match: [1] year [2] month [3] day - - year = +(match[1]); - month = +(match[2]) - 1; // JS month starts with 0 - day = +(match[3]); - - if (!match[4]) { // no hour - return new Date(Date.UTC(year, month, day)); - } - - // match: [4] hour [5] minute [6] second [7] fraction - - hour = +(match[4]); - minute = +(match[5]); - second = +(match[6]); - - if (match[7]) { - fraction = match[7].slice(0, 3); - while (fraction.length < 3) { // milli-seconds - fraction += '0'; - } - fraction = +fraction; - } - - // match: [8] tz [9] tz_sign [10] tz_hour [11] tz_minute - - if (match[9]) { - tz_hour = +(match[10]); - tz_minute = +(match[11] || 0); - delta = (tz_hour * 60 + tz_minute) * 60000; // delta in mili-seconds - if (match[9] === '-') delta = -delta; - } - - date = new Date(Date.UTC(year, month, day, hour, minute, second, fraction)); - - if (delta) date.setTime(date.getTime() - delta); - - return date; - } - - function representYamlTimestamp(object /*, style*/) { - return object.toISOString(); - } - - var timestamp = new type('tag:yaml.org,2002:timestamp', { - kind: 'scalar', - resolve: resolveYamlTimestamp, - construct: constructYamlTimestamp, - instanceOf: Date, - represent: representYamlTimestamp - }); - - function resolveYamlMerge(data) { - return data === '<<' || data === null; - } - - var merge = new type('tag:yaml.org,2002:merge', { - kind: 'scalar', - resolve: resolveYamlMerge - }); - - /*eslint-disable no-bitwise*/ - - - - - - // [ 64, 65, 66 ] -> [ padding, CR, LF ] - var BASE64_MAP = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=\n\r'; - - - function resolveYamlBinary(data) { - if (data === null) return false; - - var code, idx, bitlen = 0, max = data.length, map = BASE64_MAP; - - // Convert one by one. - for (idx = 0; idx < max; idx++) { - code = map.indexOf(data.charAt(idx)); - - // Skip CR/LF - if (code > 64) continue; - - // Fail on illegal characters - if (code < 0) return false; - - bitlen += 6; - } - - // If there are any bits left, source was corrupted - return (bitlen % 8) === 0; - } - - function constructYamlBinary(data) { - var idx, tailbits, - input = data.replace(/[\r\n=]/g, ''), // remove CR/LF & padding to simplify scan - max = input.length, - map = BASE64_MAP, - bits = 0, - result = []; - - // Collect by 6*4 bits (3 bytes) - - for (idx = 0; idx < max; idx++) { - if ((idx % 4 === 0) && idx) { - result.push((bits >> 16) & 0xFF); - result.push((bits >> 8) & 0xFF); - result.push(bits & 0xFF); - } - - bits = (bits << 6) | map.indexOf(input.charAt(idx)); - } - - // Dump tail - - tailbits = (max % 4) * 6; - - if (tailbits === 0) { - result.push((bits >> 16) & 0xFF); - result.push((bits >> 8) & 0xFF); - result.push(bits & 0xFF); - } else if (tailbits === 18) { - result.push((bits >> 10) & 0xFF); - result.push((bits >> 2) & 0xFF); - } else if (tailbits === 12) { - result.push((bits >> 4) & 0xFF); - } - - return new Uint8Array(result); - } - - function representYamlBinary(object /*, style*/) { - var result = '', bits = 0, idx, tail, - max = object.length, - map = BASE64_MAP; - - // Convert every three bytes to 4 ASCII characters. - - for (idx = 0; idx < max; idx++) { - if ((idx % 3 === 0) && idx) { - result += map[(bits >> 18) & 0x3F]; - result += map[(bits >> 12) & 0x3F]; - result += map[(bits >> 6) & 0x3F]; - result += map[bits & 0x3F]; - } - - bits = (bits << 8) + object[idx]; - } - - // Dump tail - - tail = max % 3; - - if (tail === 0) { - result += map[(bits >> 18) & 0x3F]; - result += map[(bits >> 12) & 0x3F]; - result += map[(bits >> 6) & 0x3F]; - result += map[bits & 0x3F]; - } else if (tail === 2) { - result += map[(bits >> 10) & 0x3F]; - result += map[(bits >> 4) & 0x3F]; - result += map[(bits << 2) & 0x3F]; - result += map[64]; - } else if (tail === 1) { - result += map[(bits >> 2) & 0x3F]; - result += map[(bits << 4) & 0x3F]; - result += map[64]; - result += map[64]; - } - - return result; - } - - function isBinary(obj) { - return Object.prototype.toString.call(obj) === '[object Uint8Array]'; - } - - var binary = new type('tag:yaml.org,2002:binary', { - kind: 'scalar', - resolve: resolveYamlBinary, - construct: constructYamlBinary, - predicate: isBinary, - represent: representYamlBinary - }); - - var _hasOwnProperty$3 = Object.prototype.hasOwnProperty; - var _toString$2 = Object.prototype.toString; - - function resolveYamlOmap(data) { - if (data === null) return true; - - var objectKeys = [], index, length, pair, pairKey, pairHasKey, - object = data; - - for (index = 0, length = object.length; index < length; index += 1) { - pair = object[index]; - pairHasKey = false; - - if (_toString$2.call(pair) !== '[object Object]') return false; - - for (pairKey in pair) { - if (_hasOwnProperty$3.call(pair, pairKey)) { - if (!pairHasKey) pairHasKey = true; - else return false; + } + function isRegionalIndicator(code) { + return code >= 0x1F1E6 && code <= 0x1F1FF; + } + const ZWJ = 0x200d; + /** + Returns a next grapheme cluster break _after_ (not equal to) + `pos`, if `forward` is true, or before otherwise. Returns `pos` + itself if no further cluster break is available in the string. + Moves across surrogate pairs, extending characters (when + `includeExtending` is true), characters joined with zero-width + joiners, and flag emoji. + */ + function findClusterBreak(str, pos, forward = true, includeExtending = true) { + return (forward ? nextClusterBreak : prevClusterBreak)(str, pos, includeExtending); + } + function nextClusterBreak(str, pos, includeExtending) { + if (pos == str.length) + return pos; + // If pos is in the middle of a surrogate pair, move to its start + if (pos && surrogateLow(str.charCodeAt(pos)) && surrogateHigh(str.charCodeAt(pos - 1))) + pos--; + let prev = codePointAt(str, pos); + pos += codePointSize(prev); + while (pos < str.length) { + let next = codePointAt(str, pos); + if (prev == ZWJ || next == ZWJ || includeExtending && isExtendingChar(next)) { + pos += codePointSize(next); + prev = next; } - } - - if (!pairHasKey) return false; - - if (objectKeys.indexOf(pairKey) === -1) objectKeys.push(pairKey); - else return false; - } - - return true; - } - - function constructYamlOmap(data) { - return data !== null ? data : []; - } - - var omap = new type('tag:yaml.org,2002:omap', { - kind: 'sequence', - resolve: resolveYamlOmap, - construct: constructYamlOmap - }); - - var _toString$1 = Object.prototype.toString; - - function resolveYamlPairs(data) { - if (data === null) return true; - - var index, length, pair, keys, result, - object = data; - - result = new Array(object.length); - - for (index = 0, length = object.length; index < length; index += 1) { - pair = object[index]; - - if (_toString$1.call(pair) !== '[object Object]') return false; - - keys = Object.keys(pair); - - if (keys.length !== 1) return false; - - result[index] = [ keys[0], pair[keys[0]] ]; - } - - return true; - } - - function constructYamlPairs(data) { - if (data === null) return []; - - var index, length, pair, keys, result, - object = data; - - result = new Array(object.length); - - for (index = 0, length = object.length; index < length; index += 1) { - pair = object[index]; - - keys = Object.keys(pair); - - result[index] = [ keys[0], pair[keys[0]] ]; - } - - return result; - } - - var pairs = new type('tag:yaml.org,2002:pairs', { - kind: 'sequence', - resolve: resolveYamlPairs, - construct: constructYamlPairs - }); - - var _hasOwnProperty$2 = Object.prototype.hasOwnProperty; - - function resolveYamlSet(data) { - if (data === null) return true; - - var key, object = data; - - for (key in object) { - if (_hasOwnProperty$2.call(object, key)) { - if (object[key] !== null) return false; - } - } - - return true; - } - - function constructYamlSet(data) { - return data !== null ? data : {}; - } - - var set = new type('tag:yaml.org,2002:set', { - kind: 'mapping', - resolve: resolveYamlSet, - construct: constructYamlSet - }); - - var _default = core.extend({ - implicit: [ - timestamp, - merge - ], - explicit: [ - binary, - omap, - pairs, - set - ] - }); - - /*eslint-disable max-len,no-use-before-define*/ - - - - - - - - var _hasOwnProperty$1 = Object.prototype.hasOwnProperty; - - - var CONTEXT_FLOW_IN = 1; - var CONTEXT_FLOW_OUT = 2; - var CONTEXT_BLOCK_IN = 3; - var CONTEXT_BLOCK_OUT = 4; - - - var CHOMPING_CLIP = 1; - var CHOMPING_STRIP = 2; - var CHOMPING_KEEP = 3; - - - var PATTERN_NON_PRINTABLE = /[\x00-\x08\x0B\x0C\x0E-\x1F\x7F-\x84\x86-\x9F\uFFFE\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]/; - var PATTERN_NON_ASCII_LINE_BREAKS = /[\x85\u2028\u2029]/; - var PATTERN_FLOW_INDICATORS = /[,\[\]\{\}]/; - var PATTERN_TAG_HANDLE = /^(?:!|!!|![a-z\-]+!)$/i; - var PATTERN_TAG_URI = /^(?:!|[^,\[\]\{\}])(?:%[0-9a-f]{2}|[0-9a-z\-#;\/\?:@&=\+\$,_\.!~\*'\(\)\[\]])*$/i; - - - function _class(obj) { return Object.prototype.toString.call(obj); } - - function is_EOL(c) { - return (c === 0x0A/* LF */) || (c === 0x0D/* CR */); - } - - function is_WHITE_SPACE(c) { - return (c === 0x09/* Tab */) || (c === 0x20/* Space */); - } - - function is_WS_OR_EOL(c) { - return (c === 0x09/* Tab */) || - (c === 0x20/* Space */) || - (c === 0x0A/* LF */) || - (c === 0x0D/* CR */); - } - - function is_FLOW_INDICATOR(c) { - return c === 0x2C/* , */ || - c === 0x5B/* [ */ || - c === 0x5D/* ] */ || - c === 0x7B/* { */ || - c === 0x7D/* } */; - } - - function fromHexCode(c) { - var lc; - - if ((0x30/* 0 */ <= c) && (c <= 0x39/* 9 */)) { - return c - 0x30; - } - - /*eslint-disable no-bitwise*/ - lc = c | 0x20; - - if ((0x61/* a */ <= lc) && (lc <= 0x66/* f */)) { - return lc - 0x61 + 10; - } - - return -1; - } - - function escapedHexLen(c) { - if (c === 0x78/* x */) { return 2; } - if (c === 0x75/* u */) { return 4; } - if (c === 0x55/* U */) { return 8; } - return 0; - } - - function fromDecimalCode(c) { - if ((0x30/* 0 */ <= c) && (c <= 0x39/* 9 */)) { - return c - 0x30; - } - - return -1; - } - - function simpleEscapeSequence(c) { - /* eslint-disable indent */ - return (c === 0x30/* 0 */) ? '\x00' : - (c === 0x61/* a */) ? '\x07' : - (c === 0x62/* b */) ? '\x08' : - (c === 0x74/* t */) ? '\x09' : - (c === 0x09/* Tab */) ? '\x09' : - (c === 0x6E/* n */) ? '\x0A' : - (c === 0x76/* v */) ? '\x0B' : - (c === 0x66/* f */) ? '\x0C' : - (c === 0x72/* r */) ? '\x0D' : - (c === 0x65/* e */) ? '\x1B' : - (c === 0x20/* Space */) ? ' ' : - (c === 0x22/* " */) ? '\x22' : - (c === 0x2F/* / */) ? '/' : - (c === 0x5C/* \ */) ? '\x5C' : - (c === 0x4E/* N */) ? '\x85' : - (c === 0x5F/* _ */) ? '\xA0' : - (c === 0x4C/* L */) ? '\u2028' : - (c === 0x50/* P */) ? '\u2029' : ''; - } - - function charFromCodepoint(c) { - if (c <= 0xFFFF) { - return String.fromCharCode(c); - } - // Encode UTF-16 surrogate pair - // https://en.wikipedia.org/wiki/UTF-16#Code_points_U.2B010000_to_U.2B10FFFF - return String.fromCharCode( - ((c - 0x010000) >> 10) + 0xD800, - ((c - 0x010000) & 0x03FF) + 0xDC00 - ); - } - - var simpleEscapeCheck = new Array(256); // integer, for fast access - var simpleEscapeMap = new Array(256); - for (var i$1 = 0; i$1 < 256; i$1++) { - simpleEscapeCheck[i$1] = simpleEscapeSequence(i$1) ? 1 : 0; - simpleEscapeMap[i$1] = simpleEscapeSequence(i$1); - } - - - function State$1(input, options) { - this.input = input; - - this.filename = options['filename'] || null; - this.schema = options['schema'] || _default; - this.onWarning = options['onWarning'] || null; - // (Hidden) Remove? makes the loader to expect YAML 1.1 documents - // if such documents have no explicit %YAML directive - this.legacy = options['legacy'] || false; - - this.json = options['json'] || false; - this.listener = options['listener'] || null; - - this.implicitTypes = this.schema.compiledImplicit; - this.typeMap = this.schema.compiledTypeMap; - - this.length = input.length; - this.position = 0; - this.line = 0; - this.lineStart = 0; - this.lineIndent = 0; - - // position of first leading tab in the current line, - // used to make sure there are no tabs in the indentation - this.firstTabInLine = -1; - - this.documents = []; - - /* - this.version; - this.checkLineBreaks; - this.tagMap; - this.anchorMap; - this.tag; - this.anchor; - this.kind; - this.result;*/ - - } - - - function generateError(state, message) { - var mark = { - name: state.filename, - buffer: state.input.slice(0, -1), // omit trailing \0 - position: state.position, - line: state.line, - column: state.position - state.lineStart - }; - - mark.snippet = snippet(mark); - - return new exception(message, mark); - } - - function throwError(state, message) { - throw generateError(state, message); - } - - function throwWarning(state, message) { - if (state.onWarning) { - state.onWarning.call(null, generateError(state, message)); - } - } - - - var directiveHandlers = { - - YAML: function handleYamlDirective(state, name, args) { - - var match, major, minor; - - if (state.version !== null) { - throwError(state, 'duplication of %YAML directive'); - } - - if (args.length !== 1) { - throwError(state, 'YAML directive accepts exactly one argument'); - } - - match = /^([0-9]+)\.([0-9]+)$/.exec(args[0]); - - if (match === null) { - throwError(state, 'ill-formed argument of the YAML directive'); - } - - major = parseInt(match[1], 10); - minor = parseInt(match[2], 10); - - if (major !== 1) { - throwError(state, 'unacceptable YAML version of the document'); - } - - state.version = args[0]; - state.checkLineBreaks = (minor < 2); - - if (minor !== 1 && minor !== 2) { - throwWarning(state, 'unsupported YAML version of the document'); - } - }, - - TAG: function handleTagDirective(state, name, args) { - - var handle, prefix; - - if (args.length !== 2) { - throwError(state, 'TAG directive accepts exactly two arguments'); - } - - handle = args[0]; - prefix = args[1]; - - if (!PATTERN_TAG_HANDLE.test(handle)) { - throwError(state, 'ill-formed tag handle (first argument) of the TAG directive'); - } - - if (_hasOwnProperty$1.call(state.tagMap, handle)) { - throwError(state, 'there is a previously declared suffix for "' + handle + '" tag handle'); - } - - if (!PATTERN_TAG_URI.test(prefix)) { - throwError(state, 'ill-formed tag prefix (second argument) of the TAG directive'); - } - - try { - prefix = decodeURIComponent(prefix); - } catch (err) { - throwError(state, 'tag prefix is malformed: ' + prefix); - } - - state.tagMap[handle] = prefix; - } - }; - - - function captureSegment(state, start, end, checkJson) { - var _position, _length, _character, _result; - - if (start < end) { - _result = state.input.slice(start, end); - - if (checkJson) { - for (_position = 0, _length = _result.length; _position < _length; _position += 1) { - _character = _result.charCodeAt(_position); - if (!(_character === 0x09 || - (0x20 <= _character && _character <= 0x10FFFF))) { - throwError(state, 'expected valid JSON character'); - } - } - } else if (PATTERN_NON_PRINTABLE.test(_result)) { - throwError(state, 'the stream contains non-printable characters'); - } - - state.result += _result; - } - } - - function mergeMappings(state, destination, source, overridableKeys) { - var sourceKeys, key, index, quantity; - - if (!common.isObject(source)) { - throwError(state, 'cannot merge mappings; the provided source object is unacceptable'); - } - - sourceKeys = Object.keys(source); - - for (index = 0, quantity = sourceKeys.length; index < quantity; index += 1) { - key = sourceKeys[index]; - - if (!_hasOwnProperty$1.call(destination, key)) { - destination[key] = source[key]; - overridableKeys[key] = true; - } - } - } - - function storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, valueNode, - startLine, startLineStart, startPos) { - - var index, quantity; - - // The output is a plain object here, so keys can only be strings. - // We need to convert keyNode to a string, but doing so can hang the process - // (deeply nested arrays that explode exponentially using aliases). - if (Array.isArray(keyNode)) { - keyNode = Array.prototype.slice.call(keyNode); - - for (index = 0, quantity = keyNode.length; index < quantity; index += 1) { - if (Array.isArray(keyNode[index])) { - throwError(state, 'nested arrays are not supported inside keys'); - } - - if (typeof keyNode === 'object' && _class(keyNode[index]) === '[object Object]') { - keyNode[index] = '[object Object]'; - } - } - } - - // Avoid code execution in load() via toString property - // (still use its own toString for arrays, timestamps, - // and whatever user schema extensions happen to have @@toStringTag) - if (typeof keyNode === 'object' && _class(keyNode) === '[object Object]') { - keyNode = '[object Object]'; - } - - - keyNode = String(keyNode); - - if (_result === null) { - _result = {}; - } - - if (keyTag === 'tag:yaml.org,2002:merge') { - if (Array.isArray(valueNode)) { - for (index = 0, quantity = valueNode.length; index < quantity; index += 1) { - mergeMappings(state, _result, valueNode[index], overridableKeys); - } - } else { - mergeMappings(state, _result, valueNode, overridableKeys); - } - } else { - if (!state.json && - !_hasOwnProperty$1.call(overridableKeys, keyNode) && - _hasOwnProperty$1.call(_result, keyNode)) { - state.line = startLine || state.line; - state.lineStart = startLineStart || state.lineStart; - state.position = startPos || state.position; - throwError(state, 'duplicated mapping key'); - } - - // used for this specific key only because Object.defineProperty is slow - if (keyNode === '__proto__') { - Object.defineProperty(_result, keyNode, { - configurable: true, - enumerable: true, - writable: true, - value: valueNode - }); - } else { - _result[keyNode] = valueNode; - } - delete overridableKeys[keyNode]; - } - - return _result; - } - - function readLineBreak(state) { - var ch; - - ch = state.input.charCodeAt(state.position); - - if (ch === 0x0A/* LF */) { - state.position++; - } else if (ch === 0x0D/* CR */) { - state.position++; - if (state.input.charCodeAt(state.position) === 0x0A/* LF */) { - state.position++; - } - } else { - throwError(state, 'a line break is expected'); - } - - state.line += 1; - state.lineStart = state.position; - state.firstTabInLine = -1; - } - - function skipSeparationSpace(state, allowComments, checkIndent) { - var lineBreaks = 0, - ch = state.input.charCodeAt(state.position); - - while (ch !== 0) { - while (is_WHITE_SPACE(ch)) { - if (ch === 0x09/* Tab */ && state.firstTabInLine === -1) { - state.firstTabInLine = state.position; - } - ch = state.input.charCodeAt(++state.position); - } - - if (allowComments && ch === 0x23/* # */) { - do { - ch = state.input.charCodeAt(++state.position); - } while (ch !== 0x0A/* LF */ && ch !== 0x0D/* CR */ && ch !== 0); - } - - if (is_EOL(ch)) { - readLineBreak(state); - - ch = state.input.charCodeAt(state.position); - lineBreaks++; - state.lineIndent = 0; - - while (ch === 0x20/* Space */) { - state.lineIndent++; - ch = state.input.charCodeAt(++state.position); - } - } else { - break; - } - } - - if (checkIndent !== -1 && lineBreaks !== 0 && state.lineIndent < checkIndent) { - throwWarning(state, 'deficient indentation'); - } - - return lineBreaks; - } - - function testDocumentSeparator(state) { - var _position = state.position, - ch; - - ch = state.input.charCodeAt(_position); - - // Condition state.position === state.lineStart is tested - // in parent on each call, for efficiency. No needs to test here again. - if ((ch === 0x2D/* - */ || ch === 0x2E/* . */) && - ch === state.input.charCodeAt(_position + 1) && - ch === state.input.charCodeAt(_position + 2)) { - - _position += 3; - - ch = state.input.charCodeAt(_position); - - if (ch === 0 || is_WS_OR_EOL(ch)) { - return true; - } - } - - return false; - } - - function writeFoldedLines(state, count) { - if (count === 1) { - state.result += ' '; - } else if (count > 1) { - state.result += common.repeat('\n', count - 1); - } - } - - - function readPlainScalar(state, nodeIndent, withinFlowCollection) { - var preceding, - following, - captureStart, - captureEnd, - hasPendingContent, - _line, - _lineStart, - _lineIndent, - _kind = state.kind, - _result = state.result, - ch; - - ch = state.input.charCodeAt(state.position); - - if (is_WS_OR_EOL(ch) || - is_FLOW_INDICATOR(ch) || - ch === 0x23/* # */ || - ch === 0x26/* & */ || - ch === 0x2A/* * */ || - ch === 0x21/* ! */ || - ch === 0x7C/* | */ || - ch === 0x3E/* > */ || - ch === 0x27/* ' */ || - ch === 0x22/* " */ || - ch === 0x25/* % */ || - ch === 0x40/* @ */ || - ch === 0x60/* ` */) { - return false; - } - - if (ch === 0x3F/* ? */ || ch === 0x2D/* - */) { - following = state.input.charCodeAt(state.position + 1); - - if (is_WS_OR_EOL(following) || - withinFlowCollection && is_FLOW_INDICATOR(following)) { - return false; - } - } - - state.kind = 'scalar'; - state.result = ''; - captureStart = captureEnd = state.position; - hasPendingContent = false; - - while (ch !== 0) { - if (ch === 0x3A/* : */) { - following = state.input.charCodeAt(state.position + 1); - - if (is_WS_OR_EOL(following) || - withinFlowCollection && is_FLOW_INDICATOR(following)) { - break; - } - - } else if (ch === 0x23/* # */) { - preceding = state.input.charCodeAt(state.position - 1); - - if (is_WS_OR_EOL(preceding)) { - break; - } - - } else if ((state.position === state.lineStart && testDocumentSeparator(state)) || - withinFlowCollection && is_FLOW_INDICATOR(ch)) { - break; - - } else if (is_EOL(ch)) { - _line = state.line; - _lineStart = state.lineStart; - _lineIndent = state.lineIndent; - skipSeparationSpace(state, false, -1); - - if (state.lineIndent >= nodeIndent) { - hasPendingContent = true; - ch = state.input.charCodeAt(state.position); - continue; - } else { - state.position = captureEnd; - state.line = _line; - state.lineStart = _lineStart; - state.lineIndent = _lineIndent; - break; - } - } - - if (hasPendingContent) { - captureSegment(state, captureStart, captureEnd, false); - writeFoldedLines(state, state.line - _line); - captureStart = captureEnd = state.position; - hasPendingContent = false; - } - - if (!is_WHITE_SPACE(ch)) { - captureEnd = state.position + 1; - } - - ch = state.input.charCodeAt(++state.position); - } - - captureSegment(state, captureStart, captureEnd, false); - - if (state.result) { - return true; - } - - state.kind = _kind; - state.result = _result; - return false; - } - - function readSingleQuotedScalar(state, nodeIndent) { - var ch, - captureStart, captureEnd; - - ch = state.input.charCodeAt(state.position); - - if (ch !== 0x27/* ' */) { - return false; - } - - state.kind = 'scalar'; - state.result = ''; - state.position++; - captureStart = captureEnd = state.position; - - while ((ch = state.input.charCodeAt(state.position)) !== 0) { - if (ch === 0x27/* ' */) { - captureSegment(state, captureStart, state.position, true); - ch = state.input.charCodeAt(++state.position); - - if (ch === 0x27/* ' */) { - captureStart = state.position; - state.position++; - captureEnd = state.position; - } else { - return true; - } - - } else if (is_EOL(ch)) { - captureSegment(state, captureStart, captureEnd, true); - writeFoldedLines(state, skipSeparationSpace(state, false, nodeIndent)); - captureStart = captureEnd = state.position; - - } else if (state.position === state.lineStart && testDocumentSeparator(state)) { - throwError(state, 'unexpected end of the document within a single quoted scalar'); - - } else { - state.position++; - captureEnd = state.position; - } - } - - throwError(state, 'unexpected end of the stream within a single quoted scalar'); - } - - function readDoubleQuotedScalar(state, nodeIndent) { - var captureStart, - captureEnd, - hexLength, - hexResult, - tmp, - ch; - - ch = state.input.charCodeAt(state.position); - - if (ch !== 0x22/* " */) { - return false; - } - - state.kind = 'scalar'; - state.result = ''; - state.position++; - captureStart = captureEnd = state.position; - - while ((ch = state.input.charCodeAt(state.position)) !== 0) { - if (ch === 0x22/* " */) { - captureSegment(state, captureStart, state.position, true); - state.position++; - return true; - - } else if (ch === 0x5C/* \ */) { - captureSegment(state, captureStart, state.position, true); - ch = state.input.charCodeAt(++state.position); - - if (is_EOL(ch)) { - skipSeparationSpace(state, false, nodeIndent); - - // TODO: rework to inline fn with no type cast? - } else if (ch < 256 && simpleEscapeCheck[ch]) { - state.result += simpleEscapeMap[ch]; - state.position++; - - } else if ((tmp = escapedHexLen(ch)) > 0) { - hexLength = tmp; - hexResult = 0; - - for (; hexLength > 0; hexLength--) { - ch = state.input.charCodeAt(++state.position); - - if ((tmp = fromHexCode(ch)) >= 0) { - hexResult = (hexResult << 4) + tmp; - - } else { - throwError(state, 'expected hexadecimal character'); + else if (isRegionalIndicator(next)) { + let countBefore = 0, i = pos - 2; + while (i >= 0 && isRegionalIndicator(codePointAt(str, i))) { + countBefore++; + i -= 2; } - } - - state.result += charFromCodepoint(hexResult); - - state.position++; - - } else { - throwError(state, 'unknown escape sequence'); + if (countBefore % 2 == 0) + break; + else + pos += 2; } - - captureStart = captureEnd = state.position; - - } else if (is_EOL(ch)) { - captureSegment(state, captureStart, captureEnd, true); - writeFoldedLines(state, skipSeparationSpace(state, false, nodeIndent)); - captureStart = captureEnd = state.position; - - } else if (state.position === state.lineStart && testDocumentSeparator(state)) { - throwError(state, 'unexpected end of the document within a double quoted scalar'); - - } else { - state.position++; - captureEnd = state.position; - } - } - - throwError(state, 'unexpected end of the stream within a double quoted scalar'); - } - - function readFlowCollection(state, nodeIndent) { - var readNext = true, - _line, - _lineStart, - _pos, - _tag = state.tag, - _result, - _anchor = state.anchor, - following, - terminator, - isPair, - isExplicitPair, - isMapping, - overridableKeys = Object.create(null), - keyNode, - keyTag, - valueNode, - ch; - - ch = state.input.charCodeAt(state.position); - - if (ch === 0x5B/* [ */) { - terminator = 0x5D;/* ] */ - isMapping = false; - _result = []; - } else if (ch === 0x7B/* { */) { - terminator = 0x7D;/* } */ - isMapping = true; - _result = {}; - } else { - return false; - } - - if (state.anchor !== null) { - state.anchorMap[state.anchor] = _result; - } - - ch = state.input.charCodeAt(++state.position); - - while (ch !== 0) { - skipSeparationSpace(state, true, nodeIndent); - - ch = state.input.charCodeAt(state.position); - - if (ch === terminator) { - state.position++; - state.tag = _tag; - state.anchor = _anchor; - state.kind = isMapping ? 'mapping' : 'sequence'; - state.result = _result; - return true; - } else if (!readNext) { - throwError(state, 'missed comma between flow collection entries'); - } else if (ch === 0x2C/* , */) { - // "flow collection entries can never be completely empty", as per YAML 1.2, section 7.4 - throwError(state, "expected the node content, but found ','"); - } - - keyTag = keyNode = valueNode = null; - isPair = isExplicitPair = false; - - if (ch === 0x3F/* ? */) { - following = state.input.charCodeAt(state.position + 1); - - if (is_WS_OR_EOL(following)) { - isPair = isExplicitPair = true; - state.position++; - skipSeparationSpace(state, true, nodeIndent); - } - } - - _line = state.line; // Save the current line. - _lineStart = state.lineStart; - _pos = state.position; - composeNode(state, nodeIndent, CONTEXT_FLOW_IN, false, true); - keyTag = state.tag; - keyNode = state.result; - skipSeparationSpace(state, true, nodeIndent); - - ch = state.input.charCodeAt(state.position); - - if ((isExplicitPair || state.line === _line) && ch === 0x3A/* : */) { - isPair = true; - ch = state.input.charCodeAt(++state.position); - skipSeparationSpace(state, true, nodeIndent); - composeNode(state, nodeIndent, CONTEXT_FLOW_IN, false, true); - valueNode = state.result; - } - - if (isMapping) { - storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, valueNode, _line, _lineStart, _pos); - } else if (isPair) { - _result.push(storeMappingPair(state, null, overridableKeys, keyTag, keyNode, valueNode, _line, _lineStart, _pos)); - } else { - _result.push(keyNode); - } - - skipSeparationSpace(state, true, nodeIndent); - - ch = state.input.charCodeAt(state.position); - - if (ch === 0x2C/* , */) { - readNext = true; - ch = state.input.charCodeAt(++state.position); - } else { - readNext = false; - } - } - - throwError(state, 'unexpected end of the stream within a flow collection'); - } - - function readBlockScalar(state, nodeIndent) { - var captureStart, - folding, - chomping = CHOMPING_CLIP, - didReadContent = false, - detectedIndent = false, - textIndent = nodeIndent, - emptyLines = 0, - atMoreIndented = false, - tmp, - ch; - - ch = state.input.charCodeAt(state.position); - - if (ch === 0x7C/* | */) { - folding = false; - } else if (ch === 0x3E/* > */) { - folding = true; - } else { - return false; - } - - state.kind = 'scalar'; - state.result = ''; - - while (ch !== 0) { - ch = state.input.charCodeAt(++state.position); - - if (ch === 0x2B/* + */ || ch === 0x2D/* - */) { - if (CHOMPING_CLIP === chomping) { - chomping = (ch === 0x2B/* + */) ? CHOMPING_KEEP : CHOMPING_STRIP; - } else { - throwError(state, 'repeat of a chomping mode identifier'); - } - - } else if ((tmp = fromDecimalCode(ch)) >= 0) { - if (tmp === 0) { - throwError(state, 'bad explicit indentation width of a block scalar; it cannot be less than one'); - } else if (!detectedIndent) { - textIndent = nodeIndent + tmp - 1; - detectedIndent = true; - } else { - throwError(state, 'repeat of an indentation width identifier'); - } - - } else { - break; - } - } - - if (is_WHITE_SPACE(ch)) { - do { ch = state.input.charCodeAt(++state.position); } - while (is_WHITE_SPACE(ch)); - - if (ch === 0x23/* # */) { - do { ch = state.input.charCodeAt(++state.position); } - while (!is_EOL(ch) && (ch !== 0)); - } - } - - while (ch !== 0) { - readLineBreak(state); - state.lineIndent = 0; - - ch = state.input.charCodeAt(state.position); - - while ((!detectedIndent || state.lineIndent < textIndent) && - (ch === 0x20/* Space */)) { - state.lineIndent++; - ch = state.input.charCodeAt(++state.position); - } - - if (!detectedIndent && state.lineIndent > textIndent) { - textIndent = state.lineIndent; - } - - if (is_EOL(ch)) { - emptyLines++; - continue; - } - - // End of the scalar. - if (state.lineIndent < textIndent) { - - // Perform the chomping. - if (chomping === CHOMPING_KEEP) { - state.result += common.repeat('\n', didReadContent ? 1 + emptyLines : emptyLines); - } else if (chomping === CHOMPING_CLIP) { - if (didReadContent) { // i.e. only if the scalar is not empty. - state.result += '\n'; - } - } - - // Break this `while` cycle and go to the funciton's epilogue. - break; - } - - // Folded style: use fancy rules to handle line breaks. - if (folding) { - - // Lines starting with white space characters (more-indented lines) are not folded. - if (is_WHITE_SPACE(ch)) { - atMoreIndented = true; - // except for the first content line (cf. Example 8.1) - state.result += common.repeat('\n', didReadContent ? 1 + emptyLines : emptyLines); - - // End of more-indented block. - } else if (atMoreIndented) { - atMoreIndented = false; - state.result += common.repeat('\n', emptyLines + 1); - - // Just one line break - perceive as the same line. - } else if (emptyLines === 0) { - if (didReadContent) { // i.e. only if we have already read some scalar content. - state.result += ' '; - } - - // Several line breaks - perceive as different lines. - } else { - state.result += common.repeat('\n', emptyLines); - } - - // Literal style: just add exact number of line breaks between content lines. - } else { - // Keep all line breaks except the header line break. - state.result += common.repeat('\n', didReadContent ? 1 + emptyLines : emptyLines); - } - - didReadContent = true; - detectedIndent = true; - emptyLines = 0; - captureStart = state.position; - - while (!is_EOL(ch) && (ch !== 0)) { - ch = state.input.charCodeAt(++state.position); - } - - captureSegment(state, captureStart, state.position, false); - } - - return true; - } - - function readBlockSequence(state, nodeIndent) { - var _line, - _tag = state.tag, - _anchor = state.anchor, - _result = [], - following, - detected = false, - ch; - - // there is a leading tab before this token, so it can't be a block sequence/mapping; - // it can still be flow sequence/mapping or a scalar - if (state.firstTabInLine !== -1) return false; - - if (state.anchor !== null) { - state.anchorMap[state.anchor] = _result; - } - - ch = state.input.charCodeAt(state.position); - - while (ch !== 0) { - if (state.firstTabInLine !== -1) { - state.position = state.firstTabInLine; - throwError(state, 'tab characters must not be used in indentation'); - } - - if (ch !== 0x2D/* - */) { - break; - } - - following = state.input.charCodeAt(state.position + 1); - - if (!is_WS_OR_EOL(following)) { - break; - } - - detected = true; - state.position++; - - if (skipSeparationSpace(state, true, -1)) { - if (state.lineIndent <= nodeIndent) { - _result.push(null); - ch = state.input.charCodeAt(state.position); - continue; - } - } - - _line = state.line; - composeNode(state, nodeIndent, CONTEXT_BLOCK_IN, false, true); - _result.push(state.result); - skipSeparationSpace(state, true, -1); - - ch = state.input.charCodeAt(state.position); - - if ((state.line === _line || state.lineIndent > nodeIndent) && (ch !== 0)) { - throwError(state, 'bad indentation of a sequence entry'); - } else if (state.lineIndent < nodeIndent) { - break; - } - } - - if (detected) { - state.tag = _tag; - state.anchor = _anchor; - state.kind = 'sequence'; - state.result = _result; - return true; - } - return false; - } - - function readBlockMapping(state, nodeIndent, flowIndent) { - var following, - allowCompact, - _line, - _keyLine, - _keyLineStart, - _keyPos, - _tag = state.tag, - _anchor = state.anchor, - _result = {}, - overridableKeys = Object.create(null), - keyTag = null, - keyNode = null, - valueNode = null, - atExplicitKey = false, - detected = false, - ch; - - // there is a leading tab before this token, so it can't be a block sequence/mapping; - // it can still be flow sequence/mapping or a scalar - if (state.firstTabInLine !== -1) return false; - - if (state.anchor !== null) { - state.anchorMap[state.anchor] = _result; - } - - ch = state.input.charCodeAt(state.position); - - while (ch !== 0) { - if (!atExplicitKey && state.firstTabInLine !== -1) { - state.position = state.firstTabInLine; - throwError(state, 'tab characters must not be used in indentation'); - } - - following = state.input.charCodeAt(state.position + 1); - _line = state.line; // Save the current line. - - // - // Explicit notation case. There are two separate blocks: - // first for the key (denoted by "?") and second for the value (denoted by ":") - // - if ((ch === 0x3F/* ? */ || ch === 0x3A/* : */) && is_WS_OR_EOL(following)) { - - if (ch === 0x3F/* ? */) { - if (atExplicitKey) { - storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, null, _keyLine, _keyLineStart, _keyPos); - keyTag = keyNode = valueNode = null; - } - - detected = true; - atExplicitKey = true; - allowCompact = true; - - } else if (atExplicitKey) { - // i.e. 0x3A/* : */ === character after the explicit key. - atExplicitKey = false; - allowCompact = true; - - } else { - throwError(state, 'incomplete explicit mapping pair; a key node is missed; or followed by a non-tabulated empty line'); - } - - state.position += 1; - ch = following; - - // - // Implicit notation case. Flow-style node as the key first, then ":", and the value. - // - } else { - _keyLine = state.line; - _keyLineStart = state.lineStart; - _keyPos = state.position; - - if (!composeNode(state, flowIndent, CONTEXT_FLOW_OUT, false, true)) { - // Neither implicit nor explicit notation. - // Reading is done. Go to the epilogue. - break; - } - - if (state.line === _line) { - ch = state.input.charCodeAt(state.position); - - while (is_WHITE_SPACE(ch)) { - ch = state.input.charCodeAt(++state.position); - } - - if (ch === 0x3A/* : */) { - ch = state.input.charCodeAt(++state.position); - - if (!is_WS_OR_EOL(ch)) { - throwError(state, 'a whitespace character is expected after the key-value separator within a block mapping'); - } - - if (atExplicitKey) { - storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, null, _keyLine, _keyLineStart, _keyPos); - keyTag = keyNode = valueNode = null; - } - - detected = true; - atExplicitKey = false; - allowCompact = false; - keyTag = state.tag; - keyNode = state.result; - - } else if (detected) { - throwError(state, 'can not read an implicit mapping pair; a colon is missed'); - - } else { - state.tag = _tag; - state.anchor = _anchor; - return true; // Keep the result of `composeNode`. - } - - } else if (detected) { - throwError(state, 'can not read a block mapping entry; a multiline key may not be an implicit key'); - - } else { - state.tag = _tag; - state.anchor = _anchor; - return true; // Keep the result of `composeNode`. - } - } - - // - // Common reading code for both explicit and implicit notations. - // - if (state.line === _line || state.lineIndent > nodeIndent) { - if (atExplicitKey) { - _keyLine = state.line; - _keyLineStart = state.lineStart; - _keyPos = state.position; - } - - if (composeNode(state, nodeIndent, CONTEXT_BLOCK_OUT, true, allowCompact)) { - if (atExplicitKey) { - keyNode = state.result; - } else { - valueNode = state.result; - } - } - - if (!atExplicitKey) { - storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, valueNode, _keyLine, _keyLineStart, _keyPos); - keyTag = keyNode = valueNode = null; - } - - skipSeparationSpace(state, true, -1); - ch = state.input.charCodeAt(state.position); - } - - if ((state.line === _line || state.lineIndent > nodeIndent) && (ch !== 0)) { - throwError(state, 'bad indentation of a mapping entry'); - } else if (state.lineIndent < nodeIndent) { - break; - } - } - - // - // Epilogue. - // - - // Special case: last mapping's node contains only the key in explicit notation. - if (atExplicitKey) { - storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, null, _keyLine, _keyLineStart, _keyPos); - } - - // Expose the resulting mapping. - if (detected) { - state.tag = _tag; - state.anchor = _anchor; - state.kind = 'mapping'; - state.result = _result; - } - - return detected; - } - - function readTagProperty(state) { - var _position, - isVerbatim = false, - isNamed = false, - tagHandle, - tagName, - ch; - - ch = state.input.charCodeAt(state.position); - - if (ch !== 0x21/* ! */) return false; - - if (state.tag !== null) { - throwError(state, 'duplication of a tag property'); - } - - ch = state.input.charCodeAt(++state.position); - - if (ch === 0x3C/* < */) { - isVerbatim = true; - ch = state.input.charCodeAt(++state.position); - - } else if (ch === 0x21/* ! */) { - isNamed = true; - tagHandle = '!!'; - ch = state.input.charCodeAt(++state.position); - - } else { - tagHandle = '!'; - } - - _position = state.position; - - if (isVerbatim) { - do { ch = state.input.charCodeAt(++state.position); } - while (ch !== 0 && ch !== 0x3E/* > */); - - if (state.position < state.length) { - tagName = state.input.slice(_position, state.position); - ch = state.input.charCodeAt(++state.position); - } else { - throwError(state, 'unexpected end of the stream within a verbatim tag'); - } - } else { - while (ch !== 0 && !is_WS_OR_EOL(ch)) { - - if (ch === 0x21/* ! */) { - if (!isNamed) { - tagHandle = state.input.slice(_position - 1, state.position + 1); - - if (!PATTERN_TAG_HANDLE.test(tagHandle)) { - throwError(state, 'named tag handle cannot contain such characters'); - } - - isNamed = true; - _position = state.position + 1; - } else { - throwError(state, 'tag suffix cannot contain exclamation marks'); - } - } - - ch = state.input.charCodeAt(++state.position); - } - - tagName = state.input.slice(_position, state.position); - - if (PATTERN_FLOW_INDICATORS.test(tagName)) { - throwError(state, 'tag suffix cannot contain flow indicator characters'); - } - } - - if (tagName && !PATTERN_TAG_URI.test(tagName)) { - throwError(state, 'tag name cannot contain such characters: ' + tagName); - } - - try { - tagName = decodeURIComponent(tagName); - } catch (err) { - throwError(state, 'tag name is malformed: ' + tagName); - } - - if (isVerbatim) { - state.tag = tagName; - - } else if (_hasOwnProperty$1.call(state.tagMap, tagHandle)) { - state.tag = state.tagMap[tagHandle] + tagName; - - } else if (tagHandle === '!') { - state.tag = '!' + tagName; - - } else if (tagHandle === '!!') { - state.tag = 'tag:yaml.org,2002:' + tagName; - - } else { - throwError(state, 'undeclared tag handle "' + tagHandle + '"'); - } - - return true; - } - - function readAnchorProperty(state) { - var _position, - ch; - - ch = state.input.charCodeAt(state.position); - - if (ch !== 0x26/* & */) return false; - - if (state.anchor !== null) { - throwError(state, 'duplication of an anchor property'); - } - - ch = state.input.charCodeAt(++state.position); - _position = state.position; - - while (ch !== 0 && !is_WS_OR_EOL(ch) && !is_FLOW_INDICATOR(ch)) { - ch = state.input.charCodeAt(++state.position); - } - - if (state.position === _position) { - throwError(state, 'name of an anchor node must contain at least one character'); - } - - state.anchor = state.input.slice(_position, state.position); - return true; - } - - function readAlias(state) { - var _position, alias, - ch; - - ch = state.input.charCodeAt(state.position); - - if (ch !== 0x2A/* * */) return false; - - ch = state.input.charCodeAt(++state.position); - _position = state.position; - - while (ch !== 0 && !is_WS_OR_EOL(ch) && !is_FLOW_INDICATOR(ch)) { - ch = state.input.charCodeAt(++state.position); - } - - if (state.position === _position) { - throwError(state, 'name of an alias node must contain at least one character'); - } - - alias = state.input.slice(_position, state.position); - - if (!_hasOwnProperty$1.call(state.anchorMap, alias)) { - throwError(state, 'unidentified alias "' + alias + '"'); - } - - state.result = state.anchorMap[alias]; - skipSeparationSpace(state, true, -1); - return true; - } - - function composeNode(state, parentIndent, nodeContext, allowToSeek, allowCompact) { - var allowBlockStyles, - allowBlockScalars, - allowBlockCollections, - indentStatus = 1, // 1: this>parent, 0: this=parent, -1: this<parent - atNewLine = false, - hasContent = false, - typeIndex, - typeQuantity, - typeList, - type, - flowIndent, - blockIndent; - - if (state.listener !== null) { - state.listener('open', state); - } - - state.tag = null; - state.anchor = null; - state.kind = null; - state.result = null; - - allowBlockStyles = allowBlockScalars = allowBlockCollections = - CONTEXT_BLOCK_OUT === nodeContext || - CONTEXT_BLOCK_IN === nodeContext; - - if (allowToSeek) { - if (skipSeparationSpace(state, true, -1)) { - atNewLine = true; - - if (state.lineIndent > parentIndent) { - indentStatus = 1; - } else if (state.lineIndent === parentIndent) { - indentStatus = 0; - } else if (state.lineIndent < parentIndent) { - indentStatus = -1; - } - } - } - - if (indentStatus === 1) { - while (readTagProperty(state) || readAnchorProperty(state)) { - if (skipSeparationSpace(state, true, -1)) { - atNewLine = true; - allowBlockCollections = allowBlockStyles; - - if (state.lineIndent > parentIndent) { - indentStatus = 1; - } else if (state.lineIndent === parentIndent) { - indentStatus = 0; - } else if (state.lineIndent < parentIndent) { - indentStatus = -1; - } - } else { - allowBlockCollections = false; - } - } - } - - if (allowBlockCollections) { - allowBlockCollections = atNewLine || allowCompact; - } - - if (indentStatus === 1 || CONTEXT_BLOCK_OUT === nodeContext) { - if (CONTEXT_FLOW_IN === nodeContext || CONTEXT_FLOW_OUT === nodeContext) { - flowIndent = parentIndent; - } else { - flowIndent = parentIndent + 1; - } - - blockIndent = state.position - state.lineStart; - - if (indentStatus === 1) { - if (allowBlockCollections && - (readBlockSequence(state, blockIndent) || - readBlockMapping(state, blockIndent, flowIndent)) || - readFlowCollection(state, flowIndent)) { - hasContent = true; - } else { - if ((allowBlockScalars && readBlockScalar(state, flowIndent)) || - readSingleQuotedScalar(state, flowIndent) || - readDoubleQuotedScalar(state, flowIndent)) { - hasContent = true; - - } else if (readAlias(state)) { - hasContent = true; - - if (state.tag !== null || state.anchor !== null) { - throwError(state, 'alias node should not have any properties'); - } - - } else if (readPlainScalar(state, flowIndent, CONTEXT_FLOW_IN === nodeContext)) { - hasContent = true; - - if (state.tag === null) { - state.tag = '?'; - } - } - - if (state.anchor !== null) { - state.anchorMap[state.anchor] = state.result; - } - } - } else if (indentStatus === 0) { - // Special case: block sequences are allowed to have same indentation level as the parent. - // http://www.yaml.org/spec/1.2/spec.html#id2799784 - hasContent = allowBlockCollections && readBlockSequence(state, blockIndent); - } - } - - if (state.tag === null) { - if (state.anchor !== null) { - state.anchorMap[state.anchor] = state.result; - } - - } else if (state.tag === '?') { - // Implicit resolving is not allowed for non-scalar types, and '?' - // non-specific tag is only automatically assigned to plain scalars. - // - // We only need to check kind conformity in case user explicitly assigns '?' - // tag, for example like this: "!<?> [0]" - // - if (state.result !== null && state.kind !== 'scalar') { - throwError(state, 'unacceptable node kind for !<?> tag; it should be "scalar", not "' + state.kind + '"'); - } - - for (typeIndex = 0, typeQuantity = state.implicitTypes.length; typeIndex < typeQuantity; typeIndex += 1) { - type = state.implicitTypes[typeIndex]; - - if (type.resolve(state.result)) { // `state.result` updated in resolver if matched - state.result = type.construct(state.result); - state.tag = type.tag; - if (state.anchor !== null) { - state.anchorMap[state.anchor] = state.result; - } - break; - } - } - } else if (state.tag !== '!') { - if (_hasOwnProperty$1.call(state.typeMap[state.kind || 'fallback'], state.tag)) { - type = state.typeMap[state.kind || 'fallback'][state.tag]; - } else { - // looking for multi type - type = null; - typeList = state.typeMap.multi[state.kind || 'fallback']; - - for (typeIndex = 0, typeQuantity = typeList.length; typeIndex < typeQuantity; typeIndex += 1) { - if (state.tag.slice(0, typeList[typeIndex].tag.length) === typeList[typeIndex].tag) { - type = typeList[typeIndex]; + else { break; - } + } + } + return pos; + } + function prevClusterBreak(str, pos, includeExtending) { + while (pos > 0) { + let found = nextClusterBreak(str, pos - 2, includeExtending); + if (found < pos) + return found; + pos--; + } + return 0; + } + function surrogateLow(ch) { return ch >= 0xDC00 && ch < 0xE000; } + function surrogateHigh(ch) { return ch >= 0xD800 && ch < 0xDC00; } + /** + Find the code point at the given position in a string (like the + [`codePointAt`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/codePointAt) + string method). + */ + function codePointAt(str, pos) { + let code0 = str.charCodeAt(pos); + if (!surrogateHigh(code0) || pos + 1 == str.length) + return code0; + let code1 = str.charCodeAt(pos + 1); + if (!surrogateLow(code1)) + return code0; + return ((code0 - 0xd800) << 10) + (code1 - 0xdc00) + 0x10000; + } + /** + Given a Unicode codepoint, return the JavaScript string that + respresents it (like + [`String.fromCodePoint`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/fromCodePoint)). + */ + function fromCodePoint(code) { + if (code <= 0xffff) + return String.fromCharCode(code); + code -= 0x10000; + return String.fromCharCode((code >> 10) + 0xd800, (code & 1023) + 0xdc00); + } + /** + The amount of positions a character takes up a JavaScript string. + */ + function codePointSize(code) { return code < 0x10000 ? 1 : 2; } + + const DefaultSplit = /\r\n?|\n/; + /** + Distinguishes different ways in which positions can be mapped. + */ + var MapMode = /*@__PURE__*/(function (MapMode) { + /** + Map a position to a valid new position, even when its context + was deleted. + */ + MapMode[MapMode["Simple"] = 0] = "Simple"; + /** + Return null if deletion happens across the position. + */ + MapMode[MapMode["TrackDel"] = 1] = "TrackDel"; + /** + Return null if the character _before_ the position is deleted. + */ + MapMode[MapMode["TrackBefore"] = 2] = "TrackBefore"; + /** + Return null if the character _after_ the position is deleted. + */ + MapMode[MapMode["TrackAfter"] = 3] = "TrackAfter"; + return MapMode})(MapMode || (MapMode = {})); + /** + A change description is a variant of [change set](https://codemirror.net/6/docs/ref/#state.ChangeSet) + that doesn't store the inserted text. As such, it can't be + applied, but is cheaper to store and manipulate. + */ + class ChangeDesc { + // Sections are encoded as pairs of integers. The first is the + // length in the current document, and the second is -1 for + // unaffected sections, and the length of the replacement content + // otherwise. So an insertion would be (0, n>0), a deletion (n>0, + // 0), and a replacement two positive numbers. + /** + @internal + */ + constructor( + /** + @internal + */ + sections) { + this.sections = sections; + } + /** + The length of the document before the change. + */ + get length() { + let result = 0; + for (let i = 0; i < this.sections.length; i += 2) + result += this.sections[i]; + return result; + } + /** + The length of the document after the change. + */ + get newLength() { + let result = 0; + for (let i = 0; i < this.sections.length; i += 2) { + let ins = this.sections[i + 1]; + result += ins < 0 ? this.sections[i] : ins; + } + return result; + } + /** + False when there are actual changes in this set. + */ + get empty() { return this.sections.length == 0 || this.sections.length == 2 && this.sections[1] < 0; } + /** + Iterate over the unchanged parts left by these changes. `posA` + provides the position of the range in the old document, `posB` + the new position in the changed document. + */ + iterGaps(f) { + for (let i = 0, posA = 0, posB = 0; i < this.sections.length;) { + let len = this.sections[i++], ins = this.sections[i++]; + if (ins < 0) { + f(posA, posB, len); + posB += len; + } + else { + posB += ins; + } + posA += len; + } + } + /** + Iterate over the ranges changed by these changes. (See + [`ChangeSet.iterChanges`](https://codemirror.net/6/docs/ref/#state.ChangeSet.iterChanges) for a + variant that also provides you with the inserted text.) + `fromA`/`toA` provides the extent of the change in the starting + document, `fromB`/`toB` the extent of the replacement in the + changed document. + + When `individual` is true, adjacent changes (which are kept + separate for [position mapping](https://codemirror.net/6/docs/ref/#state.ChangeDesc.mapPos)) are + reported separately. + */ + iterChangedRanges(f, individual = false) { + iterChanges(this, f, individual); + } + /** + Get a description of the inverted form of these changes. + */ + get invertedDesc() { + let sections = []; + for (let i = 0; i < this.sections.length;) { + let len = this.sections[i++], ins = this.sections[i++]; + if (ins < 0) + sections.push(len, ins); + else + sections.push(ins, len); + } + return new ChangeDesc(sections); + } + /** + Compute the combined effect of applying another set of changes + after this one. The length of the document after this set should + match the length before `other`. + */ + composeDesc(other) { return this.empty ? other : other.empty ? this : composeSets(this, other); } + /** + Map this description, which should start with the same document + as `other`, over another set of changes, so that it can be + applied after it. When `before` is true, map as if the changes + in `other` happened before the ones in `this`. + */ + mapDesc(other, before = false) { return other.empty ? this : mapSet(this, other, before); } + mapPos(pos, assoc = -1, mode = MapMode.Simple) { + let posA = 0, posB = 0; + for (let i = 0; i < this.sections.length;) { + let len = this.sections[i++], ins = this.sections[i++], endA = posA + len; + if (ins < 0) { + if (endA > pos) + return posB + (pos - posA); + posB += len; + } + else { + if (mode != MapMode.Simple && endA >= pos && + (mode == MapMode.TrackDel && posA < pos && endA > pos || + mode == MapMode.TrackBefore && posA < pos || + mode == MapMode.TrackAfter && endA > pos)) + return null; + if (endA > pos || endA == pos && assoc < 0 && !len) + return pos == posA || assoc < 0 ? posB : posB + ins; + posB += ins; + } + posA = endA; + } + if (pos > posA) + throw new RangeError(`Position ${pos} is out of range for changeset of length ${posA}`); + return posB; + } + /** + Check whether these changes touch a given range. When one of the + changes entirely covers the range, the string `"cover"` is + returned. + */ + touchesRange(from, to = from) { + for (let i = 0, pos = 0; i < this.sections.length && pos <= to;) { + let len = this.sections[i++], ins = this.sections[i++], end = pos + len; + if (ins >= 0 && pos <= to && end >= from) + return pos < from && end > to ? "cover" : true; + pos = end; + } + return false; + } + /** + @internal + */ + toString() { + let result = ""; + for (let i = 0; i < this.sections.length;) { + let len = this.sections[i++], ins = this.sections[i++]; + result += (result ? " " : "") + len + (ins >= 0 ? ":" + ins : ""); + } + return result; + } + /** + Serialize this change desc to a JSON-representable value. + */ + toJSON() { return this.sections; } + /** + Create a change desc from its JSON representation (as produced + by [`toJSON`](https://codemirror.net/6/docs/ref/#state.ChangeDesc.toJSON). + */ + static fromJSON(json) { + if (!Array.isArray(json) || json.length % 2 || json.some(a => typeof a != "number")) + throw new RangeError("Invalid JSON representation of ChangeDesc"); + return new ChangeDesc(json); + } + /** + @internal + */ + static create(sections) { return new ChangeDesc(sections); } + } + /** + A change set represents a group of modifications to a document. It + stores the document length, and can only be applied to documents + with exactly that length. + */ + class ChangeSet extends ChangeDesc { + constructor(sections, + /** + @internal + */ + inserted) { + super(sections); + this.inserted = inserted; + } + /** + Apply the changes to a document, returning the modified + document. + */ + apply(doc) { + if (this.length != doc.length) + throw new RangeError("Applying change set to a document with the wrong length"); + iterChanges(this, (fromA, toA, fromB, _toB, text) => doc = doc.replace(fromB, fromB + (toA - fromA), text), false); + return doc; + } + mapDesc(other, before = false) { return mapSet(this, other, before, true); } + /** + Given the document as it existed _before_ the changes, return a + change set that represents the inverse of this set, which could + be used to go from the document created by the changes back to + the document as it existed before the changes. + */ + invert(doc) { + let sections = this.sections.slice(), inserted = []; + for (let i = 0, pos = 0; i < sections.length; i += 2) { + let len = sections[i], ins = sections[i + 1]; + if (ins >= 0) { + sections[i] = ins; + sections[i + 1] = len; + let index = i >> 1; + while (inserted.length < index) + inserted.push(Text.empty); + inserted.push(len ? doc.slice(pos, pos + len) : Text.empty); + } + pos += len; + } + return new ChangeSet(sections, inserted); + } + /** + Combine two subsequent change sets into a single set. `other` + must start in the document produced by `this`. If `this` goes + `docA` → `docB` and `other` represents `docB` → `docC`, the + returned value will represent the change `docA` → `docC`. + */ + compose(other) { return this.empty ? other : other.empty ? this : composeSets(this, other, true); } + /** + Given another change set starting in the same document, maps this + change set over the other, producing a new change set that can be + applied to the document produced by applying `other`. When + `before` is `true`, order changes as if `this` comes before + `other`, otherwise (the default) treat `other` as coming first. + + Given two changes `A` and `B`, `A.compose(B.map(A))` and + `B.compose(A.map(B, true))` will produce the same document. This + provides a basic form of [operational + transformation](https://en.wikipedia.org/wiki/Operational_transformation), + and can be used for collaborative editing. + */ + map(other, before = false) { return other.empty ? this : mapSet(this, other, before, true); } + /** + Iterate over the changed ranges in the document, calling `f` for + each, with the range in the original document (`fromA`-`toA`) + and the range that replaces it in the new document + (`fromB`-`toB`). + + When `individual` is true, adjacent changes are reported + separately. + */ + iterChanges(f, individual = false) { + iterChanges(this, f, individual); + } + /** + Get a [change description](https://codemirror.net/6/docs/ref/#state.ChangeDesc) for this change + set. + */ + get desc() { return ChangeDesc.create(this.sections); } + /** + @internal + */ + filter(ranges) { + let resultSections = [], resultInserted = [], filteredSections = []; + let iter = new SectionIter(this); + done: for (let i = 0, pos = 0;;) { + let next = i == ranges.length ? 1e9 : ranges[i++]; + while (pos < next || pos == next && iter.len == 0) { + if (iter.done) + break done; + let len = Math.min(iter.len, next - pos); + addSection(filteredSections, len, -1); + let ins = iter.ins == -1 ? -1 : iter.off == 0 ? iter.ins : 0; + addSection(resultSections, len, ins); + if (ins > 0) + addInsert(resultInserted, resultSections, iter.text); + iter.forward(len); + pos += len; + } + let end = ranges[i++]; + while (pos < end) { + if (iter.done) + break done; + let len = Math.min(iter.len, end - pos); + addSection(resultSections, len, -1); + addSection(filteredSections, len, iter.ins == -1 ? -1 : iter.off == 0 ? iter.ins : 0); + iter.forward(len); + pos += len; + } + } + return { changes: new ChangeSet(resultSections, resultInserted), + filtered: ChangeDesc.create(filteredSections) }; + } + /** + Serialize this change set to a JSON-representable value. + */ + toJSON() { + let parts = []; + for (let i = 0; i < this.sections.length; i += 2) { + let len = this.sections[i], ins = this.sections[i + 1]; + if (ins < 0) + parts.push(len); + else if (ins == 0) + parts.push([len]); + else + parts.push([len].concat(this.inserted[i >> 1].toJSON())); + } + return parts; + } + /** + Create a change set for the given changes, for a document of the + given length, using `lineSep` as line separator. + */ + static of(changes, length, lineSep) { + let sections = [], inserted = [], pos = 0; + let total = null; + function flush(force = false) { + if (!force && !sections.length) + return; + if (pos < length) + addSection(sections, length - pos, -1); + let set = new ChangeSet(sections, inserted); + total = total ? total.compose(set.map(total)) : set; + sections = []; + inserted = []; + pos = 0; + } + function process(spec) { + if (Array.isArray(spec)) { + for (let sub of spec) + process(sub); + } + else if (spec instanceof ChangeSet) { + if (spec.length != length) + throw new RangeError(`Mismatched change set length (got ${spec.length}, expected ${length})`); + flush(); + total = total ? total.compose(spec.map(total)) : spec; + } + else { + let { from, to = from, insert } = spec; + if (from > to || from < 0 || to > length) + throw new RangeError(`Invalid change range ${from} to ${to} (in doc of length ${length})`); + let insText = !insert ? Text.empty : typeof insert == "string" ? Text.of(insert.split(lineSep || DefaultSplit)) : insert; + let insLen = insText.length; + if (from == to && insLen == 0) + return; + if (from < pos) + flush(); + if (from > pos) + addSection(sections, from - pos, -1); + addSection(sections, to - from, insLen); + addInsert(inserted, sections, insText); + pos = to; + } + } + process(changes); + flush(!total); + return total; + } + /** + Create an empty changeset of the given length. + */ + static empty(length) { + return new ChangeSet(length ? [length, -1] : [], []); + } + /** + Create a changeset from its JSON representation (as produced by + [`toJSON`](https://codemirror.net/6/docs/ref/#state.ChangeSet.toJSON). + */ + static fromJSON(json) { + if (!Array.isArray(json)) + throw new RangeError("Invalid JSON representation of ChangeSet"); + let sections = [], inserted = []; + for (let i = 0; i < json.length; i++) { + let part = json[i]; + if (typeof part == "number") { + sections.push(part, -1); + } + else if (!Array.isArray(part) || typeof part[0] != "number" || part.some((e, i) => i && typeof e != "string")) { + throw new RangeError("Invalid JSON representation of ChangeSet"); + } + else if (part.length == 1) { + sections.push(part[0], 0); + } + else { + while (inserted.length < i) + inserted.push(Text.empty); + inserted[i] = Text.of(part.slice(1)); + sections.push(part[0], inserted[i].length); + } + } + return new ChangeSet(sections, inserted); + } + /** + @internal + */ + static createSet(sections, inserted) { + return new ChangeSet(sections, inserted); + } + } + function addSection(sections, len, ins, forceJoin = false) { + if (len == 0 && ins <= 0) + return; + let last = sections.length - 2; + if (last >= 0 && ins <= 0 && ins == sections[last + 1]) + sections[last] += len; + else if (len == 0 && sections[last] == 0) + sections[last + 1] += ins; + else if (forceJoin) { + sections[last] += len; + sections[last + 1] += ins; + } + else + sections.push(len, ins); + } + function addInsert(values, sections, value) { + if (value.length == 0) + return; + let index = (sections.length - 2) >> 1; + if (index < values.length) { + values[values.length - 1] = values[values.length - 1].append(value); + } + else { + while (values.length < index) + values.push(Text.empty); + values.push(value); + } + } + function iterChanges(desc, f, individual) { + let inserted = desc.inserted; + for (let posA = 0, posB = 0, i = 0; i < desc.sections.length;) { + let len = desc.sections[i++], ins = desc.sections[i++]; + if (ins < 0) { + posA += len; + posB += len; + } + else { + let endA = posA, endB = posB, text = Text.empty; + for (;;) { + endA += len; + endB += ins; + if (ins && inserted) + text = text.append(inserted[(i - 2) >> 1]); + if (individual || i == desc.sections.length || desc.sections[i + 1] < 0) + break; + len = desc.sections[i++]; + ins = desc.sections[i++]; + } + f(posA, endA, posB, endB, text); + posA = endA; + posB = endB; + } + } + } + function mapSet(setA, setB, before, mkSet = false) { + // Produce a copy of setA that applies to the document after setB + // has been applied (assuming both start at the same document). + let sections = [], insert = mkSet ? [] : null; + let a = new SectionIter(setA), b = new SectionIter(setB); + // Iterate over both sets in parallel. inserted tracks, for changes + // in A that have to be processed piece-by-piece, whether their + // content has been inserted already, and refers to the section + // index. + for (let inserted = -1;;) { + if (a.ins == -1 && b.ins == -1) { + // Move across ranges skipped by both sets. + let len = Math.min(a.len, b.len); + addSection(sections, len, -1); + a.forward(len); + b.forward(len); + } + else if (b.ins >= 0 && (a.ins < 0 || inserted == a.i || a.off == 0 && (b.len < a.len || b.len == a.len && !before))) { + // If there's a change in B that comes before the next change in + // A (ordered by start pos, then len, then before flag), skip + // that (and process any changes in A it covers). + let len = b.len; + addSection(sections, b.ins, -1); + while (len) { + let piece = Math.min(a.len, len); + if (a.ins >= 0 && inserted < a.i && a.len <= piece) { + addSection(sections, 0, a.ins); + if (insert) + addInsert(insert, sections, a.text); + inserted = a.i; + } + a.forward(piece); + len -= piece; + } + b.next(); + } + else if (a.ins >= 0) { + // Process the part of a change in A up to the start of the next + // non-deletion change in B (if overlapping). + let len = 0, left = a.len; + while (left) { + if (b.ins == -1) { + let piece = Math.min(left, b.len); + len += piece; + left -= piece; + b.forward(piece); + } + else if (b.ins == 0 && b.len < left) { + left -= b.len; + b.next(); + } + else { + break; + } + } + addSection(sections, len, inserted < a.i ? a.ins : 0); + if (insert && inserted < a.i) + addInsert(insert, sections, a.text); + inserted = a.i; + a.forward(a.len - left); + } + else if (a.done && b.done) { + return insert ? ChangeSet.createSet(sections, insert) : ChangeDesc.create(sections); + } + else { + throw new Error("Mismatched change set lengths"); + } + } + } + function composeSets(setA, setB, mkSet = false) { + let sections = []; + let insert = mkSet ? [] : null; + let a = new SectionIter(setA), b = new SectionIter(setB); + for (let open = false;;) { + if (a.done && b.done) { + return insert ? ChangeSet.createSet(sections, insert) : ChangeDesc.create(sections); + } + else if (a.ins == 0) { // Deletion in A + addSection(sections, a.len, 0, open); + a.next(); + } + else if (b.len == 0 && !b.done) { // Insertion in B + addSection(sections, 0, b.ins, open); + if (insert) + addInsert(insert, sections, b.text); + b.next(); + } + else if (a.done || b.done) { + throw new Error("Mismatched change set lengths"); + } + else { + let len = Math.min(a.len2, b.len), sectionLen = sections.length; + if (a.ins == -1) { + let insB = b.ins == -1 ? -1 : b.off ? 0 : b.ins; + addSection(sections, len, insB, open); + if (insert && insB) + addInsert(insert, sections, b.text); + } + else if (b.ins == -1) { + addSection(sections, a.off ? 0 : a.len, len, open); + if (insert) + addInsert(insert, sections, a.textBit(len)); + } + else { + addSection(sections, a.off ? 0 : a.len, b.off ? 0 : b.ins, open); + if (insert && !b.off) + addInsert(insert, sections, b.text); + } + open = (a.ins > len || b.ins >= 0 && b.len > len) && (open || sections.length > sectionLen); + a.forward2(len); + b.forward(len); + } + } + } + class SectionIter { + constructor(set) { + this.set = set; + this.i = 0; + this.next(); + } + next() { + let { sections } = this.set; + if (this.i < sections.length) { + this.len = sections[this.i++]; + this.ins = sections[this.i++]; + } + else { + this.len = 0; + this.ins = -2; + } + this.off = 0; + } + get done() { return this.ins == -2; } + get len2() { return this.ins < 0 ? this.len : this.ins; } + get text() { + let { inserted } = this.set, index = (this.i - 2) >> 1; + return index >= inserted.length ? Text.empty : inserted[index]; + } + textBit(len) { + let { inserted } = this.set, index = (this.i - 2) >> 1; + return index >= inserted.length && !len ? Text.empty + : inserted[index].slice(this.off, len == null ? undefined : this.off + len); + } + forward(len) { + if (len == this.len) + this.next(); + else { + this.len -= len; + this.off += len; + } + } + forward2(len) { + if (this.ins == -1) + this.forward(len); + else if (len == this.ins) + this.next(); + else { + this.ins -= len; + this.off += len; + } + } + } + + /** + A single selection range. When + [`allowMultipleSelections`](https://codemirror.net/6/docs/ref/#state.EditorState^allowMultipleSelections) + is enabled, a [selection](https://codemirror.net/6/docs/ref/#state.EditorSelection) may hold + multiple ranges. By default, selections hold exactly one range. + */ + class SelectionRange { + constructor( + /** + The lower boundary of the range. + */ + from, + /** + The upper boundary of the range. + */ + to, flags) { + this.from = from; + this.to = to; + this.flags = flags; + } + /** + The anchor of the range—the side that doesn't move when you + extend it. + */ + get anchor() { return this.flags & 16 /* RangeFlag.Inverted */ ? this.to : this.from; } + /** + The head of the range, which is moved when the range is + [extended](https://codemirror.net/6/docs/ref/#state.SelectionRange.extend). + */ + get head() { return this.flags & 16 /* RangeFlag.Inverted */ ? this.from : this.to; } + /** + True when `anchor` and `head` are at the same position. + */ + get empty() { return this.from == this.to; } + /** + If this is a cursor that is explicitly associated with the + character on one of its sides, this returns the side. -1 means + the character before its position, 1 the character after, and 0 + means no association. + */ + get assoc() { return this.flags & 4 /* RangeFlag.AssocBefore */ ? -1 : this.flags & 8 /* RangeFlag.AssocAfter */ ? 1 : 0; } + /** + The bidirectional text level associated with this cursor, if + any. + */ + get bidiLevel() { + let level = this.flags & 3 /* RangeFlag.BidiLevelMask */; + return level == 3 ? null : level; + } + /** + The goal column (stored vertical offset) associated with a + cursor. This is used to preserve the vertical position when + [moving](https://codemirror.net/6/docs/ref/#view.EditorView.moveVertically) across + lines of different length. + */ + get goalColumn() { + let value = this.flags >> 5 /* RangeFlag.GoalColumnOffset */; + return value == 33554431 /* RangeFlag.NoGoalColumn */ ? undefined : value; + } + /** + Map this range through a change, producing a valid range in the + updated document. + */ + map(change, assoc = -1) { + let from, to; + if (this.empty) { + from = to = change.mapPos(this.from, assoc); + } + else { + from = change.mapPos(this.from, 1); + to = change.mapPos(this.to, -1); + } + return from == this.from && to == this.to ? this : new SelectionRange(from, to, this.flags); + } + /** + Extend this range to cover at least `from` to `to`. + */ + extend(from, to = from) { + if (from <= this.anchor && to >= this.anchor) + return EditorSelection.range(from, to); + let head = Math.abs(from - this.anchor) > Math.abs(to - this.anchor) ? from : to; + return EditorSelection.range(this.anchor, head); + } + /** + Compare this range to another range. + */ + eq(other) { + return this.anchor == other.anchor && this.head == other.head; + } + /** + Return a JSON-serializable object representing the range. + */ + toJSON() { return { anchor: this.anchor, head: this.head }; } + /** + Convert a JSON representation of a range to a `SelectionRange` + instance. + */ + static fromJSON(json) { + if (!json || typeof json.anchor != "number" || typeof json.head != "number") + throw new RangeError("Invalid JSON representation for SelectionRange"); + return EditorSelection.range(json.anchor, json.head); + } + /** + @internal + */ + static create(from, to, flags) { + return new SelectionRange(from, to, flags); + } + } + /** + An editor selection holds one or more selection ranges. + */ + class EditorSelection { + constructor( + /** + The ranges in the selection, sorted by position. Ranges cannot + overlap (but they may touch, if they aren't empty). + */ + ranges, + /** + The index of the _main_ range in the selection (which is + usually the range that was added last). + */ + mainIndex) { + this.ranges = ranges; + this.mainIndex = mainIndex; + } + /** + Map a selection through a change. Used to adjust the selection + position for changes. + */ + map(change, assoc = -1) { + if (change.empty) + return this; + return EditorSelection.create(this.ranges.map(r => r.map(change, assoc)), this.mainIndex); + } + /** + Compare this selection to another selection. + */ + eq(other) { + if (this.ranges.length != other.ranges.length || + this.mainIndex != other.mainIndex) + return false; + for (let i = 0; i < this.ranges.length; i++) + if (!this.ranges[i].eq(other.ranges[i])) + return false; + return true; + } + /** + Get the primary selection range. Usually, you should make sure + your code applies to _all_ ranges, by using methods like + [`changeByRange`](https://codemirror.net/6/docs/ref/#state.EditorState.changeByRange). + */ + get main() { return this.ranges[this.mainIndex]; } + /** + Make sure the selection only has one range. Returns a selection + holding only the main range from this selection. + */ + asSingle() { + return this.ranges.length == 1 ? this : new EditorSelection([this.main], 0); + } + /** + Extend this selection with an extra range. + */ + addRange(range, main = true) { + return EditorSelection.create([range].concat(this.ranges), main ? 0 : this.mainIndex + 1); + } + /** + Replace a given range with another range, and then normalize the + selection to merge and sort ranges if necessary. + */ + replaceRange(range, which = this.mainIndex) { + let ranges = this.ranges.slice(); + ranges[which] = range; + return EditorSelection.create(ranges, this.mainIndex); + } + /** + Convert this selection to an object that can be serialized to + JSON. + */ + toJSON() { + return { ranges: this.ranges.map(r => r.toJSON()), main: this.mainIndex }; + } + /** + Create a selection from a JSON representation. + */ + static fromJSON(json) { + if (!json || !Array.isArray(json.ranges) || typeof json.main != "number" || json.main >= json.ranges.length) + throw new RangeError("Invalid JSON representation for EditorSelection"); + return new EditorSelection(json.ranges.map((r) => SelectionRange.fromJSON(r)), json.main); + } + /** + Create a selection holding a single range. + */ + static single(anchor, head = anchor) { + return new EditorSelection([EditorSelection.range(anchor, head)], 0); + } + /** + Sort and merge the given set of ranges, creating a valid + selection. + */ + static create(ranges, mainIndex = 0) { + if (ranges.length == 0) + throw new RangeError("A selection needs at least one range"); + for (let pos = 0, i = 0; i < ranges.length; i++) { + let range = ranges[i]; + if (range.empty ? range.from <= pos : range.from < pos) + return EditorSelection.normalized(ranges.slice(), mainIndex); + pos = range.to; + } + return new EditorSelection(ranges, mainIndex); + } + /** + Create a cursor selection range at the given position. You can + safely ignore the optional arguments in most situations. + */ + static cursor(pos, assoc = 0, bidiLevel, goalColumn) { + return SelectionRange.create(pos, pos, (assoc == 0 ? 0 : assoc < 0 ? 4 /* RangeFlag.AssocBefore */ : 8 /* RangeFlag.AssocAfter */) | + (bidiLevel == null ? 3 : Math.min(2, bidiLevel)) | + ((goalColumn !== null && goalColumn !== void 0 ? goalColumn : 33554431 /* RangeFlag.NoGoalColumn */) << 5 /* RangeFlag.GoalColumnOffset */)); + } + /** + Create a selection range. + */ + static range(anchor, head, goalColumn) { + let goal = (goalColumn !== null && goalColumn !== void 0 ? goalColumn : 33554431 /* RangeFlag.NoGoalColumn */) << 5 /* RangeFlag.GoalColumnOffset */; + return head < anchor ? SelectionRange.create(head, anchor, 16 /* RangeFlag.Inverted */ | goal | 8 /* RangeFlag.AssocAfter */) + : SelectionRange.create(anchor, head, goal | (head > anchor ? 4 /* RangeFlag.AssocBefore */ : 0)); + } + /** + @internal + */ + static normalized(ranges, mainIndex = 0) { + let main = ranges[mainIndex]; + ranges.sort((a, b) => a.from - b.from); + mainIndex = ranges.indexOf(main); + for (let i = 1; i < ranges.length; i++) { + let range = ranges[i], prev = ranges[i - 1]; + if (range.empty ? range.from <= prev.to : range.from < prev.to) { + let from = prev.from, to = Math.max(range.to, prev.to); + if (i <= mainIndex) + mainIndex--; + ranges.splice(--i, 2, range.anchor > range.head ? EditorSelection.range(to, from) : EditorSelection.range(from, to)); + } + } + return new EditorSelection(ranges, mainIndex); + } + } + function checkSelection(selection, docLength) { + for (let range of selection.ranges) + if (range.to > docLength) + throw new RangeError("Selection points outside of document"); + } + + let nextID = 0; + /** + A facet is a labeled value that is associated with an editor + state. It takes inputs from any number of extensions, and combines + those into a single output value. + + Examples of uses of facets are the [tab + size](https://codemirror.net/6/docs/ref/#state.EditorState^tabSize), [editor + attributes](https://codemirror.net/6/docs/ref/#view.EditorView^editorAttributes), and [update + listeners](https://codemirror.net/6/docs/ref/#view.EditorView^updateListener). + */ + class Facet { + constructor( + /** + @internal + */ + combine, + /** + @internal + */ + compareInput, + /** + @internal + */ + compare, isStatic, enables) { + this.combine = combine; + this.compareInput = compareInput; + this.compare = compare; + this.isStatic = isStatic; + /** + @internal + */ + this.id = nextID++; + this.default = combine([]); + this.extensions = typeof enables == "function" ? enables(this) : enables; + } + /** + Define a new facet. + */ + static define(config = {}) { + return new Facet(config.combine || ((a) => a), config.compareInput || ((a, b) => a === b), config.compare || (!config.combine ? sameArray$1 : (a, b) => a === b), !!config.static, config.enables); + } + /** + Returns an extension that adds the given value to this facet. + */ + of(value) { + return new FacetProvider([], this, 0 /* Provider.Static */, value); + } + /** + Create an extension that computes a value for the facet from a + state. You must take care to declare the parts of the state that + this value depends on, since your function is only called again + for a new state when one of those parts changed. + + In cases where your value depends only on a single field, you'll + want to use the [`from`](https://codemirror.net/6/docs/ref/#state.Facet.from) method instead. + */ + compute(deps, get) { + if (this.isStatic) + throw new Error("Can't compute a static facet"); + return new FacetProvider(deps, this, 1 /* Provider.Single */, get); + } + /** + Create an extension that computes zero or more values for this + facet from a state. + */ + computeN(deps, get) { + if (this.isStatic) + throw new Error("Can't compute a static facet"); + return new FacetProvider(deps, this, 2 /* Provider.Multi */, get); + } + from(field, get) { + if (!get) + get = x => x; + return this.compute([field], state => get(state.field(field))); + } + } + function sameArray$1(a, b) { + return a == b || a.length == b.length && a.every((e, i) => e === b[i]); + } + class FacetProvider { + constructor(dependencies, facet, type, value) { + this.dependencies = dependencies; + this.facet = facet; + this.type = type; + this.value = value; + this.id = nextID++; + } + dynamicSlot(addresses) { + var _a; + let getter = this.value; + let compare = this.facet.compareInput; + let id = this.id, idx = addresses[id] >> 1, multi = this.type == 2 /* Provider.Multi */; + let depDoc = false, depSel = false, depAddrs = []; + for (let dep of this.dependencies) { + if (dep == "doc") + depDoc = true; + else if (dep == "selection") + depSel = true; + else if ((((_a = addresses[dep.id]) !== null && _a !== void 0 ? _a : 1) & 1) == 0) + depAddrs.push(addresses[dep.id]); + } + return { + create(state) { + state.values[idx] = getter(state); + return 1 /* SlotStatus.Changed */; + }, + update(state, tr) { + if ((depDoc && tr.docChanged) || (depSel && (tr.docChanged || tr.selection)) || ensureAll(state, depAddrs)) { + let newVal = getter(state); + if (multi ? !compareArray(newVal, state.values[idx], compare) : !compare(newVal, state.values[idx])) { + state.values[idx] = newVal; + return 1 /* SlotStatus.Changed */; + } + } + return 0; + }, + reconfigure: (state, oldState) => { + let newVal = getter(state); + let oldAddr = oldState.config.address[id]; + if (oldAddr != null) { + let oldVal = getAddr(oldState, oldAddr); + if (this.dependencies.every(dep => { + return dep instanceof Facet ? oldState.facet(dep) === state.facet(dep) : + dep instanceof StateField ? oldState.field(dep, false) == state.field(dep, false) : true; + }) || (multi ? compareArray(newVal, oldVal, compare) : compare(newVal, oldVal))) { + state.values[idx] = oldVal; + return 0; + } + } + state.values[idx] = newVal; + return 1 /* SlotStatus.Changed */; + } + }; + } + } + function compareArray(a, b, compare) { + if (a.length != b.length) + return false; + for (let i = 0; i < a.length; i++) + if (!compare(a[i], b[i])) + return false; + return true; + } + function ensureAll(state, addrs) { + let changed = false; + for (let addr of addrs) + if (ensureAddr(state, addr) & 1 /* SlotStatus.Changed */) + changed = true; + return changed; + } + function dynamicFacetSlot(addresses, facet, providers) { + let providerAddrs = providers.map(p => addresses[p.id]); + let providerTypes = providers.map(p => p.type); + let dynamic = providerAddrs.filter(p => !(p & 1)); + let idx = addresses[facet.id] >> 1; + function get(state) { + let values = []; + for (let i = 0; i < providerAddrs.length; i++) { + let value = getAddr(state, providerAddrs[i]); + if (providerTypes[i] == 2 /* Provider.Multi */) + for (let val of value) + values.push(val); + else + values.push(value); + } + return facet.combine(values); + } + return { + create(state) { + for (let addr of providerAddrs) + ensureAddr(state, addr); + state.values[idx] = get(state); + return 1 /* SlotStatus.Changed */; + }, + update(state, tr) { + if (!ensureAll(state, dynamic)) + return 0; + let value = get(state); + if (facet.compare(value, state.values[idx])) + return 0; + state.values[idx] = value; + return 1 /* SlotStatus.Changed */; + }, + reconfigure(state, oldState) { + let depChanged = ensureAll(state, providerAddrs); + let oldProviders = oldState.config.facets[facet.id], oldValue = oldState.facet(facet); + if (oldProviders && !depChanged && sameArray$1(providers, oldProviders)) { + state.values[idx] = oldValue; + return 0; + } + let value = get(state); + if (facet.compare(value, oldValue)) { + state.values[idx] = oldValue; + return 0; + } + state.values[idx] = value; + return 1 /* SlotStatus.Changed */; + } + }; + } + const initField = /*@__PURE__*/Facet.define({ static: true }); + /** + Fields can store additional information in an editor state, and + keep it in sync with the rest of the state. + */ + class StateField { + constructor( + /** + @internal + */ + id, createF, updateF, compareF, + /** + @internal + */ + spec) { + this.id = id; + this.createF = createF; + this.updateF = updateF; + this.compareF = compareF; + this.spec = spec; + /** + @internal + */ + this.provides = undefined; + } + /** + Define a state field. + */ + static define(config) { + let field = new StateField(nextID++, config.create, config.update, config.compare || ((a, b) => a === b), config); + if (config.provide) + field.provides = config.provide(field); + return field; + } + create(state) { + let init = state.facet(initField).find(i => i.field == this); + return ((init === null || init === void 0 ? void 0 : init.create) || this.createF)(state); + } + /** + @internal + */ + slot(addresses) { + let idx = addresses[this.id] >> 1; + return { + create: (state) => { + state.values[idx] = this.create(state); + return 1 /* SlotStatus.Changed */; + }, + update: (state, tr) => { + let oldVal = state.values[idx]; + let value = this.updateF(oldVal, tr); + if (this.compareF(oldVal, value)) + return 0; + state.values[idx] = value; + return 1 /* SlotStatus.Changed */; + }, + reconfigure: (state, oldState) => { + if (oldState.config.address[this.id] != null) { + state.values[idx] = oldState.field(this); + return 0; + } + state.values[idx] = this.create(state); + return 1 /* SlotStatus.Changed */; + } + }; + } + /** + Returns an extension that enables this field and overrides the + way it is initialized. Can be useful when you need to provide a + non-default starting value for the field. + */ + init(create) { + return [this, initField.of({ field: this, create })]; + } + /** + State field instances can be used as + [`Extension`](https://codemirror.net/6/docs/ref/#state.Extension) values to enable the field in a + given state. + */ + get extension() { return this; } + } + const Prec_ = { lowest: 4, low: 3, default: 2, high: 1, highest: 0 }; + function prec(value) { + return (ext) => new PrecExtension(ext, value); + } + /** + By default extensions are registered in the order they are found + in the flattened form of nested array that was provided. + Individual extension values can be assigned a precedence to + override this. Extensions that do not have a precedence set get + the precedence of the nearest parent with a precedence, or + [`default`](https://codemirror.net/6/docs/ref/#state.Prec.default) if there is no such parent. The + final ordering of extensions is determined by first sorting by + precedence and then by order within each precedence. + */ + const Prec = { + /** + The highest precedence level, for extensions that should end up + near the start of the precedence ordering. + */ + highest: /*@__PURE__*/prec(Prec_.highest), + /** + A higher-than-default precedence, for extensions that should + come before those with default precedence. + */ + high: /*@__PURE__*/prec(Prec_.high), + /** + The default precedence, which is also used for extensions + without an explicit precedence. + */ + default: /*@__PURE__*/prec(Prec_.default), + /** + A lower-than-default precedence. + */ + low: /*@__PURE__*/prec(Prec_.low), + /** + The lowest precedence level. Meant for things that should end up + near the end of the extension order. + */ + lowest: /*@__PURE__*/prec(Prec_.lowest) + }; + class PrecExtension { + constructor(inner, prec) { + this.inner = inner; + this.prec = prec; + } + } + /** + Extension compartments can be used to make a configuration + dynamic. By [wrapping](https://codemirror.net/6/docs/ref/#state.Compartment.of) part of your + configuration in a compartment, you can later + [replace](https://codemirror.net/6/docs/ref/#state.Compartment.reconfigure) that part through a + transaction. + */ + class Compartment { + /** + Create an instance of this compartment to add to your [state + configuration](https://codemirror.net/6/docs/ref/#state.EditorStateConfig.extensions). + */ + of(ext) { return new CompartmentInstance(this, ext); } + /** + Create an [effect](https://codemirror.net/6/docs/ref/#state.TransactionSpec.effects) that + reconfigures this compartment. + */ + reconfigure(content) { + return Compartment.reconfigure.of({ compartment: this, extension: content }); + } + /** + Get the current content of the compartment in the state, or + `undefined` if it isn't present. + */ + get(state) { + return state.config.compartments.get(this); + } + } + class CompartmentInstance { + constructor(compartment, inner) { + this.compartment = compartment; + this.inner = inner; + } + } + class Configuration { + constructor(base, compartments, dynamicSlots, address, staticValues, facets) { + this.base = base; + this.compartments = compartments; + this.dynamicSlots = dynamicSlots; + this.address = address; + this.staticValues = staticValues; + this.facets = facets; + this.statusTemplate = []; + while (this.statusTemplate.length < dynamicSlots.length) + this.statusTemplate.push(0 /* SlotStatus.Unresolved */); + } + staticFacet(facet) { + let addr = this.address[facet.id]; + return addr == null ? facet.default : this.staticValues[addr >> 1]; + } + static resolve(base, compartments, oldState) { + let fields = []; + let facets = Object.create(null); + let newCompartments = new Map(); + for (let ext of flatten(base, compartments, newCompartments)) { + if (ext instanceof StateField) + fields.push(ext); + else + (facets[ext.facet.id] || (facets[ext.facet.id] = [])).push(ext); + } + let address = Object.create(null); + let staticValues = []; + let dynamicSlots = []; + for (let field of fields) { + address[field.id] = dynamicSlots.length << 1; + dynamicSlots.push(a => field.slot(a)); + } + let oldFacets = oldState === null || oldState === void 0 ? void 0 : oldState.config.facets; + for (let id in facets) { + let providers = facets[id], facet = providers[0].facet; + let oldProviders = oldFacets && oldFacets[id] || []; + if (providers.every(p => p.type == 0 /* Provider.Static */)) { + address[facet.id] = (staticValues.length << 1) | 1; + if (sameArray$1(oldProviders, providers)) { + staticValues.push(oldState.facet(facet)); + } + else { + let value = facet.combine(providers.map(p => p.value)); + staticValues.push(oldState && facet.compare(value, oldState.facet(facet)) ? oldState.facet(facet) : value); + } + } + else { + for (let p of providers) { + if (p.type == 0 /* Provider.Static */) { + address[p.id] = (staticValues.length << 1) | 1; + staticValues.push(p.value); + } + else { + address[p.id] = dynamicSlots.length << 1; + dynamicSlots.push(a => p.dynamicSlot(a)); + } + } + address[facet.id] = dynamicSlots.length << 1; + dynamicSlots.push(a => dynamicFacetSlot(a, facet, providers)); + } + } + let dynamic = dynamicSlots.map(f => f(address)); + return new Configuration(base, newCompartments, dynamic, address, staticValues, facets); + } + } + function flatten(extension, compartments, newCompartments) { + let result = [[], [], [], [], []]; + let seen = new Map(); + function inner(ext, prec) { + let known = seen.get(ext); + if (known != null) { + if (known <= prec) + return; + let found = result[known].indexOf(ext); + if (found > -1) + result[known].splice(found, 1); + if (ext instanceof CompartmentInstance) + newCompartments.delete(ext.compartment); + } + seen.set(ext, prec); + if (Array.isArray(ext)) { + for (let e of ext) + inner(e, prec); + } + else if (ext instanceof CompartmentInstance) { + if (newCompartments.has(ext.compartment)) + throw new RangeError(`Duplicate use of compartment in extensions`); + let content = compartments.get(ext.compartment) || ext.inner; + newCompartments.set(ext.compartment, content); + inner(content, prec); + } + else if (ext instanceof PrecExtension) { + inner(ext.inner, ext.prec); + } + else if (ext instanceof StateField) { + result[prec].push(ext); + if (ext.provides) + inner(ext.provides, prec); + } + else if (ext instanceof FacetProvider) { + result[prec].push(ext); + if (ext.facet.extensions) + inner(ext.facet.extensions, Prec_.default); + } + else { + let content = ext.extension; + if (!content) + throw new Error(`Unrecognized extension value in extension set (${ext}). This sometimes happens because multiple instances of @codemirror/state are loaded, breaking instanceof checks.`); + inner(content, prec); + } + } + inner(extension, Prec_.default); + return result.reduce((a, b) => a.concat(b)); + } + function ensureAddr(state, addr) { + if (addr & 1) + return 2 /* SlotStatus.Computed */; + let idx = addr >> 1; + let status = state.status[idx]; + if (status == 4 /* SlotStatus.Computing */) + throw new Error("Cyclic dependency between fields and/or facets"); + if (status & 2 /* SlotStatus.Computed */) + return status; + state.status[idx] = 4 /* SlotStatus.Computing */; + let changed = state.computeSlot(state, state.config.dynamicSlots[idx]); + return state.status[idx] = 2 /* SlotStatus.Computed */ | changed; + } + function getAddr(state, addr) { + return addr & 1 ? state.config.staticValues[addr >> 1] : state.values[addr >> 1]; + } + + const languageData = /*@__PURE__*/Facet.define(); + const allowMultipleSelections = /*@__PURE__*/Facet.define({ + combine: values => values.some(v => v), + static: true + }); + const lineSeparator = /*@__PURE__*/Facet.define({ + combine: values => values.length ? values[0] : undefined, + static: true + }); + const changeFilter = /*@__PURE__*/Facet.define(); + const transactionFilter = /*@__PURE__*/Facet.define(); + const transactionExtender = /*@__PURE__*/Facet.define(); + const readOnly = /*@__PURE__*/Facet.define({ + combine: values => values.length ? values[0] : false + }); + + /** + Annotations are tagged values that are used to add metadata to + transactions in an extensible way. They should be used to model + things that effect the entire transaction (such as its [time + stamp](https://codemirror.net/6/docs/ref/#state.Transaction^time) or information about its + [origin](https://codemirror.net/6/docs/ref/#state.Transaction^userEvent)). For effects that happen + _alongside_ the other changes made by the transaction, [state + effects](https://codemirror.net/6/docs/ref/#state.StateEffect) are more appropriate. + */ + class Annotation { + /** + @internal + */ + constructor( + /** + The annotation type. + */ + type, + /** + The value of this annotation. + */ + value) { + this.type = type; + this.value = value; + } + /** + Define a new type of annotation. + */ + static define() { return new AnnotationType(); } + } + /** + Marker that identifies a type of [annotation](https://codemirror.net/6/docs/ref/#state.Annotation). + */ + class AnnotationType { + /** + Create an instance of this annotation. + */ + of(value) { return new Annotation(this, value); } + } + /** + Representation of a type of state effect. Defined with + [`StateEffect.define`](https://codemirror.net/6/docs/ref/#state.StateEffect^define). + */ + class StateEffectType { + /** + @internal + */ + constructor( + // The `any` types in these function types are there to work + // around TypeScript issue #37631, where the type guard on + // `StateEffect.is` mysteriously stops working when these properly + // have type `Value`. + /** + @internal + */ + map) { + this.map = map; + } + /** + Create a [state effect](https://codemirror.net/6/docs/ref/#state.StateEffect) instance of this + type. + */ + of(value) { return new StateEffect(this, value); } + } + /** + State effects can be used to represent additional effects + associated with a [transaction](https://codemirror.net/6/docs/ref/#state.Transaction.effects). They + are often useful to model changes to custom [state + fields](https://codemirror.net/6/docs/ref/#state.StateField), when those changes aren't implicit in + document or selection changes. + */ + class StateEffect { + /** + @internal + */ + constructor( + /** + @internal + */ + type, + /** + The value of this effect. + */ + value) { + this.type = type; + this.value = value; + } + /** + Map this effect through a position mapping. Will return + `undefined` when that ends up deleting the effect. + */ + map(mapping) { + let mapped = this.type.map(this.value, mapping); + return mapped === undefined ? undefined : mapped == this.value ? this : new StateEffect(this.type, mapped); + } + /** + Tells you whether this effect object is of a given + [type](https://codemirror.net/6/docs/ref/#state.StateEffectType). + */ + is(type) { return this.type == type; } + /** + Define a new effect type. The type parameter indicates the type + of values that his effect holds. + */ + static define(spec = {}) { + return new StateEffectType(spec.map || (v => v)); + } + /** + Map an array of effects through a change set. + */ + static mapEffects(effects, mapping) { + if (!effects.length) + return effects; + let result = []; + for (let effect of effects) { + let mapped = effect.map(mapping); + if (mapped) + result.push(mapped); + } + return result; + } + } + /** + This effect can be used to reconfigure the root extensions of + the editor. Doing this will discard any extensions + [appended](https://codemirror.net/6/docs/ref/#state.StateEffect^appendConfig), but does not reset + the content of [reconfigured](https://codemirror.net/6/docs/ref/#state.Compartment.reconfigure) + compartments. + */ + StateEffect.reconfigure = /*@__PURE__*/StateEffect.define(); + /** + Append extensions to the top-level configuration of the editor. + */ + StateEffect.appendConfig = /*@__PURE__*/StateEffect.define(); + /** + Changes to the editor state are grouped into transactions. + Typically, a user action creates a single transaction, which may + contain any number of document changes, may change the selection, + or have other effects. Create a transaction by calling + [`EditorState.update`](https://codemirror.net/6/docs/ref/#state.EditorState.update), or immediately + dispatch one by calling + [`EditorView.dispatch`](https://codemirror.net/6/docs/ref/#view.EditorView.dispatch). + */ + class Transaction { + constructor( + /** + The state from which the transaction starts. + */ + startState, + /** + The document changes made by this transaction. + */ + changes, + /** + The selection set by this transaction, or undefined if it + doesn't explicitly set a selection. + */ + selection, + /** + The effects added to the transaction. + */ + effects, + /** + @internal + */ + annotations, + /** + Whether the selection should be scrolled into view after this + transaction is dispatched. + */ + scrollIntoView) { + this.startState = startState; + this.changes = changes; + this.selection = selection; + this.effects = effects; + this.annotations = annotations; + this.scrollIntoView = scrollIntoView; + /** + @internal + */ + this._doc = null; + /** + @internal + */ + this._state = null; + if (selection) + checkSelection(selection, changes.newLength); + if (!annotations.some((a) => a.type == Transaction.time)) + this.annotations = annotations.concat(Transaction.time.of(Date.now())); + } + /** + @internal + */ + static create(startState, changes, selection, effects, annotations, scrollIntoView) { + return new Transaction(startState, changes, selection, effects, annotations, scrollIntoView); + } + /** + The new document produced by the transaction. Contrary to + [`.state`](https://codemirror.net/6/docs/ref/#state.Transaction.state)`.doc`, accessing this won't + force the entire new state to be computed right away, so it is + recommended that [transaction + filters](https://codemirror.net/6/docs/ref/#state.EditorState^transactionFilter) use this getter + when they need to look at the new document. + */ + get newDoc() { + return this._doc || (this._doc = this.changes.apply(this.startState.doc)); + } + /** + The new selection produced by the transaction. If + [`this.selection`](https://codemirror.net/6/docs/ref/#state.Transaction.selection) is undefined, + this will [map](https://codemirror.net/6/docs/ref/#state.EditorSelection.map) the start state's + current selection through the changes made by the transaction. + */ + get newSelection() { + return this.selection || this.startState.selection.map(this.changes); + } + /** + The new state created by the transaction. Computed on demand + (but retained for subsequent access), so it is recommended not to + access it in [transaction + filters](https://codemirror.net/6/docs/ref/#state.EditorState^transactionFilter) when possible. + */ + get state() { + if (!this._state) + this.startState.applyTransaction(this); + return this._state; + } + /** + Get the value of the given annotation type, if any. + */ + annotation(type) { + for (let ann of this.annotations) + if (ann.type == type) + return ann.value; + return undefined; + } + /** + Indicates whether the transaction changed the document. + */ + get docChanged() { return !this.changes.empty; } + /** + Indicates whether this transaction reconfigures the state + (through a [configuration compartment](https://codemirror.net/6/docs/ref/#state.Compartment) or + with a top-level configuration + [effect](https://codemirror.net/6/docs/ref/#state.StateEffect^reconfigure). + */ + get reconfigured() { return this.startState.config != this.state.config; } + /** + Returns true if the transaction has a [user + event](https://codemirror.net/6/docs/ref/#state.Transaction^userEvent) annotation that is equal to + or more specific than `event`. For example, if the transaction + has `"select.pointer"` as user event, `"select"` and + `"select.pointer"` will match it. + */ + isUserEvent(event) { + let e = this.annotation(Transaction.userEvent); + return !!(e && (e == event || e.length > event.length && e.slice(0, event.length) == event && e[event.length] == ".")); + } + } + /** + Annotation used to store transaction timestamps. Automatically + added to every transaction, holding `Date.now()`. + */ + Transaction.time = /*@__PURE__*/Annotation.define(); + /** + Annotation used to associate a transaction with a user interface + event. Holds a string identifying the event, using a + dot-separated format to support attaching more specific + information. The events used by the core libraries are: + + - `"input"` when content is entered + - `"input.type"` for typed input + - `"input.type.compose"` for composition + - `"input.paste"` for pasted input + - `"input.drop"` when adding content with drag-and-drop + - `"input.complete"` when autocompleting + - `"delete"` when the user deletes content + - `"delete.selection"` when deleting the selection + - `"delete.forward"` when deleting forward from the selection + - `"delete.backward"` when deleting backward from the selection + - `"delete.cut"` when cutting to the clipboard + - `"move"` when content is moved + - `"move.drop"` when content is moved within the editor through drag-and-drop + - `"select"` when explicitly changing the selection + - `"select.pointer"` when selecting with a mouse or other pointing device + - `"undo"` and `"redo"` for history actions + + Use [`isUserEvent`](https://codemirror.net/6/docs/ref/#state.Transaction.isUserEvent) to check + whether the annotation matches a given event. + */ + Transaction.userEvent = /*@__PURE__*/Annotation.define(); + /** + Annotation indicating whether a transaction should be added to + the undo history or not. + */ + Transaction.addToHistory = /*@__PURE__*/Annotation.define(); + /** + Annotation indicating (when present and true) that a transaction + represents a change made by some other actor, not the user. This + is used, for example, to tag other people's changes in + collaborative editing. + */ + Transaction.remote = /*@__PURE__*/Annotation.define(); + function joinRanges(a, b) { + let result = []; + for (let iA = 0, iB = 0;;) { + let from, to; + if (iA < a.length && (iB == b.length || b[iB] >= a[iA])) { + from = a[iA++]; + to = a[iA++]; + } + else if (iB < b.length) { + from = b[iB++]; + to = b[iB++]; + } + else + return result; + if (!result.length || result[result.length - 1] < from) + result.push(from, to); + else if (result[result.length - 1] < to) + result[result.length - 1] = to; + } + } + function mergeTransaction(a, b, sequential) { + var _a; + let mapForA, mapForB, changes; + if (sequential) { + mapForA = b.changes; + mapForB = ChangeSet.empty(b.changes.length); + changes = a.changes.compose(b.changes); + } + else { + mapForA = b.changes.map(a.changes); + mapForB = a.changes.mapDesc(b.changes, true); + changes = a.changes.compose(mapForA); + } + return { + changes, + selection: b.selection ? b.selection.map(mapForB) : (_a = a.selection) === null || _a === void 0 ? void 0 : _a.map(mapForA), + effects: StateEffect.mapEffects(a.effects, mapForA).concat(StateEffect.mapEffects(b.effects, mapForB)), + annotations: a.annotations.length ? a.annotations.concat(b.annotations) : b.annotations, + scrollIntoView: a.scrollIntoView || b.scrollIntoView + }; + } + function resolveTransactionInner(state, spec, docSize) { + let sel = spec.selection, annotations = asArray$1(spec.annotations); + if (spec.userEvent) + annotations = annotations.concat(Transaction.userEvent.of(spec.userEvent)); + return { + changes: spec.changes instanceof ChangeSet ? spec.changes + : ChangeSet.of(spec.changes || [], docSize, state.facet(lineSeparator)), + selection: sel && (sel instanceof EditorSelection ? sel : EditorSelection.single(sel.anchor, sel.head)), + effects: asArray$1(spec.effects), + annotations, + scrollIntoView: !!spec.scrollIntoView + }; + } + function resolveTransaction(state, specs, filter) { + let s = resolveTransactionInner(state, specs.length ? specs[0] : {}, state.doc.length); + if (specs.length && specs[0].filter === false) + filter = false; + for (let i = 1; i < specs.length; i++) { + if (specs[i].filter === false) + filter = false; + let seq = !!specs[i].sequential; + s = mergeTransaction(s, resolveTransactionInner(state, specs[i], seq ? s.changes.newLength : state.doc.length), seq); + } + let tr = Transaction.create(state, s.changes, s.selection, s.effects, s.annotations, s.scrollIntoView); + return extendTransaction(filter ? filterTransaction(tr) : tr); + } + // Finish a transaction by applying filters if necessary. + function filterTransaction(tr) { + let state = tr.startState; + // Change filters + let result = true; + for (let filter of state.facet(changeFilter)) { + let value = filter(tr); + if (value === false) { + result = false; + break; + } + if (Array.isArray(value)) + result = result === true ? value : joinRanges(result, value); + } + if (result !== true) { + let changes, back; + if (result === false) { + back = tr.changes.invertedDesc; + changes = ChangeSet.empty(state.doc.length); + } + else { + let filtered = tr.changes.filter(result); + changes = filtered.changes; + back = filtered.filtered.mapDesc(filtered.changes).invertedDesc; + } + tr = Transaction.create(state, changes, tr.selection && tr.selection.map(back), StateEffect.mapEffects(tr.effects, back), tr.annotations, tr.scrollIntoView); + } + // Transaction filters + let filters = state.facet(transactionFilter); + for (let i = filters.length - 1; i >= 0; i--) { + let filtered = filters[i](tr); + if (filtered instanceof Transaction) + tr = filtered; + else if (Array.isArray(filtered) && filtered.length == 1 && filtered[0] instanceof Transaction) + tr = filtered[0]; + else + tr = resolveTransaction(state, asArray$1(filtered), false); + } + return tr; + } + function extendTransaction(tr) { + let state = tr.startState, extenders = state.facet(transactionExtender), spec = tr; + for (let i = extenders.length - 1; i >= 0; i--) { + let extension = extenders[i](tr); + if (extension && Object.keys(extension).length) + spec = mergeTransaction(spec, resolveTransactionInner(state, extension, tr.changes.newLength), true); + } + return spec == tr ? tr : Transaction.create(state, tr.changes, tr.selection, spec.effects, spec.annotations, spec.scrollIntoView); + } + const none$2 = []; + function asArray$1(value) { + return value == null ? none$2 : Array.isArray(value) ? value : [value]; + } + + /** + The categories produced by a [character + categorizer](https://codemirror.net/6/docs/ref/#state.EditorState.charCategorizer). These are used + do things like selecting by word. + */ + var CharCategory = /*@__PURE__*/(function (CharCategory) { + /** + Word characters. + */ + CharCategory[CharCategory["Word"] = 0] = "Word"; + /** + Whitespace. + */ + CharCategory[CharCategory["Space"] = 1] = "Space"; + /** + Anything else. + */ + CharCategory[CharCategory["Other"] = 2] = "Other"; + return CharCategory})(CharCategory || (CharCategory = {})); + const nonASCIISingleCaseWordChar = /[\u00df\u0587\u0590-\u05f4\u0600-\u06ff\u3040-\u309f\u30a0-\u30ff\u3400-\u4db5\u4e00-\u9fcc\uac00-\ud7af]/; + let wordChar; + try { + wordChar = /*@__PURE__*/new RegExp("[\\p{Alphabetic}\\p{Number}_]", "u"); + } + catch (_) { } + function hasWordChar(str) { + if (wordChar) + return wordChar.test(str); + for (let i = 0; i < str.length; i++) { + let ch = str[i]; + if (/\w/.test(ch) || ch > "\x80" && (ch.toUpperCase() != ch.toLowerCase() || nonASCIISingleCaseWordChar.test(ch))) + return true; + } + return false; + } + function makeCategorizer(wordChars) { + return (char) => { + if (!/\S/.test(char)) + return CharCategory.Space; + if (hasWordChar(char)) + return CharCategory.Word; + for (let i = 0; i < wordChars.length; i++) + if (char.indexOf(wordChars[i]) > -1) + return CharCategory.Word; + return CharCategory.Other; + }; + } + + /** + The editor state class is a persistent (immutable) data structure. + To update a state, you [create](https://codemirror.net/6/docs/ref/#state.EditorState.update) a + [transaction](https://codemirror.net/6/docs/ref/#state.Transaction), which produces a _new_ state + instance, without modifying the original object. + + As such, _never_ mutate properties of a state directly. That'll + just break things. + */ + class EditorState { + constructor( + /** + @internal + */ + config, + /** + The current document. + */ + doc, + /** + The current selection. + */ + selection, + /** + @internal + */ + values, computeSlot, tr) { + this.config = config; + this.doc = doc; + this.selection = selection; + this.values = values; + this.status = config.statusTemplate.slice(); + this.computeSlot = computeSlot; + // Fill in the computed state immediately, so that further queries + // for it made during the update return this state + if (tr) + tr._state = this; + for (let i = 0; i < this.config.dynamicSlots.length; i++) + ensureAddr(this, i << 1); + this.computeSlot = null; + } + field(field, require = true) { + let addr = this.config.address[field.id]; + if (addr == null) { + if (require) + throw new RangeError("Field is not present in this state"); + return undefined; + } + ensureAddr(this, addr); + return getAddr(this, addr); + } + /** + Create a [transaction](https://codemirror.net/6/docs/ref/#state.Transaction) that updates this + state. Any number of [transaction specs](https://codemirror.net/6/docs/ref/#state.TransactionSpec) + can be passed. Unless + [`sequential`](https://codemirror.net/6/docs/ref/#state.TransactionSpec.sequential) is set, the + [changes](https://codemirror.net/6/docs/ref/#state.TransactionSpec.changes) (if any) of each spec + are assumed to start in the _current_ document (not the document + produced by previous specs), and its + [selection](https://codemirror.net/6/docs/ref/#state.TransactionSpec.selection) and + [effects](https://codemirror.net/6/docs/ref/#state.TransactionSpec.effects) are assumed to refer + to the document created by its _own_ changes. The resulting + transaction contains the combined effect of all the different + specs. For [selection](https://codemirror.net/6/docs/ref/#state.TransactionSpec.selection), later + specs take precedence over earlier ones. + */ + update(...specs) { + return resolveTransaction(this, specs, true); + } + /** + @internal + */ + applyTransaction(tr) { + let conf = this.config, { base, compartments } = conf; + for (let effect of tr.effects) { + if (effect.is(Compartment.reconfigure)) { + if (conf) { + compartments = new Map; + conf.compartments.forEach((val, key) => compartments.set(key, val)); + conf = null; + } + compartments.set(effect.value.compartment, effect.value.extension); + } + else if (effect.is(StateEffect.reconfigure)) { + conf = null; + base = effect.value; + } + else if (effect.is(StateEffect.appendConfig)) { + conf = null; + base = asArray$1(base).concat(effect.value); + } + } + let startValues; + if (!conf) { + conf = Configuration.resolve(base, compartments, this); + let intermediateState = new EditorState(conf, this.doc, this.selection, conf.dynamicSlots.map(() => null), (state, slot) => slot.reconfigure(state, this), null); + startValues = intermediateState.values; + } + else { + startValues = tr.startState.values.slice(); + } + new EditorState(conf, tr.newDoc, tr.newSelection, startValues, (state, slot) => slot.update(state, tr), tr); + } + /** + Create a [transaction spec](https://codemirror.net/6/docs/ref/#state.TransactionSpec) that + replaces every selection range with the given content. + */ + replaceSelection(text) { + if (typeof text == "string") + text = this.toText(text); + return this.changeByRange(range => ({ changes: { from: range.from, to: range.to, insert: text }, + range: EditorSelection.cursor(range.from + text.length) })); + } + /** + Create a set of changes and a new selection by running the given + function for each range in the active selection. The function + can return an optional set of changes (in the coordinate space + of the start document), plus an updated range (in the coordinate + space of the document produced by the call's own changes). This + method will merge all the changes and ranges into a single + changeset and selection, and return it as a [transaction + spec](https://codemirror.net/6/docs/ref/#state.TransactionSpec), which can be passed to + [`update`](https://codemirror.net/6/docs/ref/#state.EditorState.update). + */ + changeByRange(f) { + let sel = this.selection; + let result1 = f(sel.ranges[0]); + let changes = this.changes(result1.changes), ranges = [result1.range]; + let effects = asArray$1(result1.effects); + for (let i = 1; i < sel.ranges.length; i++) { + let result = f(sel.ranges[i]); + let newChanges = this.changes(result.changes), newMapped = newChanges.map(changes); + for (let j = 0; j < i; j++) + ranges[j] = ranges[j].map(newMapped); + let mapBy = changes.mapDesc(newChanges, true); + ranges.push(result.range.map(mapBy)); + changes = changes.compose(newMapped); + effects = StateEffect.mapEffects(effects, newMapped).concat(StateEffect.mapEffects(asArray$1(result.effects), mapBy)); + } + return { + changes, + selection: EditorSelection.create(ranges, sel.mainIndex), + effects + }; + } + /** + Create a [change set](https://codemirror.net/6/docs/ref/#state.ChangeSet) from the given change + description, taking the state's document length and line + separator into account. + */ + changes(spec = []) { + if (spec instanceof ChangeSet) + return spec; + return ChangeSet.of(spec, this.doc.length, this.facet(EditorState.lineSeparator)); + } + /** + Using the state's [line + separator](https://codemirror.net/6/docs/ref/#state.EditorState^lineSeparator), create a + [`Text`](https://codemirror.net/6/docs/ref/#state.Text) instance from the given string. + */ + toText(string) { + return Text.of(string.split(this.facet(EditorState.lineSeparator) || DefaultSplit)); + } + /** + Return the given range of the document as a string. + */ + sliceDoc(from = 0, to = this.doc.length) { + return this.doc.sliceString(from, to, this.lineBreak); + } + /** + Get the value of a state [facet](https://codemirror.net/6/docs/ref/#state.Facet). + */ + facet(facet) { + let addr = this.config.address[facet.id]; + if (addr == null) + return facet.default; + ensureAddr(this, addr); + return getAddr(this, addr); + } + /** + Convert this state to a JSON-serializable object. When custom + fields should be serialized, you can pass them in as an object + mapping property names (in the resulting object, which should + not use `doc` or `selection`) to fields. + */ + toJSON(fields) { + let result = { + doc: this.sliceDoc(), + selection: this.selection.toJSON() + }; + if (fields) + for (let prop in fields) { + let value = fields[prop]; + if (value instanceof StateField && this.config.address[value.id] != null) + result[prop] = value.spec.toJSON(this.field(fields[prop]), this); + } + return result; + } + /** + Deserialize a state from its JSON representation. When custom + fields should be deserialized, pass the same object you passed + to [`toJSON`](https://codemirror.net/6/docs/ref/#state.EditorState.toJSON) when serializing as + third argument. + */ + static fromJSON(json, config = {}, fields) { + if (!json || typeof json.doc != "string") + throw new RangeError("Invalid JSON representation for EditorState"); + let fieldInit = []; + if (fields) + for (let prop in fields) { + if (Object.prototype.hasOwnProperty.call(json, prop)) { + let field = fields[prop], value = json[prop]; + fieldInit.push(field.init(state => field.spec.fromJSON(value, state))); + } + } + return EditorState.create({ + doc: json.doc, + selection: EditorSelection.fromJSON(json.selection), + extensions: config.extensions ? fieldInit.concat([config.extensions]) : fieldInit + }); + } + /** + Create a new state. You'll usually only need this when + initializing an editor—updated states are created by applying + transactions. + */ + static create(config = {}) { + let configuration = Configuration.resolve(config.extensions || [], new Map); + let doc = config.doc instanceof Text ? config.doc + : Text.of((config.doc || "").split(configuration.staticFacet(EditorState.lineSeparator) || DefaultSplit)); + let selection = !config.selection ? EditorSelection.single(0) + : config.selection instanceof EditorSelection ? config.selection + : EditorSelection.single(config.selection.anchor, config.selection.head); + checkSelection(selection, doc.length); + if (!configuration.staticFacet(allowMultipleSelections)) + selection = selection.asSingle(); + return new EditorState(configuration, doc, selection, configuration.dynamicSlots.map(() => null), (state, slot) => slot.create(state), null); + } + /** + The size (in columns) of a tab in the document, determined by + the [`tabSize`](https://codemirror.net/6/docs/ref/#state.EditorState^tabSize) facet. + */ + get tabSize() { return this.facet(EditorState.tabSize); } + /** + Get the proper [line-break](https://codemirror.net/6/docs/ref/#state.EditorState^lineSeparator) + string for this state. + */ + get lineBreak() { return this.facet(EditorState.lineSeparator) || "\n"; } + /** + Returns true when the editor is + [configured](https://codemirror.net/6/docs/ref/#state.EditorState^readOnly) to be read-only. + */ + get readOnly() { return this.facet(readOnly); } + /** + Look up a translation for the given phrase (via the + [`phrases`](https://codemirror.net/6/docs/ref/#state.EditorState^phrases) facet), or return the + original string if no translation is found. + + If additional arguments are passed, they will be inserted in + place of markers like `$1` (for the first value) and `$2`, etc. + A single `$` is equivalent to `$1`, and `$$` will produce a + literal dollar sign. + */ + phrase(phrase, ...insert) { + for (let map of this.facet(EditorState.phrases)) + if (Object.prototype.hasOwnProperty.call(map, phrase)) { + phrase = map[phrase]; + break; + } + if (insert.length) + phrase = phrase.replace(/\$(\$|\d*)/g, (m, i) => { + if (i == "$") + return "$"; + let n = +(i || 1); + return !n || n > insert.length ? m : insert[n - 1]; + }); + return phrase; + } + /** + Find the values for a given language data field, provided by the + the [`languageData`](https://codemirror.net/6/docs/ref/#state.EditorState^languageData) facet. + */ + languageDataAt(name, pos, side = -1) { + let values = []; + for (let provider of this.facet(languageData)) { + for (let result of provider(this, pos, side)) { + if (Object.prototype.hasOwnProperty.call(result, name)) + values.push(result[name]); + } + } + return values; + } + /** + Return a function that can categorize strings (expected to + represent a single [grapheme cluster](https://codemirror.net/6/docs/ref/#state.findClusterBreak)) + into one of: + + - Word (contains an alphanumeric character or a character + explicitly listed in the local language's `"wordChars"` + language data, which should be a string) + - Space (contains only whitespace) + - Other (anything else) + */ + charCategorizer(at) { + return makeCategorizer(this.languageDataAt("wordChars", at).join("")); + } + /** + Find the word at the given position, meaning the range + containing all [word](https://codemirror.net/6/docs/ref/#state.CharCategory.Word) characters + around it. If no word characters are adjacent to the position, + this returns null. + */ + wordAt(pos) { + let { text, from, length } = this.doc.lineAt(pos); + let cat = this.charCategorizer(pos); + let start = pos - from, end = pos - from; + while (start > 0) { + let prev = findClusterBreak(text, start, false); + if (cat(text.slice(prev, start)) != CharCategory.Word) + break; + start = prev; + } + while (end < length) { + let next = findClusterBreak(text, end); + if (cat(text.slice(end, next)) != CharCategory.Word) + break; + end = next; + } + return start == end ? null : EditorSelection.range(start + from, end + from); + } + } + /** + A facet that, when enabled, causes the editor to allow multiple + ranges to be selected. Be careful though, because by default the + editor relies on the native DOM selection, which cannot handle + multiple selections. An extension like + [`drawSelection`](https://codemirror.net/6/docs/ref/#view.drawSelection) can be used to make + secondary selections visible to the user. + */ + EditorState.allowMultipleSelections = allowMultipleSelections; + /** + Configures the tab size to use in this state. The first + (highest-precedence) value of the facet is used. If no value is + given, this defaults to 4. + */ + EditorState.tabSize = /*@__PURE__*/Facet.define({ + combine: values => values.length ? values[0] : 4 + }); + /** + The line separator to use. By default, any of `"\n"`, `"\r\n"` + and `"\r"` is treated as a separator when splitting lines, and + lines are joined with `"\n"`. + + When you configure a value here, only that precise separator + will be used, allowing you to round-trip documents through the + editor without normalizing line separators. + */ + EditorState.lineSeparator = lineSeparator; + /** + This facet controls the value of the + [`readOnly`](https://codemirror.net/6/docs/ref/#state.EditorState.readOnly) getter, which is + consulted by commands and extensions that implement editing + functionality to determine whether they should apply. It + defaults to false, but when its highest-precedence value is + `true`, such functionality disables itself. + + Not to be confused with + [`EditorView.editable`](https://codemirror.net/6/docs/ref/#view.EditorView^editable), which + controls whether the editor's DOM is set to be editable (and + thus focusable). + */ + EditorState.readOnly = readOnly; + /** + Registers translation phrases. The + [`phrase`](https://codemirror.net/6/docs/ref/#state.EditorState.phrase) method will look through + all objects registered with this facet to find translations for + its argument. + */ + EditorState.phrases = /*@__PURE__*/Facet.define({ + compare(a, b) { + let kA = Object.keys(a), kB = Object.keys(b); + return kA.length == kB.length && kA.every(k => a[k] == b[k]); + } + }); + /** + A facet used to register [language + data](https://codemirror.net/6/docs/ref/#state.EditorState.languageDataAt) providers. + */ + EditorState.languageData = languageData; + /** + Facet used to register change filters, which are called for each + transaction (unless explicitly + [disabled](https://codemirror.net/6/docs/ref/#state.TransactionSpec.filter)), and can suppress + part of the transaction's changes. + + Such a function can return `true` to indicate that it doesn't + want to do anything, `false` to completely stop the changes in + the transaction, or a set of ranges in which changes should be + suppressed. Such ranges are represented as an array of numbers, + with each pair of two numbers indicating the start and end of a + range. So for example `[10, 20, 100, 110]` suppresses changes + between 10 and 20, and between 100 and 110. + */ + EditorState.changeFilter = changeFilter; + /** + Facet used to register a hook that gets a chance to update or + replace transaction specs before they are applied. This will + only be applied for transactions that don't have + [`filter`](https://codemirror.net/6/docs/ref/#state.TransactionSpec.filter) set to `false`. You + can either return a single transaction spec (possibly the input + transaction), or an array of specs (which will be combined in + the same way as the arguments to + [`EditorState.update`](https://codemirror.net/6/docs/ref/#state.EditorState.update)). + + When possible, it is recommended to avoid accessing + [`Transaction.state`](https://codemirror.net/6/docs/ref/#state.Transaction.state) in a filter, + since it will force creation of a state that will then be + discarded again, if the transaction is actually filtered. + + (This functionality should be used with care. Indiscriminately + modifying transaction is likely to break something or degrade + the user experience.) + */ + EditorState.transactionFilter = transactionFilter; + /** + This is a more limited form of + [`transactionFilter`](https://codemirror.net/6/docs/ref/#state.EditorState^transactionFilter), + which can only add + [annotations](https://codemirror.net/6/docs/ref/#state.TransactionSpec.annotations) and + [effects](https://codemirror.net/6/docs/ref/#state.TransactionSpec.effects). _But_, this type + of filter runs even if the transaction has disabled regular + [filtering](https://codemirror.net/6/docs/ref/#state.TransactionSpec.filter), making it suitable + for effects that don't need to touch the changes or selection, + but do want to process every transaction. + + Extenders run _after_ filters, when both are present. + */ + EditorState.transactionExtender = transactionExtender; + Compartment.reconfigure = /*@__PURE__*/StateEffect.define(); + + /** + Utility function for combining behaviors to fill in a config + object from an array of provided configs. `defaults` should hold + default values for all optional fields in `Config`. + + The function will, by default, error + when a field gets two values that aren't `===`-equal, but you can + provide combine functions per field to do something else. + */ + function combineConfig(configs, defaults, // Should hold only the optional properties of Config, but I haven't managed to express that + combine = {}) { + let result = {}; + for (let config of configs) + for (let key of Object.keys(config)) { + let value = config[key], current = result[key]; + if (current === undefined) + result[key] = value; + else if (current === value || value === undefined) ; // No conflict + else if (Object.hasOwnProperty.call(combine, key)) + result[key] = combine[key](current, value); + else + throw new Error("Config merge conflict for field " + key); + } + for (let key in defaults) + if (result[key] === undefined) + result[key] = defaults[key]; + return result; + } + + /** + Each range is associated with a value, which must inherit from + this class. + */ + class RangeValue { + /** + Compare this value with another value. Used when comparing + rangesets. The default implementation compares by identity. + Unless you are only creating a fixed number of unique instances + of your value type, it is a good idea to implement this + properly. + */ + eq(other) { return this == other; } + /** + Create a [range](https://codemirror.net/6/docs/ref/#state.Range) with this value. + */ + range(from, to = from) { return Range$1.create(from, to, this); } + } + RangeValue.prototype.startSide = RangeValue.prototype.endSide = 0; + RangeValue.prototype.point = false; + RangeValue.prototype.mapMode = MapMode.TrackDel; + /** + A range associates a value with a range of positions. + */ + class Range$1 { + constructor( + /** + The range's start position. + */ + from, + /** + Its end position. + */ + to, + /** + The value associated with this range. + */ + value) { + this.from = from; + this.to = to; + this.value = value; + } + /** + @internal + */ + static create(from, to, value) { + return new Range$1(from, to, value); + } + } + function cmpRange(a, b) { + return a.from - b.from || a.value.startSide - b.value.startSide; + } + class Chunk { + constructor(from, to, value, + // Chunks are marked with the largest point that occurs + // in them (or -1 for no points), so that scans that are + // only interested in points (such as the + // heightmap-related logic) can skip range-only chunks. + maxPoint) { + this.from = from; + this.to = to; + this.value = value; + this.maxPoint = maxPoint; + } + get length() { return this.to[this.to.length - 1]; } + // Find the index of the given position and side. Use the ranges' + // `from` pos when `end == false`, `to` when `end == true`. + findIndex(pos, side, end, startAt = 0) { + let arr = end ? this.to : this.from; + for (let lo = startAt, hi = arr.length;;) { + if (lo == hi) + return lo; + let mid = (lo + hi) >> 1; + let diff = arr[mid] - pos || (end ? this.value[mid].endSide : this.value[mid].startSide) - side; + if (mid == lo) + return diff >= 0 ? lo : hi; + if (diff >= 0) + hi = mid; + else + lo = mid + 1; + } + } + between(offset, from, to, f) { + for (let i = this.findIndex(from, -1000000000 /* C.Far */, true), e = this.findIndex(to, 1000000000 /* C.Far */, false, i); i < e; i++) + if (f(this.from[i] + offset, this.to[i] + offset, this.value[i]) === false) + return false; + } + map(offset, changes) { + let value = [], from = [], to = [], newPos = -1, maxPoint = -1; + for (let i = 0; i < this.value.length; i++) { + let val = this.value[i], curFrom = this.from[i] + offset, curTo = this.to[i] + offset, newFrom, newTo; + if (curFrom == curTo) { + let mapped = changes.mapPos(curFrom, val.startSide, val.mapMode); + if (mapped == null) + continue; + newFrom = newTo = mapped; + if (val.startSide != val.endSide) { + newTo = changes.mapPos(curFrom, val.endSide); + if (newTo < newFrom) + continue; + } + } + else { + newFrom = changes.mapPos(curFrom, val.startSide); + newTo = changes.mapPos(curTo, val.endSide); + if (newFrom > newTo || newFrom == newTo && val.startSide > 0 && val.endSide <= 0) + continue; + } + if ((newTo - newFrom || val.endSide - val.startSide) < 0) + continue; + if (newPos < 0) + newPos = newFrom; + if (val.point) + maxPoint = Math.max(maxPoint, newTo - newFrom); + value.push(val); + from.push(newFrom - newPos); + to.push(newTo - newPos); + } + return { mapped: value.length ? new Chunk(from, to, value, maxPoint) : null, pos: newPos }; + } + } + /** + A range set stores a collection of [ranges](https://codemirror.net/6/docs/ref/#state.Range) in a + way that makes them efficient to [map](https://codemirror.net/6/docs/ref/#state.RangeSet.map) and + [update](https://codemirror.net/6/docs/ref/#state.RangeSet.update). This is an immutable data + structure. + */ + class RangeSet { + constructor( + /** + @internal + */ + chunkPos, + /** + @internal + */ + chunk, + /** + @internal + */ + nextLayer, + /** + @internal + */ + maxPoint) { + this.chunkPos = chunkPos; + this.chunk = chunk; + this.nextLayer = nextLayer; + this.maxPoint = maxPoint; + } + /** + @internal + */ + static create(chunkPos, chunk, nextLayer, maxPoint) { + return new RangeSet(chunkPos, chunk, nextLayer, maxPoint); + } + /** + @internal + */ + get length() { + let last = this.chunk.length - 1; + return last < 0 ? 0 : Math.max(this.chunkEnd(last), this.nextLayer.length); + } + /** + The number of ranges in the set. + */ + get size() { + if (this.isEmpty) + return 0; + let size = this.nextLayer.size; + for (let chunk of this.chunk) + size += chunk.value.length; + return size; + } + /** + @internal + */ + chunkEnd(index) { + return this.chunkPos[index] + this.chunk[index].length; + } + /** + Update the range set, optionally adding new ranges or filtering + out existing ones. + + (Note: The type parameter is just there as a kludge to work + around TypeScript variance issues that prevented `RangeSet<X>` + from being a subtype of `RangeSet<Y>` when `X` is a subtype of + `Y`.) + */ + update(updateSpec) { + let { add = [], sort = false, filterFrom = 0, filterTo = this.length } = updateSpec; + let filter = updateSpec.filter; + if (add.length == 0 && !filter) + return this; + if (sort) + add = add.slice().sort(cmpRange); + if (this.isEmpty) + return add.length ? RangeSet.of(add) : this; + let cur = new LayerCursor(this, null, -1).goto(0), i = 0, spill = []; + let builder = new RangeSetBuilder(); + while (cur.value || i < add.length) { + if (i < add.length && (cur.from - add[i].from || cur.startSide - add[i].value.startSide) >= 0) { + let range = add[i++]; + if (!builder.addInner(range.from, range.to, range.value)) + spill.push(range); + } + else if (cur.rangeIndex == 1 && cur.chunkIndex < this.chunk.length && + (i == add.length || this.chunkEnd(cur.chunkIndex) < add[i].from) && + (!filter || filterFrom > this.chunkEnd(cur.chunkIndex) || filterTo < this.chunkPos[cur.chunkIndex]) && + builder.addChunk(this.chunkPos[cur.chunkIndex], this.chunk[cur.chunkIndex])) { + cur.nextChunk(); + } + else { + if (!filter || filterFrom > cur.to || filterTo < cur.from || filter(cur.from, cur.to, cur.value)) { + if (!builder.addInner(cur.from, cur.to, cur.value)) + spill.push(Range$1.create(cur.from, cur.to, cur.value)); + } + cur.next(); + } + } + return builder.finishInner(this.nextLayer.isEmpty && !spill.length ? RangeSet.empty + : this.nextLayer.update({ add: spill, filter, filterFrom, filterTo })); + } + /** + Map this range set through a set of changes, return the new set. + */ + map(changes) { + if (changes.empty || this.isEmpty) + return this; + let chunks = [], chunkPos = [], maxPoint = -1; + for (let i = 0; i < this.chunk.length; i++) { + let start = this.chunkPos[i], chunk = this.chunk[i]; + let touch = changes.touchesRange(start, start + chunk.length); + if (touch === false) { + maxPoint = Math.max(maxPoint, chunk.maxPoint); + chunks.push(chunk); + chunkPos.push(changes.mapPos(start)); + } + else if (touch === true) { + let { mapped, pos } = chunk.map(start, changes); + if (mapped) { + maxPoint = Math.max(maxPoint, mapped.maxPoint); + chunks.push(mapped); + chunkPos.push(pos); + } + } + } + let next = this.nextLayer.map(changes); + return chunks.length == 0 ? next : new RangeSet(chunkPos, chunks, next || RangeSet.empty, maxPoint); + } + /** + Iterate over the ranges that touch the region `from` to `to`, + calling `f` for each. There is no guarantee that the ranges will + be reported in any specific order. When the callback returns + `false`, iteration stops. + */ + between(from, to, f) { + if (this.isEmpty) + return; + for (let i = 0; i < this.chunk.length; i++) { + let start = this.chunkPos[i], chunk = this.chunk[i]; + if (to >= start && from <= start + chunk.length && + chunk.between(start, from - start, to - start, f) === false) + return; + } + this.nextLayer.between(from, to, f); + } + /** + Iterate over the ranges in this set, in order, including all + ranges that end at or after `from`. + */ + iter(from = 0) { + return HeapCursor.from([this]).goto(from); + } + /** + @internal + */ + get isEmpty() { return this.nextLayer == this; } + /** + Iterate over the ranges in a collection of sets, in order, + starting from `from`. + */ + static iter(sets, from = 0) { + return HeapCursor.from(sets).goto(from); + } + /** + Iterate over two groups of sets, calling methods on `comparator` + to notify it of possible differences. + */ + static compare(oldSets, newSets, + /** + This indicates how the underlying data changed between these + ranges, and is needed to synchronize the iteration. `from` and + `to` are coordinates in the _new_ space, after these changes. + */ + textDiff, comparator, + /** + Can be used to ignore all non-point ranges, and points below + the given size. When -1, all ranges are compared. + */ + minPointSize = -1) { + let a = oldSets.filter(set => set.maxPoint > 0 || !set.isEmpty && set.maxPoint >= minPointSize); + let b = newSets.filter(set => set.maxPoint > 0 || !set.isEmpty && set.maxPoint >= minPointSize); + let sharedChunks = findSharedChunks(a, b, textDiff); + let sideA = new SpanCursor(a, sharedChunks, minPointSize); + let sideB = new SpanCursor(b, sharedChunks, minPointSize); + textDiff.iterGaps((fromA, fromB, length) => compare(sideA, fromA, sideB, fromB, length, comparator)); + if (textDiff.empty && textDiff.length == 0) + compare(sideA, 0, sideB, 0, 0, comparator); + } + /** + Compare the contents of two groups of range sets, returning true + if they are equivalent in the given range. + */ + static eq(oldSets, newSets, from = 0, to) { + if (to == null) + to = 1000000000 /* C.Far */; + let a = oldSets.filter(set => !set.isEmpty && newSets.indexOf(set) < 0); + let b = newSets.filter(set => !set.isEmpty && oldSets.indexOf(set) < 0); + if (a.length != b.length) + return false; + if (!a.length) + return true; + let sharedChunks = findSharedChunks(a, b); + let sideA = new SpanCursor(a, sharedChunks, 0).goto(from), sideB = new SpanCursor(b, sharedChunks, 0).goto(from); + for (;;) { + if (sideA.to != sideB.to || + !sameValues(sideA.active, sideB.active) || + sideA.point && (!sideB.point || !sideA.point.eq(sideB.point))) + return false; + if (sideA.to > to) + return true; + sideA.next(); + sideB.next(); + } + } + /** + Iterate over a group of range sets at the same time, notifying + the iterator about the ranges covering every given piece of + content. Returns the open count (see + [`SpanIterator.span`](https://codemirror.net/6/docs/ref/#state.SpanIterator.span)) at the end + of the iteration. + */ + static spans(sets, from, to, iterator, + /** + When given and greater than -1, only points of at least this + size are taken into account. + */ + minPointSize = -1) { + let cursor = new SpanCursor(sets, null, minPointSize).goto(from), pos = from; + let open = cursor.openStart; + for (;;) { + let curTo = Math.min(cursor.to, to); + if (cursor.point) { + iterator.point(pos, curTo, cursor.point, cursor.activeForPoint(cursor.to), open, cursor.pointRank); + open = cursor.openEnd(curTo) + (cursor.to > curTo ? 1 : 0); + } + else if (curTo > pos) { + iterator.span(pos, curTo, cursor.active, open); + open = cursor.openEnd(curTo); + } + if (cursor.to > to) + break; + pos = cursor.to; + cursor.next(); + } + return open; + } + /** + Create a range set for the given range or array of ranges. By + default, this expects the ranges to be _sorted_ (by start + position and, if two start at the same position, + `value.startSide`). You can pass `true` as second argument to + cause the method to sort them. + */ + static of(ranges, sort = false) { + let build = new RangeSetBuilder(); + for (let range of ranges instanceof Range$1 ? [ranges] : sort ? lazySort(ranges) : ranges) + build.add(range.from, range.to, range.value); + return build.finish(); + } + } + /** + The empty set of ranges. + */ + RangeSet.empty = /*@__PURE__*/new RangeSet([], [], null, -1); + function lazySort(ranges) { + if (ranges.length > 1) + for (let prev = ranges[0], i = 1; i < ranges.length; i++) { + let cur = ranges[i]; + if (cmpRange(prev, cur) > 0) + return ranges.slice().sort(cmpRange); + prev = cur; + } + return ranges; + } + RangeSet.empty.nextLayer = RangeSet.empty; + /** + A range set builder is a data structure that helps build up a + [range set](https://codemirror.net/6/docs/ref/#state.RangeSet) directly, without first allocating + an array of [`Range`](https://codemirror.net/6/docs/ref/#state.Range) objects. + */ + class RangeSetBuilder { + /** + Create an empty builder. + */ + constructor() { + this.chunks = []; + this.chunkPos = []; + this.chunkStart = -1; + this.last = null; + this.lastFrom = -1000000000 /* C.Far */; + this.lastTo = -1000000000 /* C.Far */; + this.from = []; + this.to = []; + this.value = []; + this.maxPoint = -1; + this.setMaxPoint = -1; + this.nextLayer = null; + } + finishChunk(newArrays) { + this.chunks.push(new Chunk(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; + if (newArrays) { + this.from = []; + this.to = []; + this.value = []; + } + } + /** + Add a range. Ranges should be added in sorted (by `from` and + `value.startSide`) order. + */ + add(from, to, value) { + if (!this.addInner(from, to, value)) + (this.nextLayer || (this.nextLayer = new RangeSetBuilder)).add(from, to, value); + } + /** + @internal + */ + addInner(from, to, value) { + let diff = from - this.lastTo || value.startSide - this.last.endSide; + if (diff <= 0 && (from - this.lastFrom || value.startSide - this.last.startSide) < 0) + throw new Error("Ranges must be added sorted by `from` position and `startSide`"); + if (diff < 0) + return false; + if (this.from.length == 250 /* C.ChunkSize */) + this.finishChunk(true); + if (this.chunkStart < 0) + this.chunkStart = from; + this.from.push(from - this.chunkStart); + this.to.push(to - this.chunkStart); + this.last = value; + this.lastFrom = from; + this.lastTo = to; + this.value.push(value); + if (value.point) + this.maxPoint = Math.max(this.maxPoint, to - from); + return true; + } + /** + @internal + */ + addChunk(from, chunk) { + if ((from - this.lastTo || chunk.value[0].startSide - this.last.endSide) < 0) + return false; + if (this.from.length) + this.finishChunk(true); + this.setMaxPoint = Math.max(this.setMaxPoint, chunk.maxPoint); + this.chunks.push(chunk); + this.chunkPos.push(from); + let last = chunk.value.length - 1; + this.last = chunk.value[last]; + this.lastFrom = chunk.from[last] + from; + this.lastTo = chunk.to[last] + from; + return true; + } + /** + Finish the range set. Returns the new set. The builder can't be + used anymore after this has been called. + */ + finish() { return this.finishInner(RangeSet.empty); } + /** + @internal + */ + finishInner(next) { + if (this.from.length) + this.finishChunk(false); + if (this.chunks.length == 0) + return next; + let result = RangeSet.create(this.chunkPos, this.chunks, this.nextLayer ? this.nextLayer.finishInner(next) : next, this.setMaxPoint); + this.from = null; // Make sure further `add` calls produce errors + return result; + } + } + function findSharedChunks(a, b, textDiff) { + let inA = new Map(); + for (let set of a) + for (let i = 0; i < set.chunk.length; i++) + if (set.chunk[i].maxPoint <= 0) + inA.set(set.chunk[i], set.chunkPos[i]); + let shared = new Set(); + for (let set of b) + for (let i = 0; i < set.chunk.length; i++) { + let known = inA.get(set.chunk[i]); + if (known != null && (textDiff ? textDiff.mapPos(known) : known) == set.chunkPos[i] && + !(textDiff === null || textDiff === void 0 ? void 0 : textDiff.touchesRange(known, known + set.chunk[i].length))) + shared.add(set.chunk[i]); + } + return shared; + } + class LayerCursor { + constructor(layer, skip, minPoint, rank = 0) { + this.layer = layer; + this.skip = skip; + this.minPoint = minPoint; + this.rank = rank; + } + get startSide() { return this.value ? this.value.startSide : 0; } + get endSide() { return this.value ? this.value.endSide : 0; } + goto(pos, side = -1000000000 /* C.Far */) { + this.chunkIndex = this.rangeIndex = 0; + this.gotoInner(pos, side, false); + return this; + } + gotoInner(pos, side, forward) { + while (this.chunkIndex < this.layer.chunk.length) { + let next = this.layer.chunk[this.chunkIndex]; + if (!(this.skip && this.skip.has(next) || + this.layer.chunkEnd(this.chunkIndex) < pos || + next.maxPoint < this.minPoint)) + break; + this.chunkIndex++; + forward = false; + } + if (this.chunkIndex < this.layer.chunk.length) { + let rangeIndex = this.layer.chunk[this.chunkIndex].findIndex(pos - this.layer.chunkPos[this.chunkIndex], side, true); + if (!forward || this.rangeIndex < rangeIndex) + this.setRangeIndex(rangeIndex); + } + this.next(); + } + forward(pos, side) { + if ((this.to - pos || this.endSide - side) < 0) + this.gotoInner(pos, side, true); + } + next() { + for (;;) { + if (this.chunkIndex == this.layer.chunk.length) { + this.from = this.to = 1000000000 /* C.Far */; + this.value = null; + break; + } + else { + let chunkPos = this.layer.chunkPos[this.chunkIndex], chunk = this.layer.chunk[this.chunkIndex]; + let from = chunkPos + chunk.from[this.rangeIndex]; + this.from = from; + this.to = chunkPos + chunk.to[this.rangeIndex]; + this.value = chunk.value[this.rangeIndex]; + this.setRangeIndex(this.rangeIndex + 1); + if (this.minPoint < 0 || this.value.point && this.to - this.from >= this.minPoint) + break; + } + } + } + setRangeIndex(index) { + if (index == this.layer.chunk[this.chunkIndex].value.length) { + this.chunkIndex++; + if (this.skip) { + while (this.chunkIndex < this.layer.chunk.length && this.skip.has(this.layer.chunk[this.chunkIndex])) + this.chunkIndex++; + } + this.rangeIndex = 0; + } + else { + this.rangeIndex = index; + } + } + nextChunk() { + this.chunkIndex++; + this.rangeIndex = 0; + this.next(); + } + compare(other) { + return this.from - other.from || this.startSide - other.startSide || this.rank - other.rank || + this.to - other.to || this.endSide - other.endSide; + } + } + class HeapCursor { + constructor(heap) { + this.heap = heap; + } + static from(sets, skip = null, minPoint = -1) { + let heap = []; + for (let i = 0; i < sets.length; i++) { + for (let cur = sets[i]; !cur.isEmpty; cur = cur.nextLayer) { + if (cur.maxPoint >= minPoint) + heap.push(new LayerCursor(cur, skip, minPoint, i)); + } + } + return heap.length == 1 ? heap[0] : new HeapCursor(heap); + } + get startSide() { return this.value ? this.value.startSide : 0; } + goto(pos, side = -1000000000 /* C.Far */) { + for (let cur of this.heap) + cur.goto(pos, side); + for (let i = this.heap.length >> 1; i >= 0; i--) + heapBubble(this.heap, i); + this.next(); + return this; + } + forward(pos, side) { + for (let cur of this.heap) + cur.forward(pos, side); + for (let i = this.heap.length >> 1; i >= 0; i--) + heapBubble(this.heap, i); + if ((this.to - pos || this.value.endSide - side) < 0) + this.next(); + } + next() { + if (this.heap.length == 0) { + this.from = this.to = 1000000000 /* C.Far */; + this.value = null; + this.rank = -1; + } + else { + let top = this.heap[0]; + this.from = top.from; + this.to = top.to; + this.value = top.value; + this.rank = top.rank; + if (top.value) + top.next(); + heapBubble(this.heap, 0); + } + } + } + function heapBubble(heap, index) { + for (let cur = heap[index];;) { + let childIndex = (index << 1) + 1; + if (childIndex >= heap.length) + break; + let child = heap[childIndex]; + if (childIndex + 1 < heap.length && child.compare(heap[childIndex + 1]) >= 0) { + child = heap[childIndex + 1]; + childIndex++; + } + if (cur.compare(child) < 0) + break; + heap[childIndex] = cur; + heap[index] = child; + index = childIndex; + } + } + class SpanCursor { + constructor(sets, skip, minPoint) { + this.minPoint = minPoint; + this.active = []; + this.activeTo = []; + this.activeRank = []; + this.minActive = -1; + // A currently active point range, if any + this.point = null; + this.pointFrom = 0; + this.pointRank = 0; + this.to = -1000000000 /* C.Far */; + this.endSide = 0; + this.openStart = -1; + this.cursor = HeapCursor.from(sets, skip, minPoint); + } + goto(pos, side = -1000000000 /* C.Far */) { + this.cursor.goto(pos, side); + this.active.length = this.activeTo.length = this.activeRank.length = 0; + this.minActive = -1; + this.to = pos; + this.endSide = side; + this.openStart = -1; + this.next(); + return this; + } + forward(pos, side) { + while (this.minActive > -1 && (this.activeTo[this.minActive] - pos || this.active[this.minActive].endSide - side) < 0) + this.removeActive(this.minActive); + this.cursor.forward(pos, side); + } + removeActive(index) { + remove(this.active, index); + remove(this.activeTo, index); + remove(this.activeRank, index); + this.minActive = findMinIndex(this.active, this.activeTo); + } + addActive(trackOpen) { + let i = 0, { value, to, rank } = this.cursor; + while (i < this.activeRank.length && this.activeRank[i] <= rank) + i++; + insert(this.active, i, value); + insert(this.activeTo, i, to); + insert(this.activeRank, i, rank); + if (trackOpen) + insert(trackOpen, i, this.cursor.from); + this.minActive = findMinIndex(this.active, this.activeTo); + } + // After calling this, if `this.point` != null, the next range is a + // point. Otherwise, it's a regular range, covered by `this.active`. + next() { + let from = this.to, wasPoint = this.point; + this.point = null; + let trackOpen = this.openStart < 0 ? [] : null, trackExtra = 0; + for (;;) { + let a = this.minActive; + if (a > -1 && (this.activeTo[a] - this.cursor.from || this.active[a].endSide - this.cursor.startSide) < 0) { + if (this.activeTo[a] > from) { + this.to = this.activeTo[a]; + this.endSide = this.active[a].endSide; + break; + } + this.removeActive(a); + if (trackOpen) + remove(trackOpen, a); + } + else if (!this.cursor.value) { + this.to = this.endSide = 1000000000 /* C.Far */; + break; + } + else if (this.cursor.from > from) { + this.to = this.cursor.from; + this.endSide = this.cursor.startSide; + break; + } + else { + let nextVal = this.cursor.value; + if (!nextVal.point) { // Opening a range + this.addActive(trackOpen); + if (this.cursor.from < from && this.cursor.to > from) + trackExtra++; + this.cursor.next(); + } + else if (wasPoint && this.cursor.to == this.to && this.cursor.from < this.cursor.to) { + // Ignore any non-empty points that end precisely at the end of the prev point + this.cursor.next(); + } + else { // New point + this.point = nextVal; + this.pointFrom = this.cursor.from; + this.pointRank = this.cursor.rank; + this.to = this.cursor.to; + this.endSide = nextVal.endSide; + if (this.cursor.from < from) + trackExtra = 1; + this.cursor.next(); + this.forward(this.to, this.endSide); + break; + } + } + } + if (trackOpen) { + let openStart = 0; + while (openStart < trackOpen.length && trackOpen[openStart] < from) + openStart++; + this.openStart = openStart + trackExtra; + } + } + activeForPoint(to) { + if (!this.active.length) + return this.active; + let active = []; + for (let i = this.active.length - 1; i >= 0; i--) { + if (this.activeRank[i] < this.pointRank) + break; + if (this.activeTo[i] > to || this.activeTo[i] == to && this.active[i].endSide >= this.point.endSide) + active.push(this.active[i]); + } + return active.reverse(); + } + openEnd(to) { + let open = 0; + for (let i = this.activeTo.length - 1; i >= 0 && this.activeTo[i] > to; i--) + open++; + return open; + } + } + function compare(a, startA, b, startB, length, comparator) { + a.goto(startA); + b.goto(startB); + let endB = startB + length; + let pos = startB, dPos = startB - startA; + for (;;) { + let diff = (a.to + dPos) - b.to || a.endSide - b.endSide; + let end = diff < 0 ? a.to + dPos : b.to, clipEnd = Math.min(end, endB); + if (a.point || b.point) { + if (!(a.point && b.point && (a.point == b.point || a.point.eq(b.point)) && + sameValues(a.activeForPoint(a.to + dPos), b.activeForPoint(b.to)))) + comparator.comparePoint(pos, clipEnd, a.point, b.point); + } + else { + if (clipEnd > pos && !sameValues(a.active, b.active)) + comparator.compareRange(pos, clipEnd, a.active, b.active); + } + if (end > endB) + break; + pos = end; + if (diff <= 0) + a.next(); + if (diff >= 0) + b.next(); + } + } + function sameValues(a, b) { + if (a.length != b.length) + return false; + for (let i = 0; i < a.length; i++) + if (a[i] != b[i] && !a[i].eq(b[i])) + return false; + return true; + } + function remove(array, index) { + for (let i = index, e = array.length - 1; i < e; i++) + array[i] = array[i + 1]; + array.pop(); + } + function insert(array, index, value) { + for (let i = array.length - 1; i >= index; i--) + array[i + 1] = array[i]; + array[index] = value; + } + function findMinIndex(value, array) { + let found = -1, foundPos = 1000000000 /* C.Far */; + for (let i = 0; i < array.length; i++) + if ((array[i] - foundPos || value[i].endSide - value[found].endSide) < 0) { + found = i; + foundPos = array[i]; + } + return found; + } + + /** + Count the column position at the given offset into the string, + taking extending characters and tab size into account. + */ + function countColumn(string, tabSize, to = string.length) { + let n = 0; + for (let i = 0; i < to;) { + if (string.charCodeAt(i) == 9) { + n += tabSize - (n % tabSize); + i++; + } + else { + n++; + i = findClusterBreak(string, i); + } + } + return n; + } + /** + Find the offset that corresponds to the given column position in a + string, taking extending characters and tab size into account. By + default, the string length is returned when it is too short to + reach the column. Pass `strict` true to make it return -1 in that + situation. + */ + function findColumn(string, col, tabSize, strict) { + for (let i = 0, n = 0;;) { + if (n >= col) + return i; + if (i == string.length) + break; + n += string.charCodeAt(i) == 9 ? tabSize - (n % tabSize) : 1; + i = findClusterBreak(string, i); + } + return strict === true ? -1 : string.length; + } + + const C = "\u037c"; + const COUNT = typeof Symbol == "undefined" ? "__" + C : Symbol.for(C); + const SET = typeof Symbol == "undefined" ? "__styleSet" + Math.floor(Math.random() * 1e8) : Symbol("styleSet"); + const top = typeof globalThis != "undefined" ? globalThis : typeof window != "undefined" ? window : {}; + + // :: - Style modules encapsulate a set of CSS rules defined from + // JavaScript. Their definitions are only available in a given DOM + // root after it has been _mounted_ there with `StyleModule.mount`. + // + // Style modules should be created once and stored somewhere, as + // opposed to re-creating them every time you need them. The amount of + // CSS rules generated for a given DOM root is bounded by the amount + // of style modules that were used. So to avoid leaking rules, don't + // create these dynamically, but treat them as one-time allocations. + class StyleModule { + // :: (Object<Style>, ?{finish: ?(string) → string}) + // Create a style module from the given spec. + // + // When `finish` is given, it is called on regular (non-`@`) + // selectors (after `&` expansion) to compute the final selector. + constructor(spec, options) { + this.rules = []; + let {finish} = options || {}; + + function splitSelector(selector) { + return /^@/.test(selector) ? [selector] : selector.split(/,\s*/) + } + + function render(selectors, spec, target, isKeyframes) { + let local = [], isAt = /^@(\w+)\b/.exec(selectors[0]), keyframes = isAt && isAt[1] == "keyframes"; + if (isAt && spec == null) return target.push(selectors[0] + ";") + for (let prop in spec) { + let value = spec[prop]; + if (/&/.test(prop)) { + render(prop.split(/,\s*/).map(part => selectors.map(sel => part.replace(/&/, sel))).reduce((a, b) => a.concat(b)), + value, target); + } else if (value && typeof value == "object") { + if (!isAt) throw new RangeError("The value of a property (" + prop + ") should be a primitive value.") + render(splitSelector(prop), value, local, keyframes); + } else if (value != null) { + local.push(prop.replace(/_.*/, "").replace(/[A-Z]/g, l => "-" + l.toLowerCase()) + ": " + value + ";"); } } - - if (!type) { - throwError(state, 'unknown tag !<' + state.tag + '>'); - } - - if (state.result !== null && type.kind !== state.kind) { - throwError(state, 'unacceptable node kind for !<' + state.tag + '> tag; it should be "' + type.kind + '", not "' + state.kind + '"'); - } - - if (!type.resolve(state.result, state.tag)) { // `state.result` updated in resolver if matched - throwError(state, 'cannot resolve a node with !<' + state.tag + '> explicit tag'); - } else { - state.result = type.construct(state.result, state.tag); - if (state.anchor !== null) { - state.anchorMap[state.anchor] = state.result; - } + if (local.length || keyframes) { + target.push((finish && !isAt && !isKeyframes ? selectors.map(finish) : selectors).join(", ") + + " {" + local.join(" ") + "}"); } } - if (state.listener !== null) { - state.listener('close', state); - } - return state.tag !== null || state.anchor !== null || hasContent; + for (let prop in spec) render(splitSelector(prop), spec[prop], this.rules); } - function readDocument(state) { - var documentStart = state.position, - _position, - directiveName, - directiveArgs, - hasDirectives = false, - ch; + // :: () → string + // Returns a string containing the module's CSS rules. + getRules() { return this.rules.join("\n") } - state.version = null; - state.checkLineBreaks = state.legacy; - state.tagMap = Object.create(null); - state.anchorMap = Object.create(null); + // :: () → string + // Generate a new unique CSS class name. + static newName() { + let id = top[COUNT] || 1; + top[COUNT] = id + 1; + return C + id.toString(36) + } - while ((ch = state.input.charCodeAt(state.position)) !== 0) { - skipSeparationSpace(state, true, -1); + // :: (union<Document, ShadowRoot>, union<[StyleModule], StyleModule>) + // + // Mount the given set of modules in the given DOM root, which ensures + // that the CSS rules defined by the module are available in that + // context. + // + // Rules are only added to the document once per root. + // + // Rule order will follow the order of the modules, so that rules from + // modules later in the array take precedence of those from earlier + // modules. If you call this function multiple times for the same root + // in a way that changes the order of already mounted modules, the old + // order will be changed. + static mount(root, modules) { + (root[SET] || new StyleSet(root)).mount(Array.isArray(modules) ? modules : [modules]); + } + } - ch = state.input.charCodeAt(state.position); + let adoptedSet = null; - if (state.lineIndent > 0 || ch !== 0x25/* % */) { - break; + class StyleSet { + constructor(root) { + if (!root.head && root.adoptedStyleSheets && typeof CSSStyleSheet != "undefined") { + if (adoptedSet) { + root.adoptedStyleSheets = [adoptedSet.sheet].concat(root.adoptedStyleSheets); + return root[SET] = adoptedSet } - - hasDirectives = true; - ch = state.input.charCodeAt(++state.position); - _position = state.position; - - while (ch !== 0 && !is_WS_OR_EOL(ch)) { - ch = state.input.charCodeAt(++state.position); - } - - directiveName = state.input.slice(_position, state.position); - directiveArgs = []; - - if (directiveName.length < 1) { - throwError(state, 'directive name must not be less than one character in length'); - } - - while (ch !== 0) { - while (is_WHITE_SPACE(ch)) { - ch = state.input.charCodeAt(++state.position); - } - - if (ch === 0x23/* # */) { - do { ch = state.input.charCodeAt(++state.position); } - while (ch !== 0 && !is_EOL(ch)); - break; - } - - if (is_EOL(ch)) break; - - _position = state.position; - - while (ch !== 0 && !is_WS_OR_EOL(ch)) { - ch = state.input.charCodeAt(++state.position); - } - - directiveArgs.push(state.input.slice(_position, state.position)); - } - - if (ch !== 0) readLineBreak(state); - - if (_hasOwnProperty$1.call(directiveHandlers, directiveName)) { - directiveHandlers[directiveName](state, directiveName, directiveArgs); - } else { - throwWarning(state, 'unknown document directive "' + directiveName + '"'); - } - } - - skipSeparationSpace(state, true, -1); - - if (state.lineIndent === 0 && - state.input.charCodeAt(state.position) === 0x2D/* - */ && - state.input.charCodeAt(state.position + 1) === 0x2D/* - */ && - state.input.charCodeAt(state.position + 2) === 0x2D/* - */) { - state.position += 3; - skipSeparationSpace(state, true, -1); - - } else if (hasDirectives) { - throwError(state, 'directives end mark is expected'); - } - - composeNode(state, state.lineIndent - 1, CONTEXT_BLOCK_OUT, false, true); - skipSeparationSpace(state, true, -1); - - if (state.checkLineBreaks && - PATTERN_NON_ASCII_LINE_BREAKS.test(state.input.slice(documentStart, state.position))) { - throwWarning(state, 'non-ASCII line breaks are interpreted as content'); - } - - state.documents.push(state.result); - - if (state.position === state.lineStart && testDocumentSeparator(state)) { - - if (state.input.charCodeAt(state.position) === 0x2E/* . */) { - state.position += 3; - skipSeparationSpace(state, true, -1); - } - return; - } - - if (state.position < (state.length - 1)) { - throwError(state, 'end of the stream or a document separator is expected'); + this.sheet = new CSSStyleSheet; + root.adoptedStyleSheets = [this.sheet].concat(root.adoptedStyleSheets); + adoptedSet = this; } else { - return; + this.styleTag = (root.ownerDocument || root).createElement("style"); + let target = root.head || root; + target.insertBefore(this.styleTag, target.firstChild); } + this.modules = []; + root[SET] = this; } - - function loadDocuments(input, options) { - input = String(input); - options = options || {}; - - if (input.length !== 0) { - - // Add tailing `\n` if not exists - if (input.charCodeAt(input.length - 1) !== 0x0A/* LF */ && - input.charCodeAt(input.length - 1) !== 0x0D/* CR */) { - input += '\n'; + mount(modules) { + let sheet = this.sheet; + let pos = 0 /* Current rule offset */, j = 0; /* Index into this.modules */ + for (let i = 0; i < modules.length; i++) { + let mod = modules[i], index = this.modules.indexOf(mod); + if (index < j && index > -1) { // Ordering conflict + this.modules.splice(index, 1); + j--; + index = -1; } - - // Strip BOM - if (input.charCodeAt(0) === 0xFEFF) { - input = input.slice(1); + if (index == -1) { + this.modules.splice(j++, 0, mod); + if (sheet) for (let k = 0; k < mod.rules.length; k++) + sheet.insertRule(mod.rules[k], pos++); + } else { + while (j < index) pos += this.modules[j++].rules.length; + pos += mod.rules.length; + j++; } } - var state = new State$1(input, options); - - var nullpos = input.indexOf('\0'); - - if (nullpos !== -1) { - state.position = nullpos; - throwError(state, 'null byte is not allowed in input'); - } - - // Use 0 as string terminator. That significantly simplifies bounds check. - state.input += '\0'; - - while (state.input.charCodeAt(state.position) === 0x20/* Space */) { - state.lineIndent += 1; - state.position += 1; - } - - while (state.position < (state.length - 1)) { - readDocument(state); - } - - return state.documents; - } - - - function loadAll$1(input, iterator, options) { - if (iterator !== null && typeof iterator === 'object' && typeof options === 'undefined') { - options = iterator; - iterator = null; - } - - var documents = loadDocuments(input, options); - - if (typeof iterator !== 'function') { - return documents; - } - - for (var index = 0, length = documents.length; index < length; index += 1) { - iterator(documents[index]); + if (!sheet) { + let text = ""; + for (let i = 0; i < this.modules.length; i++) + text += this.modules[i].getRules() + "\n"; + this.styleTag.textContent = text; } } + } + // Style::Object<union<Style,string>> + // + // A style is an object that, in the simple case, maps CSS property + // names to strings holding their values, as in `{color: "red", + // fontWeight: "bold"}`. The property names can be given in + // camel-case—the library will insert a dash before capital letters + // when converting them to CSS. + // + // If you include an underscore in a property name, it and everything + // after it will be removed from the output, which can be useful when + // providing a property multiple times, for browser compatibility + // reasons. + // + // A property in a style object can also be a sub-selector, which + // extends the current context to add a pseudo-selector or a child + // selector. Such a property should contain a `&` character, which + // will be replaced by the current selector. For example `{"&:before": + // {content: '"hi"'}}`. Sub-selectors and regular properties can + // freely be mixed in a given object. Any property containing a `&` is + // assumed to be a sub-selector. + // + // Finally, a property can specify an @-block to be wrapped around the + // styles defined inside the object that's the property's value. For + // example to create a media query you can do `{"@media screen and + // (min-width: 400px)": {...}}`. - function load$1(input, options) { - var documents = loadDocuments(input, options); + var base = { + 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: "'" + }; - if (documents.length === 0) { - /*eslint-disable no-undefined*/ - return undefined; - } else if (documents.length === 1) { - return documents[0]; + var shift = { + 48: ")", + 49: "!", + 50: "@", + 51: "#", + 52: "$", + 53: "%", + 54: "^", + 55: "&", + 56: "*", + 57: "(", + 59: ":", + 61: "+", + 173: "_", + 186: ":", + 187: "+", + 188: "<", + 189: "_", + 190: ">", + 191: "?", + 192: "~", + 219: "{", + 220: "|", + 221: "}", + 222: "\"" + }; + + var chrome$1 = typeof navigator != "undefined" && /Chrome\/(\d+)/.exec(navigator.userAgent); + typeof navigator != "undefined" && /Gecko\/\d+/.test(navigator.userAgent); + var mac = typeof navigator != "undefined" && /Mac/.test(navigator.platform); + var ie$1 = typeof navigator != "undefined" && /MSIE \d|Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(navigator.userAgent); + var brokenModifierNames = mac || chrome$1 && +chrome$1[1] < 57; + + // Fill in the digit keys + for (var i = 0; i < 10; i++) base[48 + i] = base[96 + i] = String(i); + + // The function keys + for (var i = 1; i <= 24; i++) base[i + 111] = "F" + i; + + // And the alphabetic keys + for (var i = 65; i <= 90; i++) { + base[i] = String.fromCharCode(i + 32); + shift[i] = String.fromCharCode(i); + } + + // For each code that doesn't have a shift-equivalent, copy the base name + for (var code in base) if (!shift.hasOwnProperty(code)) shift[code] = base[code]; + + function keyName(event) { + var ignoreKey = brokenModifierNames && (event.ctrlKey || event.altKey || event.metaKey) || + ie$1 && event.shiftKey && event.key && event.key.length == 1 || + event.key == "Unidentified"; + var name = (!ignoreKey && event.key) || + (event.shiftKey ? shift : base)[event.keyCode] || + event.key || "Unidentified"; + // Edge sometimes produces wrong names (Issue #3) + if (name == "Esc") name = "Escape"; + if (name == "Del") name = "Delete"; + // https://developer.microsoft.com/en-us/microsoft-edge/platform/issues/8860571/ + if (name == "Left") name = "ArrowLeft"; + if (name == "Up") name = "ArrowUp"; + if (name == "Right") name = "ArrowRight"; + if (name == "Down") name = "ArrowDown"; + return name + } + + function getSelection(root) { + let target; + // Browsers differ on whether shadow roots have a getSelection + // method. If it exists, use that, otherwise, call it on the + // document. + if (root.nodeType == 11) { // Shadow root + target = root.getSelection ? root : root.ownerDocument; } - throw new exception('expected a single document in the stream, but found more'); + else { + target = root; + } + return target.getSelection(); + } + function contains(dom, node) { + return node ? dom == node || dom.contains(node.nodeType != 1 ? node.parentNode : node) : false; + } + function deepActiveElement(doc) { + let elt = doc.activeElement; + while (elt && elt.shadowRoot) + elt = elt.shadowRoot.activeElement; + return elt; + } + function hasSelection(dom, selection) { + if (!selection.anchorNode) + return false; + try { + // Firefox will raise 'permission denied' errors when accessing + // properties of `sel.anchorNode` when it's in a generated CSS + // element. + return contains(dom, selection.anchorNode); + } + catch (_) { + return false; + } + } + function clientRectsFor(dom) { + if (dom.nodeType == 3) + return textRange(dom, 0, dom.nodeValue.length).getClientRects(); + else if (dom.nodeType == 1) + return dom.getClientRects(); + else + return []; + } + // Scans forward and backward through DOM positions equivalent to the + // given one to see if the two are in the same place (i.e. after a + // text node vs at the end of that text node) + function isEquivalentPosition(node, off, targetNode, targetOff) { + return targetNode ? (scanFor(node, off, targetNode, targetOff, -1) || + scanFor(node, off, targetNode, targetOff, 1)) : false; + } + function domIndex(node) { + for (var index = 0;; index++) { + node = node.previousSibling; + if (!node) + return index; + } + } + function scanFor(node, off, targetNode, targetOff, dir) { + for (;;) { + if (node == targetNode && off == targetOff) + return true; + if (off == (dir < 0 ? 0 : maxOffset(node))) { + if (node.nodeName == "DIV") + return false; + let parent = node.parentNode; + if (!parent || parent.nodeType != 1) + return false; + off = domIndex(node) + (dir < 0 ? 0 : 1); + node = parent; + } + else if (node.nodeType == 1) { + node = node.childNodes[off + (dir < 0 ? -1 : 0)]; + if (node.nodeType == 1 && node.contentEditable == "false") + return false; + off = dir < 0 ? maxOffset(node) : 0; + } + else { + return false; + } + } + } + function maxOffset(node) { + return node.nodeType == 3 ? node.nodeValue.length : node.childNodes.length; + } + const Rect0 = { left: 0, right: 0, top: 0, bottom: 0 }; + function flattenRect(rect, left) { + let x = left ? rect.left : rect.right; + return { left: x, right: x, top: rect.top, bottom: rect.bottom }; + } + function windowRect(win) { + return { left: 0, right: win.innerWidth, + top: 0, bottom: win.innerHeight }; + } + function scrollRectIntoView(dom, rect, side, x, y, xMargin, yMargin, ltr) { + let doc = dom.ownerDocument, win = doc.defaultView || window; + for (let cur = dom; cur;) { + if (cur.nodeType == 1) { // Element + let bounding, top = cur == doc.body; + if (top) { + bounding = windowRect(win); + } + else { + if (cur.scrollHeight <= cur.clientHeight && cur.scrollWidth <= cur.clientWidth) { + cur = cur.assignedSlot || cur.parentNode; + continue; + } + let rect = cur.getBoundingClientRect(); + // Make sure scrollbar width isn't included in the rectangle + bounding = { left: rect.left, right: rect.left + cur.clientWidth, + top: rect.top, bottom: rect.top + cur.clientHeight }; + } + let moveX = 0, moveY = 0; + if (y == "nearest") { + if (rect.top < bounding.top) { + moveY = -(bounding.top - rect.top + yMargin); + if (side > 0 && rect.bottom > bounding.bottom + moveY) + moveY = rect.bottom - bounding.bottom + moveY + yMargin; + } + else if (rect.bottom > bounding.bottom) { + moveY = rect.bottom - bounding.bottom + yMargin; + if (side < 0 && (rect.top - moveY) < bounding.top) + moveY = -(bounding.top + moveY - rect.top + yMargin); + } + } + else { + let rectHeight = rect.bottom - rect.top, boundingHeight = bounding.bottom - bounding.top; + let targetTop = y == "center" && rectHeight <= boundingHeight ? rect.top + rectHeight / 2 - boundingHeight / 2 : + y == "start" || y == "center" && side < 0 ? rect.top - yMargin : + rect.bottom - boundingHeight + yMargin; + moveY = targetTop - bounding.top; + } + if (x == "nearest") { + if (rect.left < bounding.left) { + moveX = -(bounding.left - rect.left + xMargin); + if (side > 0 && rect.right > bounding.right + moveX) + moveX = rect.right - bounding.right + moveX + xMargin; + } + else if (rect.right > bounding.right) { + moveX = rect.right - bounding.right + xMargin; + if (side < 0 && rect.left < bounding.left + moveX) + moveX = -(bounding.left + moveX - rect.left + xMargin); + } + } + else { + let targetLeft = x == "center" ? rect.left + (rect.right - rect.left) / 2 - (bounding.right - bounding.left) / 2 : + (x == "start") == ltr ? rect.left - xMargin : + rect.right - (bounding.right - bounding.left) + xMargin; + moveX = targetLeft - bounding.left; + } + if (moveX || moveY) { + if (top) { + win.scrollBy(moveX, moveY); + } + else { + let movedX = 0, movedY = 0; + if (moveY) { + let start = cur.scrollTop; + cur.scrollTop += moveY; + movedY = cur.scrollTop - start; + } + if (moveX) { + let start = cur.scrollLeft; + cur.scrollLeft += moveX; + movedX = cur.scrollLeft - start; + } + rect = { left: rect.left - movedX, top: rect.top - movedY, + right: rect.right - movedX, bottom: rect.bottom - movedY }; + if (movedX && Math.abs(movedX - moveX) < 1) + x = "nearest"; + if (movedY && Math.abs(movedY - moveY) < 1) + y = "nearest"; + } + } + if (top) + break; + cur = cur.assignedSlot || cur.parentNode; + } + else if (cur.nodeType == 11) { // A shadow root + cur = cur.host; + } + else { + break; + } + } + } + class DOMSelectionState { + constructor() { + this.anchorNode = null; + this.anchorOffset = 0; + this.focusNode = null; + this.focusOffset = 0; + } + eq(domSel) { + return this.anchorNode == domSel.anchorNode && this.anchorOffset == domSel.anchorOffset && + this.focusNode == domSel.focusNode && this.focusOffset == domSel.focusOffset; + } + setRange(range) { + this.set(range.anchorNode, range.anchorOffset, range.focusNode, range.focusOffset); + } + set(anchorNode, anchorOffset, focusNode, focusOffset) { + this.anchorNode = anchorNode; + this.anchorOffset = anchorOffset; + this.focusNode = focusNode; + this.focusOffset = focusOffset; + } + } + let preventScrollSupported = null; + // Feature-detects support for .focus({preventScroll: true}), and uses + // a fallback kludge when not supported. + function focusPreventScroll(dom) { + if (dom.setActive) + return dom.setActive(); // in IE + if (preventScrollSupported) + return dom.focus(preventScrollSupported); + let stack = []; + for (let cur = dom; cur; cur = cur.parentNode) { + stack.push(cur, cur.scrollTop, cur.scrollLeft); + if (cur == cur.ownerDocument) + break; + } + dom.focus(preventScrollSupported == null ? { + get preventScroll() { + preventScrollSupported = { preventScroll: true }; + return true; + } + } : undefined); + if (!preventScrollSupported) { + preventScrollSupported = false; + for (let i = 0; i < stack.length;) { + let elt = stack[i++], top = stack[i++], left = stack[i++]; + if (elt.scrollTop != top) + elt.scrollTop = top; + if (elt.scrollLeft != left) + elt.scrollLeft = left; + } + } + } + let scratchRange; + function textRange(node, from, to = from) { + let range = scratchRange || (scratchRange = document.createRange()); + range.setEnd(node, to); + range.setStart(node, from); + return range; + } + function dispatchKey(elt, name, code) { + let options = { key: name, code: name, keyCode: code, which: code, cancelable: true }; + let down = new KeyboardEvent("keydown", options); + down.synthetic = true; + elt.dispatchEvent(down); + let up = new KeyboardEvent("keyup", options); + up.synthetic = true; + elt.dispatchEvent(up); + return down.defaultPrevented || up.defaultPrevented; + } + function getRoot(node) { + while (node) { + if (node && (node.nodeType == 9 || node.nodeType == 11 && node.host)) + return node; + node = node.assignedSlot || node.parentNode; + } + return null; + } + function clearAttributes(node) { + while (node.attributes.length) + node.removeAttributeNode(node.attributes[0]); + } + function atElementStart(doc, selection) { + let node = selection.focusNode, offset = selection.focusOffset; + if (!node || selection.anchorNode != node || selection.anchorOffset != offset) + return false; + for (;;) { + if (offset) { + if (node.nodeType != 1) + return false; + let prev = node.childNodes[offset - 1]; + if (prev.contentEditable == "false") + offset--; + else { + node = prev; + offset = maxOffset(node); + } + } + else if (node == doc) { + return true; + } + else { + offset = domIndex(node); + node = node.parentNode; + } + } + } + + class DOMPos { + constructor(node, offset, precise = true) { + this.node = node; + this.offset = offset; + this.precise = precise; + } + static before(dom, precise) { return new DOMPos(dom.parentNode, domIndex(dom), precise); } + static after(dom, precise) { return new DOMPos(dom.parentNode, domIndex(dom) + 1, precise); } + } + const noChildren = []; + class ContentView { + constructor() { + this.parent = null; + this.dom = null; + this.dirty = 2 /* Dirty.Node */; + } + get editorView() { + if (!this.parent) + throw new Error("Accessing view in orphan content view"); + return this.parent.editorView; + } + get overrideDOMText() { return null; } + get posAtStart() { + return this.parent ? this.parent.posBefore(this) : 0; + } + get posAtEnd() { + return this.posAtStart + this.length; + } + posBefore(view) { + let pos = this.posAtStart; + for (let child of this.children) { + if (child == view) + return pos; + pos += child.length + child.breakAfter; + } + throw new RangeError("Invalid child in posBefore"); + } + posAfter(view) { + return this.posBefore(view) + view.length; + } + // Will return a rectangle directly before (when side < 0), after + // (side > 0) or directly on (when the browser supports it) the + // given position. + coordsAt(_pos, _side) { return null; } + sync(track) { + if (this.dirty & 2 /* Dirty.Node */) { + let parent = this.dom; + let prev = null, next; + for (let child of this.children) { + if (child.dirty) { + if (!child.dom && (next = prev ? prev.nextSibling : parent.firstChild)) { + let contentView = ContentView.get(next); + if (!contentView || !contentView.parent && contentView.canReuseDOM(child)) + child.reuseDOM(next); + } + child.sync(track); + child.dirty = 0 /* Dirty.Not */; + } + next = prev ? prev.nextSibling : parent.firstChild; + if (track && !track.written && track.node == parent && next != child.dom) + track.written = true; + if (child.dom.parentNode == parent) { + while (next && next != child.dom) + next = rm$1(next); + } + else { + parent.insertBefore(child.dom, next); + } + prev = child.dom; + } + next = prev ? prev.nextSibling : parent.firstChild; + if (next && track && track.node == parent) + track.written = true; + while (next) + next = rm$1(next); + } + else if (this.dirty & 1 /* Dirty.Child */) { + for (let child of this.children) + if (child.dirty) { + child.sync(track); + child.dirty = 0 /* Dirty.Not */; + } + } + } + reuseDOM(_dom) { } + localPosFromDOM(node, offset) { + let after; + if (node == this.dom) { + after = this.dom.childNodes[offset]; + } + else { + let bias = maxOffset(node) == 0 ? 0 : offset == 0 ? -1 : 1; + for (;;) { + let parent = node.parentNode; + if (parent == this.dom) + break; + if (bias == 0 && parent.firstChild != parent.lastChild) { + if (node == parent.firstChild) + bias = -1; + else + bias = 1; + } + node = parent; + } + if (bias < 0) + after = node; + else + after = node.nextSibling; + } + if (after == this.dom.firstChild) + return 0; + while (after && !ContentView.get(after)) + after = after.nextSibling; + if (!after) + return this.length; + for (let i = 0, pos = 0;; i++) { + let child = this.children[i]; + if (child.dom == after) + return pos; + pos += child.length + child.breakAfter; + } + } + domBoundsAround(from, to, offset = 0) { + let fromI = -1, fromStart = -1, toI = -1, toEnd = -1; + for (let i = 0, pos = offset, prevEnd = offset; i < this.children.length; i++) { + let child = this.children[i], end = pos + child.length; + if (pos < from && end > to) + return child.domBoundsAround(from, to, pos); + if (end >= from && fromI == -1) { + fromI = i; + fromStart = pos; + } + if (pos > to && child.dom.parentNode == this.dom) { + toI = i; + toEnd = prevEnd; + break; + } + prevEnd = end; + pos = end + child.breakAfter; + } + return { from: fromStart, to: toEnd < 0 ? offset + this.length : toEnd, + startDOM: (fromI ? this.children[fromI - 1].dom.nextSibling : null) || this.dom.firstChild, + endDOM: toI < this.children.length && toI >= 0 ? this.children[toI].dom : null }; + } + markDirty(andParent = false) { + this.dirty |= 2 /* Dirty.Node */; + this.markParentsDirty(andParent); + } + markParentsDirty(childList) { + for (let parent = this.parent; parent; parent = parent.parent) { + if (childList) + parent.dirty |= 2 /* Dirty.Node */; + if (parent.dirty & 1 /* Dirty.Child */) + return; + parent.dirty |= 1 /* Dirty.Child */; + childList = false; + } + } + setParent(parent) { + if (this.parent != parent) { + this.parent = parent; + if (this.dirty) + this.markParentsDirty(true); + } + } + setDOM(dom) { + if (this.dom) + this.dom.cmView = null; + this.dom = dom; + dom.cmView = this; + } + get rootView() { + for (let v = this;;) { + let parent = v.parent; + if (!parent) + return v; + v = parent; + } + } + replaceChildren(from, to, children = noChildren) { + this.markDirty(); + for (let i = from; i < to; i++) { + let child = this.children[i]; + if (child.parent == this) + child.destroy(); + } + this.children.splice(from, to - from, ...children); + for (let i = 0; i < children.length; i++) + children[i].setParent(this); + } + ignoreMutation(_rec) { return false; } + ignoreEvent(_event) { return false; } + childCursor(pos = this.length) { + return new ChildCursor(this.children, pos, this.children.length); + } + childPos(pos, bias = 1) { + return this.childCursor().findPos(pos, bias); + } + toString() { + let name = this.constructor.name.replace("View", ""); + return name + (this.children.length ? "(" + this.children.join() + ")" : + this.length ? "[" + (name == "Text" ? this.text : this.length) + "]" : "") + + (this.breakAfter ? "#" : ""); + } + static get(node) { return node.cmView; } + get isEditable() { return true; } + merge(from, to, source, hasStart, openStart, openEnd) { + return false; + } + become(other) { return false; } + canReuseDOM(other) { return other.constructor == this.constructor; } + // When this is a zero-length view with a side, this should return a + // number <= 0 to indicate it is before its position, or a + // number > 0 when after its position. + getSide() { return 0; } + destroy() { + this.parent = null; + } + } + ContentView.prototype.breakAfter = 0; + // Remove a DOM node and return its next sibling. + function rm$1(dom) { + let next = dom.nextSibling; + dom.parentNode.removeChild(dom); + return next; + } + class ChildCursor { + constructor(children, pos, i) { + this.children = children; + this.pos = pos; + this.i = i; + this.off = 0; + } + findPos(pos, bias = 1) { + for (;;) { + if (pos > this.pos || pos == this.pos && + (bias > 0 || this.i == 0 || this.children[this.i - 1].breakAfter)) { + this.off = pos - this.pos; + return this; + } + let next = this.children[--this.i]; + this.pos -= next.length + next.breakAfter; + } + } + } + function replaceRange(parent, fromI, fromOff, toI, toOff, insert, breakAtStart, openStart, openEnd) { + let { children } = parent; + let before = children.length ? children[fromI] : null; + let last = insert.length ? insert[insert.length - 1] : null; + let breakAtEnd = last ? last.breakAfter : breakAtStart; + // Change within a single child + if (fromI == toI && before && !breakAtStart && !breakAtEnd && insert.length < 2 && + before.merge(fromOff, toOff, insert.length ? last : null, fromOff == 0, openStart, openEnd)) + return; + if (toI < children.length) { + let after = children[toI]; + // Make sure the end of the child after the update is preserved in `after` + if (after && toOff < after.length) { + // If we're splitting a child, separate part of it to avoid that + // being mangled when updating the child before the update. + if (fromI == toI) { + after = after.split(toOff); + toOff = 0; + } + // If the element after the replacement should be merged with + // the last replacing element, update `content` + if (!breakAtEnd && last && after.merge(0, toOff, last, true, 0, openEnd)) { + insert[insert.length - 1] = after; + } + else { + // Remove the start of the after element, if necessary, and + // add it to `content`. + if (toOff) + after.merge(0, toOff, null, false, 0, openEnd); + insert.push(after); + } + } + else if (after === null || after === void 0 ? void 0 : after.breakAfter) { + // The element at `toI` is entirely covered by this range. + // Preserve its line break, if any. + if (last) + last.breakAfter = 1; + else + breakAtStart = 1; + } + // Since we've handled the next element from the current elements + // now, make sure `toI` points after that. + toI++; + } + if (before) { + before.breakAfter = breakAtStart; + if (fromOff > 0) { + if (!breakAtStart && insert.length && before.merge(fromOff, before.length, insert[0], false, openStart, 0)) { + before.breakAfter = insert.shift().breakAfter; + } + else if (fromOff < before.length || before.children.length && before.children[before.children.length - 1].length == 0) { + before.merge(fromOff, before.length, null, false, openStart, 0); + } + fromI++; + } + } + // Try to merge widgets on the boundaries of the replacement + while (fromI < toI && insert.length) { + if (children[toI - 1].become(insert[insert.length - 1])) { + toI--; + insert.pop(); + openEnd = insert.length ? 0 : openStart; + } + else if (children[fromI].become(insert[0])) { + fromI++; + insert.shift(); + openStart = insert.length ? 0 : openEnd; + } + else { + break; + } + } + if (!insert.length && fromI && toI < children.length && !children[fromI - 1].breakAfter && + children[toI].merge(0, 0, children[fromI - 1], false, openStart, openEnd)) + fromI--; + if (fromI < toI || insert.length) + parent.replaceChildren(fromI, toI, insert); + } + function mergeChildrenInto(parent, from, to, insert, openStart, openEnd) { + let cur = parent.childCursor(); + let { i: toI, off: toOff } = cur.findPos(to, 1); + let { i: fromI, off: fromOff } = cur.findPos(from, -1); + let dLen = from - to; + for (let view of insert) + dLen += view.length; + parent.length += dLen; + replaceRange(parent, fromI, fromOff, toI, toOff, insert, 0, openStart, openEnd); + } + + let nav = typeof navigator != "undefined" ? navigator : { userAgent: "", vendor: "", platform: "" }; + let doc = typeof document != "undefined" ? document : { documentElement: { style: {} } }; + const ie_edge = /*@__PURE__*//Edge\/(\d+)/.exec(nav.userAgent); + const ie_upto10 = /*@__PURE__*//MSIE \d/.test(nav.userAgent); + const ie_11up = /*@__PURE__*//Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(nav.userAgent); + const ie = !!(ie_upto10 || ie_11up || ie_edge); + const gecko = !ie && /*@__PURE__*//gecko\/(\d+)/i.test(nav.userAgent); + const chrome = !ie && /*@__PURE__*//Chrome\/(\d+)/.exec(nav.userAgent); + const webkit = "webkitFontSmoothing" in doc.documentElement.style; + const safari = !ie && /*@__PURE__*//Apple Computer/.test(nav.vendor); + const ios = safari && (/*@__PURE__*//Mobile\/\w+/.test(nav.userAgent) || nav.maxTouchPoints > 2); + var browser = { + mac: ios || /*@__PURE__*//Mac/.test(nav.platform), + windows: /*@__PURE__*//Win/.test(nav.platform), + linux: /*@__PURE__*//Linux|X11/.test(nav.platform), + ie, + ie_version: ie_upto10 ? doc.documentMode || 6 : ie_11up ? +ie_11up[1] : ie_edge ? +ie_edge[1] : 0, + gecko, + gecko_version: gecko ? +(/*@__PURE__*//Firefox\/(\d+)/.exec(nav.userAgent) || [0, 0])[1] : 0, + chrome: !!chrome, + chrome_version: chrome ? +chrome[1] : 0, + ios, + android: /*@__PURE__*//Android\b/.test(nav.userAgent), + webkit, + safari, + webkit_version: webkit ? +(/*@__PURE__*//\bAppleWebKit\/(\d+)/.exec(navigator.userAgent) || [0, 0])[1] : 0, + tabSize: doc.documentElement.style.tabSize != null ? "tab-size" : "-moz-tab-size" + }; + + const MaxJoinLen = 256; + class TextView extends ContentView { + constructor(text) { + super(); + this.text = text; + } + get length() { return this.text.length; } + createDOM(textDOM) { + this.setDOM(textDOM || document.createTextNode(this.text)); + } + sync(track) { + if (!this.dom) + this.createDOM(); + if (this.dom.nodeValue != this.text) { + if (track && track.node == this.dom) + track.written = true; + this.dom.nodeValue = this.text; + } + } + reuseDOM(dom) { + if (dom.nodeType == 3) + this.createDOM(dom); + } + merge(from, to, source) { + if (source && (!(source instanceof TextView) || this.length - (to - from) + source.length > MaxJoinLen)) + return false; + this.text = this.text.slice(0, from) + (source ? source.text : "") + this.text.slice(to); + this.markDirty(); + return true; + } + split(from) { + let result = new TextView(this.text.slice(from)); + this.text = this.text.slice(0, from); + this.markDirty(); + return result; + } + localPosFromDOM(node, offset) { + return node == this.dom ? offset : offset ? this.text.length : 0; + } + domAtPos(pos) { return new DOMPos(this.dom, pos); } + domBoundsAround(_from, _to, offset) { + return { from: offset, to: offset + this.length, startDOM: this.dom, endDOM: this.dom.nextSibling }; + } + coordsAt(pos, side) { + return textCoords(this.dom, pos, side); + } + } + class MarkView extends ContentView { + constructor(mark, children = [], length = 0) { + super(); + this.mark = mark; + this.children = children; + this.length = length; + for (let ch of children) + ch.setParent(this); + } + setAttrs(dom) { + clearAttributes(dom); + if (this.mark.class) + dom.className = this.mark.class; + if (this.mark.attrs) + for (let name in this.mark.attrs) + dom.setAttribute(name, this.mark.attrs[name]); + return dom; + } + reuseDOM(node) { + if (node.nodeName == this.mark.tagName.toUpperCase()) { + this.setDOM(node); + this.dirty |= 4 /* Dirty.Attrs */ | 2 /* Dirty.Node */; + } + } + sync(track) { + if (!this.dom) + this.setDOM(this.setAttrs(document.createElement(this.mark.tagName))); + else if (this.dirty & 4 /* Dirty.Attrs */) + this.setAttrs(this.dom); + super.sync(track); + } + merge(from, to, source, _hasStart, openStart, openEnd) { + if (source && (!(source instanceof MarkView && source.mark.eq(this.mark)) || + (from && openStart <= 0) || (to < this.length && openEnd <= 0))) + return false; + mergeChildrenInto(this, from, to, source ? source.children : [], openStart - 1, openEnd - 1); + this.markDirty(); + return true; + } + split(from) { + let result = [], off = 0, detachFrom = -1, i = 0; + for (let elt of this.children) { + let end = off + elt.length; + if (end > from) + result.push(off < from ? elt.split(from - off) : elt); + if (detachFrom < 0 && off >= from) + detachFrom = i; + off = end; + i++; + } + let length = this.length - from; + this.length = from; + if (detachFrom > -1) { + this.children.length = detachFrom; + this.markDirty(); + } + return new MarkView(this.mark, result, length); + } + domAtPos(pos) { + return inlineDOMAtPos(this, pos); + } + coordsAt(pos, side) { + return coordsInChildren(this, pos, side); + } + } + function textCoords(text, pos, side) { + let length = text.nodeValue.length; + if (pos > length) + pos = length; + let from = pos, to = pos, flatten = 0; + if (pos == 0 && side < 0 || pos == length && side >= 0) { + if (!(browser.chrome || browser.gecko)) { // These browsers reliably return valid rectangles for empty ranges + if (pos) { + from--; + flatten = 1; + } // FIXME this is wrong in RTL text + else if (to < length) { + to++; + flatten = -1; + } + } + } + else { + if (side < 0) + from--; + else if (to < length) + to++; + } + let rects = textRange(text, from, to).getClientRects(); + if (!rects.length) + return Rect0; + let rect = rects[(flatten ? flatten < 0 : side >= 0) ? 0 : rects.length - 1]; + if (browser.safari && !flatten && rect.width == 0) + rect = Array.prototype.find.call(rects, r => r.width) || rect; + return flatten ? flattenRect(rect, flatten < 0) : rect || null; + } + // Also used for collapsed ranges that don't have a placeholder widget! + class WidgetView extends ContentView { + constructor(widget, length, side) { + super(); + this.widget = widget; + this.length = length; + this.side = side; + this.prevWidget = null; + } + static create(widget, length, side) { + return new (widget.customView || WidgetView)(widget, length, side); + } + split(from) { + let result = WidgetView.create(this.widget, this.length - from, this.side); + this.length -= from; + return result; + } + sync() { + if (!this.dom || !this.widget.updateDOM(this.dom)) { + if (this.dom && this.prevWidget) + this.prevWidget.destroy(this.dom); + this.prevWidget = null; + this.setDOM(this.widget.toDOM(this.editorView)); + this.dom.contentEditable = "false"; + } + } + getSide() { return this.side; } + merge(from, to, source, hasStart, openStart, openEnd) { + if (source && (!(source instanceof WidgetView) || !this.widget.compare(source.widget) || + from > 0 && openStart <= 0 || to < this.length && openEnd <= 0)) + return false; + this.length = from + (source ? source.length : 0) + (this.length - to); + return true; + } + become(other) { + if (other.length == this.length && other instanceof WidgetView && other.side == this.side) { + if (this.widget.constructor == other.widget.constructor) { + if (!this.widget.eq(other.widget)) + this.markDirty(true); + if (this.dom && !this.prevWidget) + this.prevWidget = this.widget; + this.widget = other.widget; + return true; + } + } + return false; + } + ignoreMutation() { return true; } + ignoreEvent(event) { return this.widget.ignoreEvent(event); } + get overrideDOMText() { + if (this.length == 0) + return Text.empty; + let top = this; + while (top.parent) + top = top.parent; + let view = top.editorView, text = view && view.state.doc, start = this.posAtStart; + return text ? text.slice(start, start + this.length) : Text.empty; + } + domAtPos(pos) { + return pos == 0 ? DOMPos.before(this.dom) : DOMPos.after(this.dom, pos == this.length); + } + domBoundsAround() { return null; } + coordsAt(pos, side) { + let rects = this.dom.getClientRects(), rect = null; + if (!rects.length) + return Rect0; + for (let i = pos > 0 ? rects.length - 1 : 0;; i += (pos > 0 ? -1 : 1)) { + rect = rects[i]; + if (pos > 0 ? i == 0 : i == rects.length - 1 || rect.top < rect.bottom) + break; + } + return (pos == 0 && side > 0 || pos == this.length && side <= 0) ? rect : flattenRect(rect, pos == 0); + } + get isEditable() { return false; } + destroy() { + super.destroy(); + if (this.dom) + this.widget.destroy(this.dom); + } + } + class CompositionView extends WidgetView { + domAtPos(pos) { + let { topView, text } = this.widget; + if (!topView) + return new DOMPos(text, Math.min(pos, text.nodeValue.length)); + return scanCompositionTree(pos, 0, topView, text, (v, p) => v.domAtPos(p), p => new DOMPos(text, Math.min(p, text.nodeValue.length))); + } + sync() { this.setDOM(this.widget.toDOM()); } + localPosFromDOM(node, offset) { + let { topView, text } = this.widget; + if (!topView) + return Math.min(offset, this.length); + return posFromDOMInCompositionTree(node, offset, topView, text); + } + ignoreMutation() { return false; } + get overrideDOMText() { return null; } + coordsAt(pos, side) { + let { topView, text } = this.widget; + if (!topView) + return textCoords(text, pos, side); + return scanCompositionTree(pos, side, topView, text, (v, pos, side) => v.coordsAt(pos, side), (pos, side) => textCoords(text, pos, side)); + } + destroy() { + var _a; + super.destroy(); + (_a = this.widget.topView) === null || _a === void 0 ? void 0 : _a.destroy(); + } + get isEditable() { return true; } + canReuseDOM() { return true; } + } + // Uses the old structure of a chunk of content view frozen for + // composition to try and find a reasonable DOM location for the given + // offset. + function scanCompositionTree(pos, side, view, text, enterView, fromText) { + if (view instanceof MarkView) { + for (let child = view.dom.firstChild; child; child = child.nextSibling) { + let desc = ContentView.get(child); + if (!desc) + return fromText(pos, side); + let hasComp = contains(child, text); + let len = desc.length + (hasComp ? text.nodeValue.length : 0); + if (pos < len || pos == len && desc.getSide() <= 0) + return hasComp ? scanCompositionTree(pos, side, desc, text, enterView, fromText) : enterView(desc, pos, side); + pos -= len; + } + return enterView(view, view.length, -1); + } + else if (view.dom == text) { + return fromText(pos, side); + } + else { + return enterView(view, pos, side); + } + } + function posFromDOMInCompositionTree(node, offset, view, text) { + if (view instanceof MarkView) { + for (let child of view.children) { + let pos = 0, hasComp = contains(child.dom, text); + if (contains(child.dom, node)) + return pos + (hasComp ? posFromDOMInCompositionTree(node, offset, child, text) : child.localPosFromDOM(node, offset)); + pos += hasComp ? text.nodeValue.length : child.length; + } + } + else if (view.dom == text) { + return Math.min(offset, text.nodeValue.length); + } + return view.localPosFromDOM(node, offset); + } + // These are drawn around uneditable widgets to avoid a number of + // browser bugs that show up when the cursor is directly next to + // uneditable inline content. + class WidgetBufferView extends ContentView { + constructor(side) { + super(); + this.side = side; + } + get length() { return 0; } + merge() { return false; } + become(other) { + return other instanceof WidgetBufferView && other.side == this.side; + } + split() { return new WidgetBufferView(this.side); } + sync() { + if (!this.dom) { + let dom = document.createElement("img"); + dom.className = "cm-widgetBuffer"; + dom.setAttribute("aria-hidden", "true"); + this.setDOM(dom); + } + } + getSide() { return this.side; } + domAtPos(pos) { return DOMPos.before(this.dom); } + localPosFromDOM() { return 0; } + domBoundsAround() { return null; } + coordsAt(pos) { + let imgRect = this.dom.getBoundingClientRect(); + // Since the <img> height doesn't correspond to text height, try + // to borrow the height from some sibling node. + let siblingRect = inlineSiblingRect(this, this.side > 0 ? -1 : 1); + return siblingRect && siblingRect.top < imgRect.bottom && siblingRect.bottom > imgRect.top + ? { left: imgRect.left, right: imgRect.right, top: siblingRect.top, bottom: siblingRect.bottom } : imgRect; + } + get overrideDOMText() { + return Text.empty; + } + } + TextView.prototype.children = WidgetView.prototype.children = WidgetBufferView.prototype.children = noChildren; + function inlineSiblingRect(view, side) { + let parent = view.parent, index = parent ? parent.children.indexOf(view) : -1; + while (parent && index >= 0) { + if (side < 0 ? index > 0 : index < parent.children.length) { + let next = parent.children[index + side]; + if (next instanceof TextView) { + let nextRect = next.coordsAt(side < 0 ? next.length : 0, side); + if (nextRect) + return nextRect; + } + index += side; + } + else if (parent instanceof MarkView && parent.parent) { + index = parent.parent.children.indexOf(parent) + (side < 0 ? 0 : 1); + parent = parent.parent; + } + else { + let last = parent.dom.lastChild; + if (last && last.nodeName == "BR") + return last.getClientRects()[0]; + break; + } + } + return undefined; + } + function inlineDOMAtPos(parent, pos) { + let dom = parent.dom, { children } = parent, i = 0; + for (let off = 0; i < children.length; i++) { + let child = children[i], end = off + child.length; + if (end == off && child.getSide() <= 0) + continue; + if (pos > off && pos < end && child.dom.parentNode == dom) + return child.domAtPos(pos - off); + if (pos <= off) + break; + off = end; + } + // if (i) return DOMPos.after(children[i - 1].dom!) + for (let j = i; j > 0; j--) { + let prev = children[j - 1]; + if (prev.dom.parentNode == dom) + return prev.domAtPos(prev.length); + } + for (let j = i; j < children.length; j++) { + let next = children[j]; + if (next.dom.parentNode == dom) + return next.domAtPos(0); + } + return new DOMPos(dom, 0); + } + // Assumes `view`, if a mark view, has precisely 1 child. + function joinInlineInto(parent, view, open) { + let last, { children } = parent; + if (open > 0 && view instanceof MarkView && children.length && + (last = children[children.length - 1]) instanceof MarkView && last.mark.eq(view.mark)) { + joinInlineInto(last, view.children[0], open - 1); + } + else { + children.push(view); + view.setParent(parent); + } + parent.length += view.length; + } + function coordsInChildren(view, pos, side) { + for (let off = 0, i = 0; i < view.children.length; i++) { + let child = view.children[i], end = off + child.length, next; + if ((side <= 0 || end == view.length || child.getSide() > 0 ? end >= pos : end > pos) && + (pos < end || i + 1 == view.children.length || (next = view.children[i + 1]).length || next.getSide() > 0)) { + let flatten = 0; + if (end == off) { + if (child.getSide() <= 0) + continue; + flatten = side = -child.getSide(); + } + let rect = child.coordsAt(Math.max(0, pos - off), side); + return flatten && rect ? flattenRect(rect, side < 0) : rect; + } + off = end; + } + let last = view.dom.lastChild; + if (!last) + return view.dom.getBoundingClientRect(); + let rects = clientRectsFor(last); + return rects[rects.length - 1] || null; + } + + function combineAttrs(source, target) { + for (let name in source) { + if (name == "class" && target.class) + target.class += " " + source.class; + else if (name == "style" && target.style) + target.style += ";" + source.style; + else + target[name] = source[name]; + } + return target; + } + function attrsEq(a, b) { + if (a == b) + return true; + if (!a || !b) + return false; + let keysA = Object.keys(a), keysB = Object.keys(b); + if (keysA.length != keysB.length) + return false; + for (let key of keysA) { + if (keysB.indexOf(key) == -1 || a[key] !== b[key]) + return false; + } + return true; + } + function updateAttrs(dom, prev, attrs) { + let changed = null; + if (prev) + for (let name in prev) + if (!(attrs && name in attrs)) + dom.removeAttribute(changed = name); + if (attrs) + for (let name in attrs) + if (!(prev && prev[name] == attrs[name])) + dom.setAttribute(changed = name, attrs[name]); + return !!changed; + } + + /** + Widgets added to the content are described by subclasses of this + class. Using a description object like that makes it possible to + delay creating of the DOM structure for a widget until it is + needed, and to avoid redrawing widgets even if the decorations + that define them are recreated. + */ + class WidgetType { + /** + Compare this instance to another instance of the same type. + (TypeScript can't express this, but only instances of the same + specific class will be passed to this method.) This is used to + avoid redrawing widgets when they are replaced by a new + decoration of the same type. The default implementation just + returns `false`, which will cause new instances of the widget to + always be redrawn. + */ + eq(widget) { return false; } + /** + Update a DOM element created by a widget of the same type (but + different, non-`eq` content) to reflect this widget. May return + true to indicate that it could update, false to indicate it + couldn't (in which case the widget will be redrawn). The default + implementation just returns false. + */ + updateDOM(dom) { return false; } + /** + @internal + */ + compare(other) { + return this == other || this.constructor == other.constructor && this.eq(other); + } + /** + The estimated height this widget will have, to be used when + estimating the height of content that hasn't been drawn. May + return -1 to indicate you don't know. The default implementation + returns -1. + */ + get estimatedHeight() { return -1; } + /** + Can be used to configure which kinds of events inside the widget + should be ignored by the editor. The default is to ignore all + events. + */ + ignoreEvent(event) { return true; } + /** + @internal + */ + get customView() { return null; } + /** + This is called when the an instance of the widget is removed + from the editor view. + */ + destroy(dom) { } + } + /** + The different types of blocks that can occur in an editor view. + */ + var BlockType = /*@__PURE__*/(function (BlockType) { + /** + A line of text. + */ + BlockType[BlockType["Text"] = 0] = "Text"; + /** + A block widget associated with the position after it. + */ + BlockType[BlockType["WidgetBefore"] = 1] = "WidgetBefore"; + /** + A block widget associated with the position before it. + */ + BlockType[BlockType["WidgetAfter"] = 2] = "WidgetAfter"; + /** + A block widget [replacing](https://codemirror.net/6/docs/ref/#view.Decoration^replace) a range of content. + */ + BlockType[BlockType["WidgetRange"] = 3] = "WidgetRange"; + return BlockType})(BlockType || (BlockType = {})); + /** + A decoration provides information on how to draw or style a piece + of content. You'll usually use it wrapped in a + [`Range`](https://codemirror.net/6/docs/ref/#state.Range), which adds a start and end position. + @nonabstract + */ + class Decoration extends RangeValue { + constructor( + /** + @internal + */ + startSide, + /** + @internal + */ + endSide, + /** + @internal + */ + widget, + /** + The config object used to create this decoration. You can + include additional properties in there to store metadata about + your decoration. + */ + spec) { + super(); + this.startSide = startSide; + this.endSide = endSide; + this.widget = widget; + this.spec = spec; + } + /** + @internal + */ + get heightRelevant() { return false; } + /** + Create a mark decoration, which influences the styling of the + content in its range. Nested mark decorations will cause nested + DOM elements to be created. Nesting order is determined by + precedence of the [facet](https://codemirror.net/6/docs/ref/#view.EditorView^decorations), with + the higher-precedence decorations creating the inner DOM nodes. + Such elements are split on line boundaries and on the boundaries + of lower-precedence decorations. + */ + static mark(spec) { + return new MarkDecoration(spec); + } + /** + Create a widget decoration, which displays a DOM element at the + given position. + */ + static widget(spec) { + let side = spec.side || 0, block = !!spec.block; + side += block ? (side > 0 ? 300000000 /* Side.BlockAfter */ : -400000000 /* Side.BlockBefore */) : (side > 0 ? 100000000 /* Side.InlineAfter */ : -100000000 /* Side.InlineBefore */); + return new PointDecoration(spec, side, side, block, spec.widget || null, false); + } + /** + Create a replace decoration which replaces the given range with + a widget, or simply hides it. + */ + static replace(spec) { + let block = !!spec.block, startSide, endSide; + if (spec.isBlockGap) { + startSide = -500000000 /* Side.GapStart */; + endSide = 400000000 /* Side.GapEnd */; + } + else { + let { start, end } = getInclusive(spec, block); + startSide = (start ? (block ? -300000000 /* Side.BlockIncStart */ : -1 /* Side.InlineIncStart */) : 500000000 /* Side.NonIncStart */) - 1; + endSide = (end ? (block ? 200000000 /* Side.BlockIncEnd */ : 1 /* Side.InlineIncEnd */) : -600000000 /* Side.NonIncEnd */) + 1; + } + return new PointDecoration(spec, startSide, endSide, block, spec.widget || null, true); + } + /** + Create a line decoration, which can add DOM attributes to the + line starting at the given position. + */ + static line(spec) { + return new LineDecoration(spec); + } + /** + Build a [`DecorationSet`](https://codemirror.net/6/docs/ref/#view.DecorationSet) from the given + decorated range or ranges. If the ranges aren't already sorted, + pass `true` for `sort` to make the library sort them for you. + */ + static set(of, sort = false) { + return RangeSet.of(of, sort); + } + /** + @internal + */ + hasHeight() { return this.widget ? this.widget.estimatedHeight > -1 : false; } + } + /** + The empty set of decorations. + */ + Decoration.none = RangeSet.empty; + class MarkDecoration extends Decoration { + constructor(spec) { + let { start, end } = getInclusive(spec); + super(start ? -1 /* Side.InlineIncStart */ : 500000000 /* Side.NonIncStart */, end ? 1 /* Side.InlineIncEnd */ : -600000000 /* Side.NonIncEnd */, null, spec); + this.tagName = spec.tagName || "span"; + this.class = spec.class || ""; + this.attrs = spec.attributes || null; + } + eq(other) { + return this == other || + other instanceof MarkDecoration && + this.tagName == other.tagName && + this.class == other.class && + attrsEq(this.attrs, other.attrs); + } + range(from, to = from) { + if (from >= to) + throw new RangeError("Mark decorations may not be empty"); + return super.range(from, to); + } + } + MarkDecoration.prototype.point = false; + class LineDecoration extends Decoration { + constructor(spec) { + super(-200000000 /* Side.Line */, -200000000 /* Side.Line */, null, spec); + } + eq(other) { + return other instanceof LineDecoration && attrsEq(this.spec.attributes, other.spec.attributes); + } + range(from, to = from) { + if (to != from) + throw new RangeError("Line decoration ranges must be zero-length"); + return super.range(from, to); + } + } + LineDecoration.prototype.mapMode = MapMode.TrackBefore; + LineDecoration.prototype.point = true; + class PointDecoration extends Decoration { + constructor(spec, startSide, endSide, block, widget, isReplace) { + super(startSide, endSide, widget, spec); + this.block = block; + this.isReplace = isReplace; + this.mapMode = !block ? MapMode.TrackDel : startSide <= 0 ? MapMode.TrackBefore : MapMode.TrackAfter; + } + // Only relevant when this.block == true + get type() { + return this.startSide < this.endSide ? BlockType.WidgetRange + : this.startSide <= 0 ? BlockType.WidgetBefore : BlockType.WidgetAfter; + } + get heightRelevant() { return this.block || !!this.widget && this.widget.estimatedHeight >= 5; } + eq(other) { + return other instanceof PointDecoration && + widgetsEq(this.widget, other.widget) && + this.block == other.block && + this.startSide == other.startSide && this.endSide == other.endSide; + } + range(from, to = from) { + if (this.isReplace && (from > to || (from == to && this.startSide > 0 && this.endSide <= 0))) + throw new RangeError("Invalid range for replacement decoration"); + if (!this.isReplace && to != from) + throw new RangeError("Widget decorations can only have zero-length ranges"); + return super.range(from, to); + } + } + PointDecoration.prototype.point = true; + function getInclusive(spec, block = false) { + let { inclusiveStart: start, inclusiveEnd: end } = spec; + if (start == null) + start = spec.inclusive; + if (end == null) + end = spec.inclusive; + return { start: start !== null && start !== void 0 ? start : block, end: end !== null && end !== void 0 ? end : block }; + } + function widgetsEq(a, b) { + return a == b || !!(a && b && a.compare(b)); + } + function addRange(from, to, ranges, margin = 0) { + let last = ranges.length - 1; + if (last >= 0 && ranges[last] + margin >= from) + ranges[last] = Math.max(ranges[last], to); + else + ranges.push(from, to); + } + + class LineView extends ContentView { + constructor() { + super(...arguments); + this.children = []; + this.length = 0; + this.prevAttrs = undefined; + this.attrs = null; + this.breakAfter = 0; + } + // Consumes source + merge(from, to, source, hasStart, openStart, openEnd) { + if (source) { + if (!(source instanceof LineView)) + return false; + if (!this.dom) + source.transferDOM(this); // Reuse source.dom when appropriate + } + if (hasStart) + this.setDeco(source ? source.attrs : null); + mergeChildrenInto(this, from, to, source ? source.children : [], openStart, openEnd); + return true; + } + split(at) { + let end = new LineView; + end.breakAfter = this.breakAfter; + if (this.length == 0) + return end; + let { i, off } = this.childPos(at); + if (off) { + end.append(this.children[i].split(off), 0); + this.children[i].merge(off, this.children[i].length, null, false, 0, 0); + i++; + } + for (let j = i; j < this.children.length; j++) + end.append(this.children[j], 0); + while (i > 0 && this.children[i - 1].length == 0) + this.children[--i].destroy(); + this.children.length = i; + this.markDirty(); + this.length = at; + return end; + } + transferDOM(other) { + if (!this.dom) + return; + this.markDirty(); + other.setDOM(this.dom); + other.prevAttrs = this.prevAttrs === undefined ? this.attrs : this.prevAttrs; + this.prevAttrs = undefined; + this.dom = null; + } + setDeco(attrs) { + if (!attrsEq(this.attrs, attrs)) { + if (this.dom) { + this.prevAttrs = this.attrs; + this.markDirty(); + } + this.attrs = attrs; + } + } + append(child, openStart) { + joinInlineInto(this, child, openStart); + } + // Only called when building a line view in ContentBuilder + addLineDeco(deco) { + let attrs = deco.spec.attributes, cls = deco.spec.class; + if (attrs) + this.attrs = combineAttrs(attrs, this.attrs || {}); + if (cls) + this.attrs = combineAttrs({ class: cls }, this.attrs || {}); + } + domAtPos(pos) { + return inlineDOMAtPos(this, pos); + } + reuseDOM(node) { + if (node.nodeName == "DIV") { + this.setDOM(node); + this.dirty |= 4 /* Dirty.Attrs */ | 2 /* Dirty.Node */; + } + } + sync(track) { + var _a; + if (!this.dom) { + this.setDOM(document.createElement("div")); + this.dom.className = "cm-line"; + this.prevAttrs = this.attrs ? null : undefined; + } + else if (this.dirty & 4 /* Dirty.Attrs */) { + clearAttributes(this.dom); + this.dom.className = "cm-line"; + this.prevAttrs = this.attrs ? null : undefined; + } + if (this.prevAttrs !== undefined) { + updateAttrs(this.dom, this.prevAttrs, this.attrs); + this.dom.classList.add("cm-line"); + this.prevAttrs = undefined; + } + super.sync(track); + let last = this.dom.lastChild; + while (last && ContentView.get(last) instanceof MarkView) + last = last.lastChild; + if (!last || !this.length || + last.nodeName != "BR" && ((_a = ContentView.get(last)) === null || _a === void 0 ? void 0 : _a.isEditable) == false && + (!browser.ios || !this.children.some(ch => ch instanceof TextView))) { + let hack = document.createElement("BR"); + hack.cmIgnore = true; + this.dom.appendChild(hack); + } + } + measureTextSize() { + if (this.children.length == 0 || this.length > 20) + return null; + let totalWidth = 0; + for (let child of this.children) { + if (!(child instanceof TextView) || /[^ -~]/.test(child.text)) + return null; + let rects = clientRectsFor(child.dom); + if (rects.length != 1) + return null; + totalWidth += rects[0].width; + } + return !totalWidth ? null : { + lineHeight: this.dom.getBoundingClientRect().height, + charWidth: totalWidth / this.length + }; + } + coordsAt(pos, side) { + return coordsInChildren(this, pos, side); + } + become(_other) { return false; } + get type() { return BlockType.Text; } + static find(docView, pos) { + for (let i = 0, off = 0; i < docView.children.length; i++) { + let block = docView.children[i], end = off + block.length; + if (end >= pos) { + if (block instanceof LineView) + return block; + if (end > pos) + break; + } + off = end + block.breakAfter; + } + return null; + } + } + class BlockWidgetView extends ContentView { + constructor(widget, length, type) { + super(); + this.widget = widget; + this.length = length; + this.type = type; + this.breakAfter = 0; + this.prevWidget = null; + } + merge(from, to, source, _takeDeco, openStart, openEnd) { + if (source && (!(source instanceof BlockWidgetView) || !this.widget.compare(source.widget) || + from > 0 && openStart <= 0 || to < this.length && openEnd <= 0)) + return false; + this.length = from + (source ? source.length : 0) + (this.length - to); + return true; + } + domAtPos(pos) { + return pos == 0 ? DOMPos.before(this.dom) : DOMPos.after(this.dom, pos == this.length); + } + split(at) { + let len = this.length - at; + this.length = at; + let end = new BlockWidgetView(this.widget, len, this.type); + end.breakAfter = this.breakAfter; + return end; + } + get children() { return noChildren; } + sync() { + if (!this.dom || !this.widget.updateDOM(this.dom)) { + if (this.dom && this.prevWidget) + this.prevWidget.destroy(this.dom); + this.prevWidget = null; + this.setDOM(this.widget.toDOM(this.editorView)); + this.dom.contentEditable = "false"; + } + } + get overrideDOMText() { + return this.parent ? this.parent.view.state.doc.slice(this.posAtStart, this.posAtEnd) : Text.empty; + } + domBoundsAround() { return null; } + become(other) { + if (other instanceof BlockWidgetView && other.type == this.type && + other.widget.constructor == this.widget.constructor) { + if (!other.widget.eq(this.widget)) + this.markDirty(true); + if (this.dom && !this.prevWidget) + this.prevWidget = this.widget; + this.widget = other.widget; + this.length = other.length; + this.breakAfter = other.breakAfter; + return true; + } + return false; + } + ignoreMutation() { return true; } + ignoreEvent(event) { return this.widget.ignoreEvent(event); } + destroy() { + super.destroy(); + if (this.dom) + this.widget.destroy(this.dom); + } + } + + class ContentBuilder { + constructor(doc, pos, end, disallowBlockEffectsFor) { + this.doc = doc; + this.pos = pos; + this.end = end; + this.disallowBlockEffectsFor = disallowBlockEffectsFor; + this.content = []; + this.curLine = null; + this.breakAtStart = 0; + this.pendingBuffer = 0 /* Buf.No */; + // Set to false directly after a widget that covers the position after it + this.atCursorPos = true; + this.openStart = -1; + this.openEnd = -1; + this.text = ""; + this.textOff = 0; + this.cursor = doc.iter(); + this.skip = pos; + } + posCovered() { + if (this.content.length == 0) + return !this.breakAtStart && this.doc.lineAt(this.pos).from != this.pos; + let last = this.content[this.content.length - 1]; + return !last.breakAfter && !(last instanceof BlockWidgetView && last.type == BlockType.WidgetBefore); + } + getLine() { + if (!this.curLine) { + this.content.push(this.curLine = new LineView); + this.atCursorPos = true; + } + return this.curLine; + } + flushBuffer(active) { + if (this.pendingBuffer) { + this.curLine.append(wrapMarks(new WidgetBufferView(-1), active), active.length); + this.pendingBuffer = 0 /* Buf.No */; + } + } + addBlockWidget(view) { + this.flushBuffer([]); + this.curLine = null; + this.content.push(view); + } + finish(openEnd) { + if (!openEnd) + this.flushBuffer([]); + else + this.pendingBuffer = 0 /* Buf.No */; + if (!this.posCovered()) + this.getLine(); + } + buildText(length, active, openStart) { + while (length > 0) { + if (this.textOff == this.text.length) { + let { value, lineBreak, done } = this.cursor.next(this.skip); + this.skip = 0; + if (done) + throw new Error("Ran out of text content when drawing inline views"); + if (lineBreak) { + if (!this.posCovered()) + this.getLine(); + if (this.content.length) + this.content[this.content.length - 1].breakAfter = 1; + else + this.breakAtStart = 1; + this.flushBuffer([]); + this.curLine = null; + length--; + continue; + } + else { + this.text = value; + this.textOff = 0; + } + } + let take = Math.min(this.text.length - this.textOff, length, 512 /* T.Chunk */); + this.flushBuffer(active.slice(0, openStart)); + this.getLine().append(wrapMarks(new TextView(this.text.slice(this.textOff, this.textOff + take)), active), openStart); + this.atCursorPos = true; + this.textOff += take; + length -= take; + openStart = 0; + } + } + span(from, to, active, openStart) { + this.buildText(to - from, active, openStart); + this.pos = to; + if (this.openStart < 0) + this.openStart = openStart; + } + point(from, to, deco, active, openStart, index) { + if (this.disallowBlockEffectsFor[index] && deco instanceof PointDecoration) { + if (deco.block) + throw new RangeError("Block decorations may not be specified via plugins"); + if (to > this.doc.lineAt(this.pos).to) + throw new RangeError("Decorations that replace line breaks may not be specified via plugins"); + } + let len = to - from; + if (deco instanceof PointDecoration) { + if (deco.block) { + let { type } = deco; + if (type == BlockType.WidgetAfter && !this.posCovered()) + this.getLine(); + this.addBlockWidget(new BlockWidgetView(deco.widget || new NullWidget("div"), len, type)); + } + else { + let view = WidgetView.create(deco.widget || new NullWidget("span"), len, deco.startSide); + let cursorBefore = this.atCursorPos && !view.isEditable && openStart <= active.length && (from < to || deco.startSide > 0); + let cursorAfter = !view.isEditable && (from < to || deco.startSide <= 0); + let line = this.getLine(); + if (this.pendingBuffer == 2 /* Buf.IfCursor */ && !cursorBefore) + this.pendingBuffer = 0 /* Buf.No */; + this.flushBuffer(active); + if (cursorBefore) { + line.append(wrapMarks(new WidgetBufferView(1), active), openStart); + openStart = active.length + Math.max(0, openStart - active.length); + } + line.append(wrapMarks(view, active), openStart); + this.atCursorPos = cursorAfter; + this.pendingBuffer = !cursorAfter ? 0 /* Buf.No */ : from < to ? 1 /* Buf.Yes */ : 2 /* Buf.IfCursor */; + } + } + else if (this.doc.lineAt(this.pos).from == this.pos) { // Line decoration + this.getLine().addLineDeco(deco); + } + if (len) { + // Advance the iterator past the replaced content + if (this.textOff + len <= this.text.length) { + this.textOff += len; + } + else { + this.skip += len - (this.text.length - this.textOff); + this.text = ""; + this.textOff = 0; + } + this.pos = to; + } + if (this.openStart < 0) + this.openStart = openStart; + } + static build(text, from, to, decorations, dynamicDecorationMap) { + let builder = new ContentBuilder(text, from, to, dynamicDecorationMap); + builder.openEnd = RangeSet.spans(decorations, from, to, builder); + if (builder.openStart < 0) + builder.openStart = builder.openEnd; + builder.finish(builder.openEnd); + return builder; + } + } + function wrapMarks(view, active) { + for (let mark of active) + view = new MarkView(mark, [view], view.length); + return view; + } + class NullWidget extends WidgetType { + constructor(tag) { + super(); + this.tag = tag; + } + eq(other) { return other.tag == this.tag; } + toDOM() { return document.createElement(this.tag); } + updateDOM(elt) { return elt.nodeName.toLowerCase() == this.tag; } + } + + const clickAddsSelectionRange = /*@__PURE__*/Facet.define(); + const dragMovesSelection$1 = /*@__PURE__*/Facet.define(); + const mouseSelectionStyle = /*@__PURE__*/Facet.define(); + const exceptionSink = /*@__PURE__*/Facet.define(); + const updateListener = /*@__PURE__*/Facet.define(); + const inputHandler$1 = /*@__PURE__*/Facet.define(); + const perLineTextDirection = /*@__PURE__*/Facet.define({ + combine: values => values.some(x => x) + }); + class ScrollTarget { + constructor(range, y = "nearest", x = "nearest", yMargin = 5, xMargin = 5) { + this.range = range; + this.y = y; + this.x = x; + this.yMargin = yMargin; + this.xMargin = xMargin; + } + map(changes) { + return changes.empty ? this : new ScrollTarget(this.range.map(changes), this.y, this.x, this.yMargin, this.xMargin); + } + } + const scrollIntoView$1 = /*@__PURE__*/StateEffect.define({ map: (t, ch) => t.map(ch) }); + /** + Log or report an unhandled exception in client code. Should + probably only be used by extension code that allows client code to + provide functions, and calls those functions in a context where an + exception can't be propagated to calling code in a reasonable way + (for example when in an event handler). + + Either calls a handler registered with + [`EditorView.exceptionSink`](https://codemirror.net/6/docs/ref/#view.EditorView^exceptionSink), + `window.onerror`, if defined, or `console.error` (in which case + it'll pass `context`, when given, as first argument). + */ + function logException(state, exception, context) { + let handler = state.facet(exceptionSink); + if (handler.length) + handler[0](exception); + else if (window.onerror) + window.onerror(String(exception), context, undefined, undefined, exception); + else if (context) + console.error(context + ":", exception); + else + console.error(exception); + } + const editable = /*@__PURE__*/Facet.define({ combine: values => values.length ? values[0] : true }); + let nextPluginID = 0; + const viewPlugin = /*@__PURE__*/Facet.define(); + /** + View plugins associate stateful values with a view. They can + influence the way the content is drawn, and are notified of things + that happen in the view. + */ + class ViewPlugin { + constructor( + /** + @internal + */ + id, + /** + @internal + */ + create, + /** + @internal + */ + domEventHandlers, buildExtensions) { + this.id = id; + this.create = create; + this.domEventHandlers = domEventHandlers; + this.extension = buildExtensions(this); + } + /** + Define a plugin from a constructor function that creates the + plugin's value, given an editor view. + */ + static define(create, spec) { + const { eventHandlers, provide, decorations: deco } = spec || {}; + return new ViewPlugin(nextPluginID++, create, eventHandlers, plugin => { + let ext = [viewPlugin.of(plugin)]; + if (deco) + ext.push(decorations.of(view => { + let pluginInst = view.plugin(plugin); + return pluginInst ? deco(pluginInst) : Decoration.none; + })); + if (provide) + ext.push(provide(plugin)); + return ext; + }); + } + /** + Create a plugin for a class whose constructor takes a single + editor view as argument. + */ + static fromClass(cls, spec) { + return ViewPlugin.define(view => new cls(view), spec); + } + } + class PluginInstance { + constructor(spec) { + this.spec = spec; + // When starting an update, all plugins have this field set to the + // update object, indicating they need to be updated. When finished + // updating, it is set to `false`. Retrieving a plugin that needs to + // be updated with `view.plugin` forces an eager update. + this.mustUpdate = null; + // This is null when the plugin is initially created, but + // initialized on the first update. + this.value = null; + } + update(view) { + if (!this.value) { + if (this.spec) { + try { + this.value = this.spec.create(view); + } + catch (e) { + logException(view.state, e, "CodeMirror plugin crashed"); + this.deactivate(); + } + } + } + else if (this.mustUpdate) { + let update = this.mustUpdate; + this.mustUpdate = null; + if (this.value.update) { + try { + this.value.update(update); + } + catch (e) { + logException(update.state, e, "CodeMirror plugin crashed"); + if (this.value.destroy) + try { + this.value.destroy(); + } + catch (_) { } + this.deactivate(); + } + } + } + return this; + } + destroy(view) { + var _a; + if ((_a = this.value) === null || _a === void 0 ? void 0 : _a.destroy) { + try { + this.value.destroy(); + } + catch (e) { + logException(view.state, e, "CodeMirror plugin crashed"); + } + } + } + deactivate() { + this.spec = this.value = null; + } + } + const editorAttributes = /*@__PURE__*/Facet.define(); + const contentAttributes = /*@__PURE__*/Facet.define(); + // Provide decorations + const decorations = /*@__PURE__*/Facet.define(); + const atomicRanges = /*@__PURE__*/Facet.define(); + const scrollMargins = /*@__PURE__*/Facet.define(); + const styleModule = /*@__PURE__*/Facet.define(); + class ChangedRange { + constructor(fromA, toA, fromB, toB) { + this.fromA = fromA; + this.toA = toA; + this.fromB = fromB; + this.toB = toB; + } + join(other) { + return new ChangedRange(Math.min(this.fromA, other.fromA), Math.max(this.toA, other.toA), Math.min(this.fromB, other.fromB), Math.max(this.toB, other.toB)); + } + addToSet(set) { + let i = set.length, me = this; + for (; i > 0; i--) { + let range = set[i - 1]; + if (range.fromA > me.toA) + continue; + if (range.toA < me.fromA) + break; + me = me.join(range); + set.splice(i - 1, 1); + } + set.splice(i, 0, me); + return set; + } + static extendWithRanges(diff, ranges) { + if (ranges.length == 0) + return diff; + let result = []; + for (let dI = 0, rI = 0, posA = 0, posB = 0;; dI++) { + let next = dI == diff.length ? null : diff[dI], off = posA - posB; + let end = next ? next.fromB : 1e9; + while (rI < ranges.length && ranges[rI] < end) { + let from = ranges[rI], to = ranges[rI + 1]; + let fromB = Math.max(posB, from), toB = Math.min(end, to); + if (fromB <= toB) + new ChangedRange(fromB + off, toB + off, fromB, toB).addToSet(result); + if (to > end) + break; + else + rI += 2; + } + if (!next) + return result; + new ChangedRange(next.fromA, next.toA, next.fromB, next.toB).addToSet(result); + posA = next.toA; + posB = next.toB; + } + } + } + /** + View [plugins](https://codemirror.net/6/docs/ref/#view.ViewPlugin) are given instances of this + class, which describe what happened, whenever the view is updated. + */ + class ViewUpdate { + constructor( + /** + The editor view that the update is associated with. + */ + view, + /** + The new editor state. + */ + state, + /** + The transactions involved in the update. May be empty. + */ + transactions) { + this.view = view; + this.state = state; + this.transactions = transactions; + /** + @internal + */ + this.flags = 0; + this.startState = view.state; + this.changes = ChangeSet.empty(this.startState.doc.length); + for (let tr of transactions) + this.changes = this.changes.compose(tr.changes); + let changedRanges = []; + this.changes.iterChangedRanges((fromA, toA, fromB, toB) => changedRanges.push(new ChangedRange(fromA, toA, fromB, toB))); + this.changedRanges = changedRanges; + let focus = view.hasFocus; + if (focus != view.inputState.notifiedFocused) { + view.inputState.notifiedFocused = focus; + this.flags |= 1 /* UpdateFlag.Focus */; + } + } + /** + @internal + */ + static create(view, state, transactions) { + return new ViewUpdate(view, state, transactions); + } + /** + Tells you whether the [viewport](https://codemirror.net/6/docs/ref/#view.EditorView.viewport) or + [visible ranges](https://codemirror.net/6/docs/ref/#view.EditorView.visibleRanges) changed in this + update. + */ + get viewportChanged() { + return (this.flags & 4 /* UpdateFlag.Viewport */) > 0; + } + /** + Indicates whether the height of a block element in the editor + changed in this update. + */ + get heightChanged() { + return (this.flags & 2 /* UpdateFlag.Height */) > 0; + } + /** + Returns true when the document was modified or the size of the + editor, or elements within the editor, changed. + */ + get geometryChanged() { + return this.docChanged || (this.flags & (8 /* UpdateFlag.Geometry */ | 2 /* UpdateFlag.Height */)) > 0; + } + /** + True when this update indicates a focus change. + */ + get focusChanged() { + return (this.flags & 1 /* UpdateFlag.Focus */) > 0; + } + /** + Whether the document changed in this update. + */ + get docChanged() { + return !this.changes.empty; + } + /** + Whether the selection was explicitly set in this update. + */ + get selectionSet() { + return this.transactions.some(tr => tr.selection); + } + /** + @internal + */ + get empty() { return this.flags == 0 && this.transactions.length == 0; } + } + + /** + Used to indicate [text direction](https://codemirror.net/6/docs/ref/#view.EditorView.textDirection). + */ + var Direction = /*@__PURE__*/(function (Direction) { + // (These are chosen to match the base levels, in bidi algorithm + // terms, of spans in that direction.) + /** + Left-to-right. + */ + Direction[Direction["LTR"] = 0] = "LTR"; + /** + Right-to-left. + */ + Direction[Direction["RTL"] = 1] = "RTL"; + return Direction})(Direction || (Direction = {})); + const LTR = Direction.LTR, RTL = Direction.RTL; + // Decode a string with each type encoded as log2(type) + function dec(str) { + let result = []; + for (let i = 0; i < str.length; i++) + result.push(1 << +str[i]); + return result; + } + // Character types for codepoints 0 to 0xf8 + const LowTypes = /*@__PURE__*/dec("88888888888888888888888888888888888666888888787833333333337888888000000000000000000000000008888880000000000000000000000000088888888888888888888888888888888888887866668888088888663380888308888800000000000000000000000800000000000000000000000000000008"); + // Character types for codepoints 0x600 to 0x6f9 + const ArabicTypes = /*@__PURE__*/dec("4444448826627288999999999992222222222222222222222222222222222222222222222229999999999999999999994444444444644222822222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222999999949999999229989999223333333333"); + const Brackets = /*@__PURE__*/Object.create(null), BracketStack = []; + // There's a lot more in + // https://www.unicode.org/Public/UCD/latest/ucd/BidiBrackets.txt, + // which are left out to keep code size down. + for (let p of ["()", "[]", "{}"]) { + let l = /*@__PURE__*/p.charCodeAt(0), r = /*@__PURE__*/p.charCodeAt(1); + Brackets[l] = r; + Brackets[r] = -l; + } + function charType(ch) { + return ch <= 0xf7 ? LowTypes[ch] : + 0x590 <= ch && ch <= 0x5f4 ? 2 /* T.R */ : + 0x600 <= ch && ch <= 0x6f9 ? ArabicTypes[ch - 0x600] : + 0x6ee <= ch && ch <= 0x8ac ? 4 /* T.AL */ : + 0x2000 <= ch && ch <= 0x200b ? 256 /* T.NI */ : + 0xfb50 <= ch && ch <= 0xfdff ? 4 /* T.AL */ : + ch == 0x200c ? 256 /* T.NI */ : 1 /* T.L */; + } + const BidiRE = /[\u0590-\u05f4\u0600-\u06ff\u0700-\u08ac\ufb50-\ufdff]/; + /** + Represents a contiguous range of text that has a single direction + (as in left-to-right or right-to-left). + */ + class BidiSpan { + /** + @internal + */ + constructor( + /** + The start of the span (relative to the start of the line). + */ + from, + /** + The end of the span. + */ + to, + /** + The ["bidi + level"](https://unicode.org/reports/tr9/#Basic_Display_Algorithm) + of the span (in this context, 0 means + left-to-right, 1 means right-to-left, 2 means left-to-right + number inside right-to-left text). + */ + level) { + this.from = from; + this.to = to; + this.level = level; + } + /** + The direction of this span. + */ + get dir() { return this.level % 2 ? RTL : LTR; } + /** + @internal + */ + side(end, dir) { return (this.dir == dir) == end ? this.to : this.from; } + /** + @internal + */ + static find(order, index, level, assoc) { + let maybe = -1; + for (let i = 0; i < order.length; i++) { + let span = order[i]; + if (span.from <= index && span.to >= index) { + if (span.level == level) + return i; + // When multiple spans match, if assoc != 0, take the one that + // covers that side, otherwise take the one with the minimum + // level. + if (maybe < 0 || (assoc != 0 ? (assoc < 0 ? span.from < index : span.to > index) : order[maybe].level > span.level)) + maybe = i; + } + } + if (maybe < 0) + throw new RangeError("Index out of range"); + return maybe; + } + } + // Reused array of character types + const types = []; + function computeOrder(line, direction) { + let len = line.length, outerType = direction == LTR ? 1 /* T.L */ : 2 /* T.R */, oppositeType = direction == LTR ? 2 /* T.R */ : 1 /* T.L */; + if (!line || outerType == 1 /* T.L */ && !BidiRE.test(line)) + return trivialOrder(len); + // 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. + // 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. + // (Left after this: L, R, EN, AN, ET, CS, NI) + for (let i = 0, prev = outerType, prevStrong = outerType; i < len; i++) { + let type = charType(line.charCodeAt(i)); + if (type == 512 /* T.NSM */) + type = prev; + else if (type == 8 /* T.EN */ && prevStrong == 4 /* T.AL */) + type = 16 /* T.AN */; + types[i] = type == 4 /* T.AL */ ? 2 /* T.R */ : type; + if (type & 7 /* T.Strong */) + prevStrong = type; + prev = type; + } + // W5. A sequence of European terminators adjacent to European + // numbers changes to all European numbers. + // W6. Otherwise, separators and terminators change to Other + // Neutral. + // 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. + // (Left after this: L, R, EN+AN, NI) + for (let i = 0, prev = outerType, prevStrong = outerType; i < len; i++) { + let type = types[i]; + if (type == 128 /* T.CS */) { + if (i < len - 1 && prev == types[i + 1] && (prev & 24 /* T.Num */)) + type = types[i] = prev; + else + types[i] = 256 /* T.NI */; + } + else if (type == 64 /* T.ET */) { + let end = i + 1; + while (end < len && types[end] == 64 /* T.ET */) + end++; + let replace = (i && prev == 8 /* T.EN */) || (end < len && types[end] == 8 /* T.EN */) ? (prevStrong == 1 /* T.L */ ? 1 /* T.L */ : 8 /* T.EN */) : 256 /* T.NI */; + for (let j = i; j < end; j++) + types[j] = replace; + i = end - 1; + } + else if (type == 8 /* T.EN */ && prevStrong == 1 /* T.L */) { + types[i] = 1 /* T.L */; + } + prev = type; + if (type & 7 /* T.Strong */) + prevStrong = type; + } + // N0. Process bracket pairs in an isolating run sequence + // sequentially in the logical order of the text positions of the + // opening paired brackets using the logic given below. Within this + // scope, bidirectional types EN and AN are treated as R. + for (let i = 0, sI = 0, context = 0, ch, br, type; i < len; i++) { + // Keeps [startIndex, type, strongSeen] triples for each open + // bracket on BracketStack. + if (br = Brackets[ch = line.charCodeAt(i)]) { + if (br < 0) { // Closing bracket + for (let sJ = sI - 3; sJ >= 0; sJ -= 3) { + if (BracketStack[sJ + 1] == -br) { + let flags = BracketStack[sJ + 2]; + let type = (flags & 2 /* Bracketed.EmbedInside */) ? outerType : + !(flags & 4 /* Bracketed.OppositeInside */) ? 0 : + (flags & 1 /* Bracketed.OppositeBefore */) ? oppositeType : outerType; + if (type) + types[i] = types[BracketStack[sJ]] = type; + sI = sJ; + break; + } + } + } + else if (BracketStack.length == 189 /* Bracketed.MaxDepth */) { + break; + } + else { + BracketStack[sI++] = i; + BracketStack[sI++] = ch; + BracketStack[sI++] = context; + } + } + else if ((type = types[i]) == 2 /* T.R */ || type == 1 /* T.L */) { + let embed = type == outerType; + context = embed ? 0 : 1 /* Bracketed.OppositeBefore */; + for (let sJ = sI - 3; sJ >= 0; sJ -= 3) { + let cur = BracketStack[sJ + 2]; + if (cur & 2 /* Bracketed.EmbedInside */) + break; + if (embed) { + BracketStack[sJ + 2] |= 2 /* Bracketed.EmbedInside */; + } + else { + if (cur & 4 /* Bracketed.OppositeInside */) + break; + BracketStack[sJ + 2] |= 4 /* Bracketed.OppositeInside */; + } + } + } + } + // 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. + // (Left after this: L, R, EN+AN) + for (let i = 0; i < len; i++) { + if (types[i] == 256 /* T.NI */) { + let end = i + 1; + while (end < len && types[end] == 256 /* T.NI */) + end++; + let beforeL = (i ? types[i - 1] : outerType) == 1 /* T.L */; + let afterL = (end < len ? types[end] : outerType) == 1 /* T.L */; + let replace = beforeL == afterL ? (beforeL ? 1 /* T.L */ : 2 /* T.R */) : outerType; + for (let j = i; j < end; j++) + types[j] = replace; + i = end - 1; + } + } + // Here we depart from the documented algorithm, in order to avoid + // building up an actual levels array. Since there are only three + // levels (0, 1, 2) in an implementation that doesn't take + // explicit embedding into account, we can build up the order on + // the fly, without following the level-based algorithm. + let order = []; + if (outerType == 1 /* T.L */) { + for (let i = 0; i < len;) { + let start = i, rtl = types[i++] != 1 /* T.L */; + while (i < len && rtl == (types[i] != 1 /* T.L */)) + i++; + if (rtl) { + for (let j = i; j > start;) { + let end = j, l = types[--j] != 2 /* T.R */; + while (j > start && l == (types[j - 1] != 2 /* T.R */)) + j--; + order.push(new BidiSpan(j, end, l ? 2 : 1)); + } + } + else { + order.push(new BidiSpan(start, i, 0)); + } + } + } + else { + for (let i = 0; i < len;) { + let start = i, rtl = types[i++] == 2 /* T.R */; + while (i < len && rtl == (types[i] == 2 /* T.R */)) + i++; + order.push(new BidiSpan(start, i, rtl ? 1 : 2)); + } + } + return order; + } + function trivialOrder(length) { + return [new BidiSpan(0, length, 0)]; + } + let movedOver = ""; + function moveVisually(line, order, dir, start, forward) { + var _a; + let startIndex = start.head - line.from, spanI = -1; + if (startIndex == 0) { + if (!forward || !line.length) + return null; + if (order[0].level != dir) { + startIndex = order[0].side(false, dir); + spanI = 0; + } + } + else if (startIndex == line.length) { + if (forward) + return null; + let last = order[order.length - 1]; + if (last.level != dir) { + startIndex = last.side(true, dir); + spanI = order.length - 1; + } + } + if (spanI < 0) + spanI = BidiSpan.find(order, startIndex, (_a = start.bidiLevel) !== null && _a !== void 0 ? _a : -1, start.assoc); + let span = order[spanI]; + // End of span. (But not end of line--that was checked for above.) + if (startIndex == span.side(forward, dir)) { + span = order[spanI += forward ? 1 : -1]; + startIndex = span.side(!forward, dir); + } + let indexForward = forward == (span.dir == dir); + let nextIndex = findClusterBreak(line.text, startIndex, indexForward); + movedOver = line.text.slice(Math.min(startIndex, nextIndex), Math.max(startIndex, nextIndex)); + if (nextIndex != span.side(forward, dir)) + return EditorSelection.cursor(nextIndex + line.from, indexForward ? -1 : 1, span.level); + let nextSpan = spanI == (forward ? order.length - 1 : 0) ? null : order[spanI + (forward ? 1 : -1)]; + if (!nextSpan && span.level != dir) + return EditorSelection.cursor(forward ? line.to : line.from, forward ? -1 : 1, dir); + if (nextSpan && nextSpan.level < span.level) + return EditorSelection.cursor(nextSpan.side(!forward, dir) + line.from, forward ? 1 : -1, nextSpan.level); + return EditorSelection.cursor(nextIndex + line.from, forward ? -1 : 1, span.level); + } + + const LineBreakPlaceholder = "\uffff"; + class DOMReader { + constructor(points, state) { + this.points = points; + this.text = ""; + this.lineSeparator = state.facet(EditorState.lineSeparator); + } + append(text) { + this.text += text; + } + lineBreak() { + this.text += LineBreakPlaceholder; + } + readRange(start, end) { + if (!start) + return this; + let parent = start.parentNode; + for (let cur = start;;) { + this.findPointBefore(parent, cur); + this.readNode(cur); + let next = cur.nextSibling; + if (next == end) + break; + let view = ContentView.get(cur), nextView = ContentView.get(next); + if (view && nextView ? view.breakAfter : + (view ? view.breakAfter : isBlockElement(cur)) || + (isBlockElement(next) && (cur.nodeName != "BR" || cur.cmIgnore))) + this.lineBreak(); + cur = next; + } + this.findPointBefore(parent, end); + return this; + } + readTextNode(node) { + let text = node.nodeValue; + for (let point of this.points) + if (point.node == node) + point.pos = this.text.length + Math.min(point.offset, text.length); + for (let off = 0, re = this.lineSeparator ? null : /\r\n?|\n/g;;) { + let nextBreak = -1, breakSize = 1, m; + if (this.lineSeparator) { + nextBreak = text.indexOf(this.lineSeparator, off); + breakSize = this.lineSeparator.length; + } + else if (m = re.exec(text)) { + nextBreak = m.index; + breakSize = m[0].length; + } + this.append(text.slice(off, nextBreak < 0 ? text.length : nextBreak)); + if (nextBreak < 0) + break; + this.lineBreak(); + if (breakSize > 1) + for (let point of this.points) + if (point.node == node && point.pos > this.text.length) + point.pos -= breakSize - 1; + off = nextBreak + breakSize; + } + } + readNode(node) { + if (node.cmIgnore) + return; + let view = ContentView.get(node); + let fromView = view && view.overrideDOMText; + if (fromView != null) { + this.findPointInside(node, fromView.length); + for (let i = fromView.iter(); !i.next().done;) { + if (i.lineBreak) + this.lineBreak(); + else + this.append(i.value); + } + } + else if (node.nodeType == 3) { + this.readTextNode(node); + } + else if (node.nodeName == "BR") { + if (node.nextSibling) + this.lineBreak(); + } + else if (node.nodeType == 1) { + this.readRange(node.firstChild, null); + } + } + findPointBefore(node, next) { + for (let point of this.points) + if (point.node == node && node.childNodes[point.offset] == next) + point.pos = this.text.length; + } + findPointInside(node, maxLen) { + for (let point of this.points) + if (node.nodeType == 3 ? point.node == node : node.contains(point.node)) + point.pos = this.text.length + Math.min(maxLen, point.offset); + } + } + function isBlockElement(node) { + return node.nodeType == 1 && /^(DIV|P|LI|UL|OL|BLOCKQUOTE|DD|DT|H\d|SECTION|PRE)$/.test(node.nodeName); + } + class DOMPoint { + constructor(node, offset) { + this.node = node; + this.offset = offset; + this.pos = -1; + } + } + + class DocView extends ContentView { + constructor(view) { + super(); + this.view = view; + this.compositionDeco = Decoration.none; + this.decorations = []; + this.dynamicDecorationMap = []; + // Track a minimum width for the editor. When measuring sizes in + // measureVisibleLineHeights, this is updated to point at the width + // of a given element and its extent in the document. When a change + // happens in that range, these are reset. That way, once we've seen + // a line/element of a given length, we keep the editor wide enough + // to fit at least that element, until it is changed, at which point + // we forget it again. + this.minWidth = 0; + this.minWidthFrom = 0; + this.minWidthTo = 0; + // Track whether the DOM selection was set in a lossy way, so that + // we don't mess it up when reading it back it + this.impreciseAnchor = null; + this.impreciseHead = null; + this.forceSelection = false; + // Used by the resize observer to ignore resizes that we caused + // ourselves + this.lastUpdate = Date.now(); + this.setDOM(view.contentDOM); + this.children = [new LineView]; + this.children[0].setParent(this); + this.updateDeco(); + this.updateInner([new ChangedRange(0, 0, 0, view.state.doc.length)], 0); + } + get editorView() { return this.view; } + get length() { return this.view.state.doc.length; } + // Update the document view to a given state. scrollIntoView can be + // used as a hint to compute a new viewport that includes that + // position, if we know the editor is going to scroll that position + // into view. + update(update) { + let changedRanges = update.changedRanges; + if (this.minWidth > 0 && changedRanges.length) { + if (!changedRanges.every(({ fromA, toA }) => toA < this.minWidthFrom || fromA > this.minWidthTo)) { + this.minWidth = this.minWidthFrom = this.minWidthTo = 0; + } + else { + this.minWidthFrom = update.changes.mapPos(this.minWidthFrom, 1); + this.minWidthTo = update.changes.mapPos(this.minWidthTo, 1); + } + } + if (this.view.inputState.composing < 0) + this.compositionDeco = Decoration.none; + else if (update.transactions.length || this.dirty) + this.compositionDeco = computeCompositionDeco(this.view, update.changes); + // When the DOM nodes around the selection are moved to another + // parent, Chrome sometimes reports a different selection through + // getSelection than the one that it actually shows to the user. + // This forces a selection update when lines are joined to work + // around that. Issue #54 + if ((browser.ie || browser.chrome) && !this.compositionDeco.size && update && + update.state.doc.lines != update.startState.doc.lines) + this.forceSelection = true; + let prevDeco = this.decorations, deco = this.updateDeco(); + let decoDiff = findChangedDeco(prevDeco, deco, update.changes); + changedRanges = ChangedRange.extendWithRanges(changedRanges, decoDiff); + if (this.dirty == 0 /* Dirty.Not */ && changedRanges.length == 0) { + return false; + } + else { + this.updateInner(changedRanges, update.startState.doc.length); + if (update.transactions.length) + this.lastUpdate = Date.now(); + return true; + } + } + // Used by update and the constructor do perform the actual DOM + // update + updateInner(changes, oldLength) { + this.view.viewState.mustMeasureContent = true; + this.updateChildren(changes, oldLength); + let { observer } = this.view; + observer.ignore(() => { + // Lock the height during redrawing, since Chrome sometimes + // messes with the scroll position during DOM mutation (though + // no relayout is triggered and I cannot imagine how it can + // recompute the scroll position without a layout) + this.dom.style.height = this.view.viewState.contentHeight + "px"; + this.dom.style.flexBasis = this.minWidth ? this.minWidth + "px" : ""; + // Chrome will sometimes, when DOM mutations occur directly + // around the selection, get confused and report a different + // selection from the one it displays (issue #218). This tries + // to detect that situation. + let track = browser.chrome || browser.ios ? { node: observer.selectionRange.focusNode, written: false } : undefined; + this.sync(track); + this.dirty = 0 /* Dirty.Not */; + if (track && (track.written || observer.selectionRange.focusNode != track.node)) + this.forceSelection = true; + this.dom.style.height = ""; + }); + let gaps = []; + if (this.view.viewport.from || this.view.viewport.to < this.view.state.doc.length) + for (let child of this.children) + if (child instanceof BlockWidgetView && child.widget instanceof BlockGapWidget) + gaps.push(child.dom); + observer.updateGaps(gaps); + } + updateChildren(changes, oldLength) { + let cursor = this.childCursor(oldLength); + for (let i = changes.length - 1;; i--) { + let next = i >= 0 ? changes[i] : null; + if (!next) + break; + let { fromA, toA, fromB, toB } = next; + let { content, breakAtStart, openStart, openEnd } = ContentBuilder.build(this.view.state.doc, fromB, toB, this.decorations, this.dynamicDecorationMap); + let { i: toI, off: toOff } = cursor.findPos(toA, 1); + let { i: fromI, off: fromOff } = cursor.findPos(fromA, -1); + replaceRange(this, fromI, fromOff, toI, toOff, content, breakAtStart, openStart, openEnd); + } + } + // Sync the DOM selection to this.state.selection + updateSelection(mustRead = false, fromPointer = false) { + if (mustRead || !this.view.observer.selectionRange.focusNode) + this.view.observer.readSelectionRange(); + if (!(fromPointer || this.mayControlSelection())) + return; + let force = this.forceSelection; + this.forceSelection = false; + let main = this.view.state.selection.main; + // FIXME need to handle the case where the selection falls inside a block range + let anchor = this.domAtPos(main.anchor); + let head = main.empty ? anchor : this.domAtPos(main.head); + // Always reset on Firefox when next to an uneditable node to + // avoid invisible cursor bugs (#111) + if (browser.gecko && main.empty && betweenUneditable(anchor)) { + let dummy = document.createTextNode(""); + this.view.observer.ignore(() => anchor.node.insertBefore(dummy, anchor.node.childNodes[anchor.offset] || null)); + anchor = head = new DOMPos(dummy, 0); + force = true; + } + let domSel = this.view.observer.selectionRange; + // If the selection is already here, or in an equivalent position, don't touch it + if (force || !domSel.focusNode || + !isEquivalentPosition(anchor.node, anchor.offset, domSel.anchorNode, domSel.anchorOffset) || + !isEquivalentPosition(head.node, head.offset, domSel.focusNode, domSel.focusOffset)) { + this.view.observer.ignore(() => { + // Chrome Android will hide the virtual keyboard when tapping + // inside an uneditable node, and not bring it back when we + // move the cursor to its proper position. This tries to + // restore the keyboard by cycling focus. + if (browser.android && browser.chrome && this.dom.contains(domSel.focusNode) && + inUneditable(domSel.focusNode, this.dom)) { + this.dom.blur(); + this.dom.focus({ preventScroll: true }); + } + let rawSel = getSelection(this.view.root); + if (!rawSel) ; + else if (main.empty) { + // Work around https://bugzilla.mozilla.org/show_bug.cgi?id=1612076 + if (browser.gecko) { + let nextTo = nextToUneditable(anchor.node, anchor.offset); + if (nextTo && nextTo != (1 /* NextTo.Before */ | 2 /* NextTo.After */)) { + let text = nearbyTextNode(anchor.node, anchor.offset, nextTo == 1 /* NextTo.Before */ ? 1 : -1); + if (text) + anchor = new DOMPos(text, nextTo == 1 /* NextTo.Before */ ? 0 : text.nodeValue.length); + } + } + rawSel.collapse(anchor.node, anchor.offset); + if (main.bidiLevel != null && domSel.cursorBidiLevel != null) + domSel.cursorBidiLevel = main.bidiLevel; + } + else if (rawSel.extend) { + // Selection.extend can be used to create an 'inverted' selection + // (one where the focus is before the anchor), but not all + // browsers support it yet. + rawSel.collapse(anchor.node, anchor.offset); + // Safari will ignore the call above when the editor is + // hidden, and then raise an error on the call to extend + // (#940). + try { + rawSel.extend(head.node, head.offset); + } + catch (_) { } + } + else { + // Primitive (IE) way + let range = document.createRange(); + if (main.anchor > main.head) + [anchor, head] = [head, anchor]; + range.setEnd(head.node, head.offset); + range.setStart(anchor.node, anchor.offset); + rawSel.removeAllRanges(); + rawSel.addRange(range); + } + }); + this.view.observer.setSelectionRange(anchor, head); + } + this.impreciseAnchor = anchor.precise ? null : new DOMPos(domSel.anchorNode, domSel.anchorOffset); + this.impreciseHead = head.precise ? null : new DOMPos(domSel.focusNode, domSel.focusOffset); + } + enforceCursorAssoc() { + if (this.compositionDeco.size) + return; + let cursor = this.view.state.selection.main; + let sel = getSelection(this.view.root); + if (!sel || !cursor.empty || !cursor.assoc || !sel.modify) + return; + let line = LineView.find(this, cursor.head); + if (!line) + return; + let lineStart = line.posAtStart; + if (cursor.head == lineStart || cursor.head == lineStart + line.length) + return; + let before = this.coordsAt(cursor.head, -1), after = this.coordsAt(cursor.head, 1); + if (!before || !after || before.bottom > after.top) + return; + let dom = this.domAtPos(cursor.head + cursor.assoc); + sel.collapse(dom.node, dom.offset); + sel.modify("move", cursor.assoc < 0 ? "forward" : "backward", "lineboundary"); + } + mayControlSelection() { + let active = this.view.root.activeElement; + return active == this.dom || + hasSelection(this.dom, this.view.observer.selectionRange) && !(active && this.dom.contains(active)); + } + nearest(dom) { + for (let cur = dom; cur;) { + let domView = ContentView.get(cur); + if (domView && domView.rootView == this) + return domView; + cur = cur.parentNode; + } + return null; + } + posFromDOM(node, offset) { + let view = this.nearest(node); + if (!view) + throw new RangeError("Trying to find position for a DOM position outside of the document"); + return view.localPosFromDOM(node, offset) + view.posAtStart; + } + domAtPos(pos) { + let { i, off } = this.childCursor().findPos(pos, -1); + for (; i < this.children.length - 1;) { + let child = this.children[i]; + if (off < child.length || child instanceof LineView) + break; + i++; + off = 0; + } + return this.children[i].domAtPos(off); + } + coordsAt(pos, side) { + for (let off = this.length, i = this.children.length - 1;; i--) { + let child = this.children[i], start = off - child.breakAfter - child.length; + if (pos > start || + (pos == start && child.type != BlockType.WidgetBefore && child.type != BlockType.WidgetAfter && + (!i || side == 2 || this.children[i - 1].breakAfter || + (this.children[i - 1].type == BlockType.WidgetBefore && side > -2)))) + return child.coordsAt(pos - start, side); + off = start; + } + } + measureVisibleLineHeights(viewport) { + let result = [], { from, to } = viewport; + let contentWidth = this.view.contentDOM.clientWidth; + let isWider = contentWidth > Math.max(this.view.scrollDOM.clientWidth, this.minWidth) + 1; + let widest = -1, ltr = this.view.textDirection == Direction.LTR; + for (let pos = 0, i = 0; i < this.children.length; i++) { + let child = this.children[i], end = pos + child.length; + if (end > to) + break; + if (pos >= from) { + let childRect = child.dom.getBoundingClientRect(); + result.push(childRect.height); + if (isWider) { + let last = child.dom.lastChild; + let rects = last ? clientRectsFor(last) : []; + if (rects.length) { + let rect = rects[rects.length - 1]; + let width = ltr ? rect.right - childRect.left : childRect.right - rect.left; + if (width > widest) { + widest = width; + this.minWidth = contentWidth; + this.minWidthFrom = pos; + this.minWidthTo = end; + } + } + } + } + pos = end + child.breakAfter; + } + return result; + } + textDirectionAt(pos) { + let { i } = this.childPos(pos, 1); + return getComputedStyle(this.children[i].dom).direction == "rtl" ? Direction.RTL : Direction.LTR; + } + measureTextSize() { + for (let child of this.children) { + if (child instanceof LineView) { + let measure = child.measureTextSize(); + if (measure) + return measure; + } + } + // If no workable line exists, force a layout of a measurable element + let dummy = document.createElement("div"), lineHeight, charWidth; + dummy.className = "cm-line"; + dummy.style.width = "99999px"; + dummy.textContent = "abc def ghi jkl mno pqr stu"; + this.view.observer.ignore(() => { + this.dom.appendChild(dummy); + let rect = clientRectsFor(dummy.firstChild)[0]; + lineHeight = dummy.getBoundingClientRect().height; + charWidth = rect ? rect.width / 27 : 7; + dummy.remove(); + }); + return { lineHeight, charWidth }; + } + childCursor(pos = this.length) { + // Move back to start of last element when possible, so that + // `ChildCursor.findPos` doesn't have to deal with the edge case + // of being after the last element. + let i = this.children.length; + if (i) + pos -= this.children[--i].length; + return new ChildCursor(this.children, pos, i); + } + computeBlockGapDeco() { + let deco = [], vs = this.view.viewState; + for (let pos = 0, i = 0;; i++) { + let next = i == vs.viewports.length ? null : vs.viewports[i]; + let end = next ? next.from - 1 : this.length; + if (end > pos) { + let height = vs.lineBlockAt(end).bottom - vs.lineBlockAt(pos).top; + deco.push(Decoration.replace({ + widget: new BlockGapWidget(height), + block: true, + inclusive: true, + isBlockGap: true, + }).range(pos, end)); + } + if (!next) + break; + pos = next.to + 1; + } + return Decoration.set(deco); + } + updateDeco() { + let allDeco = this.view.state.facet(decorations).map((d, i) => { + let dynamic = this.dynamicDecorationMap[i] = typeof d == "function"; + return dynamic ? d(this.view) : d; + }); + for (let i = allDeco.length; i < allDeco.length + 3; i++) + this.dynamicDecorationMap[i] = false; + return this.decorations = [ + ...allDeco, + this.compositionDeco, + this.computeBlockGapDeco(), + this.view.viewState.lineGapDeco + ]; + } + scrollIntoView(target) { + let { range } = target; + let rect = this.coordsAt(range.head, range.empty ? range.assoc : range.head > range.anchor ? -1 : 1), other; + if (!rect) + return; + if (!range.empty && (other = this.coordsAt(range.anchor, range.anchor > range.head ? -1 : 1))) + rect = { left: Math.min(rect.left, other.left), top: Math.min(rect.top, other.top), + right: Math.max(rect.right, other.right), bottom: Math.max(rect.bottom, other.bottom) }; + let mLeft = 0, mRight = 0, mTop = 0, mBottom = 0; + for (let margins of this.view.state.facet(scrollMargins).map(f => f(this.view))) + if (margins) { + let { left, right, top, bottom } = margins; + if (left != null) + mLeft = Math.max(mLeft, left); + if (right != null) + mRight = Math.max(mRight, right); + if (top != null) + mTop = Math.max(mTop, top); + if (bottom != null) + mBottom = Math.max(mBottom, bottom); + } + let targetRect = { + left: rect.left - mLeft, top: rect.top - mTop, + right: rect.right + mRight, bottom: rect.bottom + mBottom + }; + scrollRectIntoView(this.view.scrollDOM, targetRect, range.head < range.anchor ? -1 : 1, target.x, target.y, target.xMargin, target.yMargin, this.view.textDirection == Direction.LTR); + } + } + function betweenUneditable(pos) { + return pos.node.nodeType == 1 && pos.node.firstChild && + (pos.offset == 0 || pos.node.childNodes[pos.offset - 1].contentEditable == "false") && + (pos.offset == pos.node.childNodes.length || pos.node.childNodes[pos.offset].contentEditable == "false"); + } + class BlockGapWidget extends WidgetType { + constructor(height) { + super(); + this.height = height; + } + toDOM() { + let elt = document.createElement("div"); + this.updateDOM(elt); + return elt; + } + eq(other) { return other.height == this.height; } + updateDOM(elt) { + elt.style.height = this.height + "px"; + return true; + } + get estimatedHeight() { return this.height; } + } + function compositionSurroundingNode(view) { + let sel = view.observer.selectionRange; + let textNode = sel.focusNode && nearbyTextNode(sel.focusNode, sel.focusOffset, 0); + if (!textNode) + return null; + let cView = view.docView.nearest(textNode); + if (!cView) + return null; + if (cView instanceof LineView) { + let topNode = textNode; + while (topNode.parentNode != cView.dom) + topNode = topNode.parentNode; + let prev = topNode.previousSibling; + while (prev && !ContentView.get(prev)) + prev = prev.previousSibling; + let pos = prev ? ContentView.get(prev).posAtEnd : cView.posAtStart; + return { from: pos, to: pos, node: topNode, text: textNode }; + } + else { + for (;;) { + let { parent } = cView; + if (!parent) + return null; + if (parent instanceof LineView) + break; + cView = parent; + } + let from = cView.posAtStart; + return { from, to: from + cView.length, node: cView.dom, text: textNode }; + } + } + function computeCompositionDeco(view, changes) { + let surrounding = compositionSurroundingNode(view); + if (!surrounding) + return Decoration.none; + let { from, to, node, text: textNode } = surrounding; + let newFrom = changes.mapPos(from, 1), newTo = Math.max(newFrom, changes.mapPos(to, -1)); + let { state } = view, text = node.nodeType == 3 ? node.nodeValue : + new DOMReader([], state).readRange(node.firstChild, null).text; + if (newTo - newFrom < text.length) { + if (state.doc.sliceString(newFrom, Math.min(state.doc.length, newFrom + text.length), LineBreakPlaceholder) == text) + newTo = newFrom + text.length; + else if (state.doc.sliceString(Math.max(0, newTo - text.length), newTo, LineBreakPlaceholder) == text) + newFrom = newTo - text.length; + else + return Decoration.none; + } + else if (state.doc.sliceString(newFrom, newTo, LineBreakPlaceholder) != text) { + return Decoration.none; + } + let topView = ContentView.get(node); + if (topView instanceof CompositionView) + topView = topView.widget.topView; + else if (topView) + topView.parent = null; + return Decoration.set(Decoration.replace({ widget: new CompositionWidget(node, textNode, topView), inclusive: true }) + .range(newFrom, newTo)); + } + class CompositionWidget extends WidgetType { + constructor(top, text, topView) { + super(); + this.top = top; + this.text = text; + this.topView = topView; + } + eq(other) { return this.top == other.top && this.text == other.text; } + toDOM() { return this.top; } + ignoreEvent() { return false; } + get customView() { return CompositionView; } + } + function nearbyTextNode(node, offset, side) { + for (;;) { + if (node.nodeType == 3) + return node; + if (node.nodeType == 1 && offset > 0 && side <= 0) { + node = node.childNodes[offset - 1]; + offset = maxOffset(node); + } + else if (node.nodeType == 1 && offset < node.childNodes.length && side >= 0) { + node = node.childNodes[offset]; + offset = 0; + } + else { + return null; + } + } + } + function nextToUneditable(node, offset) { + if (node.nodeType != 1) + return 0; + return (offset && node.childNodes[offset - 1].contentEditable == "false" ? 1 /* NextTo.Before */ : 0) | + (offset < node.childNodes.length && node.childNodes[offset].contentEditable == "false" ? 2 /* NextTo.After */ : 0); + } + class DecorationComparator$1 { + constructor() { + this.changes = []; + } + compareRange(from, to) { addRange(from, to, this.changes); } + comparePoint(from, to) { addRange(from, to, this.changes); } + } + function findChangedDeco(a, b, diff) { + let comp = new DecorationComparator$1; + RangeSet.compare(a, b, diff, comp); + return comp.changes; + } + function inUneditable(node, inside) { + for (let cur = node; cur && cur != inside; cur = cur.assignedSlot || cur.parentNode) { + if (cur.nodeType == 1 && cur.contentEditable == 'false') { + return true; + } + } + return false; + } + + function groupAt(state, pos, bias = 1) { + let categorize = state.charCategorizer(pos); + let line = state.doc.lineAt(pos), linePos = pos - line.from; + if (line.length == 0) + return EditorSelection.cursor(pos); + if (linePos == 0) + bias = 1; + else if (linePos == line.length) + bias = -1; + let from = linePos, to = linePos; + if (bias < 0) + from = findClusterBreak(line.text, linePos, false); + else + to = findClusterBreak(line.text, linePos); + let cat = categorize(line.text.slice(from, to)); + while (from > 0) { + let prev = findClusterBreak(line.text, from, false); + if (categorize(line.text.slice(prev, from)) != cat) + break; + from = prev; + } + while (to < line.length) { + let next = findClusterBreak(line.text, to); + if (categorize(line.text.slice(to, next)) != cat) + break; + to = next; + } + return EditorSelection.range(from + line.from, to + line.from); + } + // Search the DOM for the {node, offset} position closest to the given + // coordinates. Very inefficient and crude, but can usually be avoided + // by calling caret(Position|Range)FromPoint instead. + function getdx(x, rect) { + return rect.left > x ? rect.left - x : Math.max(0, x - rect.right); + } + function getdy(y, rect) { + return rect.top > y ? rect.top - y : Math.max(0, y - rect.bottom); + } + function yOverlap(a, b) { + return a.top < b.bottom - 1 && a.bottom > b.top + 1; + } + function upTop(rect, top) { + return top < rect.top ? { top, left: rect.left, right: rect.right, bottom: rect.bottom } : rect; + } + function upBot(rect, bottom) { + return bottom > rect.bottom ? { top: rect.top, left: rect.left, right: rect.right, bottom } : rect; + } + function domPosAtCoords(parent, x, y) { + let closest, closestRect, closestX, closestY, closestOverlap = false; + let above, below, aboveRect, belowRect; + for (let child = parent.firstChild; child; child = child.nextSibling) { + let rects = clientRectsFor(child); + for (let i = 0; i < rects.length; i++) { + let rect = rects[i]; + if (closestRect && yOverlap(closestRect, rect)) + rect = upTop(upBot(rect, closestRect.bottom), closestRect.top); + let dx = getdx(x, rect), dy = getdy(y, rect); + if (dx == 0 && dy == 0) + return child.nodeType == 3 ? domPosInText(child, x, y) : domPosAtCoords(child, x, y); + if (!closest || closestY > dy || closestY == dy && closestX > dx) { + closest = child; + closestRect = rect; + closestX = dx; + closestY = dy; + closestOverlap = !dx || (dx > 0 ? i < rects.length - 1 : i > 0); + } + if (dx == 0) { + if (y > rect.bottom && (!aboveRect || aboveRect.bottom < rect.bottom)) { + above = child; + aboveRect = rect; + } + else if (y < rect.top && (!belowRect || belowRect.top > rect.top)) { + below = child; + belowRect = rect; + } + } + else if (aboveRect && yOverlap(aboveRect, rect)) { + aboveRect = upBot(aboveRect, rect.bottom); + } + else if (belowRect && yOverlap(belowRect, rect)) { + belowRect = upTop(belowRect, rect.top); + } + } + } + if (aboveRect && aboveRect.bottom >= y) { + closest = above; + closestRect = aboveRect; + } + else if (belowRect && belowRect.top <= y) { + closest = below; + closestRect = belowRect; + } + if (!closest) + return { node: parent, offset: 0 }; + let clipX = Math.max(closestRect.left, Math.min(closestRect.right, x)); + if (closest.nodeType == 3) + return domPosInText(closest, clipX, y); + if (closestOverlap && closest.contentEditable != "false") + return domPosAtCoords(closest, clipX, y); + let offset = Array.prototype.indexOf.call(parent.childNodes, closest) + + (x >= (closestRect.left + closestRect.right) / 2 ? 1 : 0); + return { node: parent, offset }; + } + function domPosInText(node, x, y) { + let len = node.nodeValue.length; + let closestOffset = -1, closestDY = 1e9, generalSide = 0; + for (let i = 0; i < len; i++) { + let rects = textRange(node, i, i + 1).getClientRects(); + for (let j = 0; j < rects.length; j++) { + let rect = rects[j]; + if (rect.top == rect.bottom) + continue; + if (!generalSide) + generalSide = x - rect.left; + let dy = (rect.top > y ? rect.top - y : y - rect.bottom) - 1; + if (rect.left - 1 <= x && rect.right + 1 >= x && dy < closestDY) { + let right = x >= (rect.left + rect.right) / 2, after = right; + if (browser.chrome || browser.gecko) { + // Check for RTL on browsers that support getting client + // rects for empty ranges. + let rectBefore = textRange(node, i).getBoundingClientRect(); + if (rectBefore.left == rect.right) + after = !right; + } + if (dy <= 0) + return { node, offset: i + (after ? 1 : 0) }; + closestOffset = i + (after ? 1 : 0); + closestDY = dy; + } + } + } + return { node, offset: closestOffset > -1 ? closestOffset : generalSide > 0 ? node.nodeValue.length : 0 }; + } + function posAtCoords(view, { x, y }, precise, bias = -1) { + var _a; + let content = view.contentDOM.getBoundingClientRect(), docTop = content.top + view.viewState.paddingTop; + let block, { docHeight } = view.viewState; + let yOffset = y - docTop; + if (yOffset < 0) + return 0; + if (yOffset > docHeight) + return view.state.doc.length; + // Scan for a text block near the queried y position + for (let halfLine = view.defaultLineHeight / 2, bounced = false;;) { + block = view.elementAtHeight(yOffset); + if (block.type == BlockType.Text) + break; + for (;;) { + // Move the y position out of this block + yOffset = bias > 0 ? block.bottom + halfLine : block.top - halfLine; + if (yOffset >= 0 && yOffset <= docHeight) + break; + // If the document consists entirely of replaced widgets, we + // won't find a text block, so return 0 + if (bounced) + return precise ? null : 0; + bounced = true; + bias = -bias; + } + } + y = docTop + yOffset; + let lineStart = block.from; + // If this is outside of the rendered viewport, we can't determine a position + if (lineStart < view.viewport.from) + return view.viewport.from == 0 ? 0 : precise ? null : posAtCoordsImprecise(view, content, block, x, y); + if (lineStart > view.viewport.to) + return view.viewport.to == view.state.doc.length ? view.state.doc.length : + precise ? null : posAtCoordsImprecise(view, content, block, x, y); + // Prefer ShadowRootOrDocument.elementFromPoint if present, fall back to document if not + let doc = view.dom.ownerDocument; + let root = view.root.elementFromPoint ? view.root : doc; + let element = root.elementFromPoint(x, y); + if (element && !view.contentDOM.contains(element)) + element = null; + // If the element is unexpected, clip x at the sides of the content area and try again + if (!element) { + x = Math.max(content.left + 1, Math.min(content.right - 1, x)); + element = root.elementFromPoint(x, y); + if (element && !view.contentDOM.contains(element)) + element = null; + } + // There's visible editor content under the point, so we can try + // using caret(Position|Range)FromPoint as a shortcut + let node, offset = -1; + if (element && ((_a = view.docView.nearest(element)) === null || _a === void 0 ? void 0 : _a.isEditable) != false) { + if (doc.caretPositionFromPoint) { + let pos = doc.caretPositionFromPoint(x, y); + if (pos) + ({ offsetNode: node, offset } = pos); + } + else if (doc.caretRangeFromPoint) { + let range = doc.caretRangeFromPoint(x, y); + if (range) { + ({ startContainer: node, startOffset: offset } = range); + if (!view.contentDOM.contains(node) || + browser.safari && isSuspiciousSafariCaretResult(node, offset, x) || + browser.chrome && isSuspiciousChromeCaretResult(node, offset, x)) + node = undefined; + } + } + } + // No luck, do our own (potentially expensive) search + if (!node || !view.docView.dom.contains(node)) { + let line = LineView.find(view.docView, lineStart); + if (!line) + return yOffset > block.top + block.height / 2 ? block.to : block.from; + ({ node, offset } = domPosAtCoords(line.dom, x, y)); + } + return view.docView.posFromDOM(node, offset); + } + function posAtCoordsImprecise(view, contentRect, block, x, y) { + let into = Math.round((x - contentRect.left) * view.defaultCharacterWidth); + if (view.lineWrapping && block.height > view.defaultLineHeight * 1.5) { + let line = Math.floor((y - block.top) / view.defaultLineHeight); + into += line * view.viewState.heightOracle.lineLength; + } + let content = view.state.sliceDoc(block.from, block.to); + return block.from + findColumn(content, into, view.state.tabSize); + } + // In case of a high line height, Safari's caretRangeFromPoint treats + // the space between lines as belonging to the last character of the + // line before. This is used to detect such a result so that it can be + // ignored (issue #401). + function isSuspiciousSafariCaretResult(node, offset, x) { + let len; + if (node.nodeType != 3 || offset != (len = node.nodeValue.length)) + return false; + for (let next = node.nextSibling; next; next = next.nextSibling) + if (next.nodeType != 1 || next.nodeName != "BR") + return false; + return textRange(node, len - 1, len).getBoundingClientRect().left > x; + } + // Chrome will move positions between lines to the start of the next line + function isSuspiciousChromeCaretResult(node, offset, x) { + if (offset != 0) + return false; + for (let cur = node;;) { + let parent = cur.parentNode; + if (!parent || parent.nodeType != 1 || parent.firstChild != cur) + return false; + if (parent.classList.contains("cm-line")) + break; + cur = parent; + } + let rect = node.nodeType == 1 ? node.getBoundingClientRect() + : textRange(node, 0, Math.max(node.nodeValue.length, 1)).getBoundingClientRect(); + return x - rect.left > 5; + } + function moveToLineBoundary(view, start, forward, includeWrap) { + let line = view.state.doc.lineAt(start.head); + let coords = !includeWrap || !view.lineWrapping ? null + : view.coordsAtPos(start.assoc < 0 && start.head > line.from ? start.head - 1 : start.head); + if (coords) { + let editorRect = view.dom.getBoundingClientRect(); + let direction = view.textDirectionAt(line.from); + let pos = view.posAtCoords({ x: forward == (direction == Direction.LTR) ? editorRect.right - 1 : editorRect.left + 1, + y: (coords.top + coords.bottom) / 2 }); + if (pos != null) + return EditorSelection.cursor(pos, forward ? -1 : 1); + } + let lineView = LineView.find(view.docView, start.head); + let end = lineView ? (forward ? lineView.posAtEnd : lineView.posAtStart) : (forward ? line.to : line.from); + return EditorSelection.cursor(end, forward ? -1 : 1); + } + function moveByChar(view, start, forward, by) { + let line = view.state.doc.lineAt(start.head), spans = view.bidiSpans(line); + let direction = view.textDirectionAt(line.from); + for (let cur = start, check = null;;) { + let next = moveVisually(line, spans, direction, cur, forward), char = movedOver; + if (!next) { + if (line.number == (forward ? view.state.doc.lines : 1)) + return cur; + char = "\n"; + line = view.state.doc.line(line.number + (forward ? 1 : -1)); + spans = view.bidiSpans(line); + next = EditorSelection.cursor(forward ? line.from : line.to); + } + if (!check) { + if (!by) + return next; + check = by(char); + } + else if (!check(char)) { + return cur; + } + cur = next; + } + } + function byGroup(view, pos, start) { + let categorize = view.state.charCategorizer(pos); + let cat = categorize(start); + return (next) => { + let nextCat = categorize(next); + if (cat == CharCategory.Space) + cat = nextCat; + return cat == nextCat; + }; + } + function moveVertically(view, start, forward, distance) { + let startPos = start.head, dir = forward ? 1 : -1; + if (startPos == (forward ? view.state.doc.length : 0)) + return EditorSelection.cursor(startPos, start.assoc); + let goal = start.goalColumn, startY; + let rect = view.contentDOM.getBoundingClientRect(); + let startCoords = view.coordsAtPos(startPos), docTop = view.documentTop; + if (startCoords) { + if (goal == null) + goal = startCoords.left - rect.left; + startY = dir < 0 ? startCoords.top : startCoords.bottom; + } + else { + let line = view.viewState.lineBlockAt(startPos); + if (goal == null) + goal = Math.min(rect.right - rect.left, view.defaultCharacterWidth * (startPos - line.from)); + startY = (dir < 0 ? line.top : line.bottom) + docTop; + } + let resolvedGoal = rect.left + goal; + let dist = distance !== null && distance !== void 0 ? distance : (view.defaultLineHeight >> 1); + for (let extra = 0;; extra += 10) { + let curY = startY + (dist + extra) * dir; + let pos = posAtCoords(view, { x: resolvedGoal, y: curY }, false, dir); + if (curY < rect.top || curY > rect.bottom || (dir < 0 ? pos < startPos : pos > startPos)) + return EditorSelection.cursor(pos, start.assoc, undefined, goal); + } + } + function skipAtoms(view, oldPos, pos) { + let atoms = view.state.facet(atomicRanges).map(f => f(view)); + for (;;) { + let moved = false; + for (let set of atoms) { + set.between(pos.from - 1, pos.from + 1, (from, to, value) => { + if (pos.from > from && pos.from < to) { + pos = oldPos.head > pos.from ? EditorSelection.cursor(from, 1) : EditorSelection.cursor(to, -1); + moved = true; + } + }); + } + if (!moved) + return pos; + } + } + + // This will also be where dragging info and such goes + class InputState { + constructor(view) { + this.lastKeyCode = 0; + this.lastKeyTime = 0; + this.lastTouchTime = 0; + this.lastFocusTime = 0; + this.lastScrollTop = 0; + this.lastScrollLeft = 0; + this.chromeScrollHack = -1; + // On iOS, some keys need to have their default behavior happen + // (after which we retroactively handle them and reset the DOM) to + // avoid messing up the virtual keyboard state. + this.pendingIOSKey = undefined; + this.lastSelectionOrigin = null; + this.lastSelectionTime = 0; + this.lastEscPress = 0; + this.lastContextMenu = 0; + this.scrollHandlers = []; + this.registeredEvents = []; + this.customHandlers = []; + // -1 means not in a composition. Otherwise, this counts the number + // of changes made during the composition. The count is used to + // avoid treating the start state of the composition, before any + // changes have been made, as part of the composition. + this.composing = -1; + // Tracks whether the next change should be marked as starting the + // composition (null means no composition, true means next is the + // first, false means first has already been marked for this + // composition) + this.compositionFirstChange = null; + this.compositionEndedAt = 0; + this.mouseSelection = null; + for (let type in handlers) { + let handler = handlers[type]; + view.contentDOM.addEventListener(type, (event) => { + if (!eventBelongsToEditor(view, event) || this.ignoreDuringComposition(event)) + return; + if (type == "keydown" && this.keydown(view, event)) + return; + if (this.mustFlushObserver(event)) + view.observer.forceFlush(); + if (this.runCustomHandlers(type, view, event)) + event.preventDefault(); + else + handler(view, event); + }, handlerOptions[type]); + this.registeredEvents.push(type); + } + if (browser.chrome && browser.chrome_version == 102) { // FIXME remove at some point + // On Chrome 102, viewport updates somehow stop wheel-based + // scrolling. Turning off pointer events during the scroll seems + // to avoid the issue. + view.scrollDOM.addEventListener("wheel", () => { + if (this.chromeScrollHack < 0) + view.contentDOM.style.pointerEvents = "none"; + else + window.clearTimeout(this.chromeScrollHack); + this.chromeScrollHack = setTimeout(() => { + this.chromeScrollHack = -1; + view.contentDOM.style.pointerEvents = ""; + }, 100); + }, { passive: true }); + } + this.notifiedFocused = view.hasFocus; + // On Safari adding an input event handler somehow prevents an + // issue where the composition vanishes when you press enter. + if (browser.safari) + view.contentDOM.addEventListener("input", () => null); + } + setSelectionOrigin(origin) { + this.lastSelectionOrigin = origin; + this.lastSelectionTime = Date.now(); + } + ensureHandlers(view, plugins) { + var _a; + let handlers; + this.customHandlers = []; + for (let plugin of plugins) + if (handlers = (_a = plugin.update(view).spec) === null || _a === void 0 ? void 0 : _a.domEventHandlers) { + this.customHandlers.push({ plugin: plugin.value, handlers }); + for (let type in handlers) + if (this.registeredEvents.indexOf(type) < 0 && type != "scroll") { + this.registeredEvents.push(type); + view.contentDOM.addEventListener(type, (event) => { + if (!eventBelongsToEditor(view, event)) + return; + if (this.runCustomHandlers(type, view, event)) + event.preventDefault(); + }); + } + } + } + runCustomHandlers(type, view, event) { + for (let set of this.customHandlers) { + let handler = set.handlers[type]; + if (handler) { + try { + if (handler.call(set.plugin, event, view) || event.defaultPrevented) + return true; + } + catch (e) { + logException(view.state, e); + } + } + } + return false; + } + runScrollHandlers(view, event) { + this.lastScrollTop = view.scrollDOM.scrollTop; + this.lastScrollLeft = view.scrollDOM.scrollLeft; + for (let set of this.customHandlers) { + let handler = set.handlers.scroll; + if (handler) { + try { + handler.call(set.plugin, event, view); + } + catch (e) { + logException(view.state, e); + } + } + } + } + keydown(view, event) { + // Must always run, even if a custom handler handled the event + this.lastKeyCode = event.keyCode; + this.lastKeyTime = Date.now(); + if (event.keyCode == 9 && Date.now() < this.lastEscPress + 2000) + return true; + // Chrome for Android usually doesn't fire proper key events, but + // occasionally does, usually surrounded by a bunch of complicated + // composition changes. When an enter or backspace key event is + // seen, hold off on handling DOM events for a bit, and then + // dispatch it. + if (browser.android && browser.chrome && !event.synthetic && + (event.keyCode == 13 || event.keyCode == 8)) { + view.observer.delayAndroidKey(event.key, event.keyCode); + return true; + } + // Prevent the default behavior of Enter on iOS makes the + // virtual keyboard get stuck in the wrong (lowercase) + // state. So we let it go through, and then, in + // applyDOMChange, notify key handlers of it and reset to + // the state they produce. + let pending; + if (browser.ios && !event.synthetic && !event.altKey && !event.metaKey && + ((pending = PendingKeys.find(key => key.keyCode == event.keyCode)) && !event.ctrlKey || + EmacsyPendingKeys.indexOf(event.key) > -1 && event.ctrlKey && !event.shiftKey)) { + this.pendingIOSKey = pending || event; + setTimeout(() => this.flushIOSKey(view), 250); + return true; + } + return false; + } + flushIOSKey(view) { + let key = this.pendingIOSKey; + if (!key) + return false; + this.pendingIOSKey = undefined; + return dispatchKey(view.contentDOM, key.key, key.keyCode); + } + ignoreDuringComposition(event) { + if (!/^key/.test(event.type)) + return false; + if (this.composing > 0) + return true; + // See https://www.stum.de/2016/06/24/handling-ime-events-in-javascript/. + // On some input method editors (IMEs), the Enter key is used to + // confirm character selection. On Safari, when Enter is pressed, + // compositionend and keydown events are sometimes emitted in the + // wrong order. The key event should still be ignored, even when + // it happens after the compositionend event. + if (browser.safari && !browser.ios && Date.now() - this.compositionEndedAt < 100) { + this.compositionEndedAt = 0; + return true; + } + return false; + } + mustFlushObserver(event) { + return event.type == "keydown" && event.keyCode != 229; + } + startMouseSelection(mouseSelection) { + if (this.mouseSelection) + this.mouseSelection.destroy(); + this.mouseSelection = mouseSelection; + } + update(update) { + if (this.mouseSelection) + this.mouseSelection.update(update); + if (update.transactions.length) + this.lastKeyCode = this.lastSelectionTime = 0; + } + destroy() { + if (this.mouseSelection) + this.mouseSelection.destroy(); + } + } + const PendingKeys = [ + { key: "Backspace", keyCode: 8, inputType: "deleteContentBackward" }, + { key: "Enter", keyCode: 13, inputType: "insertParagraph" }, + { key: "Delete", keyCode: 46, inputType: "deleteContentForward" } + ]; + const EmacsyPendingKeys = "dthko"; + // Key codes for modifier keys + const modifierCodes = [16, 17, 18, 20, 91, 92, 224, 225]; + class MouseSelection { + constructor(view, startEvent, style, mustSelect) { + this.view = view; + this.style = style; + this.mustSelect = mustSelect; + this.lastEvent = startEvent; + let doc = view.contentDOM.ownerDocument; + doc.addEventListener("mousemove", this.move = this.move.bind(this)); + doc.addEventListener("mouseup", this.up = this.up.bind(this)); + this.extend = startEvent.shiftKey; + this.multiple = view.state.facet(EditorState.allowMultipleSelections) && addsSelectionRange(view, startEvent); + this.dragMove = dragMovesSelection(view, startEvent); + this.dragging = isInPrimarySelection(view, startEvent) && getClickType(startEvent) == 1 ? null : false; + // When clicking outside of the selection, immediately apply the + // effect of starting the selection + if (this.dragging === false) { + startEvent.preventDefault(); + this.select(startEvent); + } + } + move(event) { + if (event.buttons == 0) + return this.destroy(); + if (this.dragging !== false) + return; + this.select(this.lastEvent = event); + } + up(event) { + if (this.dragging == null) + this.select(this.lastEvent); + if (!this.dragging) + event.preventDefault(); + this.destroy(); + } + destroy() { + let doc = this.view.contentDOM.ownerDocument; + doc.removeEventListener("mousemove", this.move); + doc.removeEventListener("mouseup", this.up); + this.view.inputState.mouseSelection = null; + } + select(event) { + let selection = this.style.get(event, this.extend, this.multiple); + if (this.mustSelect || !selection.eq(this.view.state.selection) || + selection.main.assoc != this.view.state.selection.main.assoc) + this.view.dispatch({ + selection, + userEvent: "select.pointer", + scrollIntoView: true + }); + this.mustSelect = false; + } + update(update) { + if (update.docChanged && this.dragging) + this.dragging = this.dragging.map(update.changes); + if (this.style.update(update)) + setTimeout(() => this.select(this.lastEvent), 20); + } + } + function addsSelectionRange(view, event) { + let facet = view.state.facet(clickAddsSelectionRange); + return facet.length ? facet[0](event) : browser.mac ? event.metaKey : event.ctrlKey; + } + function dragMovesSelection(view, event) { + let facet = view.state.facet(dragMovesSelection$1); + return facet.length ? facet[0](event) : browser.mac ? !event.altKey : !event.ctrlKey; + } + function isInPrimarySelection(view, event) { + let { main } = view.state.selection; + if (main.empty) + return false; + // On boundary clicks, check whether the coordinates are inside the + // selection's client rectangles + let sel = getSelection(view.root); + if (!sel || sel.rangeCount == 0) + return true; + let rects = sel.getRangeAt(0).getClientRects(); + for (let i = 0; i < rects.length; i++) { + let rect = rects[i]; + if (rect.left <= event.clientX && rect.right >= event.clientX && + rect.top <= event.clientY && rect.bottom >= event.clientY) + return true; + } + return false; + } + function eventBelongsToEditor(view, event) { + if (!event.bubbles) + return true; + if (event.defaultPrevented) + return false; + for (let node = event.target, cView; node != view.contentDOM; node = node.parentNode) + if (!node || node.nodeType == 11 || ((cView = ContentView.get(node)) && cView.ignoreEvent(event))) + return false; + return true; + } + const handlers = /*@__PURE__*/Object.create(null); + const handlerOptions = /*@__PURE__*/Object.create(null); + // This is very crude, but unfortunately both these browsers _pretend_ + // that they have a clipboard API—all the objects and methods are + // there, they just don't work, and they are hard to test. + const brokenClipboardAPI = (browser.ie && browser.ie_version < 15) || + (browser.ios && browser.webkit_version < 604); + function capturePaste(view) { + let parent = view.dom.parentNode; + if (!parent) + return; + let target = parent.appendChild(document.createElement("textarea")); + target.style.cssText = "position: fixed; left: -10000px; top: 10px"; + target.focus(); + setTimeout(() => { + view.focus(); + target.remove(); + doPaste(view, target.value); + }, 50); + } + function doPaste(view, input) { + let { state } = view, changes, i = 1, text = state.toText(input); + let byLine = text.lines == state.selection.ranges.length; + let linewise = lastLinewiseCopy != null && state.selection.ranges.every(r => r.empty) && lastLinewiseCopy == text.toString(); + if (linewise) { + let lastLine = -1; + changes = state.changeByRange(range => { + let line = state.doc.lineAt(range.from); + if (line.from == lastLine) + return { range }; + lastLine = line.from; + let insert = state.toText((byLine ? text.line(i++).text : input) + state.lineBreak); + return { changes: { from: line.from, insert }, + range: EditorSelection.cursor(range.from + insert.length) }; + }); + } + else if (byLine) { + changes = state.changeByRange(range => { + let line = text.line(i++); + return { changes: { from: range.from, to: range.to, insert: line.text }, + range: EditorSelection.cursor(range.from + line.length) }; + }); + } + else { + changes = state.replaceSelection(text); + } + view.dispatch(changes, { + userEvent: "input.paste", + scrollIntoView: true + }); + } + handlers.keydown = (view, event) => { + view.inputState.setSelectionOrigin("select"); + if (event.keyCode == 27) + view.inputState.lastEscPress = Date.now(); + else if (modifierCodes.indexOf(event.keyCode) < 0) + view.inputState.lastEscPress = 0; + }; + handlers.touchstart = (view, e) => { + view.inputState.lastTouchTime = Date.now(); + view.inputState.setSelectionOrigin("select.pointer"); + }; + handlers.touchmove = view => { + view.inputState.setSelectionOrigin("select.pointer"); + }; + handlerOptions.touchstart = handlerOptions.touchmove = { passive: true }; + handlers.mousedown = (view, event) => { + view.observer.flush(); + if (view.inputState.lastTouchTime > Date.now() - 2000) + return; // Ignore touch interaction + let style = null; + for (let makeStyle of view.state.facet(mouseSelectionStyle)) { + style = makeStyle(view, event); + if (style) + break; + } + if (!style && event.button == 0) + style = basicMouseSelection(view, event); + if (style) { + let mustFocus = view.root.activeElement != view.contentDOM; + if (mustFocus) + view.observer.ignore(() => focusPreventScroll(view.contentDOM)); + view.inputState.startMouseSelection(new MouseSelection(view, event, style, mustFocus)); + } + }; + function rangeForClick(view, pos, bias, type) { + if (type == 1) { // Single click + return EditorSelection.cursor(pos, bias); + } + else if (type == 2) { // Double click + return groupAt(view.state, pos, bias); + } + else { // Triple click + let visual = LineView.find(view.docView, pos), line = view.state.doc.lineAt(visual ? visual.posAtEnd : pos); + let from = visual ? visual.posAtStart : line.from, to = visual ? visual.posAtEnd : line.to; + if (to < view.state.doc.length && to == line.to) + to++; + return EditorSelection.range(from, to); + } + } + let insideY = (y, rect) => y >= rect.top && y <= rect.bottom; + let inside = (x, y, rect) => insideY(y, rect) && x >= rect.left && x <= rect.right; + // Try to determine, for the given coordinates, associated with the + // given position, whether they are related to the element before or + // the element after the position. + function findPositionSide(view, pos, x, y) { + let line = LineView.find(view.docView, pos); + if (!line) + return 1; + let off = pos - line.posAtStart; + // Line boundaries point into the line + if (off == 0) + return 1; + if (off == line.length) + return -1; + // Positions on top of an element point at that element + let before = line.coordsAt(off, -1); + if (before && inside(x, y, before)) + return -1; + let after = line.coordsAt(off, 1); + if (after && inside(x, y, after)) + return 1; + // This is probably a line wrap point. Pick before if the point is + // beside it. + return before && insideY(y, before) ? -1 : 1; + } + function queryPos(view, event) { + let pos = view.posAtCoords({ x: event.clientX, y: event.clientY }, false); + return { pos, bias: findPositionSide(view, pos, event.clientX, event.clientY) }; + } + const BadMouseDetail = browser.ie && browser.ie_version <= 11; + let lastMouseDown = null, lastMouseDownCount = 0, lastMouseDownTime = 0; + function getClickType(event) { + if (!BadMouseDetail) + return event.detail; + let last = lastMouseDown, lastTime = lastMouseDownTime; + lastMouseDown = event; + lastMouseDownTime = Date.now(); + return lastMouseDownCount = !last || (lastTime > Date.now() - 400 && Math.abs(last.clientX - event.clientX) < 2 && + Math.abs(last.clientY - event.clientY) < 2) ? (lastMouseDownCount + 1) % 3 : 1; + } + function basicMouseSelection(view, event) { + let start = queryPos(view, event), type = getClickType(event); + let startSel = view.state.selection; + let last = start, lastEvent = event; + return { + update(update) { + if (update.docChanged) { + start.pos = update.changes.mapPos(start.pos); + startSel = startSel.map(update.changes); + lastEvent = null; + } + }, + get(event, extend, multiple) { + let cur; + if (lastEvent && event.clientX == lastEvent.clientX && event.clientY == lastEvent.clientY) + cur = last; + else { + cur = last = queryPos(view, event); + lastEvent = event; + } + let range = rangeForClick(view, cur.pos, cur.bias, type); + if (start.pos != cur.pos && !extend) { + let startRange = rangeForClick(view, start.pos, start.bias, type); + let from = Math.min(startRange.from, range.from), to = Math.max(startRange.to, range.to); + range = from < range.from ? EditorSelection.range(from, to) : EditorSelection.range(to, from); + } + if (extend) + return startSel.replaceRange(startSel.main.extend(range.from, range.to)); + else if (multiple && startSel.ranges.length > 1 && startSel.ranges.some(r => r.eq(range))) + return removeRange(startSel, range); + else if (multiple) + return startSel.addRange(range); + else + return EditorSelection.create([range]); + } + }; + } + function removeRange(sel, range) { + for (let i = 0;; i++) { + if (sel.ranges[i].eq(range)) + return EditorSelection.create(sel.ranges.slice(0, i).concat(sel.ranges.slice(i + 1)), sel.mainIndex == i ? 0 : sel.mainIndex - (sel.mainIndex > i ? 1 : 0)); + } + } + handlers.dragstart = (view, event) => { + let { selection: { main } } = view.state; + let { mouseSelection } = view.inputState; + if (mouseSelection) + mouseSelection.dragging = main; + if (event.dataTransfer) { + event.dataTransfer.setData("Text", view.state.sliceDoc(main.from, main.to)); + event.dataTransfer.effectAllowed = "copyMove"; + } + }; + function dropText(view, event, text, direct) { + if (!text) + return; + let dropPos = view.posAtCoords({ x: event.clientX, y: event.clientY }, false); + event.preventDefault(); + let { mouseSelection } = view.inputState; + let del = direct && mouseSelection && mouseSelection.dragging && mouseSelection.dragMove ? + { from: mouseSelection.dragging.from, to: mouseSelection.dragging.to } : null; + let ins = { from: dropPos, insert: text }; + let changes = view.state.changes(del ? [del, ins] : ins); + view.focus(); + view.dispatch({ + changes, + selection: { anchor: changes.mapPos(dropPos, -1), head: changes.mapPos(dropPos, 1) }, + userEvent: del ? "move.drop" : "input.drop" + }); + } + handlers.drop = (view, event) => { + if (!event.dataTransfer) + return; + if (view.state.readOnly) + return event.preventDefault(); + let files = event.dataTransfer.files; + if (files && files.length) { // For a file drop, read the file's text. + event.preventDefault(); + let text = Array(files.length), read = 0; + let finishFile = () => { + if (++read == files.length) + dropText(view, event, text.filter(s => s != null).join(view.state.lineBreak), false); + }; + for (let i = 0; i < files.length; i++) { + let reader = new FileReader; + reader.onerror = finishFile; + reader.onload = () => { + if (!/[\x00-\x08\x0e-\x1f]{2}/.test(reader.result)) + text[i] = reader.result; + finishFile(); + }; + reader.readAsText(files[i]); + } + } + else { + dropText(view, event, event.dataTransfer.getData("Text"), true); + } + }; + handlers.paste = (view, event) => { + if (view.state.readOnly) + return event.preventDefault(); + view.observer.flush(); + let data = brokenClipboardAPI ? null : event.clipboardData; + if (data) { + doPaste(view, data.getData("text/plain")); + event.preventDefault(); + } + else { + capturePaste(view); + } + }; + function captureCopy(view, text) { + // The extra wrapper is somehow necessary on IE/Edge to prevent the + // content from being mangled when it is put onto the clipboard + let parent = view.dom.parentNode; + if (!parent) + return; + let target = parent.appendChild(document.createElement("textarea")); + target.style.cssText = "position: fixed; left: -10000px; top: 10px"; + target.value = text; + target.focus(); + target.selectionEnd = text.length; + target.selectionStart = 0; + setTimeout(() => { + target.remove(); + view.focus(); + }, 50); + } + function copiedRange(state) { + let content = [], ranges = [], linewise = false; + for (let range of state.selection.ranges) + if (!range.empty) { + content.push(state.sliceDoc(range.from, range.to)); + ranges.push(range); + } + if (!content.length) { + // Nothing selected, do a line-wise copy + let upto = -1; + for (let { from } of state.selection.ranges) { + let line = state.doc.lineAt(from); + if (line.number > upto) { + content.push(line.text); + ranges.push({ from: line.from, to: Math.min(state.doc.length, line.to + 1) }); + } + upto = line.number; + } + linewise = true; + } + return { text: content.join(state.lineBreak), ranges, linewise }; + } + let lastLinewiseCopy = null; + handlers.copy = handlers.cut = (view, event) => { + let { text, ranges, linewise } = copiedRange(view.state); + if (!text && !linewise) + return; + lastLinewiseCopy = linewise ? text : null; + let data = brokenClipboardAPI ? null : event.clipboardData; + if (data) { + event.preventDefault(); + data.clearData(); + data.setData("text/plain", text); + } + else { + captureCopy(view, text); + } + if (event.type == "cut" && !view.state.readOnly) + view.dispatch({ + changes: ranges, + scrollIntoView: true, + userEvent: "delete.cut" + }); + }; + function updateForFocusChange(view) { + setTimeout(() => { + if (view.hasFocus != view.inputState.notifiedFocused) + view.update([]); + }, 10); + } + handlers.focus = view => { + view.inputState.lastFocusTime = Date.now(); + // When focusing reset the scroll position, move it back to where it was + if (!view.scrollDOM.scrollTop && (view.inputState.lastScrollTop || view.inputState.lastScrollLeft)) { + view.scrollDOM.scrollTop = view.inputState.lastScrollTop; + view.scrollDOM.scrollLeft = view.inputState.lastScrollLeft; + } + updateForFocusChange(view); + }; + handlers.blur = view => { + view.observer.clearSelectionRange(); + updateForFocusChange(view); + }; + handlers.compositionstart = handlers.compositionupdate = view => { + if (view.inputState.compositionFirstChange == null) + view.inputState.compositionFirstChange = true; + if (view.inputState.composing < 0) { + // FIXME possibly set a timeout to clear it again on Android + view.inputState.composing = 0; + } + }; + handlers.compositionend = view => { + view.inputState.composing = -1; + view.inputState.compositionEndedAt = Date.now(); + view.inputState.compositionFirstChange = null; + if (browser.chrome && browser.android) + view.observer.flushSoon(); + setTimeout(() => { + // Force the composition state to be cleared if it hasn't already been + if (view.inputState.composing < 0 && view.docView.compositionDeco.size) + view.update([]); + }, 50); + }; + handlers.contextmenu = view => { + view.inputState.lastContextMenu = Date.now(); + }; + handlers.beforeinput = (view, event) => { + var _a; + // Because Chrome Android doesn't fire useful key events, use + // beforeinput to detect backspace (and possibly enter and delete, + // but those usually don't even seem to fire beforeinput events at + // the moment) and fake a key event for it. + // + // (preventDefault on beforeinput, though supported in the spec, + // seems to do nothing at all on Chrome). + let pending; + if (browser.chrome && browser.android && (pending = PendingKeys.find(key => key.inputType == event.inputType))) { + view.observer.delayAndroidKey(pending.key, pending.keyCode); + if (pending.key == "Backspace" || pending.key == "Delete") { + let startViewHeight = ((_a = window.visualViewport) === null || _a === void 0 ? void 0 : _a.height) || 0; + setTimeout(() => { + var _a; + // Backspacing near uneditable nodes on Chrome Android sometimes + // closes the virtual keyboard. This tries to crudely detect + // that and refocus to get it back. + if ((((_a = window.visualViewport) === null || _a === void 0 ? void 0 : _a.height) || 0) > startViewHeight + 10 && view.hasFocus) { + view.contentDOM.blur(); + view.focus(); + } + }, 100); + } + } + }; + + const wrappingWhiteSpace = ["pre-wrap", "normal", "pre-line", "break-spaces"]; + class HeightOracle { + constructor() { + this.doc = Text.empty; + this.lineWrapping = false; + this.heightSamples = {}; + this.lineHeight = 14; + this.charWidth = 7; + this.lineLength = 30; + // Used to track, during updateHeight, if any actual heights changed + this.heightChanged = false; + } + heightForGap(from, to) { + let lines = this.doc.lineAt(to).number - this.doc.lineAt(from).number + 1; + if (this.lineWrapping) + lines += Math.ceil(((to - from) - (lines * this.lineLength * 0.5)) / this.lineLength); + return this.lineHeight * lines; + } + heightForLine(length) { + if (!this.lineWrapping) + return this.lineHeight; + let lines = 1 + Math.max(0, Math.ceil((length - this.lineLength) / (this.lineLength - 5))); + return lines * this.lineHeight; + } + setDoc(doc) { this.doc = doc; return this; } + mustRefreshForWrapping(whiteSpace) { + return (wrappingWhiteSpace.indexOf(whiteSpace) > -1) != this.lineWrapping; + } + mustRefreshForHeights(lineHeights) { + let newHeight = false; + for (let i = 0; i < lineHeights.length; i++) { + let h = lineHeights[i]; + if (h < 0) { + i++; + } + else if (!this.heightSamples[Math.floor(h * 10)]) { // Round to .1 pixels + newHeight = true; + this.heightSamples[Math.floor(h * 10)] = true; + } + } + return newHeight; + } + refresh(whiteSpace, lineHeight, charWidth, lineLength, knownHeights) { + let lineWrapping = wrappingWhiteSpace.indexOf(whiteSpace) > -1; + let changed = Math.round(lineHeight) != Math.round(this.lineHeight) || this.lineWrapping != lineWrapping; + this.lineWrapping = lineWrapping; + this.lineHeight = lineHeight; + this.charWidth = charWidth; + this.lineLength = lineLength; + if (changed) { + this.heightSamples = {}; + for (let i = 0; i < knownHeights.length; i++) { + let h = knownHeights[i]; + if (h < 0) + i++; + else + this.heightSamples[Math.floor(h * 10)] = true; + } + } + return changed; + } + } + // This object is used by `updateHeight` to make DOM measurements + // arrive at the right nides. The `heights` array is a sequence of + // block heights, starting from position `from`. + class MeasuredHeights { + constructor(from, heights) { + this.from = from; + this.heights = heights; + this.index = 0; + } + get more() { return this.index < this.heights.length; } + } + /** + Record used to represent information about a block-level element + in the editor view. + */ + class BlockInfo { + /** + @internal + */ + constructor( + /** + The start of the element in the document. + */ + from, + /** + The length of the element. + */ + length, + /** + The top position of the element (relative to the top of the + document). + */ + top, + /** + Its height. + */ + height, + /** + The type of element this is. When querying lines, this may be + an array of all the blocks that make up the line. + */ + type) { + this.from = from; + this.length = length; + this.top = top; + this.height = height; + this.type = type; + } + /** + The end of the element as a document position. + */ + get to() { return this.from + this.length; } + /** + The bottom position of the element. + */ + get bottom() { return this.top + this.height; } + /** + @internal + */ + join(other) { + let detail = (Array.isArray(this.type) ? this.type : [this]) + .concat(Array.isArray(other.type) ? other.type : [other]); + return new BlockInfo(this.from, this.length + other.length, this.top, this.height + other.height, detail); + } + } + var QueryType$1 = /*@__PURE__*/(function (QueryType) { + QueryType[QueryType["ByPos"] = 0] = "ByPos"; + QueryType[QueryType["ByHeight"] = 1] = "ByHeight"; + QueryType[QueryType["ByPosNoHeight"] = 2] = "ByPosNoHeight"; + return QueryType})(QueryType$1 || (QueryType$1 = {})); + const Epsilon = 1e-3; + class HeightMap { + constructor(length, // The number of characters covered + height, // Height of this part of the document + flags = 2 /* Flag.Outdated */) { + this.length = length; + this.height = height; + this.flags = flags; + } + get outdated() { return (this.flags & 2 /* Flag.Outdated */) > 0; } + set outdated(value) { this.flags = (value ? 2 /* Flag.Outdated */ : 0) | (this.flags & ~2 /* Flag.Outdated */); } + setHeight(oracle, height) { + if (this.height != height) { + if (Math.abs(this.height - height) > Epsilon) + oracle.heightChanged = true; + this.height = height; + } + } + // Base case is to replace a leaf node, which simply builds a tree + // from the new nodes and returns that (HeightMapBranch and + // HeightMapGap override this to actually use from/to) + replace(_from, _to, nodes) { + return HeightMap.of(nodes); + } + // Again, these are base cases, and are overridden for branch and gap nodes. + decomposeLeft(_to, result) { result.push(this); } + decomposeRight(_from, result) { result.push(this); } + applyChanges(decorations, oldDoc, oracle, changes) { + let me = this; + for (let i = changes.length - 1; i >= 0; i--) { + let { fromA, toA, fromB, toB } = changes[i]; + let start = me.lineAt(fromA, QueryType$1.ByPosNoHeight, oldDoc, 0, 0); + let end = start.to >= toA ? start : me.lineAt(toA, QueryType$1.ByPosNoHeight, oldDoc, 0, 0); + toB += end.to - toA; + toA = end.to; + while (i > 0 && start.from <= changes[i - 1].toA) { + fromA = changes[i - 1].fromA; + fromB = changes[i - 1].fromB; + i--; + if (fromA < start.from) + start = me.lineAt(fromA, QueryType$1.ByPosNoHeight, oldDoc, 0, 0); + } + fromB += start.from - fromA; + fromA = start.from; + let nodes = NodeBuilder.build(oracle, decorations, fromB, toB); + me = me.replace(fromA, toA, nodes); + } + return me.updateHeight(oracle, 0); + } + static empty() { return new HeightMapText(0, 0); } + // nodes uses null values to indicate the position of line breaks. + // There are never line breaks at the start or end of the array, or + // two line breaks next to each other, and the array isn't allowed + // to be empty (same restrictions as return value from the builder). + static of(nodes) { + if (nodes.length == 1) + return nodes[0]; + let i = 0, j = nodes.length, before = 0, after = 0; + for (;;) { + if (i == j) { + if (before > after * 2) { + let split = nodes[i - 1]; + if (split.break) + nodes.splice(--i, 1, split.left, null, split.right); + else + nodes.splice(--i, 1, split.left, split.right); + j += 1 + split.break; + before -= split.size; + } + else if (after > before * 2) { + let split = nodes[j]; + if (split.break) + nodes.splice(j, 1, split.left, null, split.right); + else + nodes.splice(j, 1, split.left, split.right); + j += 2 + split.break; + after -= split.size; + } + else { + break; + } + } + else if (before < after) { + let next = nodes[i++]; + if (next) + before += next.size; + } + else { + let next = nodes[--j]; + if (next) + after += next.size; + } + } + let brk = 0; + if (nodes[i - 1] == null) { + brk = 1; + i--; + } + else if (nodes[i] == null) { + brk = 1; + j++; + } + return new HeightMapBranch(HeightMap.of(nodes.slice(0, i)), brk, HeightMap.of(nodes.slice(j))); + } + } + HeightMap.prototype.size = 1; + class HeightMapBlock extends HeightMap { + constructor(length, height, type) { + super(length, height); + this.type = type; + } + blockAt(_height, _doc, top, offset) { + return new BlockInfo(offset, this.length, top, this.height, this.type); + } + lineAt(_value, _type, doc, top, offset) { + return this.blockAt(0, doc, top, offset); + } + forEachLine(from, to, doc, top, offset, f) { + if (from <= offset + this.length && to >= offset) + f(this.blockAt(0, doc, top, offset)); + } + updateHeight(oracle, offset = 0, _force = false, measured) { + if (measured && measured.from <= offset && measured.more) + this.setHeight(oracle, measured.heights[measured.index++]); + this.outdated = false; + return this; + } + toString() { return `block(${this.length})`; } + } + class HeightMapText extends HeightMapBlock { + constructor(length, height) { + super(length, height, BlockType.Text); + this.collapsed = 0; // Amount of collapsed content in the line + this.widgetHeight = 0; // Maximum inline widget height + } + replace(_from, _to, nodes) { + let node = nodes[0]; + if (nodes.length == 1 && (node instanceof HeightMapText || node instanceof HeightMapGap && (node.flags & 4 /* Flag.SingleLine */)) && + Math.abs(this.length - node.length) < 10) { + if (node instanceof HeightMapGap) + node = new HeightMapText(node.length, this.height); + else + node.height = this.height; + if (!this.outdated) + node.outdated = false; + return node; + } + else { + return HeightMap.of(nodes); + } + } + updateHeight(oracle, offset = 0, force = false, measured) { + if (measured && measured.from <= offset && measured.more) + this.setHeight(oracle, measured.heights[measured.index++]); + else if (force || this.outdated) + this.setHeight(oracle, Math.max(this.widgetHeight, oracle.heightForLine(this.length - this.collapsed))); + this.outdated = false; + return this; + } + toString() { + return `line(${this.length}${this.collapsed ? -this.collapsed : ""}${this.widgetHeight ? ":" + this.widgetHeight : ""})`; + } + } + class HeightMapGap extends HeightMap { + constructor(length) { super(length, 0); } + lines(doc, offset) { + let firstLine = doc.lineAt(offset).number, lastLine = doc.lineAt(offset + this.length).number; + return { firstLine, lastLine, lineHeight: this.height / (lastLine - firstLine + 1) }; + } + blockAt(height, doc, top, offset) { + let { firstLine, lastLine, lineHeight } = this.lines(doc, offset); + let line = Math.max(0, Math.min(lastLine - firstLine, Math.floor((height - top) / lineHeight))); + let { from, length } = doc.line(firstLine + line); + return new BlockInfo(from, length, top + lineHeight * line, lineHeight, BlockType.Text); + } + lineAt(value, type, doc, top, offset) { + if (type == QueryType$1.ByHeight) + return this.blockAt(value, doc, top, offset); + if (type == QueryType$1.ByPosNoHeight) { + let { from, to } = doc.lineAt(value); + return new BlockInfo(from, to - from, 0, 0, BlockType.Text); + } + let { firstLine, lineHeight } = this.lines(doc, offset); + let { from, length, number } = doc.lineAt(value); + return new BlockInfo(from, length, top + lineHeight * (number - firstLine), lineHeight, BlockType.Text); + } + forEachLine(from, to, doc, top, offset, f) { + let { firstLine, lineHeight } = this.lines(doc, offset); + for (let pos = Math.max(from, offset), end = Math.min(offset + this.length, to); pos <= end;) { + let line = doc.lineAt(pos); + if (pos == from) + top += lineHeight * (line.number - firstLine); + f(new BlockInfo(line.from, line.length, top, lineHeight, BlockType.Text)); + top += lineHeight; + pos = line.to + 1; + } + } + replace(from, to, nodes) { + let after = this.length - to; + if (after > 0) { + let last = nodes[nodes.length - 1]; + if (last instanceof HeightMapGap) + nodes[nodes.length - 1] = new HeightMapGap(last.length + after); + else + nodes.push(null, new HeightMapGap(after - 1)); + } + if (from > 0) { + let first = nodes[0]; + if (first instanceof HeightMapGap) + nodes[0] = new HeightMapGap(from + first.length); + else + nodes.unshift(new HeightMapGap(from - 1), null); + } + return HeightMap.of(nodes); + } + decomposeLeft(to, result) { + result.push(new HeightMapGap(to - 1), null); + } + decomposeRight(from, result) { + result.push(null, new HeightMapGap(this.length - from - 1)); + } + updateHeight(oracle, offset = 0, force = false, measured) { + let end = offset + this.length; + if (measured && measured.from <= offset + this.length && measured.more) { + // Fill in part of this gap with measured lines. We know there + // can't be widgets or collapsed ranges in those lines, because + // they would already have been added to the heightmap (gaps + // only contain plain text). + let nodes = [], pos = Math.max(offset, measured.from), singleHeight = -1; + let wasChanged = oracle.heightChanged; + if (measured.from > offset) + nodes.push(new HeightMapGap(measured.from - offset - 1).updateHeight(oracle, offset)); + while (pos <= end && measured.more) { + let len = oracle.doc.lineAt(pos).length; + if (nodes.length) + nodes.push(null); + let height = measured.heights[measured.index++]; + if (singleHeight == -1) + singleHeight = height; + else if (Math.abs(height - singleHeight) >= Epsilon) + singleHeight = -2; + let line = new HeightMapText(len, height); + line.outdated = false; + nodes.push(line); + pos += len + 1; + } + if (pos <= end) + nodes.push(null, new HeightMapGap(end - pos).updateHeight(oracle, pos)); + let result = HeightMap.of(nodes); + oracle.heightChanged = wasChanged || singleHeight < 0 || Math.abs(result.height - this.height) >= Epsilon || + Math.abs(singleHeight - this.lines(oracle.doc, offset).lineHeight) >= Epsilon; + return result; + } + else if (force || this.outdated) { + this.setHeight(oracle, oracle.heightForGap(offset, offset + this.length)); + this.outdated = false; + } + return this; + } + toString() { return `gap(${this.length})`; } + } + class HeightMapBranch extends HeightMap { + constructor(left, brk, right) { + super(left.length + brk + right.length, left.height + right.height, brk | (left.outdated || right.outdated ? 2 /* Flag.Outdated */ : 0)); + this.left = left; + this.right = right; + this.size = left.size + right.size; + } + get break() { return this.flags & 1 /* Flag.Break */; } + blockAt(height, doc, top, offset) { + let mid = top + this.left.height; + return height < mid ? this.left.blockAt(height, doc, top, offset) + : this.right.blockAt(height, doc, mid, offset + this.left.length + this.break); + } + lineAt(value, type, doc, top, offset) { + let rightTop = top + this.left.height, rightOffset = offset + this.left.length + this.break; + let left = type == QueryType$1.ByHeight ? value < rightTop : value < rightOffset; + let base = left ? this.left.lineAt(value, type, doc, top, offset) + : this.right.lineAt(value, type, doc, rightTop, rightOffset); + if (this.break || (left ? base.to < rightOffset : base.from > rightOffset)) + return base; + let subQuery = type == QueryType$1.ByPosNoHeight ? QueryType$1.ByPosNoHeight : QueryType$1.ByPos; + if (left) + return base.join(this.right.lineAt(rightOffset, subQuery, doc, rightTop, rightOffset)); + else + return this.left.lineAt(rightOffset, subQuery, doc, top, offset).join(base); + } + forEachLine(from, to, doc, top, offset, f) { + let rightTop = top + this.left.height, rightOffset = offset + this.left.length + this.break; + if (this.break) { + if (from < rightOffset) + this.left.forEachLine(from, to, doc, top, offset, f); + if (to >= rightOffset) + this.right.forEachLine(from, to, doc, rightTop, rightOffset, f); + } + else { + let mid = this.lineAt(rightOffset, QueryType$1.ByPos, doc, top, offset); + if (from < mid.from) + this.left.forEachLine(from, mid.from - 1, doc, top, offset, f); + if (mid.to >= from && mid.from <= to) + f(mid); + if (to > mid.to) + this.right.forEachLine(mid.to + 1, to, doc, rightTop, rightOffset, f); + } + } + replace(from, to, nodes) { + let rightStart = this.left.length + this.break; + if (to < rightStart) + return this.balanced(this.left.replace(from, to, nodes), this.right); + if (from > this.left.length) + return this.balanced(this.left, this.right.replace(from - rightStart, to - rightStart, nodes)); + let result = []; + if (from > 0) + this.decomposeLeft(from, result); + let left = result.length; + for (let node of nodes) + result.push(node); + if (from > 0) + mergeGaps(result, left - 1); + if (to < this.length) { + let right = result.length; + this.decomposeRight(to, result); + mergeGaps(result, right); + } + return HeightMap.of(result); + } + decomposeLeft(to, result) { + let left = this.left.length; + if (to <= left) + return this.left.decomposeLeft(to, result); + result.push(this.left); + if (this.break) { + left++; + if (to >= left) + result.push(null); + } + if (to > left) + this.right.decomposeLeft(to - left, result); + } + decomposeRight(from, result) { + let left = this.left.length, right = left + this.break; + if (from >= right) + return this.right.decomposeRight(from - right, result); + if (from < left) + this.left.decomposeRight(from, result); + if (this.break && from < right) + result.push(null); + result.push(this.right); + } + balanced(left, right) { + if (left.size > 2 * right.size || right.size > 2 * left.size) + return HeightMap.of(this.break ? [left, null, right] : [left, right]); + this.left = left; + this.right = right; + this.height = left.height + right.height; + this.outdated = left.outdated || right.outdated; + this.size = left.size + right.size; + this.length = left.length + this.break + right.length; + return this; + } + updateHeight(oracle, offset = 0, force = false, measured) { + let { left, right } = this, rightStart = offset + left.length + this.break, rebalance = null; + if (measured && measured.from <= offset + left.length && measured.more) + rebalance = left = left.updateHeight(oracle, offset, force, measured); + else + left.updateHeight(oracle, offset, force); + if (measured && measured.from <= rightStart + right.length && measured.more) + rebalance = right = right.updateHeight(oracle, rightStart, force, measured); + else + right.updateHeight(oracle, rightStart, force); + if (rebalance) + return this.balanced(left, right); + this.height = this.left.height + this.right.height; + this.outdated = false; + return this; + } + toString() { return this.left + (this.break ? " " : "-") + this.right; } + } + function mergeGaps(nodes, around) { + let before, after; + if (nodes[around] == null && + (before = nodes[around - 1]) instanceof HeightMapGap && + (after = nodes[around + 1]) instanceof HeightMapGap) + nodes.splice(around - 1, 3, new HeightMapGap(before.length + 1 + after.length)); + } + const relevantWidgetHeight = 5; + class NodeBuilder { + constructor(pos, oracle) { + this.pos = pos; + this.oracle = oracle; + this.nodes = []; + this.lineStart = -1; + this.lineEnd = -1; + this.covering = null; + this.writtenTo = pos; + } + get isCovered() { + return this.covering && this.nodes[this.nodes.length - 1] == this.covering; + } + span(_from, to) { + if (this.lineStart > -1) { + let end = Math.min(to, this.lineEnd), last = this.nodes[this.nodes.length - 1]; + if (last instanceof HeightMapText) + last.length += end - this.pos; + else if (end > this.pos || !this.isCovered) + this.nodes.push(new HeightMapText(end - this.pos, -1)); + this.writtenTo = end; + if (to > end) { + this.nodes.push(null); + this.writtenTo++; + this.lineStart = -1; + } + } + this.pos = to; + } + point(from, to, deco) { + if (from < to || deco.heightRelevant) { + let height = deco.widget ? deco.widget.estimatedHeight : 0; + if (height < 0) + height = this.oracle.lineHeight; + let len = to - from; + if (deco.block) { + this.addBlock(new HeightMapBlock(len, height, deco.type)); + } + else if (len || height >= relevantWidgetHeight) { + this.addLineDeco(height, len); + } + } + else if (to > from) { + this.span(from, to); + } + if (this.lineEnd > -1 && this.lineEnd < this.pos) + this.lineEnd = this.oracle.doc.lineAt(this.pos).to; + } + enterLine() { + if (this.lineStart > -1) + return; + let { from, to } = this.oracle.doc.lineAt(this.pos); + this.lineStart = from; + this.lineEnd = to; + if (this.writtenTo < from) { + if (this.writtenTo < from - 1 || this.nodes[this.nodes.length - 1] == null) + this.nodes.push(this.blankContent(this.writtenTo, from - 1)); + this.nodes.push(null); + } + if (this.pos > from) + this.nodes.push(new HeightMapText(this.pos - from, -1)); + this.writtenTo = this.pos; + } + blankContent(from, to) { + let gap = new HeightMapGap(to - from); + if (this.oracle.doc.lineAt(from).to == to) + gap.flags |= 4 /* Flag.SingleLine */; + return gap; + } + ensureLine() { + this.enterLine(); + let last = this.nodes.length ? this.nodes[this.nodes.length - 1] : null; + if (last instanceof HeightMapText) + return last; + let line = new HeightMapText(0, -1); + this.nodes.push(line); + return line; + } + addBlock(block) { + this.enterLine(); + if (block.type == BlockType.WidgetAfter && !this.isCovered) + this.ensureLine(); + this.nodes.push(block); + this.writtenTo = this.pos = this.pos + block.length; + if (block.type != BlockType.WidgetBefore) + this.covering = block; + } + addLineDeco(height, length) { + let line = this.ensureLine(); + line.length += length; + line.collapsed += length; + line.widgetHeight = Math.max(line.widgetHeight, height); + this.writtenTo = this.pos = this.pos + length; + } + finish(from) { + let last = this.nodes.length == 0 ? null : this.nodes[this.nodes.length - 1]; + if (this.lineStart > -1 && !(last instanceof HeightMapText) && !this.isCovered) + this.nodes.push(new HeightMapText(0, -1)); + else if (this.writtenTo < this.pos || last == null) + this.nodes.push(this.blankContent(this.writtenTo, this.pos)); + let pos = from; + for (let node of this.nodes) { + if (node instanceof HeightMapText) + node.updateHeight(this.oracle, pos); + pos += node ? node.length : 1; + } + return this.nodes; + } + // Always called with a region that on both sides either stretches + // to a line break or the end of the document. + // The returned array uses null to indicate line breaks, but never + // starts or ends in a line break, or has multiple line breaks next + // to each other. + static build(oracle, decorations, from, to) { + let builder = new NodeBuilder(from, oracle); + RangeSet.spans(decorations, from, to, builder, 0); + return builder.finish(from); + } + } + function heightRelevantDecoChanges(a, b, diff) { + let comp = new DecorationComparator; + RangeSet.compare(a, b, diff, comp, 0); + return comp.changes; + } + class DecorationComparator { + constructor() { + this.changes = []; + } + compareRange() { } + comparePoint(from, to, a, b) { + if (from < to || a && a.heightRelevant || b && b.heightRelevant) + addRange(from, to, this.changes, 5); + } + } + + function visiblePixelRange(dom, paddingTop) { + let rect = dom.getBoundingClientRect(); + let doc = dom.ownerDocument, win = doc.defaultView || window; + let left = Math.max(0, rect.left), right = Math.min(win.innerWidth, rect.right); + let top = Math.max(0, rect.top), bottom = Math.min(win.innerHeight, rect.bottom); + for (let parent = dom.parentNode; parent && parent != doc.body;) { + if (parent.nodeType == 1) { + let elt = parent; + let style = window.getComputedStyle(elt); + if ((elt.scrollHeight > elt.clientHeight || elt.scrollWidth > elt.clientWidth) && + style.overflow != "visible") { + let parentRect = elt.getBoundingClientRect(); + left = Math.max(left, parentRect.left); + right = Math.min(right, parentRect.right); + top = Math.max(top, parentRect.top); + bottom = parent == dom.parentNode ? parentRect.bottom : Math.min(bottom, parentRect.bottom); + } + parent = style.position == "absolute" || style.position == "fixed" ? elt.offsetParent : elt.parentNode; + } + else if (parent.nodeType == 11) { // Shadow root + parent = parent.host; + } + else { + break; + } + } + return { left: left - rect.left, right: Math.max(left, right) - rect.left, + top: top - (rect.top + paddingTop), bottom: Math.max(top, bottom) - (rect.top + paddingTop) }; + } + function fullPixelRange(dom, paddingTop) { + let rect = dom.getBoundingClientRect(); + return { left: 0, right: rect.right - rect.left, + top: paddingTop, bottom: rect.bottom - (rect.top + paddingTop) }; + } + // Line gaps are placeholder widgets used to hide pieces of overlong + // lines within the viewport, as a kludge to keep the editor + // responsive when a ridiculously long line is loaded into it. + class LineGap { + constructor(from, to, size) { + this.from = from; + this.to = to; + this.size = size; + } + static same(a, b) { + if (a.length != b.length) + return false; + for (let i = 0; i < a.length; i++) { + let gA = a[i], gB = b[i]; + if (gA.from != gB.from || gA.to != gB.to || gA.size != gB.size) + return false; + } + return true; + } + draw(wrapping) { + return Decoration.replace({ widget: new LineGapWidget(this.size, wrapping) }).range(this.from, this.to); + } + } + class LineGapWidget extends WidgetType { + constructor(size, vertical) { + super(); + this.size = size; + this.vertical = vertical; + } + eq(other) { return other.size == this.size && other.vertical == this.vertical; } + toDOM() { + let elt = document.createElement("div"); + if (this.vertical) { + elt.style.height = this.size + "px"; + } + else { + elt.style.width = this.size + "px"; + elt.style.height = "2px"; + elt.style.display = "inline-block"; + } + return elt; + } + get estimatedHeight() { return this.vertical ? this.size : -1; } + } + class ViewState { + constructor(state) { + this.state = state; + // These are contentDOM-local coordinates + this.pixelViewport = { left: 0, right: window.innerWidth, top: 0, bottom: 0 }; + this.inView = true; + this.paddingTop = 0; + this.paddingBottom = 0; + this.contentDOMWidth = 0; + this.contentDOMHeight = 0; + this.editorHeight = 0; + this.editorWidth = 0; + this.heightOracle = new HeightOracle; + // See VP.MaxDOMHeight + this.scaler = IdScaler; + this.scrollTarget = null; + // Briefly set to true when printing, to disable viewport limiting + this.printing = false; + // Flag set when editor content was redrawn, so that the next + // measure stage knows it must read DOM layout + this.mustMeasureContent = true; + this.defaultTextDirection = Direction.RTL; + this.visibleRanges = []; + // Cursor 'assoc' is only significant when the cursor is on a line + // wrap point, where it must stick to the character that it is + // associated with. Since browsers don't provide a reasonable + // interface to set or query this, when a selection is set that + // might cause this to be significant, this flag is set. The next + // measure phase will check whether the cursor is on a line-wrapping + // boundary and, if so, reset it to make sure it is positioned in + // the right place. + this.mustEnforceCursorAssoc = false; + this.stateDeco = state.facet(decorations).filter(d => typeof d != "function"); + this.heightMap = HeightMap.empty().applyChanges(this.stateDeco, Text.empty, this.heightOracle.setDoc(state.doc), [new ChangedRange(0, 0, 0, state.doc.length)]); + this.viewport = this.getViewport(0, null); + this.updateViewportLines(); + this.updateForViewport(); + this.lineGaps = this.ensureLineGaps([]); + this.lineGapDeco = Decoration.set(this.lineGaps.map(gap => gap.draw(false))); + this.computeVisibleRanges(); + } + updateForViewport() { + let viewports = [this.viewport], { main } = this.state.selection; + for (let i = 0; i <= 1; i++) { + let pos = i ? main.head : main.anchor; + if (!viewports.some(({ from, to }) => pos >= from && pos <= to)) { + let { from, to } = this.lineBlockAt(pos); + viewports.push(new Viewport(from, to)); + } + } + this.viewports = viewports.sort((a, b) => a.from - b.from); + this.scaler = this.heightMap.height <= 7000000 /* VP.MaxDOMHeight */ ? IdScaler : + new BigScaler(this.heightOracle.doc, this.heightMap, this.viewports); + } + updateViewportLines() { + this.viewportLines = []; + this.heightMap.forEachLine(this.viewport.from, this.viewport.to, this.state.doc, 0, 0, block => { + this.viewportLines.push(this.scaler.scale == 1 ? block : scaleBlock(block, this.scaler)); + }); + } + update(update, scrollTarget = null) { + this.state = update.state; + let prevDeco = this.stateDeco; + this.stateDeco = this.state.facet(decorations).filter(d => typeof d != "function"); + let contentChanges = update.changedRanges; + let heightChanges = ChangedRange.extendWithRanges(contentChanges, heightRelevantDecoChanges(prevDeco, this.stateDeco, update ? update.changes : ChangeSet.empty(this.state.doc.length))); + let prevHeight = this.heightMap.height; + this.heightMap = this.heightMap.applyChanges(this.stateDeco, update.startState.doc, this.heightOracle.setDoc(this.state.doc), heightChanges); + if (this.heightMap.height != prevHeight) + update.flags |= 2 /* UpdateFlag.Height */; + let viewport = heightChanges.length ? this.mapViewport(this.viewport, update.changes) : this.viewport; + if (scrollTarget && (scrollTarget.range.head < viewport.from || scrollTarget.range.head > viewport.to) || + !this.viewportIsAppropriate(viewport)) + viewport = this.getViewport(0, scrollTarget); + let updateLines = !update.changes.empty || (update.flags & 2 /* UpdateFlag.Height */) || + viewport.from != this.viewport.from || viewport.to != this.viewport.to; + this.viewport = viewport; + this.updateForViewport(); + if (updateLines) + this.updateViewportLines(); + if (this.lineGaps.length || this.viewport.to - this.viewport.from > (2000 /* LG.Margin */ << 1)) + this.updateLineGaps(this.ensureLineGaps(this.mapLineGaps(this.lineGaps, update.changes))); + update.flags |= this.computeVisibleRanges(); + if (scrollTarget) + this.scrollTarget = scrollTarget; + if (!this.mustEnforceCursorAssoc && update.selectionSet && update.view.lineWrapping && + update.state.selection.main.empty && update.state.selection.main.assoc) + this.mustEnforceCursorAssoc = true; + } + measure(view) { + let dom = view.contentDOM, style = window.getComputedStyle(dom); + let oracle = this.heightOracle; + let whiteSpace = style.whiteSpace; + this.defaultTextDirection = style.direction == "rtl" ? Direction.RTL : Direction.LTR; + let refresh = this.heightOracle.mustRefreshForWrapping(whiteSpace); + let measureContent = refresh || this.mustMeasureContent || this.contentDOMHeight != dom.clientHeight; + this.contentDOMHeight = dom.clientHeight; + this.mustMeasureContent = false; + let result = 0, bias = 0; + // Vertical padding + let paddingTop = parseInt(style.paddingTop) || 0, paddingBottom = parseInt(style.paddingBottom) || 0; + if (this.paddingTop != paddingTop || this.paddingBottom != paddingBottom) { + this.paddingTop = paddingTop; + this.paddingBottom = paddingBottom; + result |= 8 /* UpdateFlag.Geometry */ | 2 /* UpdateFlag.Height */; + } + if (this.editorWidth != view.scrollDOM.clientWidth) { + if (oracle.lineWrapping) + measureContent = true; + this.editorWidth = view.scrollDOM.clientWidth; + result |= 8 /* UpdateFlag.Geometry */; + } + // Pixel viewport + let pixelViewport = (this.printing ? fullPixelRange : visiblePixelRange)(dom, this.paddingTop); + let dTop = pixelViewport.top - this.pixelViewport.top, dBottom = pixelViewport.bottom - this.pixelViewport.bottom; + this.pixelViewport = pixelViewport; + let inView = this.pixelViewport.bottom > this.pixelViewport.top && this.pixelViewport.right > this.pixelViewport.left; + if (inView != this.inView) { + this.inView = inView; + if (inView) + measureContent = true; + } + if (!this.inView && !this.scrollTarget) + return 0; + let contentWidth = dom.clientWidth; + if (this.contentDOMWidth != contentWidth || this.editorHeight != view.scrollDOM.clientHeight) { + this.contentDOMWidth = contentWidth; + this.editorHeight = view.scrollDOM.clientHeight; + result |= 8 /* UpdateFlag.Geometry */; + } + if (measureContent) { + let lineHeights = view.docView.measureVisibleLineHeights(this.viewport); + if (oracle.mustRefreshForHeights(lineHeights)) + refresh = true; + if (refresh || oracle.lineWrapping && Math.abs(contentWidth - this.contentDOMWidth) > oracle.charWidth) { + let { lineHeight, charWidth } = view.docView.measureTextSize(); + refresh = oracle.refresh(whiteSpace, lineHeight, charWidth, contentWidth / charWidth, lineHeights); + if (refresh) { + view.docView.minWidth = 0; + result |= 8 /* UpdateFlag.Geometry */; + } + } + if (dTop > 0 && dBottom > 0) + bias = Math.max(dTop, dBottom); + else if (dTop < 0 && dBottom < 0) + bias = Math.min(dTop, dBottom); + oracle.heightChanged = false; + for (let vp of this.viewports) { + let heights = vp.from == this.viewport.from ? lineHeights : view.docView.measureVisibleLineHeights(vp); + this.heightMap = this.heightMap.updateHeight(oracle, 0, refresh, new MeasuredHeights(vp.from, heights)); + } + if (oracle.heightChanged) + result |= 2 /* UpdateFlag.Height */; + } + let viewportChange = !this.viewportIsAppropriate(this.viewport, bias) || + this.scrollTarget && (this.scrollTarget.range.head < this.viewport.from || this.scrollTarget.range.head > this.viewport.to); + if (viewportChange) + this.viewport = this.getViewport(bias, this.scrollTarget); + this.updateForViewport(); + if ((result & 2 /* UpdateFlag.Height */) || viewportChange) + this.updateViewportLines(); + if (this.lineGaps.length || this.viewport.to - this.viewport.from > (2000 /* LG.Margin */ << 1)) + this.updateLineGaps(this.ensureLineGaps(refresh ? [] : this.lineGaps, view)); + result |= this.computeVisibleRanges(); + if (this.mustEnforceCursorAssoc) { + this.mustEnforceCursorAssoc = false; + // This is done in the read stage, because moving the selection + // to a line end is going to trigger a layout anyway, so it + // can't be a pure write. It should be rare that it does any + // writing. + view.docView.enforceCursorAssoc(); + } + return result; + } + get visibleTop() { return this.scaler.fromDOM(this.pixelViewport.top); } + get visibleBottom() { return this.scaler.fromDOM(this.pixelViewport.bottom); } + getViewport(bias, scrollTarget) { + // This will divide VP.Margin between the top and the + // bottom, depending on the bias (the change in viewport position + // since the last update). It'll hold a number between 0 and 1 + let marginTop = 0.5 - Math.max(-0.5, Math.min(0.5, bias / 1000 /* VP.Margin */ / 2)); + let map = this.heightMap, doc = this.state.doc, { visibleTop, visibleBottom } = this; + let viewport = new Viewport(map.lineAt(visibleTop - marginTop * 1000 /* VP.Margin */, QueryType$1.ByHeight, doc, 0, 0).from, map.lineAt(visibleBottom + (1 - marginTop) * 1000 /* VP.Margin */, QueryType$1.ByHeight, doc, 0, 0).to); + // If scrollTarget is given, make sure the viewport includes that position + if (scrollTarget) { + let { head } = scrollTarget.range; + if (head < viewport.from || head > viewport.to) { + let viewHeight = Math.min(this.editorHeight, this.pixelViewport.bottom - this.pixelViewport.top); + let block = map.lineAt(head, QueryType$1.ByPos, doc, 0, 0), topPos; + if (scrollTarget.y == "center") + topPos = (block.top + block.bottom) / 2 - viewHeight / 2; + else if (scrollTarget.y == "start" || scrollTarget.y == "nearest" && head < viewport.from) + topPos = block.top; + else + topPos = block.bottom - viewHeight; + viewport = new Viewport(map.lineAt(topPos - 1000 /* VP.Margin */ / 2, QueryType$1.ByHeight, doc, 0, 0).from, map.lineAt(topPos + viewHeight + 1000 /* VP.Margin */ / 2, QueryType$1.ByHeight, doc, 0, 0).to); + } + } + return viewport; + } + mapViewport(viewport, changes) { + let from = changes.mapPos(viewport.from, -1), to = changes.mapPos(viewport.to, 1); + return new Viewport(this.heightMap.lineAt(from, QueryType$1.ByPos, this.state.doc, 0, 0).from, this.heightMap.lineAt(to, QueryType$1.ByPos, this.state.doc, 0, 0).to); + } + // Checks if a given viewport covers the visible part of the + // document and not too much beyond that. + viewportIsAppropriate({ from, to }, bias = 0) { + if (!this.inView) + return true; + let { top } = this.heightMap.lineAt(from, QueryType$1.ByPos, this.state.doc, 0, 0); + let { bottom } = this.heightMap.lineAt(to, QueryType$1.ByPos, this.state.doc, 0, 0); + let { visibleTop, visibleBottom } = this; + return (from == 0 || top <= visibleTop - Math.max(10 /* VP.MinCoverMargin */, Math.min(-bias, 250 /* VP.MaxCoverMargin */))) && + (to == this.state.doc.length || + bottom >= visibleBottom + Math.max(10 /* VP.MinCoverMargin */, Math.min(bias, 250 /* VP.MaxCoverMargin */))) && + (top > visibleTop - 2 * 1000 /* VP.Margin */ && bottom < visibleBottom + 2 * 1000 /* VP.Margin */); + } + mapLineGaps(gaps, changes) { + if (!gaps.length || changes.empty) + return gaps; + let mapped = []; + for (let gap of gaps) + if (!changes.touchesRange(gap.from, gap.to)) + mapped.push(new LineGap(changes.mapPos(gap.from), changes.mapPos(gap.to), gap.size)); + return mapped; + } + // Computes positions in the viewport where the start or end of a + // line should be hidden, trying to reuse existing line gaps when + // appropriate to avoid unneccesary redraws. + // Uses crude character-counting for the positioning and sizing, + // since actual DOM coordinates aren't always available and + // predictable. Relies on generous margins (see LG.Margin) to hide + // the artifacts this might produce from the user. + ensureLineGaps(current, mayMeasure) { + let wrapping = this.heightOracle.lineWrapping; + let margin = wrapping ? 10000 /* LG.MarginWrap */ : 2000 /* LG.Margin */, halfMargin = margin >> 1, doubleMargin = margin << 1; + // The non-wrapping logic won't work at all in predominantly right-to-left text. + if (this.defaultTextDirection != Direction.LTR && !wrapping) + return []; + let gaps = []; + let addGap = (from, to, line, structure) => { + if (to - from < halfMargin) + return; + let sel = this.state.selection.main, avoid = [sel.from]; + if (!sel.empty) + avoid.push(sel.to); + for (let pos of avoid) { + if (pos > from && pos < to) { + addGap(from, pos - 10 /* LG.SelectionMargin */, line, structure); + addGap(pos + 10 /* LG.SelectionMargin */, to, line, structure); + return; + } + } + let gap = find(current, gap => gap.from >= line.from && gap.to <= line.to && + Math.abs(gap.from - from) < halfMargin && Math.abs(gap.to - to) < halfMargin && + !avoid.some(pos => gap.from < pos && gap.to > pos)); + if (!gap) { + // When scrolling down, snap gap ends to line starts to avoid shifts in wrapping + if (to < line.to && mayMeasure && wrapping && + mayMeasure.visibleRanges.some(r => r.from <= to && r.to >= to)) { + let lineStart = mayMeasure.moveToLineBoundary(EditorSelection.cursor(to), false, true).head; + if (lineStart > from) + to = lineStart; + } + gap = new LineGap(from, to, this.gapSize(line, from, to, structure)); + } + gaps.push(gap); + }; + for (let line of this.viewportLines) { + if (line.length < doubleMargin) + continue; + let structure = lineStructure(line.from, line.to, this.stateDeco); + if (structure.total < doubleMargin) + continue; + let target = this.scrollTarget ? this.scrollTarget.range.head : null; + let viewFrom, viewTo; + if (wrapping) { + let marginHeight = (margin / this.heightOracle.lineLength) * this.heightOracle.lineHeight; + let top, bot; + if (target != null) { + top = Math.max(line.from, target - margin); + bot = Math.min(line.to, target + margin); + } + else { + top = (this.visibleTop - line.top - marginHeight) / line.height; + bot = (this.visibleBottom - line.top + marginHeight) / line.height; + } + viewFrom = findPosition(structure, top); + viewTo = findPosition(structure, bot); + } + else { + let left, right; + if (target != null) { + left = Math.max(line.from, target - doubleMargin); + right = Math.min(line.to, target + doubleMargin); + } + else { + let totalWidth = structure.total * this.heightOracle.charWidth; + let marginWidth = margin * this.heightOracle.charWidth; + left = (this.pixelViewport.left - marginWidth) / totalWidth; + right = (this.pixelViewport.right + marginWidth) / totalWidth; + } + viewFrom = findPosition(structure, left); + viewTo = findPosition(structure, right); + } + if (viewFrom > line.from) + addGap(line.from, viewFrom, line, structure); + if (viewTo < line.to) + addGap(viewTo, line.to, line, structure); + } + return gaps; + } + gapSize(line, from, to, structure) { + let fraction = findFraction(structure, to) - findFraction(structure, from); + if (this.heightOracle.lineWrapping) { + return line.height * fraction; + } + else { + return structure.total * this.heightOracle.charWidth * fraction; + } + } + updateLineGaps(gaps) { + if (!LineGap.same(gaps, this.lineGaps)) { + this.lineGaps = gaps; + this.lineGapDeco = Decoration.set(gaps.map(gap => gap.draw(this.heightOracle.lineWrapping))); + } + } + computeVisibleRanges() { + let deco = this.stateDeco; + if (this.lineGaps.length) + deco = deco.concat(this.lineGapDeco); + let ranges = []; + RangeSet.spans(deco, this.viewport.from, this.viewport.to, { + span(from, to) { ranges.push({ from, to }); }, + point() { } + }, 20); + let changed = ranges.length != this.visibleRanges.length || + this.visibleRanges.some((r, i) => r.from != ranges[i].from || r.to != ranges[i].to); + this.visibleRanges = ranges; + return changed ? 4 /* UpdateFlag.Viewport */ : 0; + } + lineBlockAt(pos) { + return (pos >= this.viewport.from && pos <= this.viewport.to && this.viewportLines.find(b => b.from <= pos && b.to >= pos)) || + scaleBlock(this.heightMap.lineAt(pos, QueryType$1.ByPos, this.state.doc, 0, 0), this.scaler); + } + lineBlockAtHeight(height) { + return scaleBlock(this.heightMap.lineAt(this.scaler.fromDOM(height), QueryType$1.ByHeight, this.state.doc, 0, 0), this.scaler); + } + elementAtHeight(height) { + return scaleBlock(this.heightMap.blockAt(this.scaler.fromDOM(height), this.state.doc, 0, 0), this.scaler); + } + get docHeight() { + return this.scaler.toDOM(this.heightMap.height); + } + get contentHeight() { + return this.docHeight + this.paddingTop + this.paddingBottom; + } + } + class Viewport { + constructor(from, to) { + this.from = from; + this.to = to; + } + } + function lineStructure(from, to, stateDeco) { + let ranges = [], pos = from, total = 0; + RangeSet.spans(stateDeco, from, to, { + span() { }, + point(from, to) { + if (from > pos) { + ranges.push({ from: pos, to: from }); + total += from - pos; + } + pos = to; + } + }, 20); // We're only interested in collapsed ranges of a significant size + if (pos < to) { + ranges.push({ from: pos, to }); + total += to - pos; + } + return { total, ranges }; + } + function findPosition({ total, ranges }, ratio) { + if (ratio <= 0) + return ranges[0].from; + if (ratio >= 1) + return ranges[ranges.length - 1].to; + let dist = Math.floor(total * ratio); + for (let i = 0;; i++) { + let { from, to } = ranges[i], size = to - from; + if (dist <= size) + return from + dist; + dist -= size; + } + } + function findFraction(structure, pos) { + let counted = 0; + for (let { from, to } of structure.ranges) { + if (pos <= to) { + counted += pos - from; + break; + } + counted += to - from; + } + return counted / structure.total; + } + function find(array, f) { + for (let val of array) + if (f(val)) + return val; + return undefined; + } + // Don't scale when the document height is within the range of what + // the DOM can handle. + const IdScaler = { + toDOM(n) { return n; }, + fromDOM(n) { return n; }, + scale: 1 + }; + // When the height is too big (> VP.MaxDOMHeight), scale down the + // regions outside the viewports so that the total height is + // VP.MaxDOMHeight. + class BigScaler { + constructor(doc, heightMap, viewports) { + let vpHeight = 0, base = 0, domBase = 0; + this.viewports = viewports.map(({ from, to }) => { + let top = heightMap.lineAt(from, QueryType$1.ByPos, doc, 0, 0).top; + let bottom = heightMap.lineAt(to, QueryType$1.ByPos, doc, 0, 0).bottom; + vpHeight += bottom - top; + return { from, to, top, bottom, domTop: 0, domBottom: 0 }; + }); + this.scale = (7000000 /* VP.MaxDOMHeight */ - vpHeight) / (heightMap.height - vpHeight); + for (let obj of this.viewports) { + obj.domTop = domBase + (obj.top - base) * this.scale; + domBase = obj.domBottom = obj.domTop + (obj.bottom - obj.top); + base = obj.bottom; + } + } + toDOM(n) { + for (let i = 0, base = 0, domBase = 0;; i++) { + let vp = i < this.viewports.length ? this.viewports[i] : null; + if (!vp || n < vp.top) + return domBase + (n - base) * this.scale; + if (n <= vp.bottom) + return vp.domTop + (n - vp.top); + base = vp.bottom; + domBase = vp.domBottom; + } + } + fromDOM(n) { + for (let i = 0, base = 0, domBase = 0;; i++) { + let vp = i < this.viewports.length ? this.viewports[i] : null; + if (!vp || n < vp.domTop) + return base + (n - domBase) / this.scale; + if (n <= vp.domBottom) + return vp.top + (n - vp.domTop); + base = vp.bottom; + domBase = vp.domBottom; + } + } + } + function scaleBlock(block, scaler) { + if (scaler.scale == 1) + return block; + let bTop = scaler.toDOM(block.top), bBottom = scaler.toDOM(block.bottom); + return new BlockInfo(block.from, block.length, bTop, bBottom - bTop, Array.isArray(block.type) ? block.type.map(b => scaleBlock(b, scaler)) : block.type); + } + + const theme = /*@__PURE__*/Facet.define({ combine: strs => strs.join(" ") }); + const darkTheme = /*@__PURE__*/Facet.define({ combine: values => values.indexOf(true) > -1 }); + const baseThemeID = /*@__PURE__*/StyleModule.newName(), baseLightID = /*@__PURE__*/StyleModule.newName(), baseDarkID = /*@__PURE__*/StyleModule.newName(); + const lightDarkIDs = { "&light": "." + baseLightID, "&dark": "." + baseDarkID }; + function buildTheme(main, spec, scopes) { + return new StyleModule(spec, { + finish(sel) { + return /&/.test(sel) ? sel.replace(/&\w*/, m => { + if (m == "&") + return main; + if (!scopes || !scopes[m]) + throw new RangeError(`Unsupported selector: ${m}`); + return scopes[m]; + }) : main + " " + sel; + } + }); + } + const baseTheme$1$3 = /*@__PURE__*/buildTheme("." + baseThemeID, { + "&.cm-editor": { + position: "relative !important", + boxSizing: "border-box", + "&.cm-focused": { + // Provide a simple default outline to make sure a focused + // editor is visually distinct. Can't leave the default behavior + // because that will apply to the content element, which is + // inside the scrollable container and doesn't include the + // gutters. We also can't use an 'auto' outline, since those + // are, for some reason, drawn behind the element content, which + // will cause things like the active line background to cover + // the outline (#297). + 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, + minHeight: "100%", + display: "block", + whiteSpace: "pre", + wordWrap: "normal", + boxSizing: "border-box", + 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 4px" + }, + ".cm-selectionLayer": { + zIndex: -1, + contain: "size style" + }, + ".cm-selectionBackground": { + position: "absolute", + }, + "&light .cm-selectionBackground": { + background: "#d9d9d9" + }, + "&dark .cm-selectionBackground": { + background: "#222" + }, + "&light.cm-focused .cm-selectionBackground": { + background: "#d7d4f0" + }, + "&dark.cm-focused .cm-selectionBackground": { + background: "#233" + }, + ".cm-cursorLayer": { + zIndex: 100, + contain: "size style", + pointerEvents: "none" + }, + "&.cm-focused .cm-cursorLayer": { + animation: "steps(1) cm-blink 1.2s infinite" + }, + // Two animations defined so that we can switch between them to + // restart the animation without forcing another style + // recomputation. + "@keyframes cm-blink": { "0%": {}, "50%": { opacity: 0 }, "100%": {} }, + "@keyframes cm-blink2": { "0%": {}, "50%": { opacity: 0 }, "100%": {} }, + ".cm-cursor, .cm-dropCursor": { + position: "absolute", + borderLeft: "1.2px solid black", + marginLeft: "-0.6px", + pointerEvents: "none", + }, + ".cm-cursor": { + display: "none" + }, + "&dark .cm-cursor": { + borderLeftColor: "#444" + }, + "&.cm-focused .cm-cursor": { + display: "block" + }, + "&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", + left: 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-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" + } + }, lightDarkIDs); + + const observeOptions = { + childList: true, + characterData: true, + subtree: true, + attributes: true, + characterDataOldValue: true + }; + // IE11 has very broken mutation observers, so we also listen to + // DOMCharacterDataModified there + const useCharData = browser.ie && browser.ie_version <= 11; + class DOMObserver { + constructor(view, onChange, onScrollChanged) { + this.view = view; + this.onChange = onChange; + this.onScrollChanged = onScrollChanged; + this.active = false; + // The known selection. Kept in our own object, as opposed to just + // directly accessing the selection because: + // - Safari doesn't report the right selection in shadow DOM + // - Reading from the selection forces a DOM layout + // - This way, we can ignore selectionchange events if we have + // already seen the 'new' selection + this.selectionRange = new DOMSelectionState; + // Set when a selection change is detected, cleared on flush + this.selectionChanged = false; + this.delayedFlush = -1; + this.resizeTimeout = -1; + this.queue = []; + this.delayedAndroidKey = null; + this.lastChange = 0; + this.scrollTargets = []; + this.intersection = null; + this.resize = null; + this.intersecting = false; + this.gapIntersection = null; + this.gaps = []; + // Timeout for scheduling check of the parents that need scroll handlers + this.parentCheck = -1; + this.dom = view.contentDOM; + this.observer = new MutationObserver(mutations => { + for (let mut of mutations) + this.queue.push(mut); + // IE11 will sometimes (on typing over a selection or + // backspacing out a single character text node) call the + // observer callback before actually updating the DOM. + // + // Unrelatedly, iOS Safari will, when ending a composition, + // sometimes first clear it, deliver the mutations, and then + // reinsert the finished text. CodeMirror's handling of the + // deletion will prevent the reinsertion from happening, + // breaking composition. + if ((browser.ie && browser.ie_version <= 11 || browser.ios && view.composing) && + mutations.some(m => m.type == "childList" && m.removedNodes.length || + m.type == "characterData" && m.oldValue.length > m.target.nodeValue.length)) + this.flushSoon(); + else + this.flush(); + }); + if (useCharData) + this.onCharData = (event) => { + this.queue.push({ target: event.target, + type: "characterData", + oldValue: event.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); + if (typeof ResizeObserver == "function") { + this.resize = new ResizeObserver(() => { + if (this.view.docView.lastUpdate < Date.now() - 75) + this.onResize(); + }); + this.resize.observe(view.scrollDOM); + } + this.addWindowListeners(this.win = view.win); + this.start(); + if (typeof IntersectionObserver == "function") { + this.intersection = new IntersectionObserver(entries => { + if (this.parentCheck < 0) + this.parentCheck = setTimeout(this.listenForScroll.bind(this), 1000); + if (entries.length > 0 && (entries[entries.length - 1].intersectionRatio > 0) != this.intersecting) { + this.intersecting = !this.intersecting; + if (this.intersecting != this.view.inView) + this.onScrollChanged(document.createEvent("Event")); + } + }, {}); + this.intersection.observe(this.dom); + this.gapIntersection = new IntersectionObserver(entries => { + if (entries.length > 0 && entries[entries.length - 1].intersectionRatio > 0) + this.onScrollChanged(document.createEvent("Event")); + }, {}); + } + this.listenForScroll(); + this.readSelectionRange(); + } + onScroll(e) { + if (this.intersecting) + this.flush(false); + this.onScrollChanged(e); + } + onResize() { + if (this.resizeTimeout < 0) + this.resizeTimeout = setTimeout(() => { + this.resizeTimeout = -1; + this.view.requestMeasure(); + }, 50); + } + onPrint() { + this.view.viewState.printing = true; + this.view.measure(); + setTimeout(() => { + this.view.viewState.printing = false; + this.view.requestMeasure(); + }, 500); + } + updateGaps(gaps) { + if (this.gapIntersection && (gaps.length != this.gaps.length || this.gaps.some((g, i) => g != gaps[i]))) { + this.gapIntersection.disconnect(); + for (let gap of gaps) + this.gapIntersection.observe(gap); + this.gaps = gaps; + } + } + onSelectionChange(event) { + let wasChanged = this.selectionChanged; + if (!this.readSelectionRange() || this.delayedAndroidKey) + return; + let { view } = this, sel = this.selectionRange; + if (view.state.facet(editable) ? view.root.activeElement != this.dom : !hasSelection(view.dom, sel)) + return; + let context = sel.anchorNode && view.docView.nearest(sel.anchorNode); + if (context && context.ignoreEvent(event)) { + if (!wasChanged) + this.selectionChanged = false; + return; + } + // Deletions on IE11 fire their events in the wrong order, giving + // us a selection change event before the DOM changes are + // reported. + // Chrome Android has a similar issue when backspacing out a + // selection (#645). + if ((browser.ie && browser.ie_version <= 11 || browser.android && browser.chrome) && !view.state.selection.main.empty && + // (Selection.isCollapsed isn't reliable on IE) + sel.focusNode && isEquivalentPosition(sel.focusNode, sel.focusOffset, sel.anchorNode, sel.anchorOffset)) + this.flushSoon(); + else + this.flush(false); + } + readSelectionRange() { + let { view } = this; + // The Selection object is broken in shadow roots in Safari. See + // https://github.com/codemirror/dev/issues/414 + let range = browser.safari && view.root.nodeType == 11 && + deepActiveElement(this.dom.ownerDocument) == this.dom && + safariSelectionRangeHack(this.view) || getSelection(view.root); + if (!range || this.selectionRange.eq(range)) + return false; + let local = hasSelection(this.dom, range); + // Detect the situation where the browser has, on focus, moved the + // selection to the start of the content element. Reset it to the + // position from the editor state. + if (local && !this.selectionChanged && + view.inputState.lastFocusTime > Date.now() - 200 && + view.inputState.lastTouchTime < Date.now() - 300 && + atElementStart(this.dom, range)) { + this.view.inputState.lastFocusTime = 0; + view.docView.updateSelection(); + return false; + } + this.selectionRange.setRange(range); + if (local) + this.selectionChanged = true; + return true; + } + setSelectionRange(anchor, head) { + this.selectionRange.set(anchor.node, anchor.offset, head.node, head.offset); + this.selectionChanged = false; + } + clearSelectionRange() { + this.selectionRange.set(null, 0, null, 0); + } + listenForScroll() { + this.parentCheck = -1; + let i = 0, changed = null; + for (let dom = this.dom; dom;) { + if (dom.nodeType == 1) { + if (!changed && i < this.scrollTargets.length && this.scrollTargets[i] == dom) + i++; + else if (!changed) + changed = this.scrollTargets.slice(0, i); + if (changed) + changed.push(dom); + dom = dom.assignedSlot || dom.parentNode; + } + else if (dom.nodeType == 11) { // Shadow root + dom = dom.host; + } + else { + break; + } + } + if (i < this.scrollTargets.length && !changed) + changed = this.scrollTargets.slice(0, i); + if (changed) { + for (let dom of this.scrollTargets) + dom.removeEventListener("scroll", this.onScroll); + for (let dom of this.scrollTargets = changed) + dom.addEventListener("scroll", this.onScroll); + } + } + ignore(f) { + if (!this.active) + return f(); + try { + this.stop(); + return f(); + } + finally { + this.start(); + this.clear(); + } + } + start() { + if (this.active) + return; + this.observer.observe(this.dom, observeOptions); + if (useCharData) + this.dom.addEventListener("DOMCharacterDataModified", this.onCharData); + this.active = true; + } + stop() { + if (!this.active) + return; + this.active = false; + this.observer.disconnect(); + if (useCharData) + this.dom.removeEventListener("DOMCharacterDataModified", this.onCharData); + } + // Throw away any pending changes + clear() { + this.processRecords(); + this.queue.length = 0; + this.selectionChanged = false; + } + // Chrome Android, especially in combination with GBoard, not only + // doesn't reliably fire regular key events, but also often + // surrounds the effect of enter or backspace with a bunch of + // composition events that, when interrupted, cause text duplication + // or other kinds of corruption. This hack makes the editor back off + // from handling DOM changes for a moment when such a key is + // detected (via beforeinput or keydown), and then tries to flush + // them or, if that has no effect, dispatches the given key. + delayAndroidKey(key, keyCode) { + var _a; + if (!this.delayedAndroidKey) + this.view.win.requestAnimationFrame(() => { + let key = this.delayedAndroidKey; + this.delayedAndroidKey = null; + this.delayedFlush = -1; + if (!this.flush() && key.force) + dispatchKey(this.dom, key.key, key.keyCode); + }); + // Since backspace beforeinput is sometimes signalled spuriously, + // Enter always takes precedence. + if (!this.delayedAndroidKey || key == "Enter") + this.delayedAndroidKey = { + key, keyCode, + // Only run the key handler when no changes are detected if + // this isn't coming right after another change, in which case + // it is probably part of a weird chain of updates, and should + // be ignored if it returns the DOM to its previous state. + force: this.lastChange < Date.now() - 50 || !!((_a = this.delayedAndroidKey) === null || _a === void 0 ? void 0 : _a.force) + }; + } + flushSoon() { + if (this.delayedFlush < 0) + this.delayedFlush = this.view.win.requestAnimationFrame(() => { this.delayedFlush = -1; this.flush(); }); + } + forceFlush() { + if (this.delayedFlush >= 0) { + this.view.win.cancelAnimationFrame(this.delayedFlush); + this.delayedFlush = -1; + } + this.flush(); + } + processRecords() { + let records = this.queue; + for (let mut of this.observer.takeRecords()) + records.push(mut); + if (records.length) + this.queue = []; + let from = -1, to = -1, typeOver = false; + for (let record of records) { + let range = this.readMutation(record); + if (!range) + continue; + if (range.typeOver) + typeOver = true; + if (from == -1) { + ({ from, to } = range); + } + else { + from = Math.min(range.from, from); + to = Math.max(range.to, to); + } + } + return { from, to, typeOver }; + } + // Apply pending changes, if any + flush(readSelection = true) { + // Completely hold off flushing when pending keys are set—the code + // managing those will make sure processRecords is called and the + // view is resynchronized after + if (this.delayedFlush >= 0 || this.delayedAndroidKey) + return false; + if (readSelection) + this.readSelectionRange(); + let { from, to, typeOver } = this.processRecords(); + let newSel = this.selectionChanged && hasSelection(this.dom, this.selectionRange); + if (from < 0 && !newSel) + return false; + if (from > -1) + this.lastChange = Date.now(); + this.view.inputState.lastFocusTime = 0; + this.selectionChanged = false; + let startState = this.view.state; + let handled = this.onChange(from, to, typeOver); + // The view wasn't updated + if (this.view.state == startState) + this.view.update([]); + return handled; + } + readMutation(rec) { + let cView = this.view.docView.nearest(rec.target); + if (!cView || cView.ignoreMutation(rec)) + return null; + cView.markDirty(rec.type == "attributes"); + if (rec.type == "attributes") + cView.dirty |= 4 /* Dirty.Attrs */; + if (rec.type == "childList") { + let childBefore = findChild(cView, rec.previousSibling || rec.target.previousSibling, -1); + let childAfter = findChild(cView, rec.nextSibling || rec.target.nextSibling, 1); + return { from: childBefore ? cView.posAfter(childBefore) : cView.posAtStart, + to: childAfter ? cView.posBefore(childAfter) : cView.posAtEnd, typeOver: false }; + } + else if (rec.type == "characterData") { + return { from: cView.posAtStart, to: cView.posAtEnd, typeOver: rec.target.nodeValue == rec.oldValue }; + } + else { + return null; + } + } + setWindow(win) { + if (win != this.win) { + this.removeWindowListeners(this.win); + this.win = win; + this.addWindowListeners(this.win); + } + } + addWindowListeners(win) { + win.addEventListener("resize", this.onResize); + win.addEventListener("beforeprint", this.onPrint); + win.addEventListener("scroll", this.onScroll); + win.document.addEventListener("selectionchange", this.onSelectionChange); + } + removeWindowListeners(win) { + win.removeEventListener("scroll", this.onScroll); + win.removeEventListener("resize", this.onResize); + win.removeEventListener("beforeprint", this.onPrint); + win.document.removeEventListener("selectionchange", this.onSelectionChange); + } + destroy() { + var _a, _b, _c; + this.stop(); + (_a = this.intersection) === null || _a === void 0 ? void 0 : _a.disconnect(); + (_b = this.gapIntersection) === null || _b === void 0 ? void 0 : _b.disconnect(); + (_c = this.resize) === null || _c === void 0 ? void 0 : _c.disconnect(); + for (let dom of this.scrollTargets) + dom.removeEventListener("scroll", this.onScroll); + this.removeWindowListeners(this.win); + clearTimeout(this.parentCheck); + clearTimeout(this.resizeTimeout); + } + } + function findChild(cView, dom, dir) { + while (dom) { + let curView = ContentView.get(dom); + if (curView && curView.parent == cView) + return curView; + let parent = dom.parentNode; + dom = parent != cView.dom ? parent : dir > 0 ? dom.nextSibling : dom.previousSibling; + } + return null; + } + // Used to work around a Safari Selection/shadow DOM bug (#414) + function safariSelectionRangeHack(view) { + let found = null; + // Because Safari (at least in 2018-2021) doesn't provide regular + // access to the selection inside a shadowroot, we have to perform a + // ridiculous hack to get at it—using `execCommand` to trigger a + // `beforeInput` event so that we can read the target range from the + // event. + function read(event) { + event.preventDefault(); + event.stopImmediatePropagation(); + found = event.getTargetRanges()[0]; + } + view.contentDOM.addEventListener("beforeinput", read, true); + view.dom.ownerDocument.execCommand("indent"); + view.contentDOM.removeEventListener("beforeinput", read, true); + if (!found) + return null; + let anchorNode = found.startContainer, anchorOffset = found.startOffset; + let focusNode = found.endContainer, focusOffset = found.endOffset; + let curAnchor = view.docView.domAtPos(view.state.selection.main.anchor); + // Since such a range doesn't distinguish between anchor and head, + // use a heuristic that flips it around if its end matches the + // current anchor. + if (isEquivalentPosition(curAnchor.node, curAnchor.offset, focusNode, focusOffset)) + [anchorNode, anchorOffset, focusNode, focusOffset] = [focusNode, focusOffset, anchorNode, anchorOffset]; + return { anchorNode, anchorOffset, focusNode, focusOffset }; + } + + function applyDOMChange(view, start, end, typeOver) { + let change, newSel; + let sel = view.state.selection.main; + if (start > -1) { + let bounds = view.docView.domBoundsAround(start, end, 0); + if (!bounds || view.state.readOnly) + return false; + let { from, to } = bounds; + let selPoints = view.docView.impreciseHead || view.docView.impreciseAnchor ? [] : selectionPoints(view); + let reader = new DOMReader(selPoints, view.state); + reader.readRange(bounds.startDOM, bounds.endDOM); + let preferredPos = sel.from, preferredSide = null; + // Prefer anchoring to end when Backspace is pressed (or, on + // Android, when something was deleted) + if (view.inputState.lastKeyCode === 8 && view.inputState.lastKeyTime > Date.now() - 100 || + browser.android && reader.text.length < to - from) { + preferredPos = sel.to; + preferredSide = "end"; + } + let diff = findDiff(view.state.doc.sliceString(from, to, LineBreakPlaceholder), reader.text, preferredPos - from, preferredSide); + if (diff) { + // Chrome inserts two newlines when pressing shift-enter at the + // end of a line. This drops one of those. + if (browser.chrome && view.inputState.lastKeyCode == 13 && + diff.toB == diff.from + 2 && reader.text.slice(diff.from, diff.toB) == LineBreakPlaceholder + LineBreakPlaceholder) + diff.toB--; + change = { from: from + diff.from, to: from + diff.toA, + insert: Text.of(reader.text.slice(diff.from, diff.toB).split(LineBreakPlaceholder)) }; + } + newSel = selectionFromPoints(selPoints, from); + } + else if (view.hasFocus || !view.state.facet(editable)) { + let domSel = view.observer.selectionRange; + let { impreciseHead: iHead, impreciseAnchor: iAnchor } = view.docView; + let head = iHead && iHead.node == domSel.focusNode && iHead.offset == domSel.focusOffset || + !contains(view.contentDOM, domSel.focusNode) + ? view.state.selection.main.head + : view.docView.posFromDOM(domSel.focusNode, domSel.focusOffset); + let anchor = iAnchor && iAnchor.node == domSel.anchorNode && iAnchor.offset == domSel.anchorOffset || + !contains(view.contentDOM, domSel.anchorNode) + ? view.state.selection.main.anchor + : view.docView.posFromDOM(domSel.anchorNode, domSel.anchorOffset); + if (head != sel.head || anchor != sel.anchor) + newSel = EditorSelection.single(anchor, head); + } + if (!change && !newSel) + return false; + if (!change && typeOver && !sel.empty && newSel && newSel.main.empty) { + // Heuristic to notice typing over a selected character + change = { from: sel.from, to: sel.to, insert: view.state.doc.slice(sel.from, sel.to) }; + } + else if (change && change.from >= sel.from && change.to <= sel.to && + (change.from != sel.from || change.to != sel.to) && + (sel.to - sel.from) - (change.to - change.from) <= 4) { + // If the change is inside the selection and covers most of it, + // assume it is a selection replace (with identical characters at + // the start/end not included in the diff) + change = { + from: sel.from, to: sel.to, + insert: view.state.doc.slice(sel.from, change.from).append(change.insert).append(view.state.doc.slice(change.to, sel.to)) + }; + } + else if ((browser.mac || browser.android) && change && change.from == change.to && change.from == sel.head - 1 && + /^\. ?$/.test(change.insert.toString())) { + // Detect insert-period-on-double-space Mac and Android behavior, + // and transform it into a regular space insert. + if (newSel && change.insert.length == 2) + newSel = EditorSelection.single(newSel.main.anchor - 1, newSel.main.head - 1); + change = { from: sel.from, to: sel.to, insert: Text.of([" "]) }; + } + if (change) { + let startState = view.state; + if (browser.ios && view.inputState.flushIOSKey(view)) + return true; + // Android browsers don't fire reasonable key events for enter, + // backspace, or delete. So this detects changes that look like + // they're caused by those keys, and reinterprets them as key + // events. (Some of these keys are also handled by beforeinput + // events and the pendingAndroidKey mechanism, but that's not + // reliable in all situations.) + if (browser.android && + ((change.from == sel.from && change.to == sel.to && + change.insert.length == 1 && change.insert.lines == 2 && + dispatchKey(view.contentDOM, "Enter", 13)) || + (change.from == sel.from - 1 && change.to == sel.to && change.insert.length == 0 && + dispatchKey(view.contentDOM, "Backspace", 8)) || + (change.from == sel.from && change.to == sel.to + 1 && change.insert.length == 0 && + dispatchKey(view.contentDOM, "Delete", 46)))) + return true; + let text = change.insert.toString(); + if (view.state.facet(inputHandler$1).some(h => h(view, change.from, change.to, text))) + return true; + if (view.inputState.composing >= 0) + view.inputState.composing++; + let tr; + if (change.from >= sel.from && change.to <= sel.to && change.to - change.from >= (sel.to - sel.from) / 3 && + (!newSel || newSel.main.empty && newSel.main.from == change.from + change.insert.length) && + view.inputState.composing < 0) { + let before = sel.from < change.from ? startState.sliceDoc(sel.from, change.from) : ""; + let after = sel.to > change.to ? startState.sliceDoc(change.to, sel.to) : ""; + tr = startState.replaceSelection(view.state.toText(before + change.insert.sliceString(0, undefined, view.state.lineBreak) + after)); + } + else { + let changes = startState.changes(change); + let mainSel = newSel && !startState.selection.main.eq(newSel.main) && newSel.main.to <= changes.newLength + ? newSel.main : undefined; + // Try to apply a composition change to all cursors + if (startState.selection.ranges.length > 1 && view.inputState.composing >= 0 && + change.to <= sel.to && change.to >= sel.to - 10) { + let replaced = view.state.sliceDoc(change.from, change.to); + let compositionRange = compositionSurroundingNode(view) || view.state.doc.lineAt(sel.head); + let offset = sel.to - change.to, size = sel.to - sel.from; + tr = startState.changeByRange(range => { + if (range.from == sel.from && range.to == sel.to) + return { changes, range: mainSel || range.map(changes) }; + let to = range.to - offset, from = to - replaced.length; + if (range.to - range.from != size || view.state.sliceDoc(from, to) != replaced || + // Unfortunately, there's no way to make multiple + // changes in the same node work without aborting + // composition, so cursors in the composition range are + // ignored. + compositionRange && range.to >= compositionRange.from && range.from <= compositionRange.to) + return { range }; + let rangeChanges = startState.changes({ from, to, insert: change.insert }), selOff = range.to - sel.to; + return { + changes: rangeChanges, + range: !mainSel ? range.map(rangeChanges) : + EditorSelection.range(Math.max(0, mainSel.anchor + selOff), Math.max(0, mainSel.head + selOff)) + }; + }); + } + else { + tr = { + changes, + selection: mainSel && startState.selection.replaceRange(mainSel) + }; + } + } + let userEvent = "input.type"; + if (view.composing) { + userEvent += ".compose"; + if (view.inputState.compositionFirstChange) { + userEvent += ".start"; + view.inputState.compositionFirstChange = false; + } + } + view.dispatch(tr, { scrollIntoView: true, userEvent }); + return true; + } + else if (newSel && !newSel.main.eq(sel)) { + let scrollIntoView = false, userEvent = "select"; + if (view.inputState.lastSelectionTime > Date.now() - 50) { + if (view.inputState.lastSelectionOrigin == "select") + scrollIntoView = true; + userEvent = view.inputState.lastSelectionOrigin; + } + view.dispatch({ selection: newSel, scrollIntoView, userEvent }); + return true; + } + else { + return false; + } + } + function findDiff(a, b, preferredPos, preferredSide) { + let minLen = Math.min(a.length, b.length); + let from = 0; + while (from < minLen && a.charCodeAt(from) == b.charCodeAt(from)) + from++; + if (from == minLen && a.length == b.length) + return null; + let toA = a.length, toB = b.length; + while (toA > 0 && toB > 0 && a.charCodeAt(toA - 1) == b.charCodeAt(toB - 1)) { + toA--; + toB--; + } + if (preferredSide == "end") { + let adjust = Math.max(0, from - Math.min(toA, toB)); + preferredPos -= toA + adjust - from; + } + if (toA < from && a.length < b.length) { + let move = preferredPos <= from && preferredPos >= toA ? from - preferredPos : 0; + from -= move; + toB = from + (toB - toA); + toA = from; + } + else if (toB < from) { + let move = preferredPos <= from && preferredPos >= toB ? from - preferredPos : 0; + from -= move; + toA = from + (toA - toB); + toB = from; + } + return { from, toA, toB }; + } + function selectionPoints(view) { + let result = []; + if (view.root.activeElement != view.contentDOM) + return result; + let { anchorNode, anchorOffset, focusNode, focusOffset } = view.observer.selectionRange; + if (anchorNode) { + result.push(new DOMPoint(anchorNode, anchorOffset)); + if (focusNode != anchorNode || focusOffset != anchorOffset) + result.push(new DOMPoint(focusNode, focusOffset)); + } + return result; + } + function selectionFromPoints(points, base) { + if (points.length == 0) + return null; + let anchor = points[0].pos, head = points.length == 2 ? points[1].pos : anchor; + return anchor > -1 && head > -1 ? EditorSelection.single(anchor + base, head + base) : null; + } + + // The editor's update state machine looks something like this: + // + // Idle → Updating ⇆ Idle (unchecked) → Measuring → Idle + // ↑ ↓ + // Updating (measure) + // + // The difference between 'Idle' and 'Idle (unchecked)' lies in + // whether a layout check has been scheduled. A regular update through + // the `update` method updates the DOM in a write-only fashion, and + // relies on a check (scheduled with `requestAnimationFrame`) to make + // sure everything is where it should be and the viewport covers the + // visible code. That check continues to measure and then optionally + // update until it reaches a coherent state. + /** + An editor view represents the editor's user interface. It holds + the editable DOM surface, and possibly other elements such as the + line number gutter. It handles events and dispatches state + transactions for editing actions. + */ + class EditorView { + /** + Construct a new view. You'll want to either provide a `parent` + option, or put `view.dom` into your document after creating a + view, so that the user can see the editor. + */ + constructor(config = {}) { + this.plugins = []; + this.pluginMap = new Map; + this.editorAttrs = {}; + this.contentAttrs = {}; + this.bidiCache = []; + this.destroyed = false; + /** + @internal + */ + this.updateState = 2 /* UpdateState.Updating */; + /** + @internal + */ + this.measureScheduled = -1; + /** + @internal + */ + 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.style.cssText = "position: absolute; top: -10000px"; + this.announceDOM.setAttribute("aria-live", "polite"); + this.dom = document.createElement("div"); + this.dom.appendChild(this.announceDOM); + this.dom.appendChild(this.scrollDOM); + this._dispatch = config.dispatch || ((tr) => this.update([tr])); + this.dispatch = this.dispatch.bind(this); + this._root = (config.root || getRoot(config.parent) || document); + this.viewState = new ViewState(config.state || EditorState.create(config)); + this.plugins = this.state.facet(viewPlugin).map(spec => new PluginInstance(spec)); + for (let plugin of this.plugins) + plugin.update(this); + this.observer = new DOMObserver(this, (from, to, typeOver) => { + return applyDOMChange(this, from, to, typeOver); + }, event => { + this.inputState.runScrollHandlers(this, event); + if (this.observer.intersecting) + this.measure(); + }); + this.inputState = new InputState(this); + this.inputState.ensureHandlers(this, this.plugins); + this.docView = new DocView(this); + this.mountStyles(); + this.updateAttrs(); + this.updateState = 0 /* UpdateState.Idle */; + this.requestMeasure(); + if (config.parent) + config.parent.appendChild(this.dom); + } + /** + The current editor state. + */ + get state() { return this.viewState.state; } + /** + To be able to display large documents without consuming too much + memory or overloading the browser, CodeMirror only draws the + code that is visible (plus a margin around it) to the DOM. This + property tells you the extent of the current drawn viewport, in + document positions. + */ + get viewport() { return this.viewState.viewport; } + /** + When there are, for example, large collapsed ranges in the + viewport, its size can be a lot bigger than the actual visible + content. Thus, if you are doing something like styling the + content in the viewport, it is preferable to only do so for + these ranges, which are the subset of the viewport that is + actually drawn. + */ + get visibleRanges() { return this.viewState.visibleRanges; } + /** + Returns false when the editor is entirely scrolled out of view + or otherwise hidden. + */ + get inView() { return this.viewState.inView; } + /** + Indicates whether the user is currently composing text via + [IME](https://en.wikipedia.org/wiki/Input_method), and at least + one change has been made in the current composition. + */ + get composing() { return this.inputState.composing > 0; } + /** + Indicates whether the user is currently in composing state. Note + that on some platforms, like Android, this will be the case a + lot, since just putting the cursor on a word starts a + composition there. + */ + get compositionStarted() { return this.inputState.composing >= 0; } + /** + The document or shadow root that the view lives in. + */ + get root() { return this._root; } + /** + @internal + */ + get win() { return this.dom.ownerDocument.defaultView || window; } + dispatch(...input) { + this._dispatch(input.length == 1 && input[0] instanceof Transaction ? input[0] + : this.state.update(...input)); + } + /** + Update the view for the given array of transactions. This will + update the visible document and selection to match the state + produced by the transactions, and notify view plugins of the + change. You should usually call + [`dispatch`](https://codemirror.net/6/docs/ref/#view.EditorView.dispatch) instead, which uses this + as a primitive. + */ + update(transactions) { + if (this.updateState != 0 /* UpdateState.Idle */) + throw new Error("Calls to EditorView.update are not allowed while an update is in progress"); + let redrawn = false, attrsChanged = false, update; + let state = this.state; + for (let tr of transactions) { + if (tr.startState != state) + throw new RangeError("Trying to update state with a transaction that doesn't start from the previous state."); + state = tr.state; + } + if (this.destroyed) { + this.viewState.state = state; + return; + } + this.observer.clear(); + // When the phrases change, redraw the editor + if (state.facet(EditorState.phrases) != this.state.facet(EditorState.phrases)) + return this.setState(state); + update = ViewUpdate.create(this, state, transactions); + let scrollTarget = this.viewState.scrollTarget; + try { + this.updateState = 2 /* UpdateState.Updating */; + for (let tr of transactions) { + if (scrollTarget) + scrollTarget = scrollTarget.map(tr.changes); + if (tr.scrollIntoView) { + let { main } = tr.state.selection; + scrollTarget = new ScrollTarget(main.empty ? main : EditorSelection.cursor(main.head, main.head > main.anchor ? -1 : 1)); + } + for (let e of tr.effects) + if (e.is(scrollIntoView$1)) + scrollTarget = e.value; + } + this.viewState.update(update, scrollTarget); + this.bidiCache = CachedOrder.update(this.bidiCache, update.changes); + if (!update.empty) { + this.updatePlugins(update); + this.inputState.update(update); + } + redrawn = this.docView.update(update); + if (this.state.facet(styleModule) != this.styleModules) + this.mountStyles(); + attrsChanged = this.updateAttrs(); + this.showAnnouncements(transactions); + this.docView.updateSelection(redrawn, transactions.some(tr => tr.isUserEvent("select.pointer"))); + } + finally { + this.updateState = 0 /* UpdateState.Idle */; + } + if (update.startState.facet(theme) != update.state.facet(theme)) + this.viewState.mustMeasureContent = true; + if (redrawn || attrsChanged || scrollTarget || this.viewState.mustEnforceCursorAssoc || this.viewState.mustMeasureContent) + this.requestMeasure(); + if (!update.empty) + for (let listener of this.state.facet(updateListener)) + listener(update); + } + /** + Reset the view to the given state. (This will cause the entire + document to be redrawn and all view plugins to be reinitialized, + so you should probably only use it when the new state isn't + derived from the old state. Otherwise, use + [`dispatch`](https://codemirror.net/6/docs/ref/#view.EditorView.dispatch) instead.) + */ + setState(newState) { + if (this.updateState != 0 /* UpdateState.Idle */) + throw new Error("Calls to EditorView.setState are not allowed while an update is in progress"); + if (this.destroyed) { + this.viewState.state = newState; + return; + } + this.updateState = 2 /* UpdateState.Updating */; + let hadFocus = this.hasFocus; + try { + for (let plugin of this.plugins) + plugin.destroy(this); + this.viewState = new ViewState(newState); + this.plugins = newState.facet(viewPlugin).map(spec => new PluginInstance(spec)); + this.pluginMap.clear(); + for (let plugin of this.plugins) + plugin.update(this); + this.docView = new DocView(this); + this.inputState.ensureHandlers(this, this.plugins); + this.mountStyles(); + this.updateAttrs(); + this.bidiCache = []; + } + finally { + this.updateState = 0 /* UpdateState.Idle */; + } + if (hadFocus) + this.focus(); + this.requestMeasure(); + } + updatePlugins(update) { + let prevSpecs = update.startState.facet(viewPlugin), specs = update.state.facet(viewPlugin); + if (prevSpecs != specs) { + let newPlugins = []; + for (let spec of specs) { + let found = prevSpecs.indexOf(spec); + if (found < 0) { + newPlugins.push(new PluginInstance(spec)); + } + else { + let plugin = this.plugins[found]; + plugin.mustUpdate = update; + newPlugins.push(plugin); + } + } + for (let plugin of this.plugins) + if (plugin.mustUpdate != update) + plugin.destroy(this); + this.plugins = newPlugins; + this.pluginMap.clear(); + this.inputState.ensureHandlers(this, this.plugins); + } + else { + for (let p of this.plugins) + p.mustUpdate = update; + } + for (let i = 0; i < this.plugins.length; i++) + this.plugins[i].update(this); + } + /** + @internal + */ + measure(flush = true) { + if (this.destroyed) + return; + if (this.measureScheduled > -1) + cancelAnimationFrame(this.measureScheduled); + this.measureScheduled = 0; // Prevent requestMeasure calls from scheduling another animation frame + if (flush) + this.observer.forceFlush(); + let updated = null; + let { scrollHeight, scrollTop, clientHeight } = this.scrollDOM; + let refHeight = scrollTop > scrollHeight - clientHeight - 4 ? scrollHeight : scrollTop; + try { + for (let i = 0;; i++) { + this.updateState = 1 /* UpdateState.Measuring */; + let oldViewport = this.viewport; + let refBlock = this.viewState.lineBlockAtHeight(refHeight); + let changed = this.viewState.measure(this); + if (!changed && !this.measureRequests.length && this.viewState.scrollTarget == null) + break; + if (i > 5) { + console.warn(this.measureRequests.length + ? "Measure loop restarted more than 5 times" + : "Viewport failed to stabilize"); + break; + } + let measuring = []; + // Only run measure requests in this cycle when the viewport didn't change + if (!(changed & 4 /* UpdateFlag.Viewport */)) + [this.measureRequests, measuring] = [measuring, this.measureRequests]; + let measured = measuring.map(m => { + try { + return m.read(this); + } + catch (e) { + logException(this.state, e); + return BadMeasure; + } + }); + let update = ViewUpdate.create(this, this.state, []), redrawn = false, scrolled = false; + update.flags |= changed; + if (!updated) + updated = update; + else + updated.flags |= changed; + this.updateState = 2 /* UpdateState.Updating */; + if (!update.empty) { + this.updatePlugins(update); + this.inputState.update(update); + this.updateAttrs(); + redrawn = this.docView.update(update); + } + for (let i = 0; i < measuring.length; i++) + if (measured[i] != BadMeasure) { + try { + let m = measuring[i]; + if (m.write) + m.write(measured[i], this); + } + catch (e) { + logException(this.state, e); + } + } + if (this.viewState.scrollTarget) { + this.docView.scrollIntoView(this.viewState.scrollTarget); + this.viewState.scrollTarget = null; + scrolled = true; + } + else { + let diff = this.viewState.lineBlockAt(refBlock.from).top - refBlock.top; + if (diff > 1 || diff < -1) { + this.scrollDOM.scrollTop += diff; + scrolled = true; + } + } + if (redrawn) + this.docView.updateSelection(true); + if (this.viewport.from == oldViewport.from && this.viewport.to == oldViewport.to && + !scrolled && this.measureRequests.length == 0) + break; + } + } + finally { + this.updateState = 0 /* UpdateState.Idle */; + this.measureScheduled = -1; + } + if (updated && !updated.empty) + for (let listener of this.state.facet(updateListener)) + listener(updated); + } + /** + Get the CSS classes for the currently active editor themes. + */ + get themeClasses() { + return baseThemeID + " " + + (this.state.facet(darkTheme) ? baseDarkID : baseLightID) + " " + + this.state.facet(theme); + } + updateAttrs() { + let editorAttrs = attrsFromFacet(this, editorAttributes, { + class: "cm-editor" + (this.hasFocus ? " cm-focused " : " ") + this.themeClasses + }); + let contentAttrs = { + spellcheck: "false", + autocorrect: "off", + autocapitalize: "off", + translate: "no", + contenteditable: !this.state.facet(editable) ? "false" : "true", + class: "cm-content", + style: `${browser.tabSize}: ${this.state.tabSize}`, + role: "textbox", + "aria-multiline": "true" + }; + if (this.state.readOnly) + contentAttrs["aria-readonly"] = "true"; + attrsFromFacet(this, contentAttributes, contentAttrs); + let changed = this.observer.ignore(() => { + let changedContent = updateAttrs(this.contentDOM, this.contentAttrs, contentAttrs); + let changedEditor = updateAttrs(this.dom, this.editorAttrs, editorAttrs); + return changedContent || changedEditor; + }); + this.editorAttrs = editorAttrs; + this.contentAttrs = contentAttrs; + return changed; + } + showAnnouncements(trs) { + let first = true; + for (let tr of trs) + for (let effect of tr.effects) + if (effect.is(EditorView.announce)) { + if (first) + this.announceDOM.textContent = ""; + first = false; + let div = this.announceDOM.appendChild(document.createElement("div")); + div.textContent = effect.value; + } + } + mountStyles() { + this.styleModules = this.state.facet(styleModule); + StyleModule.mount(this.root, this.styleModules.concat(baseTheme$1$3).reverse()); + } + readMeasured() { + if (this.updateState == 2 /* UpdateState.Updating */) + throw new Error("Reading the editor layout isn't allowed during an update"); + if (this.updateState == 0 /* UpdateState.Idle */ && this.measureScheduled > -1) + this.measure(false); + } + /** + Schedule a layout measurement, optionally providing callbacks to + do custom DOM measuring followed by a DOM write phase. Using + this is preferable reading DOM layout directly from, for + example, an event handler, because it'll make sure measuring and + drawing done by other components is synchronized, avoiding + unnecessary DOM layout computations. + */ + requestMeasure(request) { + if (this.measureScheduled < 0) + this.measureScheduled = this.win.requestAnimationFrame(() => this.measure()); + if (request) { + if (request.key != null) + for (let i = 0; i < this.measureRequests.length; i++) { + if (this.measureRequests[i].key === request.key) { + this.measureRequests[i] = request; + return; + } + } + this.measureRequests.push(request); + } + } + /** + Get the value of a specific plugin, if present. Note that + plugins that crash can be dropped from a view, so even when you + know you registered a given plugin, it is recommended to check + the return value of this method. + */ + plugin(plugin) { + let known = this.pluginMap.get(plugin); + if (known === undefined || known && known.spec != plugin) + this.pluginMap.set(plugin, known = this.plugins.find(p => p.spec == plugin) || null); + return known && known.update(this).value; + } + /** + The top position of the document, in screen coordinates. This + may be negative when the editor is scrolled down. Points + directly to the top of the first line, not above the padding. + */ + get documentTop() { + return this.contentDOM.getBoundingClientRect().top + this.viewState.paddingTop; + } + /** + Reports the padding above and below the document. + */ + get documentPadding() { + return { top: this.viewState.paddingTop, bottom: this.viewState.paddingBottom }; + } + /** + Find the text line or block widget at the given vertical + position (which is interpreted as relative to the [top of the + document](https://codemirror.net/6/docs/ref/#view.EditorView.documentTop)). + */ + elementAtHeight(height) { + this.readMeasured(); + return this.viewState.elementAtHeight(height); + } + /** + Find the line block (see + [`lineBlockAt`](https://codemirror.net/6/docs/ref/#view.EditorView.lineBlockAt) at the given + height, again interpreted relative to the [top of the + document](https://codemirror.net/6/docs/ref/#view.EditorView.documentTop). + */ + lineBlockAtHeight(height) { + this.readMeasured(); + return this.viewState.lineBlockAtHeight(height); + } + /** + Get the extent and vertical position of all [line + blocks](https://codemirror.net/6/docs/ref/#view.EditorView.lineBlockAt) in the viewport. Positions + are relative to the [top of the + document](https://codemirror.net/6/docs/ref/#view.EditorView.documentTop); + */ + get viewportLineBlocks() { + return this.viewState.viewportLines; + } + /** + Find the line block around the given document position. A line + block is a range delimited on both sides by either a + non-[hidden](https://codemirror.net/6/docs/ref/#view.Decoration^replace) line breaks, or the + start/end of the document. It will usually just hold a line of + text, but may be broken into multiple textblocks by block + widgets. + */ + lineBlockAt(pos) { + return this.viewState.lineBlockAt(pos); + } + /** + The editor's total content height. + */ + get contentHeight() { + return this.viewState.contentHeight; + } + /** + Move a cursor position by [grapheme + cluster](https://codemirror.net/6/docs/ref/#state.findClusterBreak). `forward` determines whether + the motion is away from the line start, or towards it. In + bidirectional text, the line is traversed in visual order, using + the editor's [text direction](https://codemirror.net/6/docs/ref/#view.EditorView.textDirection). + When the start position was the last one on the line, the + returned position will be across the line break. If there is no + further line, the original position is returned. + + By default, this method moves over a single cluster. The + optional `by` argument can be used to move across more. It will + be called with the first cluster as argument, and should return + a predicate that determines, for each subsequent cluster, + whether it should also be moved over. + */ + moveByChar(start, forward, by) { + return skipAtoms(this, start, moveByChar(this, start, forward, by)); + } + /** + Move a cursor position across the next group of either + [letters](https://codemirror.net/6/docs/ref/#state.EditorState.charCategorizer) or non-letter + non-whitespace characters. + */ + moveByGroup(start, forward) { + return skipAtoms(this, start, moveByChar(this, start, forward, initial => byGroup(this, start.head, initial))); + } + /** + Move to the next line boundary in the given direction. If + `includeWrap` is true, line wrapping is on, and there is a + further wrap point on the current line, the wrap point will be + returned. Otherwise this function will return the start or end + of the line. + */ + moveToLineBoundary(start, forward, includeWrap = true) { + return moveToLineBoundary(this, start, forward, includeWrap); + } + /** + Move a cursor position vertically. When `distance` isn't given, + it defaults to moving to the next line (including wrapped + lines). Otherwise, `distance` should provide a positive distance + in pixels. + + When `start` has a + [`goalColumn`](https://codemirror.net/6/docs/ref/#state.SelectionRange.goalColumn), the vertical + motion will use that as a target horizontal position. Otherwise, + the cursor's own horizontal position is used. The returned + cursor will have its goal column set to whichever column was + used. + */ + moveVertically(start, forward, distance) { + return skipAtoms(this, start, moveVertically(this, start, forward, distance)); + } + /** + Find the DOM parent node and offset (child offset if `node` is + an element, character offset when it is a text node) at the + given document position. + + Note that for positions that aren't currently in + `visibleRanges`, the resulting DOM position isn't necessarily + meaningful (it may just point before or after a placeholder + element). + */ + domAtPos(pos) { + return this.docView.domAtPos(pos); + } + /** + Find the document position at the given DOM node. Can be useful + for associating positions with DOM events. Will raise an error + when `node` isn't part of the editor content. + */ + posAtDOM(node, offset = 0) { + return this.docView.posFromDOM(node, offset); + } + posAtCoords(coords, precise = true) { + this.readMeasured(); + return posAtCoords(this, coords, precise); + } + /** + Get the screen coordinates at the given document position. + `side` determines whether the coordinates are based on the + element before (-1) or after (1) the position (if no element is + available on the given side, the method will transparently use + another strategy to get reasonable coordinates). + */ + coordsAtPos(pos, side = 1) { + this.readMeasured(); + let rect = this.docView.coordsAt(pos, side); + if (!rect || rect.left == rect.right) + return rect; + let line = this.state.doc.lineAt(pos), order = this.bidiSpans(line); + let span = order[BidiSpan.find(order, pos - line.from, -1, side)]; + return flattenRect(rect, (span.dir == Direction.LTR) == (side > 0)); + } + /** + The default width of a character in the editor. May not + accurately reflect the width of all characters (given variable + width fonts or styling of invididual ranges). + */ + get defaultCharacterWidth() { return this.viewState.heightOracle.charWidth; } + /** + The default height of a line in the editor. May not be accurate + for all lines. + */ + get defaultLineHeight() { return this.viewState.heightOracle.lineHeight; } + /** + The text direction + ([`direction`](https://developer.mozilla.org/en-US/docs/Web/CSS/direction) + CSS property) of the editor's content element. + */ + get textDirection() { return this.viewState.defaultTextDirection; } + /** + Find the text direction of the block at the given position, as + assigned by CSS. If + [`perLineTextDirection`](https://codemirror.net/6/docs/ref/#view.EditorView^perLineTextDirection) + isn't enabled, or the given position is outside of the viewport, + this will always return the same as + [`textDirection`](https://codemirror.net/6/docs/ref/#view.EditorView.textDirection). Note that + this may trigger a DOM layout. + */ + textDirectionAt(pos) { + let perLine = this.state.facet(perLineTextDirection); + if (!perLine || pos < this.viewport.from || pos > this.viewport.to) + return this.textDirection; + this.readMeasured(); + return this.docView.textDirectionAt(pos); + } + /** + Whether this editor [wraps lines](https://codemirror.net/6/docs/ref/#view.EditorView.lineWrapping) + (as determined by the + [`white-space`](https://developer.mozilla.org/en-US/docs/Web/CSS/white-space) + CSS property of its content element). + */ + get lineWrapping() { return this.viewState.heightOracle.lineWrapping; } + /** + Returns the bidirectional text structure of the given line + (which should be in the current document) as an array of span + objects. The order of these spans matches the [text + direction](https://codemirror.net/6/docs/ref/#view.EditorView.textDirection)—if that is + left-to-right, the leftmost spans come first, otherwise the + rightmost spans come first. + */ + bidiSpans(line) { + if (line.length > MaxBidiLine) + return trivialOrder(line.length); + let dir = this.textDirectionAt(line.from); + for (let entry of this.bidiCache) + if (entry.from == line.from && entry.dir == dir) + return entry.order; + let order = computeOrder(line.text, dir); + this.bidiCache.push(new CachedOrder(line.from, line.to, dir, order)); + return order; + } + /** + Check whether the editor has focus. + */ + get hasFocus() { + var _a; + // Safari return false for hasFocus when the context menu is open + // or closing, which leads us to ignore selection changes from the + // context menu because it looks like the editor isn't focused. + // This kludges around that. + return (this.dom.ownerDocument.hasFocus() || browser.safari && ((_a = this.inputState) === null || _a === void 0 ? void 0 : _a.lastContextMenu) > Date.now() - 3e4) && + this.root.activeElement == this.contentDOM; + } + /** + Put focus on the editor. + */ + focus() { + this.observer.ignore(() => { + focusPreventScroll(this.contentDOM); + this.docView.updateSelection(); + }); + } + /** + Update the [root](https://codemirror.net/6/docs/ref/##view.EditorViewConfig.root) in which the editor lives. This is only + necessary when moving the editor's existing DOM to a new window or shadow root. + */ + setRoot(root) { + if (this._root != root) { + this._root = root; + this.observer.setWindow((root.nodeType == 9 ? root : root.ownerDocument).defaultView || window); + this.mountStyles(); + } + } + /** + Clean up this editor view, removing its element from the + document, unregistering event handlers, and notifying + plugins. The view instance can no longer be used after + calling this. + */ + destroy() { + for (let plugin of this.plugins) + plugin.destroy(this); + this.plugins = []; + this.inputState.destroy(); + this.dom.remove(); + this.observer.destroy(); + if (this.measureScheduled > -1) + cancelAnimationFrame(this.measureScheduled); + this.destroyed = true; + } + /** + Returns an effect that can be + [added](https://codemirror.net/6/docs/ref/#state.TransactionSpec.effects) to a transaction to + cause it to scroll the given position or range into view. + */ + static scrollIntoView(pos, options = {}) { + return scrollIntoView$1.of(new ScrollTarget(typeof pos == "number" ? EditorSelection.cursor(pos) : pos, options.y, options.x, options.yMargin, options.xMargin)); + } + /** + Returns an extension that can be used to add DOM event handlers. + The value should be an object mapping event names to handler + functions. For any given event, such functions are ordered by + extension precedence, and the first handler to return true will + be assumed to have handled that event, and no other handlers or + built-in behavior will be activated for it. These are registered + on the [content element](https://codemirror.net/6/docs/ref/#view.EditorView.contentDOM), except + for `scroll` handlers, which will be called any time the + editor's [scroll element](https://codemirror.net/6/docs/ref/#view.EditorView.scrollDOM) or one of + its parent nodes is scrolled. + */ + static domEventHandlers(handlers) { + return ViewPlugin.define(() => ({}), { eventHandlers: handlers }); + } + /** + Create a theme extension. The first argument can be a + [`style-mod`](https://github.com/marijnh/style-mod#documentation) + style spec providing the styles for the theme. These will be + prefixed with a generated class for the style. + + Because the selectors will be prefixed with a scope class, rule + that directly match the editor's [wrapper + element](https://codemirror.net/6/docs/ref/#view.EditorView.dom)—to which the scope class will be + added—need to be explicitly differentiated by adding an `&` to + the selector for that element—for example + `&.cm-focused`. + + When `dark` is set to true, the theme will be marked as dark, + which will cause the `&dark` rules from [base + themes](https://codemirror.net/6/docs/ref/#view.EditorView^baseTheme) to be used (as opposed to + `&light` when a light theme is active). + */ + static theme(spec, options) { + let prefix = StyleModule.newName(); + let result = [theme.of(prefix), styleModule.of(buildTheme(`.${prefix}`, spec))]; + if (options && options.dark) + result.push(darkTheme.of(true)); + return result; + } + /** + Create an extension that adds styles to the base theme. Like + with [`theme`](https://codemirror.net/6/docs/ref/#view.EditorView^theme), use `&` to indicate the + place of the editor wrapper element when directly targeting + that. You can also use `&dark` or `&light` instead to only + target editors with a dark or light theme. + */ + static baseTheme(spec) { + return Prec.lowest(styleModule.of(buildTheme("." + baseThemeID, spec, lightDarkIDs))); + } + /** + Retrieve an editor view instance from the view's DOM + representation. + */ + static findFromDOM(dom) { + var _a; + let content = dom.querySelector(".cm-content"); + let cView = content && ContentView.get(content) || ContentView.get(dom); + return ((_a = cView === null || cView === void 0 ? void 0 : cView.rootView) === null || _a === void 0 ? void 0 : _a.view) || null; + } + } + /** + Facet to add a [style + module](https://github.com/marijnh/style-mod#documentation) to + an editor view. The view will ensure that the module is + mounted in its [document + root](https://codemirror.net/6/docs/ref/#view.EditorView.constructor^config.root). + */ + EditorView.styleModule = styleModule; + /** + An input handler can override the way changes to the editable + DOM content are handled. Handlers are passed the document + positions between which the change was found, and the new + content. When one returns true, no further input handlers are + called and the default behavior is prevented. + */ + EditorView.inputHandler = inputHandler$1; + /** + By default, the editor assumes all its content has the same + [text direction](https://codemirror.net/6/docs/ref/#view.Direction). Configure this with a `true` + value to make it read the text direction of every (rendered) + line separately. + */ + EditorView.perLineTextDirection = perLineTextDirection; + /** + Allows you to provide a function that should be called when the + library catches an exception from an extension (mostly from view + plugins, but may be used by other extensions to route exceptions + from user-code-provided callbacks). This is mostly useful for + debugging and logging. See [`logException`](https://codemirror.net/6/docs/ref/#view.logException). + */ + EditorView.exceptionSink = exceptionSink; + /** + A facet that can be used to register a function to be called + every time the view updates. + */ + EditorView.updateListener = updateListener; + /** + Facet that controls whether the editor content DOM is editable. + When its highest-precedence value is `false`, the element will + not have its `contenteditable` attribute set. (Note that this + doesn't affect API calls that change the editor content, even + when those are bound to keys or buttons. See the + [`readOnly`](https://codemirror.net/6/docs/ref/#state.EditorState.readOnly) facet for that.) + */ + EditorView.editable = editable; + /** + Allows you to influence the way mouse selection happens. The + functions in this facet will be called for a `mousedown` event + on the editor, and can return an object that overrides the way a + selection is computed from that mouse click or drag. + */ + EditorView.mouseSelectionStyle = mouseSelectionStyle; + /** + Facet used to configure whether a given selection drag event + should move or copy the selection. The given predicate will be + called with the `mousedown` event, and can return `true` when + the drag should move the content. + */ + EditorView.dragMovesSelection = dragMovesSelection$1; + /** + Facet used to configure whether a given selecting click adds a + new range to the existing selection or replaces it entirely. The + default behavior is to check `event.metaKey` on macOS, and + `event.ctrlKey` elsewhere. + */ + EditorView.clickAddsSelectionRange = clickAddsSelectionRange; + /** + A facet that determines which [decorations](https://codemirror.net/6/docs/ref/#view.Decoration) + are shown in the view. Decorations can be provided in two + ways—directly, or via a function that takes an editor view. + + Only decoration sets provided directly are allowed to influence + the editor's vertical layout structure. The ones provided as + functions are called _after_ the new viewport has been computed, + and thus **must not** introduce block widgets or replacing + decorations that cover line breaks. + + If you want decorated ranges to behave like atomic units for + cursor motion and deletion purposes, also provide the range set + containing the decorations to + [`EditorView.atomicRanges`](https://codemirror.net/6/docs/ref/#view.EditorView^atomicRanges). + */ + EditorView.decorations = decorations; + /** + Used to provide ranges that should be treated as atoms as far as + cursor motion is concerned. This causes methods like + [`moveByChar`](https://codemirror.net/6/docs/ref/#view.EditorView.moveByChar) and + [`moveVertically`](https://codemirror.net/6/docs/ref/#view.EditorView.moveVertically) (and the + commands built on top of them) to skip across such regions when + a selection endpoint would enter them. This does _not_ prevent + direct programmatic [selection + updates](https://codemirror.net/6/docs/ref/#state.TransactionSpec.selection) from moving into such + regions. + */ + EditorView.atomicRanges = atomicRanges; + /** + Facet that allows extensions to provide additional scroll + margins (space around the sides of the scrolling element that + should be considered invisible). This can be useful when the + plugin introduces elements that cover part of that element (for + example a horizontally fixed gutter). + */ + EditorView.scrollMargins = scrollMargins; + /** + This facet records whether a dark theme is active. The extension + returned by [`theme`](https://codemirror.net/6/docs/ref/#view.EditorView^theme) automatically + includes an instance of this when the `dark` option is set to + true. + */ + EditorView.darkTheme = darkTheme; + /** + Facet that provides additional DOM attributes for the editor's + editable DOM element. + */ + EditorView.contentAttributes = contentAttributes; + /** + Facet that provides DOM attributes for the editor's outer + element. + */ + EditorView.editorAttributes = editorAttributes; + /** + An extension that enables line wrapping in the editor (by + setting CSS `white-space` to `pre-wrap` in the content). + */ + EditorView.lineWrapping = /*@__PURE__*/EditorView.contentAttributes.of({ "class": "cm-lineWrapping" }); + /** + State effect used to include screen reader announcements in a + transaction. These will be added to the DOM in a visually hidden + element with `aria-live="polite"` set, and should be used to + describe effects that are visually obvious but may not be + noticed by screen reader users (such as moving to the next + search match). + */ + EditorView.announce = /*@__PURE__*/StateEffect.define(); + // Maximum line length for which we compute accurate bidi info + const MaxBidiLine = 4096; + const BadMeasure = {}; + class CachedOrder { + constructor(from, to, dir, order) { + this.from = from; + this.to = to; + this.dir = dir; + this.order = order; + } + static update(cache, changes) { + if (changes.empty) + return cache; + let result = [], lastDir = cache.length ? cache[cache.length - 1].dir : Direction.LTR; + for (let i = Math.max(0, cache.length - 10); i < cache.length; i++) { + let entry = cache[i]; + if (entry.dir == lastDir && !changes.touchesRange(entry.from, entry.to)) + result.push(new CachedOrder(changes.mapPos(entry.from, 1), changes.mapPos(entry.to, -1), entry.dir, entry.order)); + } + return result; + } + } + function attrsFromFacet(view, facet, base) { + for (let sources = view.state.facet(facet), i = sources.length - 1; i >= 0; i--) { + let source = sources[i], value = typeof source == "function" ? source(view) : source; + if (value) + combineAttrs(value, base); + } + return base; + } + + const currentPlatform = browser.mac ? "mac" : browser.windows ? "win" : browser.linux ? "linux" : "key"; + function normalizeKeyName(name, platform) { + const parts = name.split(/-(?!$)/); + let result = parts[parts.length - 1]; + if (result == "Space") + result = " "; + let alt, ctrl, shift, meta; + for (let i = 0; i < parts.length - 1; ++i) { + const mod = parts[i]; + if (/^(cmd|meta|m)$/i.test(mod)) + meta = 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 if (/^mod$/i.test(mod)) { + if (platform == "mac") + meta = true; + else + ctrl = true; + } + else + throw new Error("Unrecognized modifier name: " + mod); + } + if (alt) + result = "Alt-" + result; + if (ctrl) + result = "Ctrl-" + result; + if (meta) + result = "Meta-" + result; + if (shift) + result = "Shift-" + result; + return result; + } + function modifiers(name, event, shift) { + if (event.altKey) + name = "Alt-" + name; + if (event.ctrlKey) + name = "Ctrl-" + name; + if (event.metaKey) + name = "Meta-" + name; + if (shift !== false && event.shiftKey) + name = "Shift-" + name; + return name; + } + const handleKeyEvents = /*@__PURE__*/Prec.default(/*@__PURE__*/EditorView.domEventHandlers({ + keydown(event, view) { + return runHandlers(getKeymap(view.state), event, view, "editor"); + } + })); + /** + Facet used for registering keymaps. + + You can add multiple keymaps to an editor. Their priorities + determine their precedence (the ones specified early or with high + priority get checked first). When a handler has returned `true` + for a given key, no further handlers are called. + */ + const keymap = /*@__PURE__*/Facet.define({ enables: handleKeyEvents }); + const Keymaps = /*@__PURE__*/new WeakMap(); + // This is hidden behind an indirection, rather than directly computed + // by the facet, to keep internal types out of the facet's type. + function getKeymap(state) { + let bindings = state.facet(keymap); + let map = Keymaps.get(bindings); + if (!map) + Keymaps.set(bindings, map = buildKeymap(bindings.reduce((a, b) => a.concat(b), []))); + return map; + } + /** + Run the key handlers registered for a given scope. The event + object should be a `"keydown"` event. Returns true if any of the + handlers handled it. + */ + function runScopeHandlers(view, event, scope) { + return runHandlers(getKeymap(view.state), event, view, scope); + } + let storedPrefix = null; + const PrefixTimeout = 4000; + function buildKeymap(bindings, platform = currentPlatform) { + let bound = Object.create(null); + let isPrefix = Object.create(null); + let checkPrefix = (name, is) => { + let current = isPrefix[name]; + if (current == null) + isPrefix[name] = is; + else if (current != is) + throw new Error("Key binding " + name + " is used both as a regular binding and as a multi-stroke prefix"); + }; + let add = (scope, key, command, preventDefault) => { + var _a, _b; + let scopeObj = bound[scope] || (bound[scope] = Object.create(null)); + let parts = key.split(/ (?!$)/).map(k => normalizeKeyName(k, platform)); + for (let i = 1; i < parts.length; i++) { + let prefix = parts.slice(0, i).join(" "); + checkPrefix(prefix, true); + if (!scopeObj[prefix]) + scopeObj[prefix] = { + preventDefault: true, + run: [(view) => { + let ourObj = storedPrefix = { view, prefix, scope }; + setTimeout(() => { if (storedPrefix == ourObj) + storedPrefix = null; }, PrefixTimeout); + return true; + }] + }; + } + let full = parts.join(" "); + checkPrefix(full, false); + let binding = scopeObj[full] || (scopeObj[full] = { preventDefault: false, run: ((_b = (_a = scopeObj._any) === null || _a === void 0 ? void 0 : _a.run) === null || _b === void 0 ? void 0 : _b.slice()) || [] }); + if (command) + binding.run.push(command); + if (preventDefault) + binding.preventDefault = true; + }; + for (let b of bindings) { + let scopes = b.scope ? b.scope.split(" ") : ["editor"]; + if (b.any) + for (let scope of scopes) { + let scopeObj = bound[scope] || (bound[scope] = Object.create(null)); + if (!scopeObj._any) + scopeObj._any = { preventDefault: false, run: [] }; + for (let key in scopeObj) + scopeObj[key].run.push(b.any); + } + let name = b[platform] || b.key; + if (!name) + continue; + for (let scope of scopes) { + add(scope, name, b.run, b.preventDefault); + if (b.shift) + add(scope, "Shift-" + name, b.shift, b.preventDefault); + } + } + return bound; + } + function runHandlers(map, event, view, scope) { + let name = keyName(event); + let charCode = codePointAt(name, 0), isChar = codePointSize(charCode) == name.length && name != " "; + let prefix = "", fallthrough = false; + if (storedPrefix && storedPrefix.view == view && storedPrefix.scope == scope) { + prefix = storedPrefix.prefix + " "; + if (fallthrough = modifierCodes.indexOf(event.keyCode) < 0) + storedPrefix = null; + } + let ran = new Set; + let runFor = (binding) => { + if (binding) { + for (let cmd of binding.run) + if (!ran.has(cmd)) { + ran.add(cmd); + if (cmd(view, event)) + return true; + } + if (binding.preventDefault) + fallthrough = true; + } + return false; + }; + let scopeObj = map[scope], baseName, shiftName; + if (scopeObj) { + if (runFor(scopeObj[prefix + modifiers(name, event, !isChar)])) + return true; + if (isChar && (event.shiftKey || event.altKey || event.metaKey || charCode > 127) && + (baseName = base[event.keyCode]) && baseName != name) { + if (runFor(scopeObj[prefix + modifiers(baseName, event, true)])) + return true; + else if (event.shiftKey && (shiftName = shift[event.keyCode]) != name && shiftName != baseName && + runFor(scopeObj[prefix + modifiers(shiftName, event, false)])) + return true; + } + else if (isChar && event.shiftKey) { + if (runFor(scopeObj[prefix + modifiers(name, event, true)])) + return true; + } + if (runFor(scopeObj._any)) + return true; + } + return fallthrough; + } + + const CanHidePrimary = !browser.ios; // FIXME test IE + const selectionConfig = /*@__PURE__*/Facet.define({ + combine(configs) { + return combineConfig(configs, { + cursorBlinkRate: 1200, + drawRangeCursor: true + }, { + cursorBlinkRate: (a, b) => Math.min(a, b), + drawRangeCursor: (a, b) => a || b + }); + } + }); + /** + Returns an extension that hides the browser's native selection and + cursor, replacing the selection with a background behind the text + (with the `cm-selectionBackground` class), and the + cursors with elements overlaid over the code (using + `cm-cursor-primary` and `cm-cursor-secondary`). + + This allows the editor to display secondary selection ranges, and + tends to produce a type of selection more in line with that users + expect in a text editor (the native selection styling will often + leave gaps between lines and won't fill the horizontal space after + a line when the selection continues past it). + + It does have a performance cost, in that it requires an extra DOM + layout cycle for many updates (the selection is drawn based on DOM + layout information that's only available after laying out the + content). + */ + function drawSelection(config = {}) { + return [ + selectionConfig.of(config), + drawSelectionPlugin, + hideNativeSelection + ]; + } + class Piece { + constructor(left, top, width, height, className) { + this.left = left; + this.top = top; + this.width = width; + this.height = height; + this.className = className; + } + draw() { + let elt = document.createElement("div"); + elt.className = this.className; + this.adjust(elt); + return elt; + } + adjust(elt) { + elt.style.left = this.left + "px"; + elt.style.top = this.top + "px"; + if (this.width >= 0) + elt.style.width = this.width + "px"; + elt.style.height = this.height + "px"; + } + eq(p) { + return this.left == p.left && this.top == p.top && this.width == p.width && this.height == p.height && + this.className == p.className; + } + } + const drawSelectionPlugin = /*@__PURE__*/ViewPlugin.fromClass(class { + constructor(view) { + this.view = view; + this.rangePieces = []; + this.cursors = []; + this.measureReq = { read: this.readPos.bind(this), write: this.drawSel.bind(this) }; + this.selectionLayer = view.scrollDOM.appendChild(document.createElement("div")); + this.selectionLayer.className = "cm-selectionLayer"; + this.selectionLayer.setAttribute("aria-hidden", "true"); + this.cursorLayer = view.scrollDOM.appendChild(document.createElement("div")); + this.cursorLayer.className = "cm-cursorLayer"; + this.cursorLayer.setAttribute("aria-hidden", "true"); + view.requestMeasure(this.measureReq); + this.setBlinkRate(); + } + setBlinkRate() { + this.cursorLayer.style.animationDuration = this.view.state.facet(selectionConfig).cursorBlinkRate + "ms"; + } + update(update) { + let confChanged = update.startState.facet(selectionConfig) != update.state.facet(selectionConfig); + if (confChanged || update.selectionSet || update.geometryChanged || update.viewportChanged) + this.view.requestMeasure(this.measureReq); + if (update.transactions.some(tr => tr.scrollIntoView)) + this.cursorLayer.style.animationName = this.cursorLayer.style.animationName == "cm-blink" ? "cm-blink2" : "cm-blink"; + if (confChanged) + this.setBlinkRate(); + } + readPos() { + let { state } = this.view, conf = state.facet(selectionConfig); + let rangePieces = state.selection.ranges.map(r => r.empty ? [] : measureRange(this.view, r)).reduce((a, b) => a.concat(b)); + let cursors = []; + for (let r of state.selection.ranges) { + let prim = r == state.selection.main; + if (r.empty ? !prim || CanHidePrimary : conf.drawRangeCursor) { + let piece = measureCursor(this.view, r, prim); + if (piece) + cursors.push(piece); + } + } + return { rangePieces, cursors }; + } + drawSel({ rangePieces, cursors }) { + if (rangePieces.length != this.rangePieces.length || rangePieces.some((p, i) => !p.eq(this.rangePieces[i]))) { + this.selectionLayer.textContent = ""; + for (let p of rangePieces) + this.selectionLayer.appendChild(p.draw()); + this.rangePieces = rangePieces; + } + if (cursors.length != this.cursors.length || cursors.some((c, i) => !c.eq(this.cursors[i]))) { + let oldCursors = this.cursorLayer.children; + if (oldCursors.length !== cursors.length) { + this.cursorLayer.textContent = ""; + for (const c of cursors) + this.cursorLayer.appendChild(c.draw()); + } + else { + cursors.forEach((c, idx) => c.adjust(oldCursors[idx])); + } + this.cursors = cursors; + } + } + destroy() { + this.selectionLayer.remove(); + this.cursorLayer.remove(); + } + }); + const themeSpec = { + ".cm-line": { + "& ::selection": { backgroundColor: "transparent !important" }, + "&::selection": { backgroundColor: "transparent !important" } + } + }; + if (CanHidePrimary) + themeSpec[".cm-line"].caretColor = "transparent !important"; + const hideNativeSelection = /*@__PURE__*/Prec.highest(/*@__PURE__*/EditorView.theme(themeSpec)); + function getBase(view) { + let rect = view.scrollDOM.getBoundingClientRect(); + let left = view.textDirection == Direction.LTR ? rect.left : rect.right - view.scrollDOM.clientWidth; + return { left: left - view.scrollDOM.scrollLeft, top: rect.top - view.scrollDOM.scrollTop }; + } + function wrappedLine(view, pos, inside) { + let range = EditorSelection.cursor(pos); + return { from: Math.max(inside.from, view.moveToLineBoundary(range, false, true).from), + to: Math.min(inside.to, view.moveToLineBoundary(range, true, true).from), + type: BlockType.Text }; + } + function blockAt(view, pos) { + let line = view.lineBlockAt(pos); + if (Array.isArray(line.type)) + for (let l of line.type) { + if (l.to > pos || l.to == pos && (l.to == line.to || l.type == BlockType.Text)) + return l; + } + return line; + } + function measureRange(view, range) { + if (range.to <= view.viewport.from || range.from >= view.viewport.to) + return []; + let from = Math.max(range.from, view.viewport.from), to = Math.min(range.to, view.viewport.to); + let ltr = view.textDirection == Direction.LTR; + let content = view.contentDOM, contentRect = content.getBoundingClientRect(), base = getBase(view); + let lineStyle = window.getComputedStyle(content.firstChild); + let leftSide = contentRect.left + parseInt(lineStyle.paddingLeft) + Math.min(0, parseInt(lineStyle.textIndent)); + let rightSide = contentRect.right - parseInt(lineStyle.paddingRight); + let startBlock = blockAt(view, from), endBlock = blockAt(view, to); + let visualStart = startBlock.type == BlockType.Text ? startBlock : null; + let visualEnd = endBlock.type == BlockType.Text ? endBlock : null; + if (view.lineWrapping) { + if (visualStart) + visualStart = wrappedLine(view, from, visualStart); + if (visualEnd) + visualEnd = wrappedLine(view, to, visualEnd); + } + if (visualStart && visualEnd && visualStart.from == visualEnd.from) { + return pieces(drawForLine(range.from, range.to, visualStart)); + } + else { + let top = visualStart ? drawForLine(range.from, null, visualStart) : drawForWidget(startBlock, false); + let bottom = visualEnd ? drawForLine(null, range.to, visualEnd) : drawForWidget(endBlock, true); + let between = []; + if ((visualStart || startBlock).to < (visualEnd || endBlock).from - 1) + between.push(piece(leftSide, top.bottom, rightSide, bottom.top)); + else if (top.bottom < bottom.top && view.elementAtHeight((top.bottom + bottom.top) / 2).type == BlockType.Text) + top.bottom = bottom.top = (top.bottom + bottom.top) / 2; + return pieces(top).concat(between).concat(pieces(bottom)); + } + function piece(left, top, right, bottom) { + return new Piece(left - base.left, top - base.top - 0.01 /* C.Epsilon */, right - left, bottom - top + 0.01 /* C.Epsilon */, "cm-selectionBackground"); + } + function pieces({ top, bottom, horizontal }) { + let pieces = []; + for (let i = 0; i < horizontal.length; i += 2) + pieces.push(piece(horizontal[i], top, horizontal[i + 1], bottom)); + return pieces; + } + // Gets passed from/to in line-local positions + function drawForLine(from, to, line) { + let top = 1e9, bottom = -1e9, horizontal = []; + function addSpan(from, fromOpen, to, toOpen, dir) { + // Passing 2/-2 is a kludge to force the view to return + // coordinates on the proper side of block widgets, since + // normalizing the side there, though appropriate for most + // coordsAtPos queries, would break selection drawing. + let fromCoords = view.coordsAtPos(from, (from == line.to ? -2 : 2)); + let toCoords = view.coordsAtPos(to, (to == line.from ? 2 : -2)); + top = Math.min(fromCoords.top, toCoords.top, top); + bottom = Math.max(fromCoords.bottom, toCoords.bottom, bottom); + if (dir == Direction.LTR) + horizontal.push(ltr && fromOpen ? leftSide : fromCoords.left, ltr && toOpen ? rightSide : toCoords.right); + else + horizontal.push(!ltr && toOpen ? leftSide : toCoords.left, !ltr && fromOpen ? rightSide : fromCoords.right); + } + let start = from !== null && from !== void 0 ? from : line.from, end = to !== null && to !== void 0 ? to : line.to; + // Split the range by visible range and document line + for (let r of view.visibleRanges) + if (r.to > start && r.from < end) { + for (let pos = Math.max(r.from, start), endPos = Math.min(r.to, end);;) { + let docLine = view.state.doc.lineAt(pos); + for (let span of view.bidiSpans(docLine)) { + let spanFrom = span.from + docLine.from, spanTo = span.to + docLine.from; + if (spanFrom >= endPos) + break; + if (spanTo > pos) + addSpan(Math.max(spanFrom, pos), from == null && spanFrom <= start, Math.min(spanTo, endPos), to == null && spanTo >= end, span.dir); + } + pos = docLine.to + 1; + if (pos >= endPos) + break; + } + } + if (horizontal.length == 0) + addSpan(start, from == null, end, to == null, view.textDirection); + return { top, bottom, horizontal }; + } + function drawForWidget(block, top) { + let y = contentRect.top + (top ? block.top : block.bottom); + return { top: y, bottom: y, horizontal: [] }; + } + } + function measureCursor(view, cursor, primary) { + let pos = view.coordsAtPos(cursor.head, cursor.assoc || 1); + if (!pos) + return null; + let base = getBase(view); + return new Piece(pos.left - base.left, pos.top - base.top, -1, pos.bottom - pos.top, primary ? "cm-cursor cm-cursor-primary" : "cm-cursor cm-cursor-secondary"); + } + + const setDropCursorPos = /*@__PURE__*/StateEffect.define({ + map(pos, mapping) { return pos == null ? null : mapping.mapPos(pos); } + }); + const dropCursorPos = /*@__PURE__*/StateField.define({ + create() { return null; }, + update(pos, tr) { + if (pos != null) + pos = tr.changes.mapPos(pos); + return tr.effects.reduce((pos, e) => e.is(setDropCursorPos) ? e.value : pos, pos); + } + }); + const drawDropCursor = /*@__PURE__*/ViewPlugin.fromClass(class { + constructor(view) { + this.view = view; + this.cursor = null; + this.measureReq = { read: this.readPos.bind(this), write: this.drawCursor.bind(this) }; + } + update(update) { + var _a; + let cursorPos = update.state.field(dropCursorPos); + if (cursorPos == null) { + if (this.cursor != null) { + (_a = this.cursor) === null || _a === void 0 ? void 0 : _a.remove(); + this.cursor = null; + } + } + else { + if (!this.cursor) { + this.cursor = this.view.scrollDOM.appendChild(document.createElement("div")); + this.cursor.className = "cm-dropCursor"; + } + if (update.startState.field(dropCursorPos) != cursorPos || update.docChanged || update.geometryChanged) + this.view.requestMeasure(this.measureReq); + } + } + readPos() { + let pos = this.view.state.field(dropCursorPos); + let rect = pos != null && this.view.coordsAtPos(pos); + if (!rect) + return null; + let outer = this.view.scrollDOM.getBoundingClientRect(); + return { + left: rect.left - outer.left + this.view.scrollDOM.scrollLeft, + top: rect.top - outer.top + this.view.scrollDOM.scrollTop, + height: rect.bottom - rect.top + }; + } + drawCursor(pos) { + if (this.cursor) { + if (pos) { + this.cursor.style.left = pos.left + "px"; + this.cursor.style.top = pos.top + "px"; + this.cursor.style.height = pos.height + "px"; + } + else { + this.cursor.style.left = "-100000px"; + } + } + } + destroy() { + if (this.cursor) + this.cursor.remove(); + } + setDropPos(pos) { + if (this.view.state.field(dropCursorPos) != pos) + this.view.dispatch({ effects: setDropCursorPos.of(pos) }); + } + }, { + eventHandlers: { + dragover(event) { + this.setDropPos(this.view.posAtCoords({ x: event.clientX, y: event.clientY })); + }, + dragleave(event) { + if (event.target == this.view.contentDOM || !this.view.contentDOM.contains(event.relatedTarget)) + this.setDropPos(null); + }, + dragend() { + this.setDropPos(null); + }, + drop() { + this.setDropPos(null); + } + } + }); + /** + Draws a cursor at the current drop position when something is + dragged over the editor. + */ + function dropCursor() { + return [dropCursorPos, drawDropCursor]; + } + + function iterMatches(doc, re, from, to, f) { + re.lastIndex = 0; + for (let cursor = doc.iterRange(from, to), pos = from, m; !cursor.next().done; pos += cursor.value.length) { + if (!cursor.lineBreak) + while (m = re.exec(cursor.value)) + f(pos + m.index, m); + } + } + function matchRanges(view, maxLength) { + let visible = view.visibleRanges; + if (visible.length == 1 && visible[0].from == view.viewport.from && + visible[0].to == view.viewport.to) + return visible; + let result = []; + for (let { from, to } of visible) { + from = Math.max(view.state.doc.lineAt(from).from, from - maxLength); + to = Math.min(view.state.doc.lineAt(to).to, to + maxLength); + if (result.length && result[result.length - 1].to >= from) + result[result.length - 1].to = to; + else + result.push({ from, to }); + } + return result; + } + /** + Helper class used to make it easier to maintain decorations on + visible code that matches a given regular expression. To be used + in a [view plugin](https://codemirror.net/6/docs/ref/#view.ViewPlugin). Instances of this object + represent a matching configuration. + */ + class MatchDecorator { + /** + Create a decorator. + */ + constructor(config) { + const { regexp, decoration, decorate, boundary, maxLength = 1000 } = config; + if (!regexp.global) + throw new RangeError("The regular expression given to MatchDecorator should have its 'g' flag set"); + this.regexp = regexp; + if (decorate) { + this.addMatch = (match, view, from, add) => decorate(add, from, from + match[0].length, match, view); + } + else if (typeof decoration == "function") { + this.addMatch = (match, view, from, add) => { + let deco = decoration(match, view, from); + if (deco) + add(from, from + match[0].length, deco); + }; + } + else if (decoration) { + this.addMatch = (match, _view, from, add) => add(from, from + match[0].length, decoration); + } + else { + throw new RangeError("Either 'decorate' or 'decoration' should be provided to MatchDecorator"); + } + this.boundary = boundary; + this.maxLength = maxLength; + } + /** + Compute the full set of decorations for matches in the given + view's viewport. You'll want to call this when initializing your + plugin. + */ + createDeco(view) { + let build = new RangeSetBuilder(), add = build.add.bind(build); + for (let { from, to } of matchRanges(view, this.maxLength)) + iterMatches(view.state.doc, this.regexp, from, to, (from, m) => this.addMatch(m, view, from, add)); + return build.finish(); + } + /** + Update a set of decorations for a view update. `deco` _must_ be + the set of decorations produced by _this_ `MatchDecorator` for + the view state before the update. + */ + updateDeco(update, deco) { + let changeFrom = 1e9, changeTo = -1; + if (update.docChanged) + update.changes.iterChanges((_f, _t, from, to) => { + if (to > update.view.viewport.from && from < update.view.viewport.to) { + changeFrom = Math.min(from, changeFrom); + changeTo = Math.max(to, changeTo); + } + }); + if (update.viewportChanged || changeTo - changeFrom > 1000) + return this.createDeco(update.view); + if (changeTo > -1) + return this.updateRange(update.view, deco.map(update.changes), changeFrom, changeTo); + return deco; + } + updateRange(view, deco, updateFrom, updateTo) { + for (let r of view.visibleRanges) { + let from = Math.max(r.from, updateFrom), to = Math.min(r.to, updateTo); + if (to > from) { + let fromLine = view.state.doc.lineAt(from), toLine = fromLine.to < to ? view.state.doc.lineAt(to) : fromLine; + let start = Math.max(r.from, fromLine.from), end = Math.min(r.to, toLine.to); + if (this.boundary) { + for (; from > fromLine.from; from--) + if (this.boundary.test(fromLine.text[from - 1 - fromLine.from])) { + start = from; + break; + } + for (; to < toLine.to; to++) + if (this.boundary.test(toLine.text[to - toLine.from])) { + end = to; + break; + } + } + let ranges = [], m; + let add = (from, to, deco) => ranges.push(deco.range(from, to)); + if (fromLine == toLine) { + this.regexp.lastIndex = start - fromLine.from; + while ((m = this.regexp.exec(fromLine.text)) && m.index < end - fromLine.from) + this.addMatch(m, view, m.index + fromLine.from, add); + } + else { + iterMatches(view.state.doc, this.regexp, start, end, (from, m) => this.addMatch(m, view, from, add)); + } + deco = deco.update({ filterFrom: start, filterTo: end, filter: (from, to) => from < start || to > end, add: ranges }); + } + } + return deco; + } + } + + const UnicodeRegexpSupport = /x/.unicode != null ? "gu" : "g"; + const Specials = /*@__PURE__*/new RegExp("[\u0000-\u0008\u000a-\u001f\u007f-\u009f\u00ad\u061c\u200b\u200e\u200f\u2028\u2029\u202d\u202e\u2066\u2067\u2069\ufeff\ufff9-\ufffc]", UnicodeRegexpSupport); + const Names = { + 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 _supportsTabSize = null; + function supportsTabSize() { + var _a; + if (_supportsTabSize == null && typeof document != "undefined" && document.body) { + let styles = document.body.style; + _supportsTabSize = ((_a = styles.tabSize) !== null && _a !== void 0 ? _a : styles.MozTabSize) != null; + } + return _supportsTabSize || false; + } + const specialCharConfig = /*@__PURE__*/Facet.define({ + combine(configs) { + let config = combineConfig(configs, { + render: null, + specialChars: Specials, + addSpecialChars: null + }); + if (config.replaceTabs = !supportsTabSize()) + config.specialChars = new RegExp("\t|" + config.specialChars.source, UnicodeRegexpSupport); + if (config.addSpecialChars) + config.specialChars = new RegExp(config.specialChars.source + "|" + config.addSpecialChars.source, UnicodeRegexpSupport); + return config; + } + }); + /** + Returns an extension that installs highlighting of special + characters. + */ + function highlightSpecialChars( + /** + Configuration options. + */ + config = {}) { + return [specialCharConfig.of(config), specialCharPlugin()]; + } + let _plugin = null; + function specialCharPlugin() { + return _plugin || (_plugin = ViewPlugin.fromClass(class { + constructor(view) { + this.view = view; + this.decorations = Decoration.none; + this.decorationCache = Object.create(null); + this.decorator = this.makeDecorator(view.state.facet(specialCharConfig)); + this.decorations = this.decorator.createDeco(view); + } + makeDecorator(conf) { + return new MatchDecorator({ + regexp: conf.specialChars, + decoration: (m, view, pos) => { + let { doc } = view.state; + let code = codePointAt(m[0], 0); + if (code == 9) { + let line = doc.lineAt(pos); + let size = view.state.tabSize, col = countColumn(line.text, size, pos - line.from); + return Decoration.replace({ widget: new TabWidget((size - (col % size)) * this.view.defaultCharacterWidth) }); + } + return this.decorationCache[code] || + (this.decorationCache[code] = Decoration.replace({ widget: new SpecialCharWidget(conf, code) })); + }, + boundary: conf.replaceTabs ? undefined : /[^]/ + }); + } + update(update) { + let conf = update.state.facet(specialCharConfig); + if (update.startState.facet(specialCharConfig) != conf) { + this.decorator = this.makeDecorator(conf); + this.decorations = this.decorator.createDeco(update.view); + } + else { + this.decorations = this.decorator.updateDeco(update, this.decorations); + } + } + }, { + decorations: v => v.decorations + })); + } + const DefaultPlaceholder = "\u2022"; + // Assigns placeholder characters from the Control Pictures block to + // ASCII control characters + function placeholder$1(code) { + if (code >= 32) + return DefaultPlaceholder; + if (code == 10) + return "\u2424"; + return String.fromCharCode(9216 + code); + } + class SpecialCharWidget extends WidgetType { + constructor(options, code) { + super(); + this.options = options; + this.code = code; + } + eq(other) { return other.code == this.code; } + toDOM(view) { + let ph = placeholder$1(this.code); + let desc = view.state.phrase("Control character") + " " + (Names[this.code] || "0x" + this.code.toString(16)); + let custom = this.options.render && this.options.render(this.code, desc, ph); + if (custom) + return custom; + let span = document.createElement("span"); + span.textContent = ph; + span.title = desc; + span.setAttribute("aria-label", desc); + span.className = "cm-specialChar"; + return span; + } + ignoreEvent() { return false; } + } + class TabWidget extends WidgetType { + constructor(width) { + super(); + this.width = width; + } + eq(other) { return other.width == this.width; } + toDOM() { + let span = document.createElement("span"); + span.textContent = "\t"; + span.className = "cm-tab"; + span.style.width = this.width + "px"; + return span; + } + ignoreEvent() { return false; } + } + + /** + Mark lines that have a cursor on them with the `"cm-activeLine"` + DOM class. + */ + function highlightActiveLine() { + return activeLineHighlighter; + } + const lineDeco = /*@__PURE__*/Decoration.line({ class: "cm-activeLine" }); + const activeLineHighlighter = /*@__PURE__*/ViewPlugin.fromClass(class { + constructor(view) { + this.decorations = this.getDeco(view); + } + update(update) { + if (update.docChanged || update.selectionSet) + this.decorations = this.getDeco(update.view); + } + getDeco(view) { + let lastLineStart = -1, deco = []; + for (let r of view.state.selection.ranges) { + let line = view.lineBlockAt(r.head); + if (line.from > lastLineStart) { + deco.push(lineDeco.range(line.from)); + lastLineStart = line.from; + } + } + return Decoration.set(deco); + } + }, { + decorations: v => v.decorations + }); + + // Don't compute precise column positions for line offsets above this + // (since it could get expensive). Assume offset==column for them. + const MaxOff = 2000; + function rectangleFor(state, a, b) { + let startLine = Math.min(a.line, b.line), endLine = Math.max(a.line, b.line); + let ranges = []; + if (a.off > MaxOff || b.off > MaxOff || a.col < 0 || b.col < 0) { + let startOff = Math.min(a.off, b.off), endOff = Math.max(a.off, b.off); + for (let i = startLine; i <= endLine; i++) { + let line = state.doc.line(i); + if (line.length <= endOff) + ranges.push(EditorSelection.range(line.from + startOff, line.to + endOff)); + } + } + else { + let startCol = Math.min(a.col, b.col), endCol = Math.max(a.col, b.col); + for (let i = startLine; i <= endLine; i++) { + let line = state.doc.line(i); + let start = findColumn(line.text, startCol, state.tabSize, true); + if (start > -1) { + let end = findColumn(line.text, endCol, state.tabSize); + ranges.push(EditorSelection.range(line.from + start, line.from + end)); + } + } + } + return ranges; + } + function absoluteColumn(view, x) { + let ref = view.coordsAtPos(view.viewport.from); + return ref ? Math.round(Math.abs((ref.left - x) / view.defaultCharacterWidth)) : -1; + } + function getPos(view, event) { + let offset = view.posAtCoords({ x: event.clientX, y: event.clientY }, false); + let line = view.state.doc.lineAt(offset), off = offset - line.from; + let col = off > MaxOff ? -1 + : off == line.length ? absoluteColumn(view, event.clientX) + : countColumn(line.text, view.state.tabSize, offset - line.from); + return { line: line.number, col, off }; + } + function rectangleSelectionStyle(view, event) { + let start = getPos(view, event), startSel = view.state.selection; + if (!start) + return null; + return { + update(update) { + if (update.docChanged) { + let newStart = update.changes.mapPos(update.startState.doc.line(start.line).from); + let newLine = update.state.doc.lineAt(newStart); + start = { line: newLine.number, col: start.col, off: Math.min(start.off, newLine.length) }; + startSel = startSel.map(update.changes); + } + }, + get(event, _extend, multiple) { + let cur = getPos(view, event); + if (!cur) + return startSel; + let ranges = rectangleFor(view.state, start, cur); + if (!ranges.length) + return startSel; + if (multiple) + return EditorSelection.create(ranges.concat(startSel.ranges)); + else + return EditorSelection.create(ranges); + } + }; + } + /** + Create an extension that enables rectangular selections. By + default, it will react to left mouse drag with the Alt key held + down. When such a selection occurs, the text within the rectangle + that was dragged over will be selected, as one selection + [range](https://codemirror.net/6/docs/ref/#state.SelectionRange) per line. + */ + function rectangularSelection(options) { + let filter = (options === null || options === void 0 ? void 0 : options.eventFilter) || (e => e.altKey && e.button == 0); + return EditorView.mouseSelectionStyle.of((view, event) => filter(event) ? rectangleSelectionStyle(view, event) : null); + } + const keys = { + Alt: [18, e => e.altKey], + Control: [17, e => e.ctrlKey], + Shift: [16, e => e.shiftKey], + Meta: [91, e => e.metaKey] + }; + const showCrosshair = { style: "cursor: crosshair" }; + /** + Returns an extension that turns the pointer cursor into a + crosshair when a given modifier key, defaulting to Alt, is held + down. Can serve as a visual hint that rectangular selection is + going to happen when paired with + [`rectangularSelection`](https://codemirror.net/6/docs/ref/#view.rectangularSelection). + */ + function crosshairCursor(options = {}) { + let [code, getter] = keys[options.key || "Alt"]; + let plugin = ViewPlugin.fromClass(class { + constructor(view) { + this.view = view; + this.isDown = false; + } + set(isDown) { + if (this.isDown != isDown) { + this.isDown = isDown; + this.view.update([]); + } + } + }, { + eventHandlers: { + keydown(e) { + this.set(e.keyCode == code || getter(e)); + }, + keyup(e) { + if (e.keyCode == code || !getter(e)) + this.set(false); + } + } + }); + return [ + plugin, + EditorView.contentAttributes.of(view => { var _a; return ((_a = view.plugin(plugin)) === null || _a === void 0 ? void 0 : _a.isDown) ? showCrosshair : null; }) + ]; + } + + const Outside = "-10000px"; + class TooltipViewManager { + constructor(view, facet, createTooltipView) { + this.facet = facet; + this.createTooltipView = createTooltipView; + this.input = view.state.facet(facet); + this.tooltips = this.input.filter(t => t); + this.tooltipViews = this.tooltips.map(createTooltipView); + } + update(update) { + let input = update.state.facet(this.facet); + let tooltips = input.filter(x => x); + if (input === this.input) { + for (let t of this.tooltipViews) + if (t.update) + t.update(update); + return false; + } + let tooltipViews = []; + for (let i = 0; i < tooltips.length; i++) { + let tip = tooltips[i], known = -1; + if (!tip) + continue; + for (let i = 0; i < this.tooltips.length; i++) { + let other = this.tooltips[i]; + if (other && other.create == tip.create) + known = i; + } + if (known < 0) { + tooltipViews[i] = this.createTooltipView(tip); + } + else { + let tooltipView = tooltipViews[i] = this.tooltipViews[known]; + if (tooltipView.update) + tooltipView.update(update); + } + } + for (let t of this.tooltipViews) + if (tooltipViews.indexOf(t) < 0) + t.dom.remove(); + this.input = input; + this.tooltips = tooltips; + this.tooltipViews = tooltipViews; + return true; + } + } + function windowSpace(view) { + let { win } = view; + return { top: 0, left: 0, bottom: win.innerHeight, right: win.innerWidth }; + } + const tooltipConfig = /*@__PURE__*/Facet.define({ + combine: values => { + var _a, _b, _c; + return ({ + position: browser.ios ? "absolute" : ((_a = values.find(conf => conf.position)) === null || _a === void 0 ? void 0 : _a.position) || "fixed", + parent: ((_b = values.find(conf => conf.parent)) === null || _b === void 0 ? void 0 : _b.parent) || null, + tooltipSpace: ((_c = values.find(conf => conf.tooltipSpace)) === null || _c === void 0 ? void 0 : _c.tooltipSpace) || windowSpace, + }); + } + }); + const tooltipPlugin = /*@__PURE__*/ViewPlugin.fromClass(class { + constructor(view) { + this.view = view; + this.inView = true; + this.lastTransaction = 0; + this.measureTimeout = -1; + let config = view.state.facet(tooltipConfig); + this.position = config.position; + this.parent = config.parent; + this.classes = view.themeClasses; + this.createContainer(); + this.measureReq = { read: this.readMeasure.bind(this), write: this.writeMeasure.bind(this), key: this }; + this.manager = new TooltipViewManager(view, showTooltip, t => this.createTooltip(t)); + this.intersectionObserver = typeof IntersectionObserver == "function" ? new IntersectionObserver(entries => { + if (Date.now() > this.lastTransaction - 50 && + entries.length > 0 && entries[entries.length - 1].intersectionRatio < 1) + this.measureSoon(); + }, { threshold: [1] }) : null; + this.observeIntersection(); + view.win.addEventListener("resize", this.measureSoon = this.measureSoon.bind(this)); + this.maybeMeasure(); + } + createContainer() { + if (this.parent) { + this.container = document.createElement("div"); + this.container.style.position = "relative"; + this.container.className = this.view.themeClasses; + this.parent.appendChild(this.container); + } + else { + this.container = this.view.dom; + } + } + observeIntersection() { + if (this.intersectionObserver) { + this.intersectionObserver.disconnect(); + for (let tooltip of this.manager.tooltipViews) + this.intersectionObserver.observe(tooltip.dom); + } + } + measureSoon() { + if (this.measureTimeout < 0) + this.measureTimeout = setTimeout(() => { + this.measureTimeout = -1; + this.maybeMeasure(); + }, 50); + } + update(update) { + if (update.transactions.length) + this.lastTransaction = Date.now(); + let updated = this.manager.update(update); + if (updated) + this.observeIntersection(); + let shouldMeasure = updated || update.geometryChanged; + let newConfig = update.state.facet(tooltipConfig); + if (newConfig.position != this.position) { + this.position = newConfig.position; + for (let t of this.manager.tooltipViews) + t.dom.style.position = this.position; + shouldMeasure = true; + } + if (newConfig.parent != this.parent) { + if (this.parent) + this.container.remove(); + this.parent = newConfig.parent; + this.createContainer(); + for (let t of this.manager.tooltipViews) + this.container.appendChild(t.dom); + shouldMeasure = true; + } + else if (this.parent && this.view.themeClasses != this.classes) { + this.classes = this.container.className = this.view.themeClasses; + } + if (shouldMeasure) + this.maybeMeasure(); + } + createTooltip(tooltip) { + let tooltipView = tooltip.create(this.view); + tooltipView.dom.classList.add("cm-tooltip"); + if (tooltip.arrow && !tooltipView.dom.querySelector(".cm-tooltip > .cm-tooltip-arrow")) { + let arrow = document.createElement("div"); + arrow.className = "cm-tooltip-arrow"; + tooltipView.dom.appendChild(arrow); + } + tooltipView.dom.style.position = this.position; + tooltipView.dom.style.top = Outside; + this.container.appendChild(tooltipView.dom); + if (tooltipView.mount) + tooltipView.mount(this.view); + return tooltipView; + } + destroy() { + var _a; + this.view.win.removeEventListener("resize", this.measureSoon); + for (let { dom } of this.manager.tooltipViews) + dom.remove(); + (_a = this.intersectionObserver) === null || _a === void 0 ? void 0 : _a.disconnect(); + clearTimeout(this.measureTimeout); + } + readMeasure() { + let editor = this.view.dom.getBoundingClientRect(); + return { + editor, + parent: this.parent ? this.container.getBoundingClientRect() : editor, + pos: this.manager.tooltips.map((t, i) => { + let tv = this.manager.tooltipViews[i]; + return tv.getCoords ? tv.getCoords(t.pos) : this.view.coordsAtPos(t.pos); + }), + size: this.manager.tooltipViews.map(({ dom }) => dom.getBoundingClientRect()), + space: this.view.state.facet(tooltipConfig).tooltipSpace(this.view), + }; + } + writeMeasure(measured) { + let { editor, space } = measured; + let others = []; + for (let i = 0; i < this.manager.tooltips.length; i++) { + let tooltip = this.manager.tooltips[i], tView = this.manager.tooltipViews[i], { dom } = tView; + let pos = measured.pos[i], size = measured.size[i]; + // Hide tooltips that are outside of the editor. + if (!pos || pos.bottom <= Math.max(editor.top, space.top) || + pos.top >= Math.min(editor.bottom, space.bottom) || + pos.right < Math.max(editor.left, space.left) - .1 || + pos.left > Math.min(editor.right, space.right) + .1) { + dom.style.top = Outside; + continue; + } + let arrow = tooltip.arrow ? tView.dom.querySelector(".cm-tooltip-arrow") : null; + let arrowHeight = arrow ? 7 /* Arrow.Size */ : 0; + let width = size.right - size.left, height = size.bottom - size.top; + let offset = tView.offset || noOffset, ltr = this.view.textDirection == Direction.LTR; + let left = size.width > space.right - space.left ? (ltr ? space.left : space.right - size.width) + : ltr ? Math.min(pos.left - (arrow ? 14 /* Arrow.Offset */ : 0) + offset.x, space.right - width) + : Math.max(space.left, pos.left - width + (arrow ? 14 /* Arrow.Offset */ : 0) - offset.x); + let above = !!tooltip.above; + if (!tooltip.strictSide && (above + ? pos.top - (size.bottom - size.top) - offset.y < space.top + : pos.bottom + (size.bottom - size.top) + offset.y > space.bottom) && + above == (space.bottom - pos.bottom > pos.top - space.top)) + above = !above; + let top = above ? pos.top - height - arrowHeight - offset.y : pos.bottom + arrowHeight + offset.y; + let right = left + width; + if (tView.overlap !== true) + for (let r of others) + if (r.left < right && r.right > left && r.top < top + height && r.bottom > top) + top = above ? r.top - height - 2 - arrowHeight : r.bottom + arrowHeight + 2; + if (this.position == "absolute") { + dom.style.top = (top - measured.parent.top) + "px"; + dom.style.left = (left - measured.parent.left) + "px"; + } + else { + dom.style.top = top + "px"; + dom.style.left = left + "px"; + } + if (arrow) + arrow.style.left = `${pos.left + (ltr ? offset.x : -offset.x) - (left + 14 /* Arrow.Offset */ - 7 /* Arrow.Size */)}px`; + if (tView.overlap !== true) + others.push({ left, top, right, bottom: top + height }); + dom.classList.toggle("cm-tooltip-above", above); + dom.classList.toggle("cm-tooltip-below", !above); + if (tView.positioned) + tView.positioned(); + } + } + maybeMeasure() { + if (this.manager.tooltips.length) { + if (this.view.inView) + this.view.requestMeasure(this.measureReq); + if (this.inView != this.view.inView) { + this.inView = this.view.inView; + if (!this.inView) + for (let tv of this.manager.tooltipViews) + tv.dom.style.top = Outside; + } + } + } + }, { + eventHandlers: { + scroll() { this.maybeMeasure(); } + } + }); + const baseTheme$4 = /*@__PURE__*/EditorView.baseTheme({ + ".cm-tooltip": { + zIndex: 100 + }, + "&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: `${7 /* Arrow.Size */}px`, + width: `${7 /* Arrow.Size */ * 2}px`, + position: "absolute", + zIndex: -1, + overflow: "hidden", + "&:before, &:after": { + content: "''", + position: "absolute", + width: 0, + height: 0, + borderLeft: `${7 /* Arrow.Size */}px solid transparent`, + borderRight: `${7 /* Arrow.Size */}px solid transparent`, + }, + ".cm-tooltip-above &": { + bottom: `-${7 /* Arrow.Size */}px`, + "&:before": { + borderTop: `${7 /* Arrow.Size */}px solid #bbb`, + }, + "&:after": { + borderTop: `${7 /* Arrow.Size */}px solid #f5f5f5`, + bottom: "1px" + } + }, + ".cm-tooltip-below &": { + top: `-${7 /* Arrow.Size */}px`, + "&:before": { + borderBottom: `${7 /* Arrow.Size */}px solid #bbb`, + }, + "&:after": { + borderBottom: `${7 /* Arrow.Size */}px solid #f5f5f5`, + top: "1px" + } + }, + }, + "&dark .cm-tooltip .cm-tooltip-arrow": { + "&:before": { + borderTopColor: "#333338", + borderBottomColor: "#333338" + }, + "&:after": { + borderTopColor: "transparent", + borderBottomColor: "transparent" + } + } + }); + const noOffset = { x: 0, y: 0 }; + /** + Facet to which an extension can add a value to show a tooltip. + */ + const showTooltip = /*@__PURE__*/Facet.define({ + enables: [tooltipPlugin, baseTheme$4] + }); + const showHoverTooltip = /*@__PURE__*/Facet.define(); + class HoverTooltipHost { + constructor(view) { + this.view = view; + this.mounted = false; + this.dom = document.createElement("div"); + this.dom.classList.add("cm-tooltip-hover"); + this.manager = new TooltipViewManager(view, showHoverTooltip, t => this.createHostedView(t)); + } + // Needs to be static so that host tooltip instances always match + static create(view) { + return new HoverTooltipHost(view); + } + createHostedView(tooltip) { + let hostedView = tooltip.create(this.view); + hostedView.dom.classList.add("cm-tooltip-section"); + this.dom.appendChild(hostedView.dom); + if (this.mounted && hostedView.mount) + hostedView.mount(this.view); + return hostedView; + } + mount(view) { + for (let hostedView of this.manager.tooltipViews) { + if (hostedView.mount) + hostedView.mount(view); + } + this.mounted = true; + } + positioned() { + for (let hostedView of this.manager.tooltipViews) { + if (hostedView.positioned) + hostedView.positioned(); + } + } + update(update) { + this.manager.update(update); + } + } + const showHoverTooltipHost = /*@__PURE__*/showTooltip.compute([showHoverTooltip], state => { + let tooltips = state.facet(showHoverTooltip).filter(t => t); + if (tooltips.length === 0) + return null; + return { + pos: Math.min(...tooltips.map(t => t.pos)), + end: Math.max(...tooltips.filter(t => t.end != null).map(t => t.end)), + create: HoverTooltipHost.create, + above: tooltips[0].above, + arrow: tooltips.some(t => t.arrow), + }; + }); + class HoverPlugin { + constructor(view, source, field, setHover, hoverTime) { + this.view = view; + this.source = source; + this.field = field; + this.setHover = setHover; + this.hoverTime = hoverTime; + this.hoverTimeout = -1; + this.restartTimeout = -1; + this.pending = null; + this.lastMove = { x: 0, y: 0, target: view.dom, time: 0 }; + this.checkHover = this.checkHover.bind(this); + view.dom.addEventListener("mouseleave", this.mouseleave = this.mouseleave.bind(this)); + view.dom.addEventListener("mousemove", this.mousemove = this.mousemove.bind(this)); + } + update() { + if (this.pending) { + this.pending = null; + clearTimeout(this.restartTimeout); + this.restartTimeout = setTimeout(() => this.startHover(), 20); + } + } + get active() { + return this.view.state.field(this.field); + } + checkHover() { + this.hoverTimeout = -1; + if (this.active) + return; + let hovered = Date.now() - this.lastMove.time; + if (hovered < this.hoverTime) + this.hoverTimeout = setTimeout(this.checkHover, this.hoverTime - hovered); + else + this.startHover(); + } + startHover() { + clearTimeout(this.restartTimeout); + let { lastMove } = this; + let pos = this.view.contentDOM.contains(lastMove.target) ? this.view.posAtCoords(lastMove) : null; + if (pos == null) + return; + let posCoords = this.view.coordsAtPos(pos); + if (posCoords == null || lastMove.y < posCoords.top || lastMove.y > posCoords.bottom || + lastMove.x < posCoords.left - this.view.defaultCharacterWidth || + lastMove.x > posCoords.right + this.view.defaultCharacterWidth) + return; + let bidi = this.view.bidiSpans(this.view.state.doc.lineAt(pos)).find(s => s.from <= pos && s.to >= pos); + let rtl = bidi && bidi.dir == Direction.RTL ? -1 : 1; + let open = this.source(this.view, pos, (lastMove.x < posCoords.left ? -rtl : rtl)); + if (open === null || open === void 0 ? void 0 : open.then) { + let pending = this.pending = { pos }; + open.then(result => { + if (this.pending == pending) { + this.pending = null; + if (result) + this.view.dispatch({ effects: this.setHover.of(result) }); + } + }, e => logException(this.view.state, e, "hover tooltip")); + } + else if (open) { + this.view.dispatch({ effects: this.setHover.of(open) }); + } + } + mousemove(event) { + var _a; + this.lastMove = { x: event.clientX, y: event.clientY, target: event.target, time: Date.now() }; + if (this.hoverTimeout < 0) + this.hoverTimeout = setTimeout(this.checkHover, this.hoverTime); + let tooltip = this.active; + if (tooltip && !isInTooltip(this.lastMove.target) || this.pending) { + let { pos } = tooltip || this.pending, end = (_a = tooltip === null || tooltip === void 0 ? void 0 : tooltip.end) !== null && _a !== void 0 ? _a : pos; + if ((pos == end ? this.view.posAtCoords(this.lastMove) != pos + : !isOverRange(this.view, pos, end, event.clientX, event.clientY, 6 /* Hover.MaxDist */))) { + this.view.dispatch({ effects: this.setHover.of(null) }); + this.pending = null; + } + } + } + mouseleave() { + clearTimeout(this.hoverTimeout); + this.hoverTimeout = -1; + if (this.active) + this.view.dispatch({ effects: this.setHover.of(null) }); + } + destroy() { + clearTimeout(this.hoverTimeout); + this.view.dom.removeEventListener("mouseleave", this.mouseleave); + this.view.dom.removeEventListener("mousemove", this.mousemove); + } + } + function isInTooltip(elt) { + for (let cur = elt; cur; cur = cur.parentNode) + if (cur.nodeType == 1 && cur.classList.contains("cm-tooltip")) + return true; + return false; + } + function isOverRange(view, from, to, x, y, margin) { + let range = document.createRange(); + let fromDOM = view.domAtPos(from), toDOM = view.domAtPos(to); + range.setEnd(toDOM.node, toDOM.offset); + range.setStart(fromDOM.node, fromDOM.offset); + let rects = range.getClientRects(); + range.detach(); + for (let i = 0; i < rects.length; i++) { + let rect = rects[i]; + let dist = Math.max(rect.top - y, y - rect.bottom, rect.left - x, x - rect.right); + if (dist <= margin) + return true; + } + return false; + } + /** + Set up a hover tooltip, which shows up when the pointer hovers + over ranges of text. The callback is called when the mouse hovers + over the document text. It should, if there is a tooltip + associated with position `pos`, return the tooltip description + (either directly or in a promise). The `side` argument indicates + on which side of the position the pointer is—it will be -1 if the + pointer is before the position, 1 if after the position. + + Note that all hover tooltips are hosted within a single tooltip + container element. This allows multiple tooltips over the same + range to be "merged" together without overlapping. + */ + function hoverTooltip(source, options = {}) { + let setHover = StateEffect.define(); + let hoverState = StateField.define({ + create() { return null; }, + update(value, tr) { + if (value && (options.hideOnChange && (tr.docChanged || tr.selection) || + options.hideOn && options.hideOn(tr, value))) + return null; + if (value && tr.docChanged) { + let newPos = tr.changes.mapPos(value.pos, -1, MapMode.TrackDel); + if (newPos == null) + return null; + let copy = Object.assign(Object.create(null), value); + copy.pos = newPos; + if (value.end != null) + copy.end = tr.changes.mapPos(value.end); + value = copy; + } + for (let effect of tr.effects) { + if (effect.is(setHover)) + value = effect.value; + if (effect.is(closeHoverTooltipEffect)) + value = null; + } + return value; + }, + provide: f => showHoverTooltip.from(f) + }); + return [ + hoverState, + ViewPlugin.define(view => new HoverPlugin(view, source, hoverState, setHover, options.hoverTime || 300 /* Hover.Time */)), + showHoverTooltipHost + ]; + } + /** + Get the active tooltip view for a given tooltip, if available. + */ + function getTooltip(view, tooltip) { + let plugin = view.plugin(tooltipPlugin); + if (!plugin) + return null; + let found = plugin.manager.tooltips.indexOf(tooltip); + return found < 0 ? null : plugin.manager.tooltipViews[found]; + } + const closeHoverTooltipEffect = /*@__PURE__*/StateEffect.define(); + + const panelConfig = /*@__PURE__*/Facet.define({ + combine(configs) { + let topContainer, bottomContainer; + for (let c of configs) { + topContainer = topContainer || c.topContainer; + bottomContainer = bottomContainer || c.bottomContainer; + } + return { topContainer, bottomContainer }; + } + }); + /** + Get the active panel created by the given constructor, if any. + This can be useful when you need access to your panels' DOM + structure. + */ + function getPanel(view, panel) { + let plugin = view.plugin(panelPlugin); + let index = plugin ? plugin.specs.indexOf(panel) : -1; + return index > -1 ? plugin.panels[index] : null; + } + const panelPlugin = /*@__PURE__*/ViewPlugin.fromClass(class { + constructor(view) { + this.input = view.state.facet(showPanel); + this.specs = this.input.filter(s => s); + this.panels = this.specs.map(spec => spec(view)); + let conf = view.state.facet(panelConfig); + this.top = new PanelGroup(view, true, conf.topContainer); + this.bottom = new PanelGroup(view, false, conf.bottomContainer); + this.top.sync(this.panels.filter(p => p.top)); + this.bottom.sync(this.panels.filter(p => !p.top)); + for (let p of this.panels) { + p.dom.classList.add("cm-panel"); + if (p.mount) + p.mount(); + } + } + update(update) { + let conf = update.state.facet(panelConfig); + if (this.top.container != conf.topContainer) { + this.top.sync([]); + this.top = new PanelGroup(update.view, true, conf.topContainer); + } + if (this.bottom.container != conf.bottomContainer) { + this.bottom.sync([]); + this.bottom = new PanelGroup(update.view, false, conf.bottomContainer); + } + this.top.syncClasses(); + this.bottom.syncClasses(); + let input = update.state.facet(showPanel); + if (input != this.input) { + let specs = input.filter(x => x); + let panels = [], top = [], bottom = [], mount = []; + for (let spec of specs) { + let known = this.specs.indexOf(spec), panel; + if (known < 0) { + panel = spec(update.view); + mount.push(panel); + } + else { + panel = this.panels[known]; + if (panel.update) + panel.update(update); + } + panels.push(panel); + (panel.top ? top : bottom).push(panel); + } + this.specs = specs; + this.panels = panels; + this.top.sync(top); + this.bottom.sync(bottom); + for (let p of mount) { + p.dom.classList.add("cm-panel"); + if (p.mount) + p.mount(); + } + } + else { + for (let p of this.panels) + if (p.update) + p.update(update); + } + } + destroy() { + this.top.sync([]); + this.bottom.sync([]); + } + }, { + provide: plugin => EditorView.scrollMargins.of(view => { + let value = view.plugin(plugin); + return value && { top: value.top.scrollMargin(), bottom: value.bottom.scrollMargin() }; + }) + }); + class PanelGroup { + constructor(view, top, container) { + this.view = view; + this.top = top; + this.container = container; + this.dom = undefined; + this.classes = ""; + this.panels = []; + this.syncClasses(); + } + sync(panels) { + for (let p of this.panels) + if (p.destroy && panels.indexOf(p) < 0) + p.destroy(); + this.panels = panels; + this.syncDOM(); + } + syncDOM() { + if (this.panels.length == 0) { + if (this.dom) { + this.dom.remove(); + this.dom = undefined; + } + return; + } + 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 parent = this.container || this.view.dom; + parent.insertBefore(this.dom, this.top ? parent.firstChild : null); + } + let curDOM = this.dom.firstChild; + for (let panel of this.panels) { + if (panel.dom.parentNode == this.dom) { + while (curDOM != panel.dom) + curDOM = rm(curDOM); + curDOM = curDOM.nextSibling; + } + else { + this.dom.insertBefore(panel.dom, curDOM); + } + } + while (curDOM) + curDOM = rm(curDOM); + } + 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) + return; + for (let cls of this.classes.split(" ")) + if (cls) + this.container.classList.remove(cls); + for (let cls of (this.classes = this.view.themeClasses).split(" ")) + if (cls) + this.container.classList.add(cls); + } + } + function rm(node) { + let next = node.nextSibling; + node.remove(); + return next; + } + /** + Opening a panel is done by providing a constructor function for + the panel through this facet. (The panel is closed again when its + constructor is no longer provided.) Values of `null` are ignored. + */ + const showPanel = /*@__PURE__*/Facet.define({ + enables: panelPlugin + }); + + /** + A gutter marker represents a bit of information attached to a line + in a specific gutter. Your own custom markers have to extend this + class. + */ + class GutterMarker extends RangeValue { + /** + @internal + */ + compare(other) { + return this == other || this.constructor == other.constructor && this.eq(other); + } + /** + Compare this marker to another marker of the same type. + */ + eq(other) { return false; } + /** + Called if the marker has a `toDOM` method and its representation + was removed from a gutter. + */ + destroy(dom) { } + } + GutterMarker.prototype.elementClass = ""; + GutterMarker.prototype.toDOM = undefined; + GutterMarker.prototype.mapMode = MapMode.TrackBefore; + GutterMarker.prototype.startSide = GutterMarker.prototype.endSide = -1; + GutterMarker.prototype.point = true; + /** + Facet used to add a class to all gutter elements for a given line. + Markers given to this facet should _only_ define an + [`elementclass`](https://codemirror.net/6/docs/ref/#view.GutterMarker.elementClass), not a + [`toDOM`](https://codemirror.net/6/docs/ref/#view.GutterMarker.toDOM) (or the marker will appear + in all gutters for the line). + */ + const gutterLineClass = /*@__PURE__*/Facet.define(); + const defaults$1 = { + class: "", + renderEmptyElements: false, + elementStyle: "", + markers: () => RangeSet.empty, + lineMarker: () => null, + lineMarkerChange: null, + initialSpacer: null, + updateSpacer: null, + domEventHandlers: {} + }; + const activeGutters = /*@__PURE__*/Facet.define(); + /** + Define an editor gutter. The order in which the gutters appear is + determined by their extension priority. + */ + function gutter(config) { + return [gutters(), activeGutters.of(Object.assign(Object.assign({}, defaults$1), config))]; + } + const unfixGutters = /*@__PURE__*/Facet.define({ + combine: values => values.some(x => x) + }); + /** + The gutter-drawing plugin is automatically enabled when you add a + gutter, but you can use this function to explicitly configure it. + + Unless `fixed` is explicitly set to `false`, the gutters are + fixed, meaning they don't scroll along with the content + horizontally (except on Internet Explorer, which doesn't support + CSS [`position: + sticky`](https://developer.mozilla.org/en-US/docs/Web/CSS/position#sticky)). + */ + function gutters(config) { + let result = [ + gutterView, + ]; + if (config && config.fixed === false) + result.push(unfixGutters.of(true)); + return result; + } + const gutterView = /*@__PURE__*/ViewPlugin.fromClass(class { + constructor(view) { + this.view = view; + this.prevViewport = view.viewport; + this.dom = document.createElement("div"); + this.dom.className = "cm-gutters"; + this.dom.setAttribute("aria-hidden", "true"); + this.dom.style.minHeight = this.view.contentHeight + "px"; + this.gutters = view.state.facet(activeGutters).map(conf => new SingleGutterView(view, conf)); + for (let gutter of this.gutters) + this.dom.appendChild(gutter.dom); + this.fixed = !view.state.facet(unfixGutters); + if (this.fixed) { + // FIXME IE11 fallback, which doesn't support position: sticky, + // by using position: relative + event handlers that realign the + // gutter (or just force fixed=false on IE11?) + this.dom.style.position = "sticky"; + } + this.syncGutters(false); + view.scrollDOM.insertBefore(this.dom, view.contentDOM); + } + update(update) { + if (this.updateGutters(update)) { + // Detach during sync when the viewport changed significantly + // (such as during scrolling), since for large updates that is + // faster. + let vpA = this.prevViewport, vpB = update.view.viewport; + let vpOverlap = Math.min(vpA.to, vpB.to) - Math.max(vpA.from, vpB.from); + this.syncGutters(vpOverlap < (vpB.to - vpB.from) * 0.8); + } + if (update.geometryChanged) + this.dom.style.minHeight = this.view.contentHeight + "px"; + if (this.view.state.facet(unfixGutters) != !this.fixed) { + this.fixed = !this.fixed; + this.dom.style.position = this.fixed ? "sticky" : ""; + } + this.prevViewport = update.view.viewport; + } + syncGutters(detach) { + let after = this.dom.nextSibling; + if (detach) + this.dom.remove(); + let lineClasses = RangeSet.iter(this.view.state.facet(gutterLineClass), this.view.viewport.from); + let classSet = []; + let contexts = this.gutters.map(gutter => new UpdateContext(gutter, this.view.viewport, -this.view.documentPadding.top)); + for (let line of this.view.viewportLineBlocks) { + let text; + if (Array.isArray(line.type)) { + for (let b of line.type) + if (b.type == BlockType.Text) { + text = b; + break; + } + } + else { + text = line.type == BlockType.Text ? line : undefined; + } + if (!text) + continue; + if (classSet.length) + classSet = []; + advanceCursor(lineClasses, classSet, line.from); + for (let cx of contexts) + cx.line(this.view, text, classSet); + } + for (let cx of contexts) + cx.finish(); + if (detach) + this.view.scrollDOM.insertBefore(this.dom, after); + } + updateGutters(update) { + let prev = update.startState.facet(activeGutters), cur = update.state.facet(activeGutters); + let change = update.docChanged || update.heightChanged || update.viewportChanged || + !RangeSet.eq(update.startState.facet(gutterLineClass), update.state.facet(gutterLineClass), update.view.viewport.from, update.view.viewport.to); + if (prev == cur) { + for (let gutter of this.gutters) + if (gutter.update(update)) + change = true; + } + else { + change = true; + let gutters = []; + for (let conf of cur) { + let known = prev.indexOf(conf); + if (known < 0) { + gutters.push(new SingleGutterView(this.view, conf)); + } + else { + this.gutters[known].update(update); + gutters.push(this.gutters[known]); + } + } + for (let g of this.gutters) { + g.dom.remove(); + if (gutters.indexOf(g) < 0) + g.destroy(); + } + for (let g of gutters) + this.dom.appendChild(g.dom); + this.gutters = gutters; + } + return change; + } + destroy() { + for (let view of this.gutters) + view.destroy(); + this.dom.remove(); + } + }, { + provide: plugin => EditorView.scrollMargins.of(view => { + let value = view.plugin(plugin); + if (!value || value.gutters.length == 0 || !value.fixed) + return null; + return view.textDirection == Direction.LTR ? { left: value.dom.offsetWidth } : { right: value.dom.offsetWidth }; + }) + }); + function asArray(val) { return (Array.isArray(val) ? val : [val]); } + function advanceCursor(cursor, collect, pos) { + while (cursor.value && cursor.from <= pos) { + if (cursor.from == pos) + collect.push(cursor.value); + cursor.next(); + } + } + class UpdateContext { + constructor(gutter, viewport, height) { + this.gutter = gutter; + this.height = height; + this.localMarkers = []; + this.i = 0; + this.cursor = RangeSet.iter(gutter.markers, viewport.from); + } + line(view, line, extraMarkers) { + if (this.localMarkers.length) + this.localMarkers = []; + advanceCursor(this.cursor, this.localMarkers, line.from); + let localMarkers = extraMarkers.length ? this.localMarkers.concat(extraMarkers) : this.localMarkers; + let forLine = this.gutter.config.lineMarker(view, line, localMarkers); + if (forLine) + localMarkers.unshift(forLine); + let gutter = this.gutter; + if (localMarkers.length == 0 && !gutter.config.renderEmptyElements) + return; + let above = line.top - this.height; + if (this.i == gutter.elements.length) { + let newElt = new GutterElement(view, line.height, above, localMarkers); + gutter.elements.push(newElt); + gutter.dom.appendChild(newElt.dom); + } + else { + gutter.elements[this.i].update(view, line.height, above, localMarkers); + } + this.height = line.bottom; + this.i++; + } + finish() { + let gutter = this.gutter; + while (gutter.elements.length > this.i) { + let last = gutter.elements.pop(); + gutter.dom.removeChild(last.dom); + last.destroy(); + } + } + } + class SingleGutterView { + constructor(view, config) { + this.view = view; + this.config = config; + this.elements = []; + this.spacer = null; + this.dom = document.createElement("div"); + this.dom.className = "cm-gutter" + (this.config.class ? " " + this.config.class : ""); + for (let prop in config.domEventHandlers) { + this.dom.addEventListener(prop, (event) => { + let line = view.lineBlockAtHeight(event.clientY - view.documentTop); + if (config.domEventHandlers[prop](view, line, event)) + event.preventDefault(); + }); + } + this.markers = asArray(config.markers(view)); + if (config.initialSpacer) { + this.spacer = new GutterElement(view, 0, 0, [config.initialSpacer(view)]); + this.dom.appendChild(this.spacer.dom); + this.spacer.dom.style.cssText += "visibility: hidden; pointer-events: none"; + } + } + update(update) { + let prevMarkers = this.markers; + this.markers = asArray(this.config.markers(update.view)); + if (this.spacer && this.config.updateSpacer) { + let updated = this.config.updateSpacer(this.spacer.markers[0], update); + if (updated != this.spacer.markers[0]) + this.spacer.update(update.view, 0, 0, [updated]); + } + let vp = update.view.viewport; + return !RangeSet.eq(this.markers, prevMarkers, vp.from, vp.to) || + (this.config.lineMarkerChange ? this.config.lineMarkerChange(update) : false); + } + destroy() { + for (let elt of this.elements) + elt.destroy(); + } + } + class GutterElement { + constructor(view, height, above, markers) { + this.height = -1; + this.above = 0; + this.markers = []; + this.dom = document.createElement("div"); + this.dom.className = "cm-gutterElement"; + this.update(view, height, above, markers); + } + update(view, height, above, markers) { + if (this.height != height) + this.dom.style.height = (this.height = height) + "px"; + if (this.above != above) + this.dom.style.marginTop = (this.above = above) ? above + "px" : ""; + if (!sameMarkers(this.markers, markers)) + this.setMarkers(view, markers); + } + setMarkers(view, markers) { + let cls = "cm-gutterElement", domPos = this.dom.firstChild; + for (let iNew = 0, iOld = 0;;) { + let skipTo = iOld, marker = iNew < markers.length ? markers[iNew++] : null, matched = false; + if (marker) { + let c = marker.elementClass; + if (c) + cls += " " + c; + for (let i = iOld; i < this.markers.length; i++) + if (this.markers[i].compare(marker)) { + skipTo = i; + matched = true; + break; + } + } + else { + skipTo = this.markers.length; + } + while (iOld < skipTo) { + let next = this.markers[iOld++]; + if (next.toDOM) { + next.destroy(domPos); + let after = domPos.nextSibling; + domPos.remove(); + domPos = after; + } + } + if (!marker) + break; + if (marker.toDOM) { + if (matched) + domPos = domPos.nextSibling; + else + this.dom.insertBefore(marker.toDOM(view), domPos); + } + if (matched) + iOld++; + } + this.dom.className = cls; + this.markers = markers; + } + destroy() { + this.setMarkers(null, []); // First argument not used unless creating markers + } + } + function sameMarkers(a, b) { + if (a.length != b.length) + return false; + for (let i = 0; i < a.length; i++) + if (!a[i].compare(b[i])) + return false; + return true; + } + /** + Facet used to provide markers to the line number gutter. + */ + const lineNumberMarkers = /*@__PURE__*/Facet.define(); + const lineNumberConfig = /*@__PURE__*/Facet.define({ + combine(values) { + return combineConfig(values, { formatNumber: String, domEventHandlers: {} }, { + domEventHandlers(a, b) { + let result = Object.assign({}, a); + for (let event in b) { + let exists = result[event], add = b[event]; + result[event] = exists ? (view, line, event) => exists(view, line, event) || add(view, line, event) : add; + } + return result; + } + }); + } + }); + class NumberMarker extends GutterMarker { + constructor(number) { + super(); + this.number = number; + } + eq(other) { return this.number == other.number; } + toDOM() { return document.createTextNode(this.number); } + } + function formatNumber(view, number) { + return view.state.facet(lineNumberConfig).formatNumber(number, view.state); + } + const lineNumberGutter = /*@__PURE__*/activeGutters.compute([lineNumberConfig], state => ({ + class: "cm-lineNumbers", + renderEmptyElements: false, + markers(view) { return view.state.facet(lineNumberMarkers); }, + lineMarker(view, line, others) { + if (others.some(m => m.toDOM)) + return null; + return new NumberMarker(formatNumber(view, view.state.doc.lineAt(line.from).number)); + }, + lineMarkerChange: update => update.startState.facet(lineNumberConfig) != update.state.facet(lineNumberConfig), + initialSpacer(view) { + return new NumberMarker(formatNumber(view, maxLineNumber(view.state.doc.lines))); + }, + updateSpacer(spacer, update) { + let max = formatNumber(update.view, maxLineNumber(update.view.state.doc.lines)); + return max == spacer.number ? spacer : new NumberMarker(max); + }, + domEventHandlers: state.facet(lineNumberConfig).domEventHandlers + })); + /** + Create a line number gutter extension. + */ + function lineNumbers(config = {}) { + return [ + lineNumberConfig.of(config), + gutters(), + lineNumberGutter + ]; + } + function maxLineNumber(lines) { + let last = 9; + while (last < lines) + last = last * 10 + 9; + return last; + } + const activeLineGutterMarker = /*@__PURE__*/new class extends GutterMarker { + constructor() { + super(...arguments); + this.elementClass = "cm-activeLineGutter"; + } + }; + const activeLineGutterHighlighter = /*@__PURE__*/gutterLineClass.compute(["selection"], state => { + let marks = [], last = -1; + for (let range of state.selection.ranges) { + let linePos = state.doc.lineAt(range.head).from; + if (linePos > last) { + last = linePos; + marks.push(activeLineGutterMarker.range(linePos)); + } + } + return RangeSet.of(marks); + }); + /** + Returns an extension that adds a `cm-activeLineGutter` class to + all gutter elements on the [active + line](https://codemirror.net/6/docs/ref/#view.highlightActiveLine). + */ + function highlightActiveLineGutter() { + return activeLineGutterHighlighter; + } + + // FIXME profile adding a per-Tree TreeNode cache, validating it by + // parent pointer + /// The default maximum length of a `TreeBuffer` node. + const DefaultBufferLength = 1024; + let nextPropID = 0; + class Range { + constructor(from, to) { + this.from = from; + this.to = to; + } + } + /// Each [node type](#common.NodeType) or [individual tree](#common.Tree) + /// can have metadata associated with it in props. Instances of this + /// class represent prop names. + class NodeProp { + /// Create a new node prop type. + constructor(config = {}) { + this.id = nextPropID++; + this.perNode = !!config.perNode; + this.deserialize = config.deserialize || (() => { + throw new Error("This node type doesn't define a deserialize function"); + }); + } + /// This is meant to be used with + /// [`NodeSet.extend`](#common.NodeSet.extend) or + /// [`LRParser.configure`](#lr.ParserConfig.props) to compute + /// prop values for each node type in the set. Takes a [match + /// object](#common.NodeType^match) or function that returns undefined + /// if the node type doesn't get this prop, and the prop's value if + /// it does. + add(match) { + if (this.perNode) + throw new RangeError("Can't add per-node props to node types"); + if (typeof match != "function") + match = NodeType.match(match); + return (type) => { + let result = match(type); + return result === undefined ? null : [this, result]; + }; + } + } + /// Prop that is used to describe matching delimiters. For opening + /// delimiters, this holds an array of node names (written as a + /// space-separated string when declaring this prop in a grammar) + /// for the node types of closing delimiters that match it. + NodeProp.closedBy = new NodeProp({ deserialize: str => str.split(" ") }); + /// The inverse of [`closedBy`](#common.NodeProp^closedBy). This is + /// attached to closing delimiters, holding an array of node names + /// of types of matching opening delimiters. + NodeProp.openedBy = new NodeProp({ deserialize: str => str.split(" ") }); + /// Used to assign node types to groups (for example, all node + /// types that represent an expression could be tagged with an + /// `"Expression"` group). + NodeProp.group = new NodeProp({ deserialize: str => str.split(" ") }); + /// The hash of the [context](#lr.ContextTracker.constructor) + /// that the node was parsed in, if any. Used to limit reuse of + /// contextual nodes. + NodeProp.contextHash = new NodeProp({ perNode: true }); + /// The distance beyond the end of the node that the tokenizer + /// looked ahead for any of the tokens inside the node. (The LR + /// parser only stores this when it is larger than 25, for + /// efficiency reasons.) + NodeProp.lookAhead = new NodeProp({ perNode: true }); + /// This per-node prop is used to replace a given node, or part of a + /// node, with another tree. This is useful to include trees from + /// different languages in mixed-language parsers. + NodeProp.mounted = new NodeProp({ perNode: true }); + const noProps = Object.create(null); + /// Each node in a syntax tree has a node type associated with it. + class NodeType { + /// @internal + constructor( + /// The name of the node type. Not necessarily unique, but if the + /// grammar was written properly, different node types with the + /// same name within a node set should play the same semantic + /// role. + name, + /// @internal + props, + /// The id of this node in its set. Corresponds to the term ids + /// used in the parser. + id, + /// @internal + flags = 0) { + this.name = name; + this.props = props; + this.id = id; + this.flags = flags; + } + /// Define a node type. + static define(spec) { + let props = spec.props && spec.props.length ? Object.create(null) : noProps; + let flags = (spec.top ? 1 /* Top */ : 0) | (spec.skipped ? 2 /* Skipped */ : 0) | + (spec.error ? 4 /* Error */ : 0) | (spec.name == null ? 8 /* Anonymous */ : 0); + let type = new NodeType(spec.name || "", props, spec.id, flags); + if (spec.props) + for (let src of spec.props) { + if (!Array.isArray(src)) + src = src(type); + if (src) { + if (src[0].perNode) + throw new RangeError("Can't store a per-node prop on a node type"); + props[src[0].id] = src[1]; + } + } + return type; + } + /// Retrieves a node prop for this type. Will return `undefined` if + /// the prop isn't present on this node. + prop(prop) { return this.props[prop.id]; } + /// True when this is the top node of a grammar. + get isTop() { return (this.flags & 1 /* Top */) > 0; } + /// True when this node is produced by a skip rule. + get isSkipped() { return (this.flags & 2 /* Skipped */) > 0; } + /// Indicates whether this is an error node. + get isError() { return (this.flags & 4 /* Error */) > 0; } + /// When true, this node type doesn't correspond to a user-declared + /// named node, for example because it is used to cache repetition. + get isAnonymous() { return (this.flags & 8 /* Anonymous */) > 0; } + /// Returns true when this node's name or one of its + /// [groups](#common.NodeProp^group) matches the given string. + is(name) { + if (typeof name == 'string') { + if (this.name == name) + return true; + let group = this.prop(NodeProp.group); + return group ? group.indexOf(name) > -1 : false; + } + return this.id == name; + } + /// Create a function from node types to arbitrary values by + /// specifying an object whose property names are node or + /// [group](#common.NodeProp^group) names. Often useful with + /// [`NodeProp.add`](#common.NodeProp.add). You can put multiple + /// names, separated by spaces, in a single property name to map + /// multiple node names to a single value. + static match(map) { + let direct = Object.create(null); + for (let prop in map) + for (let name of prop.split(" ")) + direct[name] = map[prop]; + return (node) => { + for (let groups = node.prop(NodeProp.group), i = -1; i < (groups ? groups.length : 0); i++) { + let found = direct[i < 0 ? node.name : groups[i]]; + if (found) + return found; + } + }; + } + } + /// An empty dummy node type to use when no actual type is available. + NodeType.none = new NodeType("", Object.create(null), 0, 8 /* Anonymous */); + /// A node set holds a collection of node types. It is used to + /// compactly represent trees by storing their type ids, rather than a + /// full pointer to the type object, in a numeric array. Each parser + /// [has](#lr.LRParser.nodeSet) a node set, and [tree + /// buffers](#common.TreeBuffer) can only store collections of nodes + /// from the same set. A set can have a maximum of 2**16 (65536) node + /// types in it, so that the ids fit into 16-bit typed array slots. + class NodeSet { + /// Create a set with the given types. The `id` property of each + /// type should correspond to its position within the array. + constructor( + /// The node types in this set, by id. + types) { + this.types = types; + for (let i = 0; i < types.length; i++) + if (types[i].id != i) + throw new RangeError("Node type ids should correspond to array positions when creating a node set"); + } + /// Create a copy of this set with some node properties added. The + /// arguments to this method can be created with + /// [`NodeProp.add`](#common.NodeProp.add). + extend(...props) { + let newTypes = []; + for (let type of this.types) { + let newProps = null; + for (let source of props) { + let add = source(type); + if (add) { + if (!newProps) + newProps = Object.assign({}, type.props); + newProps[add[0].id] = add[1]; + } + } + newTypes.push(newProps ? new NodeType(type.name, newProps, type.id, type.flags) : type); + } + return new NodeSet(newTypes); + } + } + const CachedNode = new WeakMap(), CachedInnerNode = new WeakMap(); + /// Options that control iteration. Can be combined with the `|` + /// operator to enable multiple ones. + var IterMode; + (function (IterMode) { + /// When enabled, iteration will only visit [`Tree`](#common.Tree) + /// objects, not nodes packed into + /// [`TreeBuffer`](#common.TreeBuffer)s. + IterMode[IterMode["ExcludeBuffers"] = 1] = "ExcludeBuffers"; + /// Enable this to make iteration include anonymous nodes (such as + /// the nodes that wrap repeated grammar constructs into a balanced + /// tree). + IterMode[IterMode["IncludeAnonymous"] = 2] = "IncludeAnonymous"; + /// By default, regular [mounted](#common.NodeProp^mounted) nodes + /// replace their base node in iteration. Enable this to ignore them + /// instead. + IterMode[IterMode["IgnoreMounts"] = 4] = "IgnoreMounts"; + /// This option only applies in + /// [`enter`](#common.SyntaxNode.enter)-style methods. It tells the + /// library to not enter mounted overlays if one covers the given + /// position. + IterMode[IterMode["IgnoreOverlays"] = 8] = "IgnoreOverlays"; + })(IterMode || (IterMode = {})); + /// A piece of syntax tree. There are two ways to approach these + /// trees: the way they are actually stored in memory, and the + /// convenient way. + /// + /// Syntax trees are stored as a tree of `Tree` and `TreeBuffer` + /// objects. By packing detail information into `TreeBuffer` leaf + /// nodes, the representation is made a lot more memory-efficient. + /// + /// However, when you want to actually work with tree nodes, this + /// representation is very awkward, so most client code will want to + /// use the [`TreeCursor`](#common.TreeCursor) or + /// [`SyntaxNode`](#common.SyntaxNode) interface instead, which provides + /// a view on some part of this data structure, and can be used to + /// move around to adjacent nodes. + class Tree { + /// Construct a new tree. See also [`Tree.build`](#common.Tree^build). + constructor( + /// The type of the top node. + type, + /// This node's child nodes. + children, + /// The positions (offsets relative to the start of this tree) of + /// the children. + positions, + /// The total length of this tree + length, + /// Per-node [node props](#common.NodeProp) to associate with this node. + props) { + this.type = type; + this.children = children; + this.positions = positions; + this.length = length; + /// @internal + this.props = null; + if (props && props.length) { + this.props = Object.create(null); + for (let [prop, value] of props) + this.props[typeof prop == "number" ? prop : prop.id] = value; + } + } + /// @internal + toString() { + let mounted = this.prop(NodeProp.mounted); + if (mounted && !mounted.overlay) + return mounted.tree.toString(); + let children = ""; + for (let ch of this.children) { + let str = ch.toString(); + if (str) { + if (children) + children += ","; + children += str; + } + } + return !this.type.name ? children : + (/\W/.test(this.type.name) && !this.type.isError ? JSON.stringify(this.type.name) : this.type.name) + + (children.length ? "(" + children + ")" : ""); + } + /// Get a [tree cursor](#common.TreeCursor) positioned at the top of + /// the tree. Mode can be used to [control](#common.IterMode) which + /// nodes the cursor visits. + cursor(mode = 0) { + return new TreeCursor(this.topNode, mode); + } + /// Get a [tree cursor](#common.TreeCursor) pointing into this tree + /// at the given position and side (see + /// [`moveTo`](#common.TreeCursor.moveTo). + cursorAt(pos, side = 0, mode = 0) { + let scope = CachedNode.get(this) || this.topNode; + let cursor = new TreeCursor(scope); + cursor.moveTo(pos, side); + CachedNode.set(this, cursor._tree); + return cursor; + } + /// Get a [syntax node](#common.SyntaxNode) object for the top of the + /// tree. + get topNode() { + return new TreeNode(this, 0, 0, null); + } + /// Get the [syntax node](#common.SyntaxNode) at the given position. + /// If `side` is -1, this will move into nodes that end at the + /// position. If 1, it'll move into nodes that start at the + /// position. With 0, it'll only enter nodes that cover the position + /// from both sides. + /// + /// Note that this will not enter + /// [overlays](#common.MountedTree.overlay), and you often want + /// [`resolveInner`](#common.Tree.resolveInner) instead. + resolve(pos, side = 0) { + let node = resolveNode(CachedNode.get(this) || this.topNode, pos, side, false); + CachedNode.set(this, node); + return node; + } + /// Like [`resolve`](#common.Tree.resolve), but will enter + /// [overlaid](#common.MountedTree.overlay) nodes, producing a syntax node + /// pointing into the innermost overlaid tree at the given position + /// (with parent links going through all parent structure, including + /// the host trees). + resolveInner(pos, side = 0) { + let node = resolveNode(CachedInnerNode.get(this) || this.topNode, pos, side, true); + CachedInnerNode.set(this, node); + return node; + } + /// Iterate over the tree and its children, calling `enter` for any + /// node that touches the `from`/`to` region (if given) before + /// running over such a node's children, and `leave` (if given) when + /// leaving the node. When `enter` returns `false`, that node will + /// not have its children iterated over (or `leave` called). + iterate(spec) { + let { enter, leave, from = 0, to = this.length } = spec; + for (let c = this.cursor((spec.mode || 0) | IterMode.IncludeAnonymous);;) { + let entered = false; + if (c.from <= to && c.to >= from && (c.type.isAnonymous || enter(c) !== false)) { + if (c.firstChild()) + continue; + entered = true; + } + for (;;) { + if (entered && leave && !c.type.isAnonymous) + leave(c); + if (c.nextSibling()) + break; + if (!c.parent()) + return; + entered = true; + } + } + } + /// Get the value of the given [node prop](#common.NodeProp) for this + /// node. Works with both per-node and per-type props. + prop(prop) { + return !prop.perNode ? this.type.prop(prop) : this.props ? this.props[prop.id] : undefined; + } + /// Returns the node's [per-node props](#common.NodeProp.perNode) in a + /// format that can be passed to the [`Tree`](#common.Tree) + /// constructor. + get propValues() { + let result = []; + if (this.props) + for (let id in this.props) + result.push([+id, this.props[id]]); + return result; + } + /// Balance the direct children of this tree, producing a copy of + /// which may have children grouped into subtrees with type + /// [`NodeType.none`](#common.NodeType^none). + balance(config = {}) { + return this.children.length <= 8 /* BranchFactor */ ? this : + balanceRange(NodeType.none, this.children, this.positions, 0, this.children.length, 0, this.length, (children, positions, length) => new Tree(this.type, children, positions, length, this.propValues), config.makeTree || ((children, positions, length) => new Tree(NodeType.none, children, positions, length))); + } + /// Build a tree from a postfix-ordered buffer of node information, + /// or a cursor over such a buffer. + static build(data) { return buildTree(data); } + } + /// The empty tree + Tree.empty = new Tree(NodeType.none, [], [], 0); + class FlatBufferCursor { + constructor(buffer, index) { + this.buffer = buffer; + this.index = index; + } + 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 FlatBufferCursor(this.buffer, this.index); } + } + /// Tree buffers contain (type, start, end, endIndex) quads for each + /// node. In such a buffer, nodes are stored in prefix order (parents + /// before children, with the endIndex of the parent indicating which + /// children belong to it). + class TreeBuffer { + /// Create a tree buffer. + constructor( + /// The buffer's content. + buffer, + /// The total length of the group of nodes in the buffer. + length, + /// The node set used in this buffer. + set) { + this.buffer = buffer; + this.length = length; + this.set = set; + } + /// @internal + get type() { return NodeType.none; } + /// @internal + toString() { + let result = []; + for (let index = 0; index < this.buffer.length;) { + result.push(this.childString(index)); + index = this.buffer[index + 3]; + } + return result.join(","); + } + /// @internal + childString(index) { + let id = this.buffer[index], endIndex = this.buffer[index + 3]; + let type = this.set.types[id], result = type.name; + if (/\W/.test(result) && !type.isError) + result = JSON.stringify(result); + index += 4; + if (endIndex == index) + return result; + let children = []; + while (index < endIndex) { + children.push(this.childString(index)); + index = this.buffer[index + 3]; + } + return result + "(" + children.join(",") + ")"; + } + /// @internal + findChild(startIndex, endIndex, dir, pos, side) { + let { buffer } = this, pick = -1; + for (let i = startIndex; i != endIndex; i = buffer[i + 3]) { + if (checkSide(side, pos, buffer[i + 1], buffer[i + 2])) { + pick = i; + if (dir > 0) + break; + } + } + return pick; + } + /// @internal + slice(startI, endI, from, to) { + let b = this.buffer; + let copy = new Uint16Array(endI - startI); + for (let i = startI, j = 0; i < endI;) { + copy[j++] = b[i++]; + copy[j++] = b[i++] - from; + copy[j++] = b[i++] - from; + copy[j++] = b[i++] - startI; + } + return new TreeBuffer(copy, to - from, this.set); + } + } + function checkSide(side, pos, from, to) { + switch (side) { + case -2 /* Before */: return from < pos; + case -1 /* AtOrBefore */: return to >= pos && from < pos; + case 0 /* Around */: return from < pos && to > pos; + case 1 /* AtOrAfter */: return from <= pos && to > pos; + case 2 /* After */: return to > pos; + case 4 /* DontCare */: return true; + } + } + function enterUnfinishedNodesBefore(node, pos) { + let scan = node.childBefore(pos); + while (scan) { + let last = scan.lastChild; + if (!last || last.to != scan.to) + break; + if (last.type.isError && last.from == last.to) { + node = scan; + scan = last.prevSibling; + } + else { + scan = last; + } + } + return node; + } + function resolveNode(node, pos, side, overlays) { + var _a; + // Move up to a node that actually holds the position, if possible + while (node.from == node.to || + (side < 1 ? node.from >= pos : node.from > pos) || + (side > -1 ? node.to <= pos : node.to < pos)) { + let parent = !overlays && node instanceof TreeNode && node.index < 0 ? null : node.parent; + if (!parent) + return node; + node = parent; + } + let mode = overlays ? 0 : IterMode.IgnoreOverlays; + // Must go up out of overlays when those do not overlap with pos + if (overlays) + for (let scan = node, parent = scan.parent; parent; scan = parent, parent = scan.parent) { + if (scan instanceof TreeNode && scan.index < 0 && ((_a = parent.enter(pos, side, mode)) === null || _a === void 0 ? void 0 : _a.from) != scan.from) + node = parent; + } + for (;;) { + let inner = node.enter(pos, side, mode); + if (!inner) + return node; + node = inner; + } + } + class TreeNode { + constructor(_tree, from, + // Index in parent node, set to -1 if the node is not a direct child of _parent.node (overlay) + index, _parent) { + this._tree = _tree; + this.from = from; + this.index = index; + this._parent = _parent; + } + get type() { return this._tree.type; } + get name() { return this._tree.type.name; } + get to() { return this.from + this._tree.length; } + nextChild(i, dir, pos, side, mode = 0) { + for (let parent = this;;) { + for (let { children, positions } = parent._tree, e = dir > 0 ? children.length : -1; i != e; i += dir) { + let next = children[i], start = positions[i] + parent.from; + if (!checkSide(side, pos, start, start + next.length)) + continue; + if (next instanceof TreeBuffer) { + if (mode & IterMode.ExcludeBuffers) + continue; + let index = next.findChild(0, next.buffer.length, dir, pos - start, side); + if (index > -1) + return new BufferNode(new BufferContext(parent, next, i, start), null, index); + } + else if ((mode & IterMode.IncludeAnonymous) || (!next.type.isAnonymous || hasChild(next))) { + let mounted; + if (!(mode & IterMode.IgnoreMounts) && + next.props && (mounted = next.prop(NodeProp.mounted)) && !mounted.overlay) + return new TreeNode(mounted.tree, start, i, parent); + let inner = new TreeNode(next, start, i, parent); + return (mode & IterMode.IncludeAnonymous) || !inner.type.isAnonymous ? inner + : inner.nextChild(dir < 0 ? next.children.length - 1 : 0, dir, pos, side); + } + } + if ((mode & IterMode.IncludeAnonymous) || !parent.type.isAnonymous) + return null; + if (parent.index >= 0) + i = parent.index + dir; + else + i = dir < 0 ? -1 : parent._parent._tree.children.length; + parent = parent._parent; + if (!parent) + return null; + } + } + get firstChild() { return this.nextChild(0, 1, 0, 4 /* DontCare */); } + get lastChild() { return this.nextChild(this._tree.children.length - 1, -1, 0, 4 /* DontCare */); } + childAfter(pos) { return this.nextChild(0, 1, pos, 2 /* After */); } + childBefore(pos) { return this.nextChild(this._tree.children.length - 1, -1, pos, -2 /* Before */); } + enter(pos, side, mode = 0) { + let mounted; + if (!(mode & IterMode.IgnoreOverlays) && (mounted = this._tree.prop(NodeProp.mounted)) && mounted.overlay) { + let rPos = pos - this.from; + for (let { from, to } of mounted.overlay) { + if ((side > 0 ? from <= rPos : from < rPos) && + (side < 0 ? to >= rPos : to > rPos)) + return new TreeNode(mounted.tree, mounted.overlay[0].from + this.from, -1, this); + } + } + return this.nextChild(0, 1, pos, side, mode); + } + nextSignificantParent() { + let val = this; + while (val.type.isAnonymous && val._parent) + val = val._parent; + return val; + } + 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 /* DontCare */) : null; + } + get prevSibling() { + return this._parent && this.index >= 0 ? this._parent.nextChild(this.index - 1, -1, 0, 4 /* DontCare */) : null; + } + cursor(mode = 0) { return new TreeCursor(this, mode); } + get tree() { return this._tree; } + toTree() { return this._tree; } + resolve(pos, side = 0) { + return resolveNode(this, pos, side, false); + } + resolveInner(pos, side = 0) { + return resolveNode(this, pos, side, true); + } + enterUnfinishedNodesBefore(pos) { return enterUnfinishedNodesBefore(this, pos); } + getChild(type, before = null, after = null) { + let r = getChildren(this, type, before, after); + return r.length ? r[0] : null; + } + getChildren(type, before = null, after = null) { + return getChildren(this, type, before, after); + } + /// @internal + toString() { return this._tree.toString(); } + get node() { return this; } + matchContext(context) { return matchNodeContext(this, context); } + } + function getChildren(node, type, before, after) { + let cur = node.cursor(), result = []; + if (!cur.firstChild()) + return result; + if (before != null) + while (!cur.type.is(before)) + if (!cur.nextSibling()) + return result; + for (;;) { + if (after != null && cur.type.is(after)) + return result; + if (cur.type.is(type)) + result.push(cur.node); + if (!cur.nextSibling()) + return after == null ? result : []; + } + } + function matchNodeContext(node, context, i = context.length - 1) { + for (let p = node.parent; i >= 0; p = p.parent) { + if (!p) + return false; + if (!p.type.isAnonymous) { + if (context[i] && context[i] != p.name) + return false; + i--; + } + } + return true; + } + class BufferContext { + constructor(parent, buffer, index, start) { + this.parent = parent; + this.buffer = buffer; + this.index = index; + this.start = start; + } + } + class BufferNode { + constructor(context, _parent, index) { + this.context = context; + this._parent = _parent; + this.index = index; + this.type = context.buffer.set.types[context.buffer.buffer[index]]; + } + 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]; } + child(dir, pos, side) { + let { buffer } = this.context; + let index = buffer.findChild(this.index + 4, buffer.buffer[this.index + 3], dir, pos - this.context.start, side); + return index < 0 ? null : new BufferNode(this.context, this, index); + } + get firstChild() { return this.child(1, 0, 4 /* DontCare */); } + get lastChild() { return this.child(-1, 0, 4 /* DontCare */); } + childAfter(pos) { return this.child(1, pos, 2 /* After */); } + childBefore(pos) { return this.child(-1, pos, -2 /* Before */); } + enter(pos, side, mode = 0) { + if (mode & IterMode.ExcludeBuffers) + return null; + let { buffer } = this.context; + let index = buffer.findChild(this.index + 4, buffer.buffer[this.index + 3], side > 0 ? 1 : -1, pos - this.context.start, side); + return index < 0 ? null : new BufferNode(this.context, this, index); + } + get parent() { + return this._parent || this.context.parent.nextSignificantParent(); + } + externalSibling(dir) { + return this._parent ? null : this.context.parent.nextChild(this.context.index + dir, dir, 0, 4 /* DontCare */); + } + get nextSibling() { + let { buffer } = this.context; + let after = buffer.buffer[this.index + 3]; + if (after < (this._parent ? buffer.buffer[this._parent.index + 3] : buffer.buffer.length)) + return new BufferNode(this.context, this._parent, after); + return this.externalSibling(1); + } + get prevSibling() { + let { buffer } = this.context; + let parentStart = this._parent ? this._parent.index + 4 : 0; + if (this.index == parentStart) + return this.externalSibling(-1); + return new BufferNode(this.context, this._parent, buffer.findChild(parentStart, this.index, -1, 0, 4 /* DontCare */)); + } + cursor(mode = 0) { return new TreeCursor(this, mode); } + get tree() { return null; } + toTree() { + let children = [], positions = []; + let { buffer } = this.context; + let startI = this.index + 4, endI = buffer.buffer[this.index + 3]; + if (endI > startI) { + let from = buffer.buffer[this.index + 1], to = buffer.buffer[this.index + 2]; + children.push(buffer.slice(startI, endI, from, to)); + positions.push(0); + } + return new Tree(this.type, children, positions, this.to - this.from); + } + resolve(pos, side = 0) { + return resolveNode(this, pos, side, false); + } + resolveInner(pos, side = 0) { + return resolveNode(this, pos, side, true); + } + enterUnfinishedNodesBefore(pos) { return enterUnfinishedNodesBefore(this, pos); } + /// @internal + toString() { return this.context.buffer.childString(this.index); } + getChild(type, before = null, after = null) { + let r = getChildren(this, type, before, after); + return r.length ? r[0] : null; + } + getChildren(type, before = null, after = null) { + return getChildren(this, type, before, after); + } + get node() { return this; } + matchContext(context) { return matchNodeContext(this, context); } + } + /// A tree cursor object focuses on a given node in a syntax tree, and + /// allows you to move to adjacent nodes. + class TreeCursor { + /// @internal + constructor(node, + /// @internal + mode = 0) { + this.mode = mode; + /// @internal + this.buffer = null; + this.stack = []; + /// @internal + this.index = 0; + this.bufferNode = null; + if (node instanceof TreeNode) { + this.yieldNode(node); + } + else { + this._tree = node.context.parent; + this.buffer = node.context; + for (let n = node._parent; n; n = n._parent) + this.stack.unshift(n.index); + this.bufferNode = node; + this.yieldBuf(node.index); + } + } + /// Shorthand for `.type.name`. + get name() { return this.type.name; } + yieldNode(node) { + if (!node) + return false; + this._tree = node; + this.type = node.type; + this.from = node.from; + this.to = node.to; + return true; + } + yieldBuf(index, type) { + this.index = index; + let { start, buffer } = this.buffer; + this.type = type || buffer.set.types[buffer.buffer[index]]; + this.from = start + buffer.buffer[index + 1]; + this.to = start + buffer.buffer[index + 2]; + return true; + } + yield(node) { + if (!node) + return false; + if (node instanceof TreeNode) { + this.buffer = null; + return this.yieldNode(node); + } + this.buffer = node.context; + return this.yieldBuf(node.index, node.type); + } + /// @internal + toString() { + return this.buffer ? this.buffer.buffer.childString(this.index) : this._tree.toString(); + } + /// @internal + enterChild(dir, pos, side) { + if (!this.buffer) + return this.yield(this._tree.nextChild(dir < 0 ? this._tree._tree.children.length - 1 : 0, dir, pos, side, this.mode)); + let { buffer } = this.buffer; + let index = buffer.findChild(this.index + 4, buffer.buffer[this.index + 3], dir, pos - this.buffer.start, side); + if (index < 0) + return false; + this.stack.push(this.index); + return this.yieldBuf(index); + } + /// Move the cursor to this node's first child. When this returns + /// false, the node has no child, and the cursor has not been moved. + firstChild() { return this.enterChild(1, 0, 4 /* DontCare */); } + /// Move the cursor to this node's last child. + lastChild() { return this.enterChild(-1, 0, 4 /* DontCare */); } + /// Move the cursor to the first child that ends after `pos`. + childAfter(pos) { return this.enterChild(1, pos, 2 /* After */); } + /// Move to the last child that starts before `pos`. + childBefore(pos) { return this.enterChild(-1, pos, -2 /* Before */); } + /// Move the cursor to the child around `pos`. If side is -1 the + /// child may end at that position, when 1 it may start there. This + /// will also enter [overlaid](#common.MountedTree.overlay) + /// [mounted](#common.NodeProp^mounted) trees unless `overlays` is + /// set to false. + enter(pos, side, mode = this.mode) { + if (!this.buffer) + return this.yield(this._tree.enter(pos, side, mode)); + return mode & IterMode.ExcludeBuffers ? false : this.enterChild(1, pos, side); + } + /// Move to the node's parent node, if this isn't the top node. + parent() { + if (!this.buffer) + return this.yieldNode((this.mode & IterMode.IncludeAnonymous) ? this._tree._parent : this._tree.parent); + if (this.stack.length) + return this.yieldBuf(this.stack.pop()); + let parent = (this.mode & IterMode.IncludeAnonymous) ? this.buffer.parent : this.buffer.parent.nextSignificantParent(); + this.buffer = null; + return this.yieldNode(parent); + } + /// @internal + sibling(dir) { + if (!this.buffer) + return !this._tree._parent ? false + : this.yield(this._tree.index < 0 ? null + : this._tree._parent.nextChild(this._tree.index + dir, dir, 0, 4 /* DontCare */, this.mode)); + let { buffer } = this.buffer, d = this.stack.length - 1; + if (dir < 0) { + let parentStart = d < 0 ? 0 : this.stack[d] + 4; + if (this.index != parentStart) + return this.yieldBuf(buffer.findChild(parentStart, this.index, -1, 0, 4 /* DontCare */)); + } + else { + let after = buffer.buffer[this.index + 3]; + if (after < (d < 0 ? buffer.buffer.length : buffer.buffer[this.stack[d] + 3])) + return this.yieldBuf(after); + } + return d < 0 ? this.yield(this.buffer.parent.nextChild(this.buffer.index + dir, dir, 0, 4 /* DontCare */, this.mode)) : false; + } + /// Move to this node's next sibling, if any. + nextSibling() { return this.sibling(1); } + /// Move to this node's previous sibling, if any. + prevSibling() { return this.sibling(-1); } + atLastNode(dir) { + let index, parent, { buffer } = this; + if (buffer) { + if (dir > 0) { + if (this.index < buffer.buffer.buffer.length) + return false; + } + else { + for (let i = 0; i < this.index; i++) + if (buffer.buffer.buffer[i + 3] < this.index) + return false; + } + ({ index, parent } = buffer); + } + else { + ({ index, _parent: parent } = this._tree); + } + for (; parent; { index, _parent: parent } = parent) { + if (index > -1) + for (let i = index + dir, e = dir < 0 ? -1 : parent._tree.children.length; i != e; i += dir) { + let child = parent._tree.children[i]; + if ((this.mode & IterMode.IncludeAnonymous) || + child instanceof TreeBuffer || + !child.type.isAnonymous || + hasChild(child)) + return false; + } + } + return true; + } + move(dir, enter) { + if (enter && this.enterChild(dir, 0, 4 /* DontCare */)) + return true; + for (;;) { + if (this.sibling(dir)) + return true; + if (this.atLastNode(dir) || !this.parent()) + return false; + } + } + /// Move to the next node in a + /// [pre-order](https://en.wikipedia.org/wiki/Tree_traversal#Pre-order_(NLR)) + /// traversal, going from a node to its first child or, if the + /// current node is empty or `enter` is false, its next sibling or + /// the next sibling of the first parent node that has one. + next(enter = true) { return this.move(1, enter); } + /// Move to the next node in a last-to-first pre-order traveral. A + /// node is followed by its last child or, if it has none, its + /// previous sibling or the previous sibling of the first parent + /// node that has one. + prev(enter = true) { return this.move(-1, enter); } + /// Move the cursor to the innermost node that covers `pos`. If + /// `side` is -1, it will enter nodes that end at `pos`. If it is 1, + /// it will enter nodes that start at `pos`. + moveTo(pos, side = 0) { + // Move up to a node that actually holds the position, if possible + while (this.from == this.to || + (side < 1 ? this.from >= pos : this.from > pos) || + (side > -1 ? this.to <= pos : this.to < pos)) + if (!this.parent()) + break; + // Then scan down into child nodes as far as possible + while (this.enterChild(1, pos, side)) { } + return this; + } + /// Get a [syntax node](#common.SyntaxNode) at the cursor's current + /// position. + get node() { + if (!this.buffer) + return this._tree; + let cache = this.bufferNode, result = null, depth = 0; + if (cache && cache.context == this.buffer) { + scan: for (let index = this.index, d = this.stack.length; d >= 0;) { + for (let c = cache; c; c = c._parent) + if (c.index == index) { + if (index == this.index) + return c; + result = c; + depth = d + 1; + break scan; + } + index = this.stack[--d]; + } + } + for (let i = depth; i < this.stack.length; i++) + result = new BufferNode(this.buffer, result, this.stack[i]); + return this.bufferNode = new BufferNode(this.buffer, result, this.index); + } + /// Get the [tree](#common.Tree) that represents the current node, if + /// any. Will return null when the node is in a [tree + /// buffer](#common.TreeBuffer). + get tree() { + return this.buffer ? null : this._tree._tree; + } + /// Iterate over the current node and all its descendants, calling + /// `enter` when entering a node and `leave`, if given, when leaving + /// one. When `enter` returns `false`, any children of that node are + /// skipped, and `leave` isn't called for it. + iterate(enter, leave) { + for (let depth = 0;;) { + let mustLeave = false; + if (this.type.isAnonymous || enter(this) !== false) { + if (this.firstChild()) { + depth++; + continue; + } + if (!this.type.isAnonymous) + mustLeave = true; + } + for (;;) { + if (mustLeave && leave) + leave(this); + mustLeave = this.type.isAnonymous; + if (this.nextSibling()) + break; + if (!depth) + return; + this.parent(); + depth--; + mustLeave = true; + } + } + } + /// Test whether the current node matches a given context—a sequence + /// of direct parent node names. Empty strings in the context array + /// are treated as wildcards. + matchContext(context) { + if (!this.buffer) + return matchNodeContext(this.node, context); + let { buffer } = this.buffer, { types } = buffer.set; + for (let i = context.length - 1, d = this.stack.length - 1; i >= 0; d--) { + if (d < 0) + return matchNodeContext(this.node, context, i); + let type = types[buffer.buffer[this.stack[d]]]; + if (!type.isAnonymous) { + if (context[i] && context[i] != type.name) + return false; + i--; + } + } + return true; + } + } + function hasChild(tree) { + return tree.children.some(ch => ch instanceof TreeBuffer || !ch.type.isAnonymous || hasChild(ch)); + } + function buildTree(data) { + var _a; + let { buffer, nodeSet, maxBufferLength = DefaultBufferLength, reused = [], minRepeatType = nodeSet.types.length } = data; + let cursor = Array.isArray(buffer) ? new FlatBufferCursor(buffer, buffer.length) : buffer; + let types = nodeSet.types; + let contextHash = 0, lookAhead = 0; + function takeNode(parentStart, minPos, children, positions, inRepeat) { + let { id, start, end, size } = cursor; + let lookAheadAtStart = lookAhead; + while (size < 0) { + cursor.next(); + if (size == -1 /* Reuse */) { + let node = reused[id]; + children.push(node); + positions.push(start - parentStart); + return; + } + else if (size == -3 /* ContextChange */) { // Context change + contextHash = id; + return; + } + else if (size == -4 /* LookAhead */) { + lookAhead = id; + return; + } + else { + throw new RangeError(`Unrecognized record size: ${size}`); + } + } + let type = types[id], node, buffer; + let startPos = start - parentStart; + if (end - start <= maxBufferLength && (buffer = findBufferSize(cursor.pos - minPos, inRepeat))) { + // Small enough for a buffer, and no reused nodes inside + let data = new Uint16Array(buffer.size - buffer.skip); + let endPos = cursor.pos - buffer.size, index = data.length; + while (cursor.pos > endPos) + index = copyToBuffer(buffer.start, data, index); + node = new TreeBuffer(data, end - buffer.start, nodeSet); + startPos = buffer.start - parentStart; + } + else { // Make it a node + let endPos = cursor.pos - size; + cursor.next(); + let localChildren = [], localPositions = []; + let localInRepeat = id >= minRepeatType ? id : -1; + let lastGroup = 0, lastEnd = end; + while (cursor.pos > endPos) { + if (localInRepeat >= 0 && cursor.id == localInRepeat && cursor.size >= 0) { + if (cursor.end <= lastEnd - maxBufferLength) { + makeRepeatLeaf(localChildren, localPositions, start, lastGroup, cursor.end, lastEnd, localInRepeat, lookAheadAtStart); + lastGroup = localChildren.length; + lastEnd = cursor.end; + } + cursor.next(); + } + else { + takeNode(start, endPos, localChildren, localPositions, localInRepeat); + } + } + if (localInRepeat >= 0 && lastGroup > 0 && lastGroup < localChildren.length) + makeRepeatLeaf(localChildren, localPositions, start, lastGroup, start, lastEnd, localInRepeat, lookAheadAtStart); + localChildren.reverse(); + localPositions.reverse(); + if (localInRepeat > -1 && lastGroup > 0) { + let make = makeBalanced(type); + node = balanceRange(type, localChildren, localPositions, 0, localChildren.length, 0, end - start, make, make); + } + else { + node = makeTree(type, localChildren, localPositions, end - start, lookAheadAtStart - end); + } + } + children.push(node); + positions.push(startPos); + } + function makeBalanced(type) { + return (children, positions, length) => { + let lookAhead = 0, lastI = children.length - 1, last, lookAheadProp; + if (lastI >= 0 && (last = children[lastI]) instanceof Tree) { + if (!lastI && last.type == type && last.length == length) + return last; + if (lookAheadProp = last.prop(NodeProp.lookAhead)) + lookAhead = positions[lastI] + last.length + lookAheadProp; + } + return makeTree(type, children, positions, length, lookAhead); + }; + } + function makeRepeatLeaf(children, positions, base, i, from, to, type, lookAhead) { + let localChildren = [], localPositions = []; + while (children.length > i) { + localChildren.push(children.pop()); + localPositions.push(positions.pop() + base - from); + } + children.push(makeTree(nodeSet.types[type], localChildren, localPositions, to - from, lookAhead - to)); + positions.push(from - base); + } + function makeTree(type, children, positions, length, lookAhead = 0, props) { + if (contextHash) { + let pair = [NodeProp.contextHash, contextHash]; + props = props ? [pair].concat(props) : [pair]; + } + if (lookAhead > 25) { + let pair = [NodeProp.lookAhead, lookAhead]; + props = props ? [pair].concat(props) : [pair]; + } + return new Tree(type, children, positions, length, props); + } + function findBufferSize(maxSize, inRepeat) { + // Scan through the buffer to find previous siblings that fit + // together in a TreeBuffer, and don't contain any reused nodes + // (which can't be stored in a buffer). + // If `inRepeat` is > -1, ignore node boundaries of that type for + // nesting, but make sure the end falls either at the start + // (`maxSize`) or before such a node. + let fork = cursor.fork(); + let size = 0, start = 0, skip = 0, minStart = fork.end - maxBufferLength; + let result = { size: 0, start: 0, skip: 0 }; + scan: for (let minPos = fork.pos - maxSize; fork.pos > minPos;) { + let nodeSize = fork.size; + // Pretend nested repeat nodes of the same type don't exist + if (fork.id == inRepeat && nodeSize >= 0) { + // Except that we store the current state as a valid return + // value. + result.size = size; + result.start = start; + result.skip = skip; + skip += 4; + size += 4; + fork.next(); + continue; + } + let startPos = fork.pos - nodeSize; + if (nodeSize < 0 || startPos < minPos || fork.start < minStart) + break; + let localSkipped = fork.id >= minRepeatType ? 4 : 0; + let nodeStart = fork.start; + fork.next(); + while (fork.pos > startPos) { + if (fork.size < 0) { + if (fork.size == -3 /* ContextChange */) + localSkipped += 4; + else + break scan; + } + else if (fork.id >= minRepeatType) { + localSkipped += 4; + } + fork.next(); + } + start = nodeStart; + size += nodeSize; + skip += localSkipped; + } + if (inRepeat < 0 || size == maxSize) { + result.size = size; + result.start = start; + result.skip = skip; + } + return result.size > 4 ? result : undefined; + } + function copyToBuffer(bufferStart, buffer, index) { + let { id, start, end, size } = cursor; + cursor.next(); + if (size >= 0 && id < minRepeatType) { + let startIndex = index; + if (size > 4) { + let endPos = cursor.pos - (size - 4); + while (cursor.pos > endPos) + index = copyToBuffer(bufferStart, buffer, index); + } + buffer[--index] = startIndex; + buffer[--index] = end - bufferStart; + buffer[--index] = start - bufferStart; + buffer[--index] = id; + } + else if (size == -3 /* ContextChange */) { + contextHash = id; + } + else if (size == -4 /* LookAhead */) { + lookAhead = id; + } + return index; + } + let children = [], positions = []; + while (cursor.pos > 0) + takeNode(data.start || 0, data.bufferStart || 0, children, positions, -1); + let length = (_a = data.length) !== null && _a !== void 0 ? _a : (children.length ? positions[0] + children[0].length : 0); + return new Tree(types[data.topID], children.reverse(), positions.reverse(), length); + } + const nodeSizeCache = new WeakMap; + function nodeSize(balanceType, node) { + if (!balanceType.isAnonymous || node instanceof TreeBuffer || node.type != balanceType) + return 1; + let size = nodeSizeCache.get(node); + if (size == null) { + size = 1; + for (let child of node.children) { + if (child.type != balanceType || !(child instanceof Tree)) { + size = 1; + break; + } + size += nodeSize(balanceType, child); + } + nodeSizeCache.set(node, size); + } + return size; + } + function balanceRange( + // The type the balanced tree's inner nodes. + balanceType, + // The direct children and their positions + children, positions, + // The index range in children/positions to use + from, to, + // The start position of the nodes, relative to their parent. + start, + // Length of the outer node + length, + // Function to build the top node of the balanced tree + mkTop, + // Function to build internal nodes for the balanced tree + mkTree) { + let total = 0; + for (let i = from; i < to; i++) + total += nodeSize(balanceType, children[i]); + let maxChild = Math.ceil((total * 1.5) / 8 /* BranchFactor */); + let localChildren = [], localPositions = []; + function divide(children, positions, from, to, offset) { + for (let i = from; i < to;) { + let groupFrom = i, groupStart = positions[i], groupSize = nodeSize(balanceType, children[i]); + i++; + for (; i < to; i++) { + let nextSize = nodeSize(balanceType, children[i]); + if (groupSize + nextSize >= maxChild) + break; + groupSize += nextSize; + } + if (i == groupFrom + 1) { + if (groupSize > maxChild) { + let only = children[groupFrom]; // Only trees can have a size > 1 + divide(only.children, only.positions, 0, only.children.length, positions[groupFrom] + offset); + continue; + } + localChildren.push(children[groupFrom]); + } + else { + let length = positions[i - 1] + children[i - 1].length - groupStart; + localChildren.push(balanceRange(balanceType, children, positions, groupFrom, i, groupStart, length, null, mkTree)); + } + localPositions.push(groupStart + offset - start); + } + } + divide(children, positions, from, to, 0); + return (mkTop || mkTree)(localChildren, localPositions, length); + } + + /// Tree fragments are used during [incremental + /// parsing](#common.Parser.startParse) to track parts of old trees + /// that can be reused in a new parse. An array of fragments is used + /// to track regions of an old tree whose nodes might be reused in new + /// parses. Use the static + /// [`applyChanges`](#common.TreeFragment^applyChanges) method to + /// update fragments for document changes. + class TreeFragment { + /// Construct a tree fragment. You'll usually want to use + /// [`addTree`](#common.TreeFragment^addTree) and + /// [`applyChanges`](#common.TreeFragment^applyChanges) instead of + /// calling this directly. + constructor( + /// The start of the unchanged range pointed to by this fragment. + /// This refers to an offset in the _updated_ document (as opposed + /// to the original tree). + from, + /// The end of the unchanged range. + to, + /// The tree that this fragment is based on. + tree, + /// The offset between the fragment's tree and the document that + /// this fragment can be used against. Add this when going from + /// document to tree positions, subtract it to go from tree to + /// document positions. + offset, openStart = false, openEnd = false) { + this.from = from; + this.to = to; + this.tree = tree; + this.offset = offset; + this.open = (openStart ? 1 /* Start */ : 0) | (openEnd ? 2 /* End */ : 0); + } + /// Whether the start of the fragment represents the start of a + /// parse, or the end of a change. (In the second case, it may not + /// be safe to reuse some nodes at the start, depending on the + /// parsing algorithm.) + get openStart() { return (this.open & 1 /* Start */) > 0; } + /// Whether the end of the fragment represents the end of a + /// full-document parse, or the start of a change. + get openEnd() { return (this.open & 2 /* End */) > 0; } + /// Create a set of fragments from a freshly parsed tree, or update + /// an existing set of fragments by replacing the ones that overlap + /// with a tree with content from the new tree. When `partial` is + /// true, the parse is treated as incomplete, and the resulting + /// fragment has [`openEnd`](#common.TreeFragment.openEnd) set to + /// true. + static addTree(tree, fragments = [], partial = false) { + let result = [new TreeFragment(0, tree.length, tree, 0, false, partial)]; + for (let f of fragments) + if (f.to > tree.length) + result.push(f); + return result; + } + /// Apply a set of edits to an array of fragments, removing or + /// splitting fragments as necessary to remove edited ranges, and + /// adjusting offsets for fragments that moved. + static applyChanges(fragments, changes, minGap = 128) { + if (!changes.length) + return fragments; + let result = []; + let fI = 1, nextF = fragments.length ? fragments[0] : null; + for (let cI = 0, pos = 0, off = 0;; cI++) { + let nextC = cI < changes.length ? changes[cI] : null; + let nextPos = nextC ? nextC.fromA : 1e9; + if (nextPos - pos >= minGap) + while (nextF && nextF.from < nextPos) { + let cut = nextF; + if (pos >= cut.from || nextPos <= cut.to || off) { + let fFrom = Math.max(cut.from, pos) - off, fTo = Math.min(cut.to, nextPos) - off; + cut = fFrom >= fTo ? null : new TreeFragment(fFrom, fTo, cut.tree, cut.offset + off, cI > 0, !!nextC); + } + if (cut) + result.push(cut); + if (nextF.to > nextPos) + break; + nextF = fI < fragments.length ? fragments[fI++] : null; + } + if (!nextC) + break; + pos = nextC.toA; + off = nextC.toA - nextC.toB; + } + return result; + } + } + /// A superclass that parsers should extend. + class Parser { + /// Start a parse, returning a [partial parse](#common.PartialParse) + /// object. [`fragments`](#common.TreeFragment) can be passed in to + /// make the parse incremental. + /// + /// By default, the entire input is parsed. You can pass `ranges`, + /// which should be a sorted array of non-empty, non-overlapping + /// ranges, to parse only those ranges. The tree returned in that + /// case will start at `ranges[0].from`. + startParse(input, fragments, ranges) { + if (typeof input == "string") + input = new StringInput(input); + ranges = !ranges ? [new Range(0, input.length)] : ranges.length ? ranges.map(r => new Range(r.from, r.to)) : [new Range(0, 0)]; + return this.createParse(input, fragments || [], ranges); + } + /// Run a full parse, returning the resulting tree. + parse(input, fragments, ranges) { + let parse = this.startParse(input, fragments, ranges); + for (;;) { + let done = parse.advance(); + if (done) + return done; + } + } + } + class StringInput { + constructor(string) { + this.string = string; + } + get length() { return this.string.length; } + chunk(from) { return this.string.slice(from); } + get lineChunks() { return false; } + read(from, to) { return this.string.slice(from, to); } + } + new NodeProp({ perNode: true }); + + let nextTagID = 0; + /// Highlighting tags are markers that denote a highlighting category. + /// They are [associated](#highlight.styleTags) with parts of a syntax + /// tree by a language mode, and then mapped to an actual CSS style by + /// a [highlighter](#highlight.Highlighter). + /// + /// Because syntax tree node types and highlight styles have to be + /// able to talk the same language, CodeMirror uses a mostly _closed_ + /// [vocabulary](#highlight.tags) of syntax tags (as opposed to + /// traditional open string-based systems, which make it hard for + /// highlighting themes to cover all the tokens produced by the + /// various languages). + /// + /// It _is_ possible to [define](#highlight.Tag^define) your own + /// highlighting tags for system-internal use (where you control both + /// the language package and the highlighter), but such tags will not + /// be picked up by regular highlighters (though you can derive them + /// from standard tags to allow highlighters to fall back to those). + class Tag { + /// @internal + constructor( + /// The set of this tag and all its parent tags, starting with + /// this one itself and sorted in order of decreasing specificity. + set, + /// The base unmodified tag that this one is based on, if it's + /// modified @internal + base, + /// The modifiers applied to this.base @internal + modified) { + this.set = set; + this.base = base; + this.modified = modified; + /// @internal + this.id = nextTagID++; + } + /// Define a new tag. If `parent` is given, the tag is treated as a + /// sub-tag of that parent, and + /// [highlighters](#highlight.tagHighlighter) that don't mention + /// this tag will try to fall back to the parent tag (or grandparent + /// tag, etc). + static define(parent) { + if (parent === null || parent === void 0 ? void 0 : parent.base) + throw new Error("Can not derive from a modified tag"); + let tag = new Tag([], null, []); + tag.set.push(tag); + if (parent) + for (let t of parent.set) + tag.set.push(t); + return tag; + } + /// Define a tag _modifier_, which is a function that, given a tag, + /// will return a tag that is a subtag of the original. Applying the + /// same modifier to a twice tag will return the same value (`m1(t1) + /// == m1(t1)`) and applying multiple modifiers will, regardless or + /// order, produce the same tag (`m1(m2(t1)) == m2(m1(t1))`). + /// + /// When multiple modifiers are applied to a given base tag, each + /// smaller set of modifiers is registered as a parent, so that for + /// example `m1(m2(m3(t1)))` is a subtype of `m1(m2(t1))`, + /// `m1(m3(t1)`, and so on. + static defineModifier() { + let mod = new Modifier; + return (tag) => { + if (tag.modified.indexOf(mod) > -1) + return tag; + return Modifier.get(tag.base || tag, tag.modified.concat(mod).sort((a, b) => a.id - b.id)); + }; + } + } + let nextModifierID = 0; + class Modifier { + constructor() { + this.instances = []; + this.id = nextModifierID++; + } + static get(base, mods) { + if (!mods.length) + return base; + let exists = mods[0].instances.find(t => t.base == base && sameArray(mods, t.modified)); + if (exists) + return exists; + let set = [], tag = new Tag(set, base, mods); + for (let m of mods) + m.instances.push(tag); + let configs = permute(mods); + for (let parent of base.set) + for (let config of configs) + set.push(Modifier.get(parent, config)); + return tag; + } + } + function sameArray(a, b) { + return a.length == b.length && a.every((x, i) => x == b[i]); + } + function permute(array) { + let result = [array]; + for (let i = 0; i < array.length; i++) { + for (let a of permute(array.slice(0, i).concat(array.slice(i + 1)))) + result.push(a); + } + return result; + } + /// This function is used to add a set of tags to a language syntax + /// via [`NodeSet.extend`](#common.NodeSet.extend) or + /// [`LRParser.configure`](#lr.LRParser.configure). + /// + /// The argument object maps node selectors to [highlighting + /// tags](#highlight.Tag) or arrays of tags. + /// + /// Node selectors may hold one or more (space-separated) node paths. + /// Such a path can be a [node name](#common.NodeType.name), or + /// multiple node names (or `*` wildcards) separated by slash + /// characters, as in `"Block/Declaration/VariableName"`. Such a path + /// matches the final node but only if its direct parent nodes are the + /// other nodes mentioned. A `*` in such a path matches any parent, + /// but only a single level—wildcards that match multiple parents + /// aren't supported, both for efficiency reasons and because Lezer + /// trees make it rather hard to reason about what they would match.) + /// + /// A path can be ended with `/...` to indicate that the tag assigned + /// to the node should also apply to all child nodes, even if they + /// match their own style (by default, only the innermost style is + /// used). + /// + /// When a path ends in `!`, as in `Attribute!`, no further matching + /// happens for the node's child nodes, and the entire node gets the + /// given style. + /// + /// In this notation, node names that contain `/`, `!`, `*`, or `...` + /// must be quoted as JSON strings. + /// + /// For example: + /// + /// ```javascript + /// parser.withProps( + /// styleTags({ + /// // Style Number and BigNumber nodes + /// "Number BigNumber": tags.number, + /// // Style Escape nodes whose parent is String + /// "String/Escape": tags.escape, + /// // Style anything inside Attributes nodes + /// "Attributes!": tags.meta, + /// // Add a style to all content inside Italic nodes + /// "Italic/...": tags.emphasis, + /// // Style InvalidString nodes as both `string` and `invalid` + /// "InvalidString": [tags.string, tags.invalid], + /// // Style the node named "/" as punctuation + /// '"/"': tags.punctuation + /// }) + /// ) + /// ``` + function styleTags(spec) { + let byName = Object.create(null); + for (let prop in spec) { + let tags = spec[prop]; + if (!Array.isArray(tags)) + tags = [tags]; + for (let part of prop.split(" ")) + if (part) { + let pieces = [], mode = 2 /* Normal */, rest = part; + for (let pos = 0;;) { + if (rest == "..." && pos > 0 && pos + 3 == part.length) { + mode = 1 /* Inherit */; + break; + } + let m = /^"(?:[^"\\]|\\.)*?"|[^\/!]+/.exec(rest); + if (!m) + throw new RangeError("Invalid path: " + part); + pieces.push(m[0] == "*" ? "" : m[0][0] == '"' ? JSON.parse(m[0]) : m[0]); + pos += m[0].length; + if (pos == part.length) + break; + let next = part[pos++]; + if (pos == part.length && next == "!") { + mode = 0 /* Opaque */; + break; + } + if (next != "/") + throw new RangeError("Invalid path: " + part); + rest = part.slice(pos); + } + let last = pieces.length - 1, inner = pieces[last]; + if (!inner) + throw new RangeError("Invalid path: " + part); + let rule = new Rule(tags, mode, last > 0 ? pieces.slice(0, last) : null); + byName[inner] = rule.sort(byName[inner]); + } + } + return ruleNodeProp.add(byName); + } + const ruleNodeProp = new NodeProp(); + class Rule { + constructor(tags, mode, context, next) { + this.tags = tags; + this.mode = mode; + this.context = context; + this.next = next; + } + get opaque() { return this.mode == 0 /* Opaque */; } + get inherit() { return this.mode == 1 /* Inherit */; } + sort(other) { + if (!other || other.depth < this.depth) { + this.next = other; + return this; + } + other.next = this.sort(other.next); + return other; + } + get depth() { return this.context ? this.context.length : 0; } + } + Rule.empty = new Rule([], 2 /* Normal */, null); + /// Define a [highlighter](#highlight.Highlighter) from an array of + /// tag/class pairs. Classes associated with more specific tags will + /// take precedence. + function tagHighlighter(tags, options) { + let map = Object.create(null); + for (let style of tags) { + if (!Array.isArray(style.tag)) + map[style.tag.id] = style.class; + else + for (let tag of style.tag) + map[tag.id] = style.class; + } + let { scope, all = null } = options || {}; + return { + style: (tags) => { + let cls = all; + for (let tag of tags) { + for (let sub of tag.set) { + let tagClass = map[sub.id]; + if (tagClass) { + cls = cls ? cls + " " + tagClass : tagClass; + break; + } + } + } + return cls; + }, + scope + }; + } + function highlightTags(highlighters, tags) { + let result = null; + for (let highlighter of highlighters) { + let value = highlighter.style(tags); + if (value) + result = result ? result + " " + value : value; + } + return result; + } + /// Highlight the given [tree](#common.Tree) with the given + /// [highlighter](#highlight.Highlighter). + function highlightTree(tree, highlighter, + /// Assign styling to a region of the text. Will be called, in order + /// of position, for any ranges where more than zero classes apply. + /// `classes` is a space separated string of CSS classes. + putStyle, + /// The start of the range to highlight. + from = 0, + /// The end of the range. + to = tree.length) { + let builder = new HighlightBuilder(from, Array.isArray(highlighter) ? highlighter : [highlighter], putStyle); + builder.highlightRange(tree.cursor(), from, to, "", builder.highlighters); + builder.flush(to); + } + class HighlightBuilder { + constructor(at, highlighters, span) { + this.at = at; + this.highlighters = highlighters; + this.span = span; + this.class = ""; + } + startSpan(at, cls) { + if (cls != this.class) { + this.flush(at); + if (at > this.at) + this.at = at; + this.class = cls; + } + } + flush(to) { + if (to > this.at && this.class) + this.span(this.at, to, this.class); + } + highlightRange(cursor, from, to, inheritedClass, highlighters) { + let { type, from: start, to: end } = cursor; + if (start >= to || end <= from) + return; + if (type.isTop) + highlighters = this.highlighters.filter(h => !h.scope || h.scope(type)); + let cls = inheritedClass; + let rule = getStyleTags(cursor) || Rule.empty; + let tagCls = highlightTags(highlighters, rule.tags); + if (tagCls) { + if (cls) + cls += " "; + cls += tagCls; + if (rule.mode == 1 /* Inherit */) + inheritedClass += (inheritedClass ? " " : "") + tagCls; + } + this.startSpan(cursor.from, cls); + if (rule.opaque) + return; + let mounted = cursor.tree && cursor.tree.prop(NodeProp.mounted); + if (mounted && mounted.overlay) { + let inner = cursor.node.enter(mounted.overlay[0].from + start, 1); + let innerHighlighters = this.highlighters.filter(h => !h.scope || h.scope(mounted.tree.type)); + let hasChild = cursor.firstChild(); + for (let i = 0, pos = start;; i++) { + let next = i < mounted.overlay.length ? mounted.overlay[i] : null; + let nextPos = next ? next.from + start : end; + let rangeFrom = Math.max(from, pos), rangeTo = Math.min(to, nextPos); + if (rangeFrom < rangeTo && hasChild) { + while (cursor.from < rangeTo) { + this.highlightRange(cursor, rangeFrom, rangeTo, inheritedClass, highlighters); + this.startSpan(Math.min(to, cursor.to), cls); + if (cursor.to >= nextPos || !cursor.nextSibling()) + break; + } + } + if (!next || nextPos > to) + break; + pos = next.to + start; + if (pos > from) { + this.highlightRange(inner.cursor(), Math.max(from, next.from + start), Math.min(to, pos), inheritedClass, innerHighlighters); + this.startSpan(pos, cls); + } + } + if (hasChild) + cursor.parent(); + } + else if (cursor.firstChild()) { + do { + if (cursor.to <= from) + continue; + if (cursor.from >= to) + break; + this.highlightRange(cursor, from, to, inheritedClass, highlighters); + this.startSpan(Math.min(to, cursor.to), cls); + } while (cursor.nextSibling()); + cursor.parent(); + } + } + } + /// Match a syntax node's [highlight rules](#highlight.styleTags). If + /// there's a match, return its set of tags, and whether it is + /// opaque (uses a `!`) or applies to all child nodes (`/...`). + function getStyleTags(node) { + let rule = node.type.prop(ruleNodeProp); + while (rule && rule.context && !node.matchContext(rule.context)) + rule = rule.next; + return rule || null; + } + const t = Tag.define; + const comment = t(), name = t(), typeName = t(name), propertyName = t(name), literal = t(), string = t(literal), number = t(literal), content = t(), heading = t(content), keyword = t(), operator = t(), punctuation = t(), bracket = t(punctuation), meta = t(); + /// The default set of highlighting [tags](#highlight.Tag). + /// + /// This collection is heavily biased towards programming languages, + /// and necessarily incomplete. A full ontology of syntactic + /// constructs would fill a stack of books, and be impractical to + /// write themes for. So try to make do with this set. If all else + /// fails, [open an + /// issue](https://github.com/codemirror/codemirror.next) to propose a + /// new tag, or [define](#highlight.Tag^define) a local custom tag for + /// your use case. + /// + /// Note that it is not obligatory to always attach the most specific + /// tag possible to an element—if your grammar can't easily + /// distinguish a certain type of element (such as a local variable), + /// it is okay to style it as its more general variant (a variable). + /// + /// For tags that extend some parent tag, the documentation links to + /// the parent. + const tags = { + /// A comment. + comment, + /// A line [comment](#highlight.tags.comment). + lineComment: t(comment), + /// A block [comment](#highlight.tags.comment). + blockComment: t(comment), + /// A documentation [comment](#highlight.tags.comment). + docComment: t(comment), + /// Any kind of identifier. + name, + /// The [name](#highlight.tags.name) of a variable. + variableName: t(name), + /// A type [name](#highlight.tags.name). + typeName: typeName, + /// A tag name (subtag of [`typeName`](#highlight.tags.typeName)). + tagName: t(typeName), + /// A property or field [name](#highlight.tags.name). + propertyName: propertyName, + /// An attribute name (subtag of [`propertyName`](#highlight.tags.propertyName)). + attributeName: t(propertyName), + /// The [name](#highlight.tags.name) of a class. + className: t(name), + /// A label [name](#highlight.tags.name). + labelName: t(name), + /// A namespace [name](#highlight.tags.name). + namespace: t(name), + /// The [name](#highlight.tags.name) of a macro. + macroName: t(name), + /// A literal value. + literal, + /// A string [literal](#highlight.tags.literal). + string, + /// A documentation [string](#highlight.tags.string). + docString: t(string), + /// A character literal (subtag of [string](#highlight.tags.string)). + character: t(string), + /// An attribute value (subtag of [string](#highlight.tags.string)). + attributeValue: t(string), + /// A number [literal](#highlight.tags.literal). + number, + /// An integer [number](#highlight.tags.number) literal. + integer: t(number), + /// A floating-point [number](#highlight.tags.number) literal. + float: t(number), + /// A boolean [literal](#highlight.tags.literal). + bool: t(literal), + /// Regular expression [literal](#highlight.tags.literal). + regexp: t(literal), + /// An escape [literal](#highlight.tags.literal), for example a + /// backslash escape in a string. + escape: t(literal), + /// A color [literal](#highlight.tags.literal). + color: t(literal), + /// A URL [literal](#highlight.tags.literal). + url: t(literal), + /// A language keyword. + keyword, + /// The [keyword](#highlight.tags.keyword) for the self or this + /// object. + self: t(keyword), + /// The [keyword](#highlight.tags.keyword) for null. + null: t(keyword), + /// A [keyword](#highlight.tags.keyword) denoting some atomic value. + atom: t(keyword), + /// A [keyword](#highlight.tags.keyword) that represents a unit. + unit: t(keyword), + /// A modifier [keyword](#highlight.tags.keyword). + modifier: t(keyword), + /// A [keyword](#highlight.tags.keyword) that acts as an operator. + operatorKeyword: t(keyword), + /// A control-flow related [keyword](#highlight.tags.keyword). + controlKeyword: t(keyword), + /// A [keyword](#highlight.tags.keyword) that defines something. + definitionKeyword: t(keyword), + /// A [keyword](#highlight.tags.keyword) related to defining or + /// interfacing with modules. + moduleKeyword: t(keyword), + /// An operator. + operator, + /// An [operator](#highlight.tags.operator) that dereferences something. + derefOperator: t(operator), + /// Arithmetic-related [operator](#highlight.tags.operator). + arithmeticOperator: t(operator), + /// Logical [operator](#highlight.tags.operator). + logicOperator: t(operator), + /// Bit [operator](#highlight.tags.operator). + bitwiseOperator: t(operator), + /// Comparison [operator](#highlight.tags.operator). + compareOperator: t(operator), + /// [Operator](#highlight.tags.operator) that updates its operand. + updateOperator: t(operator), + /// [Operator](#highlight.tags.operator) that defines something. + definitionOperator: t(operator), + /// Type-related [operator](#highlight.tags.operator). + typeOperator: t(operator), + /// Control-flow [operator](#highlight.tags.operator). + controlOperator: t(operator), + /// Program or markup punctuation. + punctuation, + /// [Punctuation](#highlight.tags.punctuation) that separates + /// things. + separator: t(punctuation), + /// Bracket-style [punctuation](#highlight.tags.punctuation). + bracket, + /// Angle [brackets](#highlight.tags.bracket) (usually `<` and `>` + /// tokens). + angleBracket: t(bracket), + /// Square [brackets](#highlight.tags.bracket) (usually `[` and `]` + /// tokens). + squareBracket: t(bracket), + /// Parentheses (usually `(` and `)` tokens). Subtag of + /// [bracket](#highlight.tags.bracket). + paren: t(bracket), + /// Braces (usually `{` and `}` tokens). Subtag of + /// [bracket](#highlight.tags.bracket). + brace: t(bracket), + /// Content, for example plain text in XML or markup documents. + content, + /// [Content](#highlight.tags.content) that represents a heading. + heading, + /// A level 1 [heading](#highlight.tags.heading). + heading1: t(heading), + /// A level 2 [heading](#highlight.tags.heading). + heading2: t(heading), + /// A level 3 [heading](#highlight.tags.heading). + heading3: t(heading), + /// A level 4 [heading](#highlight.tags.heading). + heading4: t(heading), + /// A level 5 [heading](#highlight.tags.heading). + heading5: t(heading), + /// A level 6 [heading](#highlight.tags.heading). + heading6: t(heading), + /// A prose separator (such as a horizontal rule). + contentSeparator: t(content), + /// [Content](#highlight.tags.content) that represents a list. + list: t(content), + /// [Content](#highlight.tags.content) that represents a quote. + quote: t(content), + /// [Content](#highlight.tags.content) that is emphasized. + emphasis: t(content), + /// [Content](#highlight.tags.content) that is styled strong. + strong: t(content), + /// [Content](#highlight.tags.content) that is part of a link. + link: t(content), + /// [Content](#highlight.tags.content) that is styled as code or + /// monospace. + monospace: t(content), + /// [Content](#highlight.tags.content) that has a strike-through + /// style. + strikethrough: t(content), + /// Inserted text in a change-tracking format. + inserted: t(), + /// Deleted text. + deleted: t(), + /// Changed text. + changed: t(), + /// An invalid or unsyntactic element. + invalid: t(), + /// Metadata or meta-instruction. + meta, + /// [Metadata](#highlight.tags.meta) that applies to the entire + /// document. + documentMeta: t(meta), + /// [Metadata](#highlight.tags.meta) that annotates or adds + /// attributes to a given syntactic element. + annotation: t(meta), + /// Processing instruction or preprocessor directive. Subtag of + /// [meta](#highlight.tags.meta). + processingInstruction: t(meta), + /// [Modifier](#highlight.Tag^defineModifier) that indicates that a + /// given element is being defined. Expected to be used with the + /// various [name](#highlight.tags.name) tags. + definition: Tag.defineModifier(), + /// [Modifier](#highlight.Tag^defineModifier) that indicates that + /// something is constant. Mostly expected to be used with + /// [variable names](#highlight.tags.variableName). + constant: Tag.defineModifier(), + /// [Modifier](#highlight.Tag^defineModifier) used to indicate that + /// a [variable](#highlight.tags.variableName) or [property + /// name](#highlight.tags.propertyName) is being called or defined + /// as a function. + function: Tag.defineModifier(), + /// [Modifier](#highlight.Tag^defineModifier) that can be applied to + /// [names](#highlight.tags.name) to indicate that they belong to + /// the language's standard environment. + standard: Tag.defineModifier(), + /// [Modifier](#highlight.Tag^defineModifier) that indicates a given + /// [names](#highlight.tags.name) is local to some scope. + local: Tag.defineModifier(), + /// A generic variant [modifier](#highlight.Tag^defineModifier) that + /// can be used to tag language-specific alternative variants of + /// some common tag. It is recommended for themes to define special + /// forms of at least the [string](#highlight.tags.string) and + /// [variable name](#highlight.tags.variableName) tags, since those + /// come up a lot. + special: Tag.defineModifier() + }; + /// This is a highlighter that adds stable, predictable classes to + /// tokens, for styling with external CSS. + /// + /// The following tags are mapped to their name prefixed with `"tok-"` + /// (for example `"tok-comment"`): + /// + /// * [`link`](#highlight.tags.link) + /// * [`heading`](#highlight.tags.heading) + /// * [`emphasis`](#highlight.tags.emphasis) + /// * [`strong`](#highlight.tags.strong) + /// * [`keyword`](#highlight.tags.keyword) + /// * [`atom`](#highlight.tags.atom) + /// * [`bool`](#highlight.tags.bool) + /// * [`url`](#highlight.tags.url) + /// * [`labelName`](#highlight.tags.labelName) + /// * [`inserted`](#highlight.tags.inserted) + /// * [`deleted`](#highlight.tags.deleted) + /// * [`literal`](#highlight.tags.literal) + /// * [`string`](#highlight.tags.string) + /// * [`number`](#highlight.tags.number) + /// * [`variableName`](#highlight.tags.variableName) + /// * [`typeName`](#highlight.tags.typeName) + /// * [`namespace`](#highlight.tags.namespace) + /// * [`className`](#highlight.tags.className) + /// * [`macroName`](#highlight.tags.macroName) + /// * [`propertyName`](#highlight.tags.propertyName) + /// * [`operator`](#highlight.tags.operator) + /// * [`comment`](#highlight.tags.comment) + /// * [`meta`](#highlight.tags.meta) + /// * [`punctuation`](#highlight.tags.punctuation) + /// * [`invalid`](#highlight.tags.invalid) + /// + /// In addition, these mappings are provided: + /// + /// * [`regexp`](#highlight.tags.regexp), + /// [`escape`](#highlight.tags.escape), and + /// [`special`](#highlight.tags.special)[`(string)`](#highlight.tags.string) + /// are mapped to `"tok-string2"` + /// * [`special`](#highlight.tags.special)[`(variableName)`](#highlight.tags.variableName) + /// to `"tok-variableName2"` + /// * [`local`](#highlight.tags.local)[`(variableName)`](#highlight.tags.variableName) + /// to `"tok-variableName tok-local"` + /// * [`definition`](#highlight.tags.definition)[`(variableName)`](#highlight.tags.variableName) + /// to `"tok-variableName tok-definition"` + /// * [`definition`](#highlight.tags.definition)[`(propertyName)`](#highlight.tags.propertyName) + /// to `"tok-propertyName tok-definition"` + tagHighlighter([ + { tag: tags.link, class: "tok-link" }, + { tag: tags.heading, class: "tok-heading" }, + { tag: tags.emphasis, class: "tok-emphasis" }, + { tag: tags.strong, class: "tok-strong" }, + { tag: tags.keyword, class: "tok-keyword" }, + { tag: tags.atom, class: "tok-atom" }, + { tag: tags.bool, class: "tok-bool" }, + { tag: tags.url, class: "tok-url" }, + { tag: tags.labelName, class: "tok-labelName" }, + { tag: tags.inserted, class: "tok-inserted" }, + { tag: tags.deleted, class: "tok-deleted" }, + { tag: tags.literal, class: "tok-literal" }, + { tag: tags.string, class: "tok-string" }, + { tag: tags.number, class: "tok-number" }, + { tag: [tags.regexp, tags.escape, tags.special(tags.string)], class: "tok-string2" }, + { tag: tags.variableName, class: "tok-variableName" }, + { tag: tags.local(tags.variableName), class: "tok-variableName tok-local" }, + { tag: tags.definition(tags.variableName), class: "tok-variableName tok-definition" }, + { tag: tags.special(tags.variableName), class: "tok-variableName2" }, + { tag: tags.definition(tags.propertyName), class: "tok-propertyName tok-definition" }, + { tag: tags.typeName, class: "tok-typeName" }, + { tag: tags.namespace, class: "tok-namespace" }, + { tag: tags.className, class: "tok-className" }, + { tag: tags.macroName, class: "tok-macroName" }, + { tag: tags.propertyName, class: "tok-propertyName" }, + { tag: tags.operator, class: "tok-operator" }, + { tag: tags.comment, class: "tok-comment" }, + { tag: tags.meta, class: "tok-meta" }, + { tag: tags.invalid, class: "tok-invalid" }, + { tag: tags.punctuation, class: "tok-punctuation" } + ]); + + var _a; + /** + Node prop stored in a parser's top syntax node to provide the + facet that stores language-specific data for that language. + */ + const languageDataProp = /*@__PURE__*/new NodeProp(); + /** + Helper function to define a facet (to be added to the top syntax + node(s) for a language via + [`languageDataProp`](https://codemirror.net/6/docs/ref/#language.languageDataProp)), that will be + used to associate language data with the language. You + probably only need this when subclassing + [`Language`](https://codemirror.net/6/docs/ref/#language.Language). + */ + function defineLanguageFacet(baseData) { + return Facet.define({ + combine: baseData ? values => values.concat(baseData) : undefined + }); + } + /** + A language object manages parsing and per-language + [metadata](https://codemirror.net/6/docs/ref/#state.EditorState.languageDataAt). Parse data is + managed as a [Lezer](https://lezer.codemirror.net) tree. The class + can be used directly, via the [`LRLanguage`](https://codemirror.net/6/docs/ref/#language.LRLanguage) + subclass for [Lezer](https://lezer.codemirror.net/) LR parsers, or + via the [`StreamLanguage`](https://codemirror.net/6/docs/ref/#language.StreamLanguage) subclass + for stream parsers. + */ + class Language { + /** + Construct a language object. If you need to invoke this + directly, first define a data facet with + [`defineLanguageFacet`](https://codemirror.net/6/docs/ref/#language.defineLanguageFacet), and then + configure your parser to [attach](https://codemirror.net/6/docs/ref/#language.languageDataProp) it + to the language's outer syntax node. + */ + constructor( + /** + The [language data](https://codemirror.net/6/docs/ref/#state.EditorState.languageDataAt) facet + used for this language. + */ + data, parser, extraExtensions = []) { + this.data = data; + // Kludge to define EditorState.tree as a debugging helper, + // without the EditorState package actually knowing about + // languages and lezer trees. + if (!EditorState.prototype.hasOwnProperty("tree")) + Object.defineProperty(EditorState.prototype, "tree", { get() { return syntaxTree(this); } }); + this.parser = parser; + this.extension = [ + language.of(this), + EditorState.languageData.of((state, pos, side) => state.facet(languageDataFacetAt(state, pos, side))) + ].concat(extraExtensions); + } + /** + Query whether this language is active at the given position. + */ + isActiveAt(state, pos, side = -1) { + return languageDataFacetAt(state, pos, side) == this.data; + } + /** + Find the document regions that were parsed using this language. + The returned regions will _include_ any nested languages rooted + in this language, when those exist. + */ + findRegions(state) { + let lang = state.facet(language); + if ((lang === null || lang === void 0 ? void 0 : lang.data) == this.data) + return [{ from: 0, to: state.doc.length }]; + if (!lang || !lang.allowsNesting) + return []; + let result = []; + let explore = (tree, from) => { + if (tree.prop(languageDataProp) == this.data) { + result.push({ from, to: from + tree.length }); + return; + } + let mount = tree.prop(NodeProp.mounted); + if (mount) { + if (mount.tree.prop(languageDataProp) == this.data) { + if (mount.overlay) + for (let r of mount.overlay) + result.push({ from: r.from + from, to: r.to + from }); + else + result.push({ from: from, to: from + tree.length }); + return; + } + else if (mount.overlay) { + let size = result.length; + explore(mount.tree, mount.overlay[0].from + from); + if (result.length > size) + return; + } + } + for (let i = 0; i < tree.children.length; i++) { + let ch = tree.children[i]; + if (ch instanceof Tree) + explore(ch, tree.positions[i] + from); + } + }; + explore(syntaxTree(state), 0); + return result; + } + /** + Indicates whether this language allows nested languages. The + default implementation returns true. + */ + get allowsNesting() { return true; } + } + /** + @internal + */ + Language.setState = /*@__PURE__*/StateEffect.define(); + function languageDataFacetAt(state, pos, side) { + let topLang = state.facet(language); + if (!topLang) + return null; + let facet = topLang.data; + if (topLang.allowsNesting) { + for (let node = syntaxTree(state).topNode; node; node = node.enter(pos, side, IterMode.ExcludeBuffers)) + facet = node.type.prop(languageDataProp) || facet; + } + return facet; + } + /** + A subclass of [`Language`](https://codemirror.net/6/docs/ref/#language.Language) for use with Lezer + [LR parsers](https://lezer.codemirror.net/docs/ref#lr.LRParser) + parsers. + */ + class LRLanguage extends Language { + constructor(data, parser) { + super(data, parser); + this.parser = parser; + } + /** + Define a language from a parser. + */ + static define(spec) { + let data = defineLanguageFacet(spec.languageData); + return new LRLanguage(data, spec.parser.configure({ + props: [languageDataProp.add(type => type.isTop ? data : undefined)] + })); + } + /** + Create a new instance of this language with a reconfigured + version of its parser. + */ + configure(options) { + return new LRLanguage(this.data, this.parser.configure(options)); + } + get allowsNesting() { return this.parser.hasWrappers(); } + } + /** + Get the syntax tree for a state, which is the current (possibly + incomplete) parse tree of the active + [language](https://codemirror.net/6/docs/ref/#language.Language), or the empty tree if there is no + language available. + */ + function syntaxTree(state) { + let field = state.field(Language.state, false); + return field ? field.tree : Tree.empty; + } + // Lezer-style Input object for a Text document. + class DocInput { + constructor(doc, length = doc.length) { + this.doc = doc; + this.length = length; + this.cursorPos = 0; + this.string = ""; + this.cursor = doc.iter(); + } + syncTo(pos) { + this.string = this.cursor.next(pos - this.cursorPos).value; + this.cursorPos = pos + this.string.length; + return this.cursorPos - this.string.length; + } + chunk(pos) { + this.syncTo(pos); + return this.string; + } + get lineChunks() { return true; } + read(from, to) { + let stringStart = this.cursorPos - this.string.length; + if (from < stringStart || to >= this.cursorPos) + return this.doc.sliceString(from, to); + else + return this.string.slice(from - stringStart, to - stringStart); + } + } + let currentContext = null; + /** + A parse context provided to parsers working on the editor content. + */ + class ParseContext { + constructor(parser, + /** + The current editor state. + */ + state, + /** + Tree fragments that can be reused by incremental re-parses. + */ + fragments = [], + /** + @internal + */ + tree, + /** + @internal + */ + treeLen, + /** + The current editor viewport (or some overapproximation + thereof). Intended to be used for opportunistically avoiding + work (in which case + [`skipUntilInView`](https://codemirror.net/6/docs/ref/#language.ParseContext.skipUntilInView) + should be called to make sure the parser is restarted when the + skipped region becomes visible). + */ + viewport, + /** + @internal + */ + skipped, + /** + This is where skipping parsers can register a promise that, + when resolved, will schedule a new parse. It is cleared when + the parse worker picks up the promise. @internal + */ + scheduleOn) { + this.parser = parser; + this.state = state; + this.fragments = fragments; + this.tree = tree; + this.treeLen = treeLen; + this.viewport = viewport; + this.skipped = skipped; + this.scheduleOn = scheduleOn; + this.parse = null; + /** + @internal + */ + this.tempSkipped = []; + } + /** + @internal + */ + static create(parser, state, viewport) { + return new ParseContext(parser, state, [], Tree.empty, 0, viewport, [], null); + } + startParse() { + return this.parser.startParse(new DocInput(this.state.doc), this.fragments); + } + /** + @internal + */ + work(until, upto) { + if (upto != null && upto >= this.state.doc.length) + upto = undefined; + if (this.tree != Tree.empty && this.isDone(upto !== null && upto !== void 0 ? upto : this.state.doc.length)) { + this.takeTree(); + return true; + } + return this.withContext(() => { + var _a; + if (typeof until == "number") { + let endTime = Date.now() + until; + until = () => Date.now() > endTime; + } + if (!this.parse) + this.parse = this.startParse(); + if (upto != null && (this.parse.stoppedAt == null || this.parse.stoppedAt > upto) && + upto < this.state.doc.length) + this.parse.stopAt(upto); + for (;;) { + let done = this.parse.advance(); + if (done) { + this.fragments = this.withoutTempSkipped(TreeFragment.addTree(done, this.fragments, this.parse.stoppedAt != null)); + this.treeLen = (_a = this.parse.stoppedAt) !== null && _a !== void 0 ? _a : this.state.doc.length; + this.tree = done; + this.parse = null; + if (this.treeLen < (upto !== null && upto !== void 0 ? upto : this.state.doc.length)) + this.parse = this.startParse(); + else + return true; + } + if (until()) + return false; + } + }); + } + /** + @internal + */ + takeTree() { + let pos, tree; + if (this.parse && (pos = this.parse.parsedPos) >= this.treeLen) { + if (this.parse.stoppedAt == null || this.parse.stoppedAt > pos) + this.parse.stopAt(pos); + this.withContext(() => { while (!(tree = this.parse.advance())) { } }); + this.treeLen = pos; + this.tree = tree; + this.fragments = this.withoutTempSkipped(TreeFragment.addTree(this.tree, this.fragments, true)); + this.parse = null; + } + } + withContext(f) { + let prev = currentContext; + currentContext = this; + try { + return f(); + } + finally { + currentContext = prev; + } + } + withoutTempSkipped(fragments) { + for (let r; r = this.tempSkipped.pop();) + fragments = cutFragments(fragments, r.from, r.to); + return fragments; + } + /** + @internal + */ + changes(changes, newState) { + let { fragments, tree, treeLen, viewport, skipped } = this; + this.takeTree(); + if (!changes.empty) { + let ranges = []; + changes.iterChangedRanges((fromA, toA, fromB, toB) => ranges.push({ fromA, toA, fromB, toB })); + fragments = TreeFragment.applyChanges(fragments, ranges); + tree = Tree.empty; + treeLen = 0; + viewport = { from: changes.mapPos(viewport.from, -1), to: changes.mapPos(viewport.to, 1) }; + if (this.skipped.length) { + skipped = []; + for (let r of this.skipped) { + let from = changes.mapPos(r.from, 1), to = changes.mapPos(r.to, -1); + if (from < to) + skipped.push({ from, to }); + } + } + } + return new ParseContext(this.parser, newState, fragments, tree, treeLen, viewport, skipped, this.scheduleOn); + } + /** + @internal + */ + updateViewport(viewport) { + if (this.viewport.from == viewport.from && this.viewport.to == viewport.to) + return false; + this.viewport = viewport; + let startLen = this.skipped.length; + for (let i = 0; i < this.skipped.length; i++) { + let { from, to } = this.skipped[i]; + if (from < viewport.to && to > viewport.from) { + this.fragments = cutFragments(this.fragments, from, to); + this.skipped.splice(i--, 1); + } + } + if (this.skipped.length >= startLen) + return false; + this.reset(); + return true; + } + /** + @internal + */ + reset() { + if (this.parse) { + this.takeTree(); + this.parse = null; + } + } + /** + Notify the parse scheduler that the given region was skipped + because it wasn't in view, and the parse should be restarted + when it comes into view. + */ + skipUntilInView(from, to) { + this.skipped.push({ from, to }); + } + /** + Returns a parser intended to be used as placeholder when + asynchronously loading a nested parser. It'll skip its input and + mark it as not-really-parsed, so that the next update will parse + it again. + + When `until` is given, a reparse will be scheduled when that + promise resolves. + */ + static getSkippingParser(until) { + return new class extends Parser { + createParse(input, fragments, ranges) { + let from = ranges[0].from, to = ranges[ranges.length - 1].to; + let parser = { + parsedPos: from, + advance() { + let cx = currentContext; + if (cx) { + for (let r of ranges) + cx.tempSkipped.push(r); + if (until) + cx.scheduleOn = cx.scheduleOn ? Promise.all([cx.scheduleOn, until]) : until; + } + this.parsedPos = to; + return new Tree(NodeType.none, [], [], to - from); + }, + stoppedAt: null, + stopAt() { } + }; + return parser; + } + }; + } + /** + @internal + */ + isDone(upto) { + upto = Math.min(upto, this.state.doc.length); + let frags = this.fragments; + return this.treeLen >= upto && frags.length && frags[0].from == 0 && frags[0].to >= upto; + } + /** + Get the context for the current parse, or `null` if no editor + parse is in progress. + */ + static get() { return currentContext; } + } + function cutFragments(fragments, from, to) { + return TreeFragment.applyChanges(fragments, [{ fromA: from, toA: to, fromB: from, toB: to }]); + } + class LanguageState { + constructor( + // A mutable parse state that is used to preserve work done during + // the lifetime of a state when moving to the next state. + context) { + this.context = context; + this.tree = context.tree; + } + apply(tr) { + if (!tr.docChanged && this.tree == this.context.tree) + return this; + let newCx = this.context.changes(tr.changes, tr.state); + // If the previous parse wasn't done, go forward only up to its + // end position or the end of the viewport, to avoid slowing down + // state updates with parse work beyond the viewport. + let upto = this.context.treeLen == tr.startState.doc.length ? undefined + : Math.max(tr.changes.mapPos(this.context.treeLen), newCx.viewport.to); + if (!newCx.work(20 /* Apply */, upto)) + newCx.takeTree(); + return new LanguageState(newCx); + } + static init(state) { + let vpTo = Math.min(3000 /* InitViewport */, state.doc.length); + let parseState = ParseContext.create(state.facet(language).parser, state, { from: 0, to: vpTo }); + if (!parseState.work(20 /* Apply */, vpTo)) + parseState.takeTree(); + return new LanguageState(parseState); + } + } + Language.state = /*@__PURE__*/StateField.define({ + create: LanguageState.init, + update(value, tr) { + for (let e of tr.effects) + if (e.is(Language.setState)) + return e.value; + if (tr.startState.facet(language) != tr.state.facet(language)) + return LanguageState.init(tr.state); + return value.apply(tr); + } + }); + let requestIdle = (callback) => { + let timeout = setTimeout(() => callback(), 500 /* MaxPause */); + return () => clearTimeout(timeout); + }; + if (typeof requestIdleCallback != "undefined") + requestIdle = (callback) => { + let idle = -1, timeout = setTimeout(() => { + idle = requestIdleCallback(callback, { timeout: 500 /* MaxPause */ - 100 /* MinPause */ }); + }, 100 /* MinPause */); + return () => idle < 0 ? clearTimeout(timeout) : cancelIdleCallback(idle); + }; + const isInputPending = typeof navigator != "undefined" && ((_a = navigator.scheduling) === null || _a === void 0 ? void 0 : _a.isInputPending) + ? () => navigator.scheduling.isInputPending() : null; + const parseWorker = /*@__PURE__*/ViewPlugin.fromClass(class ParseWorker { + constructor(view) { + this.view = view; + this.working = null; + this.workScheduled = 0; + // End of the current time chunk + this.chunkEnd = -1; + // Milliseconds of budget left for this chunk + this.chunkBudget = -1; + this.work = this.work.bind(this); + this.scheduleWork(); + } + update(update) { + let cx = this.view.state.field(Language.state).context; + if (cx.updateViewport(update.view.viewport) || this.view.viewport.to > cx.treeLen) + this.scheduleWork(); + if (update.docChanged) { + if (this.view.hasFocus) + this.chunkBudget += 50 /* ChangeBonus */; + this.scheduleWork(); + } + this.checkAsyncSchedule(cx); + } + scheduleWork() { + if (this.working) + return; + let { state } = this.view, field = state.field(Language.state); + if (field.tree != field.context.tree || !field.context.isDone(state.doc.length)) + this.working = requestIdle(this.work); + } + work(deadline) { + this.working = null; + let now = Date.now(); + if (this.chunkEnd < now && (this.chunkEnd < 0 || this.view.hasFocus)) { // Start a new chunk + this.chunkEnd = now + 30000 /* ChunkTime */; + this.chunkBudget = 3000 /* ChunkBudget */; + } + if (this.chunkBudget <= 0) + return; // No more budget + let { state, viewport: { to: vpTo } } = this.view, field = state.field(Language.state); + if (field.tree == field.context.tree && field.context.isDone(vpTo + 100000 /* MaxParseAhead */)) + return; + let endTime = Date.now() + Math.min(this.chunkBudget, 100 /* Slice */, deadline && !isInputPending ? Math.max(25 /* MinSlice */, deadline.timeRemaining() - 5) : 1e9); + let viewportFirst = field.context.treeLen < vpTo && state.doc.length > vpTo + 1000; + let done = field.context.work(() => { + return isInputPending && isInputPending() || Date.now() > endTime; + }, vpTo + (viewportFirst ? 0 : 100000 /* MaxParseAhead */)); + this.chunkBudget -= Date.now() - now; + if (done || this.chunkBudget <= 0) { + field.context.takeTree(); + this.view.dispatch({ effects: Language.setState.of(new LanguageState(field.context)) }); + } + if (this.chunkBudget > 0 && !(done && !viewportFirst)) + this.scheduleWork(); + this.checkAsyncSchedule(field.context); + } + checkAsyncSchedule(cx) { + if (cx.scheduleOn) { + this.workScheduled++; + cx.scheduleOn + .then(() => this.scheduleWork()) + .catch(err => logException(this.view.state, err)) + .then(() => this.workScheduled--); + cx.scheduleOn = null; + } + } + destroy() { + if (this.working) + this.working(); + } + isWorking() { + return !!(this.working || this.workScheduled > 0); + } + }, { + eventHandlers: { focus() { this.scheduleWork(); } } + }); + /** + The facet used to associate a language with an editor state. Used + by `Language` object's `extension` property (so you don't need to + manually wrap your languages in this). Can be used to access the + current language on a state. + */ + const language = /*@__PURE__*/Facet.define({ + combine(languages) { return languages.length ? languages[0] : null; }, + enables: [Language.state, parseWorker] + }); + /** + This class bundles a [language](https://codemirror.net/6/docs/ref/#language.Language) with an + optional set of supporting extensions. Language packages are + encouraged to export a function that optionally takes a + configuration object and returns a `LanguageSupport` instance, as + the main way for client code to use the package. + */ + class LanguageSupport { + /** + Create a language support object. + */ + constructor( + /** + The language object. + */ + language, + /** + An optional set of supporting extensions. When nesting a + language in another language, the outer language is encouraged + to include the supporting extensions for its inner languages + in its own set of support extensions. + */ + support = []) { + this.language = language; + this.support = support; + this.extension = [language, support]; + } + } + + /** + Facet that defines a way to provide a function that computes the + appropriate indentation depth at the start of a given line, or + `null` to indicate no appropriate indentation could be determined. + */ + const indentService = /*@__PURE__*/Facet.define(); + /** + Facet for overriding the unit by which indentation happens. + Should be a string consisting either entirely of spaces or + entirely of tabs. When not set, this defaults to 2 spaces. + */ + const indentUnit = /*@__PURE__*/Facet.define({ + combine: values => { + if (!values.length) + return " "; + if (!/^(?: +|\t+)$/.test(values[0])) + throw new Error("Invalid indent unit: " + JSON.stringify(values[0])); + return values[0]; + } + }); + /** + Return the _column width_ of an indent unit in the state. + Determined by the [`indentUnit`](https://codemirror.net/6/docs/ref/#language.indentUnit) + facet, and [`tabSize`](https://codemirror.net/6/docs/ref/#state.EditorState^tabSize) when that + contains tabs. + */ + function getIndentUnit(state) { + let unit = state.facet(indentUnit); + return unit.charCodeAt(0) == 9 ? state.tabSize * unit.length : unit.length; + } + /** + Create an indentation string that covers columns 0 to `cols`. + Will use tabs for as much of the columns as possible when the + [`indentUnit`](https://codemirror.net/6/docs/ref/#language.indentUnit) facet contains + tabs. + */ + function indentString(state, cols) { + let result = "", ts = state.tabSize; + if (state.facet(indentUnit).charCodeAt(0) == 9) + while (cols >= ts) { + result += "\t"; + cols -= ts; + } + for (let i = 0; i < cols; i++) + result += " "; + return result; + } + /** + Get the indentation at the given position. Will first consult any + [indent services](https://codemirror.net/6/docs/ref/#language.indentService) that are registered, + and if none of those return an indentation, this will check the + syntax tree for the [indent node prop](https://codemirror.net/6/docs/ref/#language.indentNodeProp) + and use that if found. Returns a number when an indentation could + be determined, and null otherwise. + */ + function getIndentation(context, pos) { + if (context instanceof EditorState) + context = new IndentContext(context); + for (let service of context.state.facet(indentService)) { + let result = service(context, pos); + if (result != null) + return result; + } + let tree = syntaxTree(context.state); + return tree ? syntaxIndentation(context, tree, pos) : null; + } + /** + Indentation contexts are used when calling [indentation + services](https://codemirror.net/6/docs/ref/#language.indentService). They provide helper utilities + useful in indentation logic, and can selectively override the + indentation reported for some lines. + */ + class IndentContext { + /** + Create an indent context. + */ + constructor( + /** + The editor state. + */ + state, + /** + @internal + */ + options = {}) { + this.state = state; + this.options = options; + this.unit = getIndentUnit(state); + } + /** + Get a description of the line at the given position, taking + [simulated line + breaks](https://codemirror.net/6/docs/ref/#language.IndentContext.constructor^options.simulateBreak) + into account. If there is such a break at `pos`, the `bias` + argument determines whether the part of the line line before or + after the break is used. + */ + lineAt(pos, bias = 1) { + let line = this.state.doc.lineAt(pos); + let { simulateBreak, simulateDoubleBreak } = this.options; + if (simulateBreak != null && simulateBreak >= line.from && simulateBreak <= line.to) { + if (simulateDoubleBreak && simulateBreak == pos) + return { text: "", from: pos }; + else if (bias < 0 ? simulateBreak < pos : simulateBreak <= pos) + return { text: line.text.slice(simulateBreak - line.from), from: simulateBreak }; + else + return { text: line.text.slice(0, simulateBreak - line.from), from: line.from }; + } + return line; + } + /** + Get the text directly after `pos`, either the entire line + or the next 100 characters, whichever is shorter. + */ + textAfterPos(pos, bias = 1) { + if (this.options.simulateDoubleBreak && pos == this.options.simulateBreak) + return ""; + let { text, from } = this.lineAt(pos, bias); + return text.slice(pos - from, Math.min(text.length, pos + 100 - from)); + } + /** + Find the column for the given position. + */ + column(pos, bias = 1) { + let { text, from } = this.lineAt(pos, bias); + let result = this.countColumn(text, pos - from); + let override = this.options.overrideIndentation ? this.options.overrideIndentation(from) : -1; + if (override > -1) + result += override - this.countColumn(text, text.search(/\S|$/)); + return result; + } + /** + Find the column position (taking tabs into account) of the given + position in the given string. + */ + countColumn(line, pos = line.length) { + return countColumn(line, this.state.tabSize, pos); + } + /** + Find the indentation column of the line at the given point. + */ + lineIndent(pos, bias = 1) { + let { text, from } = this.lineAt(pos, bias); + let override = this.options.overrideIndentation; + if (override) { + let overriden = override(from); + if (overriden > -1) + return overriden; + } + return this.countColumn(text, text.search(/\S|$/)); + } + /** + Returns the [simulated line + break](https://codemirror.net/6/docs/ref/#language.IndentContext.constructor^options.simulateBreak) + for this context, if any. + */ + get simulatedBreak() { + return this.options.simulateBreak || null; + } + } + /** + A syntax tree node prop used to associate indentation strategies + with node types. Such a strategy is a function from an indentation + context to a column number or null, where null indicates that no + definitive indentation can be determined. + */ + const indentNodeProp = /*@__PURE__*/new NodeProp(); + // Compute the indentation for a given position from the syntax tree. + function syntaxIndentation(cx, ast, pos) { + return indentFrom(ast.resolveInner(pos).enterUnfinishedNodesBefore(pos), pos, cx); + } + function ignoreClosed(cx) { + return cx.pos == cx.options.simulateBreak && cx.options.simulateDoubleBreak; + } + function indentStrategy(tree) { + let strategy = tree.type.prop(indentNodeProp); + if (strategy) + return strategy; + let first = tree.firstChild, close; + if (first && (close = first.type.prop(NodeProp.closedBy))) { + let last = tree.lastChild, closed = last && close.indexOf(last.name) > -1; + return cx => delimitedStrategy(cx, true, 1, undefined, closed && !ignoreClosed(cx) ? last.from : undefined); + } + return tree.parent == null ? topIndent$1 : null; + } + function indentFrom(node, pos, base) { + for (; node; node = node.parent) { + let strategy = indentStrategy(node); + if (strategy) + return strategy(TreeIndentContext.create(base, pos, node)); + } + return null; + } + function topIndent$1() { return 0; } + /** + Objects of this type provide context information and helper + methods to indentation functions registered on syntax nodes. + */ + class TreeIndentContext extends IndentContext { + constructor(base, + /** + The position at which indentation is being computed. + */ + pos, + /** + The syntax tree node to which the indentation strategy + applies. + */ + node) { + super(base.state, base.options); + this.base = base; + this.pos = pos; + this.node = node; + } + /** + @internal + */ + static create(base, pos, node) { + return new TreeIndentContext(base, pos, node); + } + /** + Get the text directly after `this.pos`, either the entire line + or the next 100 characters, whichever is shorter. + */ + get textAfter() { + return this.textAfterPos(this.pos); + } + /** + Get the indentation at the reference line for `this.node`, which + is the line on which it starts, unless there is a node that is + _not_ a parent of this node covering the start of that line. If + so, the line at the start of that node is tried, again skipping + on if it is covered by another such node. + */ + get baseIndent() { + let line = this.state.doc.lineAt(this.node.from); + // Skip line starts that are covered by a sibling (or cousin, etc) + for (;;) { + let atBreak = this.node.resolve(line.from); + while (atBreak.parent && atBreak.parent.from == atBreak.from) + atBreak = atBreak.parent; + if (isParent(atBreak, this.node)) + break; + line = this.state.doc.lineAt(atBreak.from); + } + return this.lineIndent(line.from); + } + /** + Continue looking for indentations in the node's parent nodes, + and return the result of that. + */ + continue() { + let parent = this.node.parent; + return parent ? indentFrom(parent, this.pos, this.base) : 0; + } + } + function isParent(parent, of) { + for (let cur = of; cur; cur = cur.parent) + if (parent == cur) + return true; + return false; + } + // Check whether a delimited node is aligned (meaning there are + // non-skipped nodes on the same line as the opening delimiter). And + // if so, return the opening token. + function bracketedAligned(context) { + let tree = context.node; + let openToken = tree.childAfter(tree.from), last = tree.lastChild; + if (!openToken) + return null; + let sim = context.options.simulateBreak; + let openLine = context.state.doc.lineAt(openToken.from); + let lineEnd = sim == null || sim <= openLine.from ? openLine.to : Math.min(openLine.to, sim); + for (let pos = openToken.to;;) { + let next = tree.childAfter(pos); + if (!next || next == last) + return null; + if (!next.type.isSkipped) + return next.from < lineEnd ? openToken : null; + pos = next.to; + } + } + /** + An indentation strategy for delimited (usually bracketed) nodes. + Will, by default, indent one unit more than the parent's base + indent unless the line starts with a closing token. When `align` + is true and there are non-skipped nodes on the node's opening + line, the content of the node will be aligned with the end of the + opening node, like this: + + foo(bar, + baz) + */ + function delimitedIndent({ closing, align = true, units = 1 }) { + return (context) => delimitedStrategy(context, align, units, closing); + } + function delimitedStrategy(context, align, units, closing, closedAt) { + let after = context.textAfter, space = after.match(/^\s*/)[0].length; + let closed = closing && after.slice(space, space + closing.length) == closing || closedAt == context.pos + space; + let aligned = align ? bracketedAligned(context) : null; + if (aligned) + return closed ? context.column(aligned.from) : context.column(aligned.to); + return context.baseIndent + (closed ? 0 : context.unit * units); + } + const DontIndentBeyond = 200; + /** + Enables reindentation on input. When a language defines an + `indentOnInput` field in its [language + data](https://codemirror.net/6/docs/ref/#state.EditorState.languageDataAt), which must hold a regular + expression, the line at the cursor will be reindented whenever new + text is typed and the input from the start of the line up to the + cursor matches that regexp. + + To avoid unneccesary reindents, it is recommended to start the + regexp with `^` (usually followed by `\s*`), and end it with `$`. + For example, `/^\s*\}$/` will reindent when a closing brace is + added at the start of a line. + */ + function indentOnInput() { + return EditorState.transactionFilter.of(tr => { + if (!tr.docChanged || !tr.isUserEvent("input.type") && !tr.isUserEvent("input.complete")) + return tr; + let rules = tr.startState.languageDataAt("indentOnInput", tr.startState.selection.main.head); + if (!rules.length) + return tr; + let doc = tr.newDoc, { head } = tr.newSelection.main, line = doc.lineAt(head); + if (head > line.from + DontIndentBeyond) + return tr; + let lineStart = doc.sliceString(line.from, head); + if (!rules.some(r => r.test(lineStart))) + return tr; + let { state } = tr, last = -1, changes = []; + for (let { head } of state.selection.ranges) { + let line = state.doc.lineAt(head); + if (line.from == last) + continue; + last = line.from; + let indent = getIndentation(state, line.from); + if (indent == null) + continue; + let cur = /^\s*/.exec(line.text)[0]; + let norm = indentString(state, indent); + if (cur != norm) + changes.push({ from: line.from, to: line.from + cur.length, insert: norm }); + } + return changes.length ? [tr, { changes, sequential: true }] : tr; + }); + } + + /** + A facet that registers a code folding service. When called with + the extent of a line, such a function should return a foldable + range that starts on that line (but continues beyond it), if one + can be found. + */ + const foldService = /*@__PURE__*/Facet.define(); + /** + This node prop is used to associate folding information with + syntax node types. Given a syntax node, it should check whether + that tree is foldable and return the range that can be collapsed + when it is. + */ + const foldNodeProp = /*@__PURE__*/new NodeProp(); + /** + [Fold](https://codemirror.net/6/docs/ref/#language.foldNodeProp) function that folds everything but + the first and the last child of a syntax node. Useful for nodes + that start and end with delimiters. + */ + function foldInside(node) { + let first = node.firstChild, last = node.lastChild; + return first && first.to < last.from ? { from: first.to, to: last.type.isError ? node.to : last.from } : null; + } + function syntaxFolding(state, start, end) { + let tree = syntaxTree(state); + if (tree.length < end) + return null; + let inner = tree.resolveInner(end); + let found = null; + for (let cur = inner; cur; cur = cur.parent) { + if (cur.to <= end || cur.from > end) + continue; + if (found && cur.from < start) + break; + let prop = cur.type.prop(foldNodeProp); + if (prop && (cur.to < tree.length - 50 || tree.length == state.doc.length || !isUnfinished(cur))) { + let value = prop(cur, state); + if (value && value.from <= end && value.from >= start && value.to > end) + found = value; + } + } + return found; + } + function isUnfinished(node) { + let ch = node.lastChild; + return ch && ch.to == node.to && ch.type.isError; + } + /** + Check whether the given line is foldable. First asks any fold + services registered through + [`foldService`](https://codemirror.net/6/docs/ref/#language.foldService), and if none of them return + a result, tries to query the [fold node + prop](https://codemirror.net/6/docs/ref/#language.foldNodeProp) of syntax nodes that cover the end + of the line. + */ + function foldable(state, lineStart, lineEnd) { + for (let service of state.facet(foldService)) { + let result = service(state, lineStart, lineEnd); + if (result) + return result; + } + return syntaxFolding(state, lineStart, lineEnd); + } + function mapRange(range, mapping) { + let from = mapping.mapPos(range.from, 1), to = mapping.mapPos(range.to, -1); + return from >= to ? undefined : { from, to }; + } + /** + State effect that can be attached to a transaction to fold the + given range. (You probably only need this in exceptional + circumstances—usually you'll just want to let + [`foldCode`](https://codemirror.net/6/docs/ref/#language.foldCode) and the [fold + gutter](https://codemirror.net/6/docs/ref/#language.foldGutter) create the transactions.) + */ + const foldEffect = /*@__PURE__*/StateEffect.define({ map: mapRange }); + /** + State effect that unfolds the given range (if it was folded). + */ + const unfoldEffect = /*@__PURE__*/StateEffect.define({ map: mapRange }); + function selectedLines(view) { + let lines = []; + for (let { head } of view.state.selection.ranges) { + if (lines.some(l => l.from <= head && l.to >= head)) + continue; + lines.push(view.lineBlockAt(head)); + } + return lines; + } + /** + The state field that stores the folded ranges (as a [decoration + set](https://codemirror.net/6/docs/ref/#view.DecorationSet)). Can be passed to + [`EditorState.toJSON`](https://codemirror.net/6/docs/ref/#state.EditorState.toJSON) and + [`fromJSON`](https://codemirror.net/6/docs/ref/#state.EditorState^fromJSON) to serialize the fold + state. + */ + const foldState = /*@__PURE__*/StateField.define({ + create() { + return Decoration.none; + }, + update(folded, tr) { + folded = folded.map(tr.changes); + for (let e of tr.effects) { + if (e.is(foldEffect) && !foldExists(folded, e.value.from, e.value.to)) + folded = folded.update({ add: [foldWidget.range(e.value.from, e.value.to)] }); + else if (e.is(unfoldEffect)) + folded = folded.update({ filter: (from, to) => e.value.from != from || e.value.to != to, + filterFrom: e.value.from, filterTo: e.value.to }); + } + // Clear folded ranges that cover the selection head + if (tr.selection) { + let onSelection = false, { head } = tr.selection.main; + folded.between(head, head, (a, b) => { if (a < head && b > head) + onSelection = true; }); + if (onSelection) + folded = folded.update({ + filterFrom: head, + filterTo: head, + filter: (a, b) => b <= head || a >= head + }); + } + return folded; + }, + provide: f => EditorView.decorations.from(f), + toJSON(folded, state) { + let ranges = []; + folded.between(0, state.doc.length, (from, to) => { ranges.push(from, to); }); + return ranges; + }, + fromJSON(value) { + if (!Array.isArray(value) || value.length % 2) + throw new RangeError("Invalid JSON for fold state"); + let ranges = []; + for (let i = 0; i < value.length;) { + let from = value[i++], to = value[i++]; + if (typeof from != "number" || typeof to != "number") + throw new RangeError("Invalid JSON for fold state"); + ranges.push(foldWidget.range(from, to)); + } + return Decoration.set(ranges, true); + } + }); + function findFold(state, from, to) { + var _a; + let found = null; + (_a = state.field(foldState, false)) === null || _a === void 0 ? void 0 : _a.between(from, to, (from, to) => { + if (!found || found.from > from) + found = { from, to }; + }); + return found; + } + function foldExists(folded, from, to) { + let found = false; + folded.between(from, from, (a, b) => { if (a == from && b == to) + found = true; }); + return found; + } + function maybeEnable(state, other) { + return state.field(foldState, false) ? other : other.concat(StateEffect.appendConfig.of(codeFolding())); + } + /** + Fold the lines that are selected, if possible. + */ + const foldCode = view => { + for (let line of selectedLines(view)) { + let range = foldable(view.state, line.from, line.to); + if (range) { + view.dispatch({ effects: maybeEnable(view.state, [foldEffect.of(range), announceFold(view, range)]) }); + return true; + } + } + return false; + }; + /** + Unfold folded ranges on selected lines. + */ + const unfoldCode = view => { + if (!view.state.field(foldState, false)) + return false; + let effects = []; + for (let line of selectedLines(view)) { + let folded = findFold(view.state, line.from, line.to); + if (folded) + effects.push(unfoldEffect.of(folded), announceFold(view, folded, false)); + } + if (effects.length) + view.dispatch({ effects }); + return effects.length > 0; + }; + function announceFold(view, range, fold = true) { + let lineFrom = view.state.doc.lineAt(range.from).number, lineTo = view.state.doc.lineAt(range.to).number; + return EditorView.announce.of(`${view.state.phrase(fold ? "Folded lines" : "Unfolded lines")} ${lineFrom} ${view.state.phrase("to")} ${lineTo}.`); + } + /** + Fold all top-level foldable ranges. Note that, in most cases, + folding information will depend on the [syntax + tree](https://codemirror.net/6/docs/ref/#language.syntaxTree), and folding everything may not work + reliably when the document hasn't been fully parsed (either + because the editor state was only just initialized, or because the + document is so big that the parser decided not to parse it + entirely). + */ + const foldAll = view => { + let { state } = view, effects = []; + for (let pos = 0; pos < state.doc.length;) { + let line = view.lineBlockAt(pos), range = foldable(state, line.from, line.to); + if (range) + effects.push(foldEffect.of(range)); + pos = (range ? view.lineBlockAt(range.to) : line).to + 1; + } + if (effects.length) + view.dispatch({ effects: maybeEnable(view.state, effects) }); + return !!effects.length; + }; + /** + Unfold all folded code. + */ + const unfoldAll = view => { + let field = view.state.field(foldState, false); + if (!field || !field.size) + return false; + let effects = []; + field.between(0, view.state.doc.length, (from, to) => { effects.push(unfoldEffect.of({ from, to })); }); + view.dispatch({ effects }); + return true; + }; + /** + Default fold-related key bindings. + + - Ctrl-Shift-[ (Cmd-Alt-[ on macOS): [`foldCode`](https://codemirror.net/6/docs/ref/#language.foldCode). + - Ctrl-Shift-] (Cmd-Alt-] on macOS): [`unfoldCode`](https://codemirror.net/6/docs/ref/#language.unfoldCode). + - Ctrl-Alt-[: [`foldAll`](https://codemirror.net/6/docs/ref/#language.foldAll). + - Ctrl-Alt-]: [`unfoldAll`](https://codemirror.net/6/docs/ref/#language.unfoldAll). + */ + const foldKeymap = [ + { key: "Ctrl-Shift-[", mac: "Cmd-Alt-[", run: foldCode }, + { key: "Ctrl-Shift-]", mac: "Cmd-Alt-]", run: unfoldCode }, + { key: "Ctrl-Alt-[", run: foldAll }, + { key: "Ctrl-Alt-]", run: unfoldAll } + ]; + const defaultConfig = { + placeholderDOM: null, + placeholderText: "…" + }; + const foldConfig = /*@__PURE__*/Facet.define({ + combine(values) { return combineConfig(values, defaultConfig); } + }); + /** + Create an extension that configures code folding. + */ + function codeFolding(config) { + let result = [foldState, baseTheme$1$2]; + if (config) + result.push(foldConfig.of(config)); + return result; + } + const foldWidget = /*@__PURE__*/Decoration.replace({ widget: /*@__PURE__*/new class extends WidgetType { + toDOM(view) { + let { state } = view, conf = state.facet(foldConfig); + let onclick = (event) => { + let line = view.lineBlockAt(view.posAtDOM(event.target)); + let folded = findFold(view.state, line.from, line.to); + if (folded) + view.dispatch({ effects: unfoldEffect.of(folded) }); + event.preventDefault(); + }; + if (conf.placeholderDOM) + return conf.placeholderDOM(view, onclick); + let element = document.createElement("span"); + element.textContent = conf.placeholderText; + element.setAttribute("aria-label", state.phrase("folded code")); + element.title = state.phrase("unfold"); + element.className = "cm-foldPlaceholder"; + element.onclick = onclick; + return element; + } + } }); + const foldGutterDefaults = { + openText: "⌄", + closedText: "›", + markerDOM: null, + domEventHandlers: {}, + foldingChanged: () => false + }; + class FoldMarker extends GutterMarker { + constructor(config, open) { + super(); + this.config = config; + this.open = open; + } + eq(other) { return this.config == other.config && this.open == other.open; } + toDOM(view) { + if (this.config.markerDOM) + return this.config.markerDOM(this.open); + let span = document.createElement("span"); + span.textContent = this.open ? this.config.openText : this.config.closedText; + span.title = view.state.phrase(this.open ? "Fold line" : "Unfold line"); + return span; + } + } + /** + Create an extension that registers a fold gutter, which shows a + fold status indicator before foldable lines (which can be clicked + to fold or unfold the line). + */ + function foldGutter(config = {}) { + let fullConfig = Object.assign(Object.assign({}, foldGutterDefaults), config); + let canFold = new FoldMarker(fullConfig, true), canUnfold = new FoldMarker(fullConfig, false); + let markers = ViewPlugin.fromClass(class { + constructor(view) { + this.from = view.viewport.from; + this.markers = this.buildMarkers(view); + } + update(update) { + if (update.docChanged || update.viewportChanged || + update.startState.facet(language) != update.state.facet(language) || + update.startState.field(foldState, false) != update.state.field(foldState, false) || + syntaxTree(update.startState) != syntaxTree(update.state) || + fullConfig.foldingChanged(update)) + this.markers = this.buildMarkers(update.view); + } + buildMarkers(view) { + let builder = new RangeSetBuilder(); + for (let line of view.viewportLineBlocks) { + let mark = findFold(view.state, line.from, line.to) ? canUnfold + : foldable(view.state, line.from, line.to) ? canFold : null; + if (mark) + builder.add(line.from, line.from, mark); + } + return builder.finish(); + } + }); + let { domEventHandlers } = fullConfig; + return [ + markers, + gutter({ + class: "cm-foldGutter", + markers(view) { var _a; return ((_a = view.plugin(markers)) === null || _a === void 0 ? void 0 : _a.markers) || RangeSet.empty; }, + initialSpacer() { + return new FoldMarker(fullConfig, false); + }, + domEventHandlers: Object.assign(Object.assign({}, domEventHandlers), { click: (view, line, event) => { + if (domEventHandlers.click && domEventHandlers.click(view, line, event)) + return true; + let folded = findFold(view.state, line.from, line.to); + if (folded) { + view.dispatch({ effects: unfoldEffect.of(folded) }); + return true; + } + let range = foldable(view.state, line.from, line.to); + if (range) { + view.dispatch({ effects: foldEffect.of(range) }); + return true; + } + return false; + } }) + }), + codeFolding() + ]; + } + const baseTheme$1$2 = /*@__PURE__*/EditorView.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" + } + }); + + /** + A highlight style associates CSS styles with higlighting + [tags](https://lezer.codemirror.net/docs/ref#highlight.Tag). + */ + class HighlightStyle { + constructor(spec, options) { + let modSpec; + function def(spec) { + let cls = StyleModule.newName(); + (modSpec || (modSpec = Object.create(null)))["." + cls] = spec; + return cls; + } + const all = typeof options.all == "string" ? options.all : options.all ? def(options.all) : undefined; + const scopeOpt = options.scope; + this.scope = scopeOpt instanceof Language ? (type) => type.prop(languageDataProp) == scopeOpt.data + : scopeOpt ? (type) => type == scopeOpt : undefined; + this.style = tagHighlighter(spec.map(style => ({ + tag: style.tag, + class: style.class || def(Object.assign({}, style, { tag: null })) + })), { + all, + }).style; + this.module = modSpec ? new StyleModule(modSpec) : null; + this.themeType = options.themeType; + } + /** + Create a highlighter style that associates the given styles to + the given tags. The specs must be objects that hold a style tag + or array of tags in their `tag` property, and either a single + `class` property providing a static CSS class (for highlighter + that rely on external styling), or a + [`style-mod`](https://github.com/marijnh/style-mod#documentation)-style + set of CSS properties (which define the styling for those tags). + + The CSS rules created for a highlighter will be emitted in the + order of the spec's properties. That means that for elements that + have multiple tags associated with them, styles defined further + down in the list will have a higher CSS precedence than styles + defined earlier. + */ + static define(specs, options) { + return new HighlightStyle(specs, options || {}); + } + } + const highlighterFacet = /*@__PURE__*/Facet.define(); + const fallbackHighlighter = /*@__PURE__*/Facet.define({ + combine(values) { return values.length ? [values[0]] : null; } + }); + function getHighlighters(state) { + let main = state.facet(highlighterFacet); + return main.length ? main : state.facet(fallbackHighlighter); + } + /** + Wrap a highlighter in an editor extension that uses it to apply + syntax highlighting to the editor content. + + When multiple (non-fallback) styles are provided, the styling + applied is the union of the classes they emit. + */ + function syntaxHighlighting(highlighter, options) { + let ext = [treeHighlighter], themeType; + if (highlighter instanceof HighlightStyle) { + if (highlighter.module) + ext.push(EditorView.styleModule.of(highlighter.module)); + themeType = highlighter.themeType; + } + if (options === null || options === void 0 ? void 0 : options.fallback) + ext.push(fallbackHighlighter.of(highlighter)); + else if (themeType) + ext.push(highlighterFacet.computeN([EditorView.darkTheme], state => { + return state.facet(EditorView.darkTheme) == (themeType == "dark") ? [highlighter] : []; + })); + else + ext.push(highlighterFacet.of(highlighter)); + return ext; + } + class TreeHighlighter { + constructor(view) { + this.markCache = Object.create(null); + this.tree = syntaxTree(view.state); + this.decorations = this.buildDeco(view, getHighlighters(view.state)); + } + update(update) { + let tree = syntaxTree(update.state), highlighters = getHighlighters(update.state); + let styleChange = highlighters != getHighlighters(update.startState); + if (tree.length < update.view.viewport.to && !styleChange && tree.type == this.tree.type) { + this.decorations = this.decorations.map(update.changes); + } + else if (tree != this.tree || update.viewportChanged || styleChange) { + this.tree = tree; + this.decorations = this.buildDeco(update.view, highlighters); + } + } + buildDeco(view, highlighters) { + if (!highlighters || !this.tree.length) + return Decoration.none; + let builder = new RangeSetBuilder(); + for (let { from, to } of view.visibleRanges) { + highlightTree(this.tree, highlighters, (from, to, style) => { + builder.add(from, to, this.markCache[style] || (this.markCache[style] = Decoration.mark({ class: style }))); + }, from, to); + } + return builder.finish(); + } + } + const treeHighlighter = /*@__PURE__*/Prec.high(/*@__PURE__*/ViewPlugin.fromClass(TreeHighlighter, { + decorations: v => v.decorations + })); + /** + A default highlight style (works well with light themes). + */ + const defaultHighlightStyle = /*@__PURE__*/HighlightStyle.define([ + { tag: tags.meta, + color: "#7a757a" }, + { tag: tags.link, + textDecoration: "underline" }, + { tag: tags.heading, + textDecoration: "underline", + fontWeight: "bold" }, + { tag: tags.emphasis, + fontStyle: "italic" }, + { tag: tags.strong, + fontWeight: "bold" }, + { tag: tags.strikethrough, + textDecoration: "line-through" }, + { tag: tags.keyword, + color: "#708" }, + { tag: [tags.atom, tags.bool, tags.url, tags.contentSeparator, tags.labelName], + color: "#219" }, + { tag: [tags.literal, tags.inserted], + color: "#164" }, + { tag: [tags.string, tags.deleted], + color: "#a11" }, + { tag: [tags.regexp, tags.escape, /*@__PURE__*/tags.special(tags.string)], + color: "#e40" }, + { tag: /*@__PURE__*/tags.definition(tags.variableName), + color: "#00f" }, + { tag: /*@__PURE__*/tags.local(tags.variableName), + color: "#30a" }, + { tag: [tags.typeName, tags.namespace], + color: "#085" }, + { tag: tags.className, + color: "#167" }, + { tag: [/*@__PURE__*/tags.special(tags.variableName), tags.macroName], + color: "#256" }, + { tag: /*@__PURE__*/tags.definition(tags.propertyName), + color: "#00c" }, + { tag: tags.comment, + color: "#940" }, + { tag: tags.invalid, + color: "#f00" } + ]); + + const baseTheme$3 = /*@__PURE__*/EditorView.baseTheme({ + "&.cm-focused .cm-matchingBracket": { backgroundColor: "#328c8252" }, + "&.cm-focused .cm-nonmatchingBracket": { backgroundColor: "#bb555544" } + }); + const DefaultScanDist = 10000, DefaultBrackets = "()[]{}"; + const bracketMatchingConfig = /*@__PURE__*/Facet.define({ + combine(configs) { + return combineConfig(configs, { + afterCursor: true, + brackets: DefaultBrackets, + maxScanDistance: DefaultScanDist, + renderMatch: defaultRenderMatch + }); + } + }); + const matchingMark = /*@__PURE__*/Decoration.mark({ class: "cm-matchingBracket" }), nonmatchingMark = /*@__PURE__*/Decoration.mark({ class: "cm-nonmatchingBracket" }); + function defaultRenderMatch(match) { + let decorations = []; + let mark = match.matched ? matchingMark : nonmatchingMark; + decorations.push(mark.range(match.start.from, match.start.to)); + if (match.end) + decorations.push(mark.range(match.end.from, match.end.to)); + return decorations; + } + const bracketMatchingState = /*@__PURE__*/StateField.define({ + create() { return Decoration.none; }, + update(deco, tr) { + if (!tr.docChanged && !tr.selection) + return deco; + let decorations = []; + let config = tr.state.facet(bracketMatchingConfig); + for (let range of tr.state.selection.ranges) { + if (!range.empty) + continue; + let match = matchBrackets(tr.state, range.head, -1, config) + || (range.head > 0 && matchBrackets(tr.state, range.head - 1, 1, config)) + || (config.afterCursor && + (matchBrackets(tr.state, range.head, 1, config) || + (range.head < tr.state.doc.length && matchBrackets(tr.state, range.head + 1, -1, config)))); + if (match) + decorations = decorations.concat(config.renderMatch(match, tr.state)); + } + return Decoration.set(decorations, true); + }, + provide: f => EditorView.decorations.from(f) + }); + const bracketMatchingUnique = [ + bracketMatchingState, + baseTheme$3 + ]; + /** + Create an extension that enables bracket matching. Whenever the + cursor is next to a bracket, that bracket and the one it matches + are highlighted. Or, when no matching bracket is found, another + highlighting style is used to indicate this. + */ + function bracketMatching(config = {}) { + return [bracketMatchingConfig.of(config), bracketMatchingUnique]; + } + function matchingNodes(node, dir, brackets) { + let byProp = node.prop(dir < 0 ? NodeProp.openedBy : NodeProp.closedBy); + if (byProp) + return byProp; + if (node.name.length == 1) { + let index = brackets.indexOf(node.name); + if (index > -1 && index % 2 == (dir < 0 ? 1 : 0)) + return [brackets[index + dir]]; + } + return null; + } + /** + Find the matching bracket for the token at `pos`, scanning + direction `dir`. Only the `brackets` and `maxScanDistance` + properties are used from `config`, if given. Returns null if no + bracket was found at `pos`, or a match result otherwise. + */ + function matchBrackets(state, pos, dir, config = {}) { + let maxScanDistance = config.maxScanDistance || DefaultScanDist, brackets = config.brackets || DefaultBrackets; + let tree = syntaxTree(state), node = tree.resolveInner(pos, dir); + for (let cur = node; cur; cur = cur.parent) { + let matches = matchingNodes(cur.type, dir, brackets); + if (matches && cur.from < cur.to) + return matchMarkedBrackets(state, pos, dir, cur, matches, brackets); + } + return matchPlainBrackets(state, pos, dir, tree, node.type, maxScanDistance, brackets); + } + function matchMarkedBrackets(_state, _pos, dir, token, matching, brackets) { + let parent = token.parent, firstToken = { from: token.from, to: token.to }; + let depth = 0, cursor = parent === null || parent === void 0 ? void 0 : parent.cursor(); + if (cursor && (dir < 0 ? cursor.childBefore(token.from) : cursor.childAfter(token.to))) + do { + if (dir < 0 ? cursor.to <= token.from : cursor.from >= token.to) { + if (depth == 0 && matching.indexOf(cursor.type.name) > -1 && cursor.from < cursor.to) { + return { start: firstToken, end: { from: cursor.from, to: cursor.to }, matched: true }; + } + else if (matchingNodes(cursor.type, dir, brackets)) { + depth++; + } + else if (matchingNodes(cursor.type, -dir, brackets)) { + if (depth == 0) + return { + start: firstToken, + end: cursor.from == cursor.to ? undefined : { from: cursor.from, to: cursor.to }, + matched: false + }; + depth--; + } + } + } while (dir < 0 ? cursor.prevSibling() : cursor.nextSibling()); + return { start: firstToken, matched: false }; + } + function matchPlainBrackets(state, pos, dir, tree, tokenType, maxScanDistance, brackets) { + let startCh = dir < 0 ? state.sliceDoc(pos - 1, pos) : state.sliceDoc(pos, pos + 1); + let bracket = brackets.indexOf(startCh); + if (bracket < 0 || (bracket % 2 == 0) != (dir > 0)) + return null; + let startToken = { from: dir < 0 ? pos - 1 : pos, to: dir > 0 ? pos + 1 : pos }; + let iter = state.doc.iterRange(pos, dir > 0 ? state.doc.length : 0), depth = 0; + for (let distance = 0; !(iter.next()).done && distance <= maxScanDistance;) { + let text = iter.value; + if (dir < 0) + distance += text.length; + let basePos = pos + distance * dir; + for (let pos = dir > 0 ? 0 : text.length - 1, end = dir > 0 ? text.length : -1; pos != end; pos += dir) { + let found = brackets.indexOf(text[pos]); + if (found < 0 || tree.resolveInner(basePos + pos, 1).type != tokenType) + continue; + if ((found % 2 == 0) == (dir > 0)) { + depth++; + } + else if (depth == 1) { // Closing + return { start: startToken, end: { from: basePos + pos, to: basePos + pos + 1 }, matched: (found >> 1) == (bracket >> 1) }; + } + else { + depth--; + } + } + if (dir > 0) + distance += text.length; + } + return iter.done ? { start: startToken, matched: false } : null; + } + const noTokens = /*@__PURE__*/Object.create(null); + const typeArray = [NodeType.none]; + const warned = []; + const defaultTable = /*@__PURE__*/Object.create(null); + for (let [legacyName, name] 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"] + ]) + defaultTable[legacyName] = /*@__PURE__*/createTokenType(noTokens, name); + function warnForPart(part, msg) { + if (warned.indexOf(part) > -1) + return; + warned.push(part); + console.warn(msg); + } + function createTokenType(extra, tagStr) { + let tag = null; + for (let part of tagStr.split(".")) { + let value = (extra[part] || tags[part]); + if (!value) { + warnForPart(part, `Unknown highlighting tag ${part}`); + } + else if (typeof value == "function") { + if (!tag) + warnForPart(part, `Modifier ${part} used at start of tag`); + else + tag = value(tag); + } + else { + if (tag) + warnForPart(part, `Tag ${part} used as modifier`); + else + tag = value; + } + } + if (!tag) + return 0; + let name = tagStr.replace(/ /g, "_"), type = NodeType.define({ + id: typeArray.length, + name, + props: [styleTags({ [name]: tag })] + }); + typeArray.push(type); + return type.id; + } + + /** + Comment or uncomment the current selection. Will use line comments + if available, otherwise falling back to block comments. + */ + const toggleComment = target => { + let config = getConfig(target.state); + return config.line ? toggleLineComment(target) : config.block ? toggleBlockCommentByLine(target) : false; + }; + function command(f, option) { + return ({ state, dispatch }) => { + if (state.readOnly) + return false; + let tr = f(option, state); + if (!tr) + return false; + dispatch(state.update(tr)); + return true; + }; + } + /** + Comment or uncomment the current selection using line comments. + The line comment syntax is taken from the + [`commentTokens`](https://codemirror.net/6/docs/ref/#commands.CommentTokens) [language + data](https://codemirror.net/6/docs/ref/#state.EditorState.languageDataAt). + */ + const toggleLineComment = /*@__PURE__*/command(changeLineComment, 0 /* CommentOption.Toggle */); + /** + Comment or uncomment the current selection using block comments. + The block comment syntax is taken from the + [`commentTokens`](https://codemirror.net/6/docs/ref/#commands.CommentTokens) [language + data](https://codemirror.net/6/docs/ref/#state.EditorState.languageDataAt). + */ + const toggleBlockComment = /*@__PURE__*/command(changeBlockComment, 0 /* CommentOption.Toggle */); + /** + Comment or uncomment the lines around the current selection using + block comments. + */ + const toggleBlockCommentByLine = /*@__PURE__*/command((o, s) => changeBlockComment(o, s, selectedLineRanges(s)), 0 /* CommentOption.Toggle */); + function getConfig(state, pos = state.selection.main.head) { + let data = state.languageDataAt("commentTokens", pos); + return data.length ? data[0] : {}; + } + const SearchMargin = 50; + /** + Determines if the given range is block-commented in the given + state. + */ + function findBlockComment(state, { open, close }, from, to) { + let textBefore = state.sliceDoc(from - SearchMargin, from); + let textAfter = state.sliceDoc(to, to + SearchMargin); + let spaceBefore = /\s*$/.exec(textBefore)[0].length, spaceAfter = /^\s*/.exec(textAfter)[0].length; + let beforeOff = textBefore.length - spaceBefore; + if (textBefore.slice(beforeOff - open.length, beforeOff) == open && + textAfter.slice(spaceAfter, spaceAfter + close.length) == close) { + return { open: { pos: from - spaceBefore, margin: spaceBefore && 1 }, + close: { pos: to + spaceAfter, margin: spaceAfter && 1 } }; + } + let startText, endText; + if (to - from <= 2 * SearchMargin) { + startText = endText = state.sliceDoc(from, to); + } + else { + startText = state.sliceDoc(from, from + SearchMargin); + endText = state.sliceDoc(to - SearchMargin, to); + } + let startSpace = /^\s*/.exec(startText)[0].length, endSpace = /\s*$/.exec(endText)[0].length; + let endOff = endText.length - endSpace - close.length; + if (startText.slice(startSpace, startSpace + open.length) == open && + endText.slice(endOff, endOff + close.length) == close) { + return { open: { pos: from + startSpace + open.length, + margin: /\s/.test(startText.charAt(startSpace + open.length)) ? 1 : 0 }, + close: { pos: to - endSpace - close.length, + margin: /\s/.test(endText.charAt(endOff - 1)) ? 1 : 0 } }; + } + return null; + } + function selectedLineRanges(state) { + let ranges = []; + for (let r of state.selection.ranges) { + let fromLine = state.doc.lineAt(r.from); + let toLine = r.to <= fromLine.to ? fromLine : state.doc.lineAt(r.to); + let last = ranges.length - 1; + if (last >= 0 && ranges[last].to > fromLine.from) + ranges[last].to = toLine.to; + else + ranges.push({ from: fromLine.from, to: toLine.to }); + } + return ranges; + } + // Performs toggle, comment and uncomment of block comments in + // languages that support them. + function changeBlockComment(option, state, ranges = state.selection.ranges) { + let tokens = ranges.map(r => getConfig(state, r.from).block); + if (!tokens.every(c => c)) + return null; + let comments = ranges.map((r, i) => findBlockComment(state, tokens[i], r.from, r.to)); + if (option != 2 /* CommentOption.Uncomment */ && !comments.every(c => c)) { + return { changes: state.changes(ranges.map((range, i) => { + if (comments[i]) + return []; + return [{ from: range.from, insert: tokens[i].open + " " }, { from: range.to, insert: " " + tokens[i].close }]; + })) }; + } + else if (option != 1 /* CommentOption.Comment */ && comments.some(c => c)) { + let changes = []; + for (let i = 0, comment; i < comments.length; i++) + if (comment = comments[i]) { + let token = tokens[i], { open, close } = comment; + changes.push({ from: open.pos - token.open.length, to: open.pos + open.margin }, { from: close.pos - close.margin, to: close.pos + token.close.length }); + } + return { changes }; + } + return null; + } + // Performs toggle, comment and uncomment of line comments. + function changeLineComment(option, state, ranges = state.selection.ranges) { + let lines = []; + let prevLine = -1; + for (let { from, to } of ranges) { + let startI = lines.length, minIndent = 1e9; + for (let pos = from; pos <= to;) { + let line = state.doc.lineAt(pos); + if (line.from > prevLine && (from == to || to > line.from)) { + prevLine = line.from; + let token = getConfig(state, pos).line; + if (!token) + continue; + let indent = /^\s*/.exec(line.text)[0].length; + let empty = indent == line.length; + let comment = line.text.slice(indent, indent + token.length) == token ? indent : -1; + if (indent < line.text.length && indent < minIndent) + minIndent = indent; + lines.push({ line, comment, token, indent, empty, single: false }); + } + pos = line.to + 1; + } + if (minIndent < 1e9) + for (let i = startI; i < lines.length; i++) + if (lines[i].indent < lines[i].line.text.length) + lines[i].indent = minIndent; + if (lines.length == startI + 1) + lines[startI].single = true; + } + if (option != 2 /* CommentOption.Uncomment */ && lines.some(l => l.comment < 0 && (!l.empty || l.single))) { + let changes = []; + for (let { line, token, indent, empty, single } of lines) + if (single || !empty) + changes.push({ from: line.from + indent, insert: token + " " }); + let changeSet = state.changes(changes); + return { changes: changeSet, selection: state.selection.map(changeSet, 1) }; + } + else if (option != 1 /* CommentOption.Comment */ && lines.some(l => l.comment >= 0)) { + let changes = []; + for (let { line, comment, token } of lines) + if (comment >= 0) { + let from = line.from + comment, to = from + token.length; + if (line.text[to - line.from] == " ") + to++; + changes.push({ from, to }); + } + return { changes }; + } + return null; + } + + const fromHistory = /*@__PURE__*/Annotation.define(); + /** + Transaction annotation that will prevent that transaction from + being combined with other transactions in the undo history. Given + `"before"`, it'll prevent merging with previous transactions. With + `"after"`, subsequent transactions won't be combined with this + one. With `"full"`, the transaction is isolated on both sides. + */ + const isolateHistory = /*@__PURE__*/Annotation.define(); + /** + This facet provides a way to register functions that, given a + transaction, provide a set of effects that the history should + store when inverting the transaction. This can be used to + integrate some kinds of effects in the history, so that they can + be undone (and redone again). + */ + const invertedEffects = /*@__PURE__*/Facet.define(); + const historyConfig = /*@__PURE__*/Facet.define({ + combine(configs) { + return combineConfig(configs, { + minDepth: 100, + newGroupDelay: 500 + }, { minDepth: Math.max, newGroupDelay: Math.min }); + } + }); + function changeEnd(changes) { + let end = 0; + changes.iterChangedRanges((_, to) => end = to); + return end; + } + const historyField_ = /*@__PURE__*/StateField.define({ + create() { + return HistoryState.empty; + }, + update(state, tr) { + let config = tr.state.facet(historyConfig); + let fromHist = tr.annotation(fromHistory); + if (fromHist) { + let selection = tr.docChanged ? EditorSelection.single(changeEnd(tr.changes)) : undefined; + let item = HistEvent.fromTransaction(tr, selection), from = fromHist.side; + let other = from == 0 /* BranchName.Done */ ? state.undone : state.done; + if (item) + other = updateBranch(other, other.length, config.minDepth, item); + else + other = addSelection(other, tr.startState.selection); + return new HistoryState(from == 0 /* BranchName.Done */ ? fromHist.rest : other, from == 0 /* BranchName.Done */ ? other : fromHist.rest); + } + let isolate = tr.annotation(isolateHistory); + if (isolate == "full" || isolate == "before") + state = state.isolate(); + if (tr.annotation(Transaction.addToHistory) === false) + return !tr.changes.empty ? state.addMapping(tr.changes.desc) : state; + let event = HistEvent.fromTransaction(tr); + let time = tr.annotation(Transaction.time), userEvent = tr.annotation(Transaction.userEvent); + if (event) + state = state.addChanges(event, time, userEvent, config.newGroupDelay, config.minDepth); + else if (tr.selection) + state = state.addSelection(tr.startState.selection, time, userEvent, config.newGroupDelay); + if (isolate == "full" || isolate == "after") + state = state.isolate(); + return state; + }, + toJSON(value) { + return { done: value.done.map(e => e.toJSON()), undone: value.undone.map(e => e.toJSON()) }; + }, + fromJSON(json) { + return new HistoryState(json.done.map(HistEvent.fromJSON), json.undone.map(HistEvent.fromJSON)); + } + }); + /** + Create a history extension with the given configuration. + */ + function history(config = {}) { + return [ + historyField_, + historyConfig.of(config), + EditorView.domEventHandlers({ + beforeinput(e, view) { + let command = e.inputType == "historyUndo" ? undo : e.inputType == "historyRedo" ? redo : null; + if (!command) + return false; + e.preventDefault(); + return command(view); + } + }) + ]; + } + function cmd(side, selection) { + return function ({ state, dispatch }) { + if (!selection && state.readOnly) + return false; + let historyState = state.field(historyField_, false); + if (!historyState) + return false; + let tr = historyState.pop(side, state, selection); + if (!tr) + return false; + dispatch(tr); + return true; + }; + } + /** + Undo a single group of history events. Returns false if no group + was available. + */ + const undo = /*@__PURE__*/cmd(0 /* BranchName.Done */, false); + /** + Redo a group of history events. Returns false if no group was + available. + */ + const redo = /*@__PURE__*/cmd(1 /* BranchName.Undone */, false); + /** + Undo a change or selection change. + */ + const undoSelection = /*@__PURE__*/cmd(0 /* BranchName.Done */, true); + /** + Redo a change or selection change. + */ + const redoSelection = /*@__PURE__*/cmd(1 /* BranchName.Undone */, true); + // History events store groups of changes or effects that need to be + // undone/redone together. + class HistEvent { + constructor( + // The changes in this event. Normal events hold at least one + // change or effect. But it may be necessary to store selection + // events before the first change, in which case a special type of + // instance is created which doesn't hold any changes, with + // changes == startSelection == undefined + changes, + // The effects associated with this event + effects, + // Accumulated mapping (from addToHistory==false) that should be + // applied to events below this one. + mapped, + // The selection before this event + startSelection, + // Stores selection changes after this event, to be used for + // selection undo/redo. + selectionsAfter) { + this.changes = changes; + this.effects = effects; + this.mapped = mapped; + this.startSelection = startSelection; + this.selectionsAfter = selectionsAfter; + } + setSelAfter(after) { + return new HistEvent(this.changes, this.effects, this.mapped, this.startSelection, after); + } + toJSON() { + var _a, _b, _c; + return { + changes: (_a = this.changes) === null || _a === void 0 ? void 0 : _a.toJSON(), + mapped: (_b = this.mapped) === null || _b === void 0 ? void 0 : _b.toJSON(), + startSelection: (_c = this.startSelection) === null || _c === void 0 ? void 0 : _c.toJSON(), + selectionsAfter: this.selectionsAfter.map(s => s.toJSON()) + }; + } + static fromJSON(json) { + return new HistEvent(json.changes && ChangeSet.fromJSON(json.changes), [], json.mapped && ChangeDesc.fromJSON(json.mapped), json.startSelection && EditorSelection.fromJSON(json.startSelection), json.selectionsAfter.map(EditorSelection.fromJSON)); + } + // This does not check `addToHistory` and such, it assumes the + // transaction needs to be converted to an item. Returns null when + // there are no changes or effects in the transaction. + static fromTransaction(tr, selection) { + let effects = none$1; + for (let invert of tr.startState.facet(invertedEffects)) { + let result = invert(tr); + if (result.length) + effects = effects.concat(result); + } + if (!effects.length && tr.changes.empty) + return null; + return new HistEvent(tr.changes.invert(tr.startState.doc), effects, undefined, selection || tr.startState.selection, none$1); + } + static selection(selections) { + return new HistEvent(undefined, none$1, undefined, undefined, selections); + } + } + function updateBranch(branch, to, maxLen, newEvent) { + let start = to + 1 > maxLen + 20 ? to - maxLen - 1 : 0; + let newBranch = branch.slice(start, to); + newBranch.push(newEvent); + return newBranch; + } + function isAdjacent(a, b) { + let ranges = [], isAdjacent = false; + a.iterChangedRanges((f, t) => ranges.push(f, t)); + b.iterChangedRanges((_f, _t, f, t) => { + for (let i = 0; i < ranges.length;) { + let from = ranges[i++], to = ranges[i++]; + if (t >= from && f <= to) + isAdjacent = true; + } + }); + return isAdjacent; + } + function eqSelectionShape(a, b) { + return a.ranges.length == b.ranges.length && + a.ranges.filter((r, i) => r.empty != b.ranges[i].empty).length === 0; + } + function conc(a, b) { + return !a.length ? b : !b.length ? a : a.concat(b); + } + const none$1 = []; + const MaxSelectionsPerEvent = 200; + function addSelection(branch, selection) { + if (!branch.length) { + return [HistEvent.selection([selection])]; + } + else { + let lastEvent = branch[branch.length - 1]; + let sels = lastEvent.selectionsAfter.slice(Math.max(0, lastEvent.selectionsAfter.length - MaxSelectionsPerEvent)); + if (sels.length && sels[sels.length - 1].eq(selection)) + return branch; + sels.push(selection); + return updateBranch(branch, branch.length - 1, 1e9, lastEvent.setSelAfter(sels)); + } + } + // Assumes the top item has one or more selectionAfter values + function popSelection(branch) { + let last = branch[branch.length - 1]; + let newBranch = branch.slice(); + newBranch[branch.length - 1] = last.setSelAfter(last.selectionsAfter.slice(0, last.selectionsAfter.length - 1)); + return newBranch; + } + // Add a mapping to the top event in the given branch. If this maps + // away all the changes and effects in that item, drop it and + // propagate the mapping to the next item. + function addMappingToBranch(branch, mapping) { + if (!branch.length) + return branch; + let length = branch.length, selections = none$1; + while (length) { + let event = mapEvent(branch[length - 1], mapping, selections); + if (event.changes && !event.changes.empty || event.effects.length) { // Event survived mapping + let result = branch.slice(0, length); + result[length - 1] = event; + return result; + } + else { // Drop this event, since there's no changes or effects left + mapping = event.mapped; + length--; + selections = event.selectionsAfter; + } + } + return selections.length ? [HistEvent.selection(selections)] : none$1; + } + function mapEvent(event, mapping, extraSelections) { + let selections = conc(event.selectionsAfter.length ? event.selectionsAfter.map(s => s.map(mapping)) : none$1, extraSelections); + // Change-less events don't store mappings (they are always the last event in a branch) + if (!event.changes) + return HistEvent.selection(selections); + let mappedChanges = event.changes.map(mapping), before = mapping.mapDesc(event.changes, true); + let fullMapping = event.mapped ? event.mapped.composeDesc(before) : before; + return new HistEvent(mappedChanges, StateEffect.mapEffects(event.effects, mapping), fullMapping, event.startSelection.map(before), selections); + } + const joinableUserEvent = /^(input\.type|delete)($|\.)/; + class HistoryState { + constructor(done, undone, prevTime = 0, prevUserEvent = undefined) { + this.done = done; + this.undone = undone; + this.prevTime = prevTime; + this.prevUserEvent = prevUserEvent; + } + isolate() { + return this.prevTime ? new HistoryState(this.done, this.undone) : this; + } + addChanges(event, time, userEvent, newGroupDelay, maxLen) { + let done = this.done, lastEvent = done[done.length - 1]; + if (lastEvent && lastEvent.changes && !lastEvent.changes.empty && event.changes && + (!userEvent || joinableUserEvent.test(userEvent)) && + ((!lastEvent.selectionsAfter.length && + time - this.prevTime < newGroupDelay && + isAdjacent(lastEvent.changes, event.changes)) || + // For compose (but not compose.start) events, always join with previous event + userEvent == "input.type.compose")) { + done = updateBranch(done, done.length - 1, maxLen, new HistEvent(event.changes.compose(lastEvent.changes), conc(event.effects, lastEvent.effects), lastEvent.mapped, lastEvent.startSelection, none$1)); + } + else { + done = updateBranch(done, done.length, maxLen, event); + } + return new HistoryState(done, none$1, time, userEvent); + } + addSelection(selection, time, userEvent, newGroupDelay) { + let last = this.done.length ? this.done[this.done.length - 1].selectionsAfter : none$1; + if (last.length > 0 && + time - this.prevTime < newGroupDelay && + userEvent == this.prevUserEvent && userEvent && /^select($|\.)/.test(userEvent) && + eqSelectionShape(last[last.length - 1], selection)) + return this; + return new HistoryState(addSelection(this.done, selection), this.undone, time, userEvent); + } + addMapping(mapping) { + return new HistoryState(addMappingToBranch(this.done, mapping), addMappingToBranch(this.undone, mapping), this.prevTime, this.prevUserEvent); + } + pop(side, state, selection) { + let branch = side == 0 /* BranchName.Done */ ? this.done : this.undone; + if (branch.length == 0) + return null; + let event = branch[branch.length - 1]; + if (selection && event.selectionsAfter.length) { + return state.update({ + selection: event.selectionsAfter[event.selectionsAfter.length - 1], + annotations: fromHistory.of({ side, rest: popSelection(branch) }), + userEvent: side == 0 /* BranchName.Done */ ? "select.undo" : "select.redo", + scrollIntoView: true + }); + } + else if (!event.changes) { + return null; + } + else { + let rest = branch.length == 1 ? none$1 : branch.slice(0, branch.length - 1); + if (event.mapped) + rest = addMappingToBranch(rest, event.mapped); + return state.update({ + changes: event.changes, + selection: event.startSelection, + effects: event.effects, + annotations: fromHistory.of({ side, rest }), + filter: false, + userEvent: side == 0 /* BranchName.Done */ ? "undo" : "redo", + scrollIntoView: true + }); + } + } + } + HistoryState.empty = /*@__PURE__*/new HistoryState(none$1, none$1); + /** + Default key bindings for the undo history. + + - Mod-z: [`undo`](https://codemirror.net/6/docs/ref/#commands.undo). + - Mod-y (Mod-Shift-z on macOS) + Ctrl-Shift-z on Linux: [`redo`](https://codemirror.net/6/docs/ref/#commands.redo). + - Mod-u: [`undoSelection`](https://codemirror.net/6/docs/ref/#commands.undoSelection). + - Alt-u (Mod-Shift-u on macOS): [`redoSelection`](https://codemirror.net/6/docs/ref/#commands.redoSelection). + */ + const historyKeymap = [ + { key: "Mod-z", run: undo, preventDefault: true }, + { key: "Mod-y", mac: "Mod-Shift-z", run: redo, preventDefault: true }, + { linux: "Ctrl-Shift-z", run: redo, preventDefault: true }, + { key: "Mod-u", run: undoSelection, preventDefault: true }, + { key: "Alt-u", mac: "Mod-Shift-u", run: redoSelection, preventDefault: true } + ]; + + function updateSel(sel, by) { + return EditorSelection.create(sel.ranges.map(by), sel.mainIndex); + } + function setSel(state, selection) { + return state.update({ selection, scrollIntoView: true, userEvent: "select" }); + } + function moveSel({ state, dispatch }, how) { + let selection = updateSel(state.selection, how); + if (selection.eq(state.selection)) + return false; + dispatch(setSel(state, selection)); + return true; + } + function rangeEnd(range, forward) { + return EditorSelection.cursor(forward ? range.to : range.from); + } + function cursorByChar(view, forward) { + return moveSel(view, range => range.empty ? view.moveByChar(range, forward) : rangeEnd(range, forward)); + } + function ltrAtCursor(view) { + return view.textDirectionAt(view.state.selection.main.head) == Direction.LTR; + } + /** + Move the selection one character to the left (which is backward in + left-to-right text, forward in right-to-left text). + */ + const cursorCharLeft = view => cursorByChar(view, !ltrAtCursor(view)); + /** + Move the selection one character to the right. + */ + const cursorCharRight = view => cursorByChar(view, ltrAtCursor(view)); + function cursorByGroup(view, forward) { + return moveSel(view, range => range.empty ? view.moveByGroup(range, forward) : rangeEnd(range, forward)); + } + /** + Move the selection to the left across one group of word or + non-word (but also non-space) characters. + */ + const cursorGroupLeft = view => cursorByGroup(view, !ltrAtCursor(view)); + /** + Move the selection one group to the right. + */ + const cursorGroupRight = view => cursorByGroup(view, ltrAtCursor(view)); + function interestingNode(state, node, bracketProp) { + if (node.type.prop(bracketProp)) + return true; + let len = node.to - node.from; + return len && (len > 2 || /[^\s,.;:]/.test(state.sliceDoc(node.from, node.to))) || node.firstChild; + } + function moveBySyntax(state, start, forward) { + let pos = syntaxTree(state).resolveInner(start.head); + let bracketProp = forward ? NodeProp.closedBy : NodeProp.openedBy; + // Scan forward through child nodes to see if there's an interesting + // node ahead. + for (let at = start.head;;) { + let next = forward ? pos.childAfter(at) : pos.childBefore(at); + if (!next) + break; + if (interestingNode(state, next, bracketProp)) + pos = next; + else + at = forward ? next.to : next.from; + } + let bracket = pos.type.prop(bracketProp), match, newPos; + if (bracket && (match = forward ? matchBrackets(state, pos.from, 1) : matchBrackets(state, pos.to, -1)) && match.matched) + newPos = forward ? match.end.to : match.end.from; + else + newPos = forward ? pos.to : pos.from; + return EditorSelection.cursor(newPos, forward ? -1 : 1); + } + /** + Move the cursor over the next syntactic element to the left. + */ + const cursorSyntaxLeft = view => moveSel(view, range => moveBySyntax(view.state, range, !ltrAtCursor(view))); + /** + Move the cursor over the next syntactic element to the right. + */ + const cursorSyntaxRight = view => moveSel(view, range => moveBySyntax(view.state, range, ltrAtCursor(view))); + function cursorByLine(view, forward) { + return moveSel(view, range => { + if (!range.empty) + return rangeEnd(range, forward); + let moved = view.moveVertically(range, forward); + return moved.head != range.head ? moved : view.moveToLineBoundary(range, forward); + }); + } + /** + Move the selection one line up. + */ + const cursorLineUp = view => cursorByLine(view, false); + /** + Move the selection one line down. + */ + const cursorLineDown = view => cursorByLine(view, true); + function pageHeight(view) { + return Math.max(view.defaultLineHeight, Math.min(view.dom.clientHeight, innerHeight) - 5); + } + function cursorByPage(view, forward) { + let { state } = view, selection = updateSel(state.selection, range => { + return range.empty ? view.moveVertically(range, forward, pageHeight(view)) : rangeEnd(range, forward); + }); + if (selection.eq(state.selection)) + return false; + let startPos = view.coordsAtPos(state.selection.main.head); + let scrollRect = view.scrollDOM.getBoundingClientRect(); + let effect; + if (startPos && startPos.top > scrollRect.top && startPos.bottom < scrollRect.bottom && + startPos.top - scrollRect.top <= view.scrollDOM.scrollHeight - view.scrollDOM.scrollTop - view.scrollDOM.clientHeight) + effect = EditorView.scrollIntoView(selection.main.head, { y: "start", yMargin: startPos.top - scrollRect.top }); + view.dispatch(setSel(state, selection), { effects: effect }); + return true; + } + /** + Move the selection one page up. + */ + const cursorPageUp = view => cursorByPage(view, false); + /** + Move the selection one page down. + */ + const cursorPageDown = view => cursorByPage(view, true); + function moveByLineBoundary(view, start, forward) { + let line = view.lineBlockAt(start.head), moved = view.moveToLineBoundary(start, forward); + if (moved.head == start.head && moved.head != (forward ? line.to : line.from)) + moved = view.moveToLineBoundary(start, forward, false); + if (!forward && moved.head == line.from && line.length) { + let space = /^\s*/.exec(view.state.sliceDoc(line.from, Math.min(line.from + 100, line.to)))[0].length; + if (space && start.head != line.from + space) + moved = EditorSelection.cursor(line.from + space); + } + return moved; + } + /** + Move the selection to the next line wrap point, or to the end of + the line if there isn't one left on this line. + */ + const cursorLineBoundaryForward = view => moveSel(view, range => moveByLineBoundary(view, range, true)); + /** + Move the selection to previous line wrap point, or failing that to + the start of the line. If the line is indented, and the cursor + isn't already at the end of the indentation, this will move to the + end of the indentation instead of the start of the line. + */ + const cursorLineBoundaryBackward = view => moveSel(view, range => moveByLineBoundary(view, range, false)); + /** + Move the selection one line wrap point to the left. + */ + const cursorLineBoundaryLeft = view => moveSel(view, range => moveByLineBoundary(view, range, !ltrAtCursor(view))); + /** + Move the selection one line wrap point to the right. + */ + const cursorLineBoundaryRight = view => moveSel(view, range => moveByLineBoundary(view, range, ltrAtCursor(view))); + /** + Move the selection to the start of the line. + */ + const cursorLineStart = view => moveSel(view, range => EditorSelection.cursor(view.lineBlockAt(range.head).from, 1)); + /** + Move the selection to the end of the line. + */ + const cursorLineEnd = view => moveSel(view, range => EditorSelection.cursor(view.lineBlockAt(range.head).to, -1)); + function toMatchingBracket(state, dispatch, extend) { + let found = false, selection = updateSel(state.selection, range => { + let matching = matchBrackets(state, range.head, -1) + || matchBrackets(state, range.head, 1) + || (range.head > 0 && matchBrackets(state, range.head - 1, 1)) + || (range.head < state.doc.length && matchBrackets(state, range.head + 1, -1)); + if (!matching || !matching.end) + return range; + found = true; + let head = matching.start.from == range.head ? matching.end.to : matching.end.from; + return extend ? EditorSelection.range(range.anchor, head) : EditorSelection.cursor(head); + }); + if (!found) + return false; + dispatch(setSel(state, selection)); + return true; + } + /** + Move the selection to the bracket matching the one it is currently + on, if any. + */ + const cursorMatchingBracket = ({ state, dispatch }) => toMatchingBracket(state, dispatch, false); + function extendSel(view, how) { + let selection = updateSel(view.state.selection, range => { + let head = how(range); + return EditorSelection.range(range.anchor, head.head, head.goalColumn); + }); + if (selection.eq(view.state.selection)) + return false; + view.dispatch(setSel(view.state, selection)); + return true; + } + function selectByChar(view, forward) { + return extendSel(view, range => view.moveByChar(range, forward)); + } + /** + Move the selection head one character to the left, while leaving + the anchor in place. + */ + const selectCharLeft = view => selectByChar(view, !ltrAtCursor(view)); + /** + Move the selection head one character to the right. + */ + const selectCharRight = view => selectByChar(view, ltrAtCursor(view)); + function selectByGroup(view, forward) { + return extendSel(view, range => view.moveByGroup(range, forward)); + } + /** + Move the selection head one [group](https://codemirror.net/6/docs/ref/#commands.cursorGroupLeft) to + the left. + */ + const selectGroupLeft = view => selectByGroup(view, !ltrAtCursor(view)); + /** + Move the selection head one group to the right. + */ + const selectGroupRight = view => selectByGroup(view, ltrAtCursor(view)); + /** + Move the selection head over the next syntactic element to the left. + */ + const selectSyntaxLeft = view => extendSel(view, range => moveBySyntax(view.state, range, !ltrAtCursor(view))); + /** + Move the selection head over the next syntactic element to the right. + */ + const selectSyntaxRight = view => extendSel(view, range => moveBySyntax(view.state, range, ltrAtCursor(view))); + function selectByLine(view, forward) { + return extendSel(view, range => view.moveVertically(range, forward)); + } + /** + Move the selection head one line up. + */ + const selectLineUp = view => selectByLine(view, false); + /** + Move the selection head one line down. + */ + const selectLineDown = view => selectByLine(view, true); + function selectByPage(view, forward) { + return extendSel(view, range => view.moveVertically(range, forward, pageHeight(view))); + } + /** + Move the selection head one page up. + */ + const selectPageUp = view => selectByPage(view, false); + /** + Move the selection head one page down. + */ + const selectPageDown = view => selectByPage(view, true); + /** + Move the selection head to the next line boundary. + */ + const selectLineBoundaryForward = view => extendSel(view, range => moveByLineBoundary(view, range, true)); + /** + Move the selection head to the previous line boundary. + */ + const selectLineBoundaryBackward = view => extendSel(view, range => moveByLineBoundary(view, range, false)); + /** + Move the selection head one line boundary to the left. + */ + const selectLineBoundaryLeft = view => extendSel(view, range => moveByLineBoundary(view, range, !ltrAtCursor(view))); + /** + Move the selection head one line boundary to the right. + */ + const selectLineBoundaryRight = view => extendSel(view, range => moveByLineBoundary(view, range, ltrAtCursor(view))); + /** + Move the selection head to the start of the line. + */ + const selectLineStart = view => extendSel(view, range => EditorSelection.cursor(view.lineBlockAt(range.head).from)); + /** + Move the selection head to the end of the line. + */ + const selectLineEnd = view => extendSel(view, range => EditorSelection.cursor(view.lineBlockAt(range.head).to)); + /** + Move the selection to the start of the document. + */ + const cursorDocStart = ({ state, dispatch }) => { + dispatch(setSel(state, { anchor: 0 })); + return true; + }; + /** + Move the selection to the end of the document. + */ + const cursorDocEnd = ({ state, dispatch }) => { + dispatch(setSel(state, { anchor: state.doc.length })); + return true; + }; + /** + Move the selection head to the start of the document. + */ + const selectDocStart = ({ state, dispatch }) => { + dispatch(setSel(state, { anchor: state.selection.main.anchor, head: 0 })); + return true; + }; + /** + Move the selection head to the end of the document. + */ + const selectDocEnd = ({ state, dispatch }) => { + dispatch(setSel(state, { anchor: state.selection.main.anchor, head: state.doc.length })); + return true; + }; + /** + Select the entire document. + */ + const selectAll = ({ state, dispatch }) => { + dispatch(state.update({ selection: { anchor: 0, head: state.doc.length }, userEvent: "select" })); + return true; + }; + /** + Expand the selection to cover entire lines. + */ + const selectLine = ({ state, dispatch }) => { + let ranges = selectedLineBlocks(state).map(({ from, to }) => EditorSelection.range(from, Math.min(to + 1, state.doc.length))); + dispatch(state.update({ selection: EditorSelection.create(ranges), userEvent: "select" })); + return true; + }; + /** + Select the next syntactic construct that is larger than the + selection. Note that this will only work insofar as the language + [provider](https://codemirror.net/6/docs/ref/#language.language) you use builds up a full + syntax tree. + */ + const selectParentSyntax = ({ state, dispatch }) => { + let selection = updateSel(state.selection, range => { + var _a; + let context = syntaxTree(state).resolveInner(range.head, 1); + while (!((context.from < range.from && context.to >= range.to) || + (context.to > range.to && context.from <= range.from) || + !((_a = context.parent) === null || _a === void 0 ? void 0 : _a.parent))) + context = context.parent; + return EditorSelection.range(context.to, context.from); + }); + dispatch(setSel(state, selection)); + return true; + }; + /** + Simplify the current selection. When multiple ranges are selected, + reduce it to its main range. Otherwise, if the selection is + non-empty, convert it to a cursor selection. + */ + const simplifySelection = ({ state, dispatch }) => { + let cur = state.selection, selection = null; + if (cur.ranges.length > 1) + selection = EditorSelection.create([cur.main]); + else if (!cur.main.empty) + selection = EditorSelection.create([EditorSelection.cursor(cur.main.head)]); + if (!selection) + return false; + dispatch(setSel(state, selection)); + return true; + }; + function deleteBy(target, by) { + if (target.state.readOnly) + return false; + let event = "delete.selection", { state } = target; + let changes = state.changeByRange(range => { + let { from, to } = range; + if (from == to) { + let towards = by(from); + if (towards < from) { + event = "delete.backward"; + towards = skipAtomic(target, towards, false); + } + else if (towards > from) { + event = "delete.forward"; + towards = skipAtomic(target, towards, true); + } + from = Math.min(from, towards); + to = Math.max(to, towards); + } + else { + from = skipAtomic(target, from, false); + to = skipAtomic(target, from, true); + } + return from == to ? { range } : { changes: { from, to }, range: EditorSelection.cursor(from) }; + }); + if (changes.changes.empty) + return false; + target.dispatch(state.update(changes, { + scrollIntoView: true, + userEvent: event, + effects: event == "delete.selection" ? EditorView.announce.of(state.phrase("Selection deleted")) : undefined + })); + return true; + } + function skipAtomic(target, pos, forward) { + if (target instanceof EditorView) + for (let ranges of target.state.facet(EditorView.atomicRanges).map(f => f(target))) + ranges.between(pos, pos, (from, to) => { + if (from < pos && to > pos) + pos = forward ? to : from; + }); + return pos; + } + const deleteByChar = (target, forward) => deleteBy(target, pos => { + let { state } = target, line = state.doc.lineAt(pos), before, targetPos; + if (!forward && pos > line.from && pos < line.from + 200 && + !/[^ \t]/.test(before = line.text.slice(0, pos - line.from))) { + if (before[before.length - 1] == "\t") + return pos - 1; + let col = countColumn(before, state.tabSize), drop = col % getIndentUnit(state) || getIndentUnit(state); + for (let i = 0; i < drop && before[before.length - 1 - i] == " "; i++) + pos--; + targetPos = pos; + } + else { + targetPos = findClusterBreak(line.text, pos - line.from, forward, forward) + line.from; + if (targetPos == pos && line.number != (forward ? state.doc.lines : 1)) + targetPos += forward ? 1 : -1; + } + return targetPos; + }); + /** + Delete the selection, or, for cursor selections, the character + before the cursor. + */ + const deleteCharBackward = view => deleteByChar(view, false); + /** + Delete the selection or the character after the cursor. + */ + const deleteCharForward = view => deleteByChar(view, true); + const deleteByGroup = (target, forward) => deleteBy(target, start => { + let pos = start, { state } = target, line = state.doc.lineAt(pos); + let categorize = state.charCategorizer(pos); + for (let cat = null;;) { + if (pos == (forward ? line.to : line.from)) { + if (pos == start && line.number != (forward ? state.doc.lines : 1)) + pos += forward ? 1 : -1; + break; + } + let next = findClusterBreak(line.text, pos - line.from, forward) + line.from; + let nextChar = line.text.slice(Math.min(pos, next) - line.from, Math.max(pos, next) - line.from); + let nextCat = categorize(nextChar); + if (cat != null && nextCat != cat) + break; + if (nextChar != " " || pos != start) + cat = nextCat; + pos = next; + } + return pos; + }); + /** + Delete the selection or backward until the end of the next + [group](https://codemirror.net/6/docs/ref/#view.EditorView.moveByGroup), only skipping groups of + whitespace when they consist of a single space. + */ + const deleteGroupBackward = target => deleteByGroup(target, false); + /** + Delete the selection or forward until the end of the next group. + */ + const deleteGroupForward = target => deleteByGroup(target, true); + /** + Delete the selection, or, if it is a cursor selection, delete to + the end of the line. If the cursor is directly at the end of the + line, delete the line break after it. + */ + const deleteToLineEnd = view => deleteBy(view, pos => { + let lineEnd = view.lineBlockAt(pos).to; + return pos < lineEnd ? lineEnd : Math.min(view.state.doc.length, pos + 1); + }); + /** + Delete the selection, or, if it is a cursor selection, delete to + the start of the line. If the cursor is directly at the start of the + line, delete the line break before it. + */ + const deleteToLineStart = view => deleteBy(view, pos => { + let lineStart = view.lineBlockAt(pos).from; + return pos > lineStart ? lineStart : Math.max(0, pos - 1); + }); + /** + Replace each selection range with a line break, leaving the cursor + on the line before the break. + */ + const splitLine = ({ state, dispatch }) => { + if (state.readOnly) + return false; + let changes = state.changeByRange(range => { + return { changes: { from: range.from, to: range.to, insert: Text.of(["", ""]) }, + range: EditorSelection.cursor(range.from) }; + }); + dispatch(state.update(changes, { scrollIntoView: true, userEvent: "input" })); + return true; + }; + /** + Flip the characters before and after the cursor(s). + */ + const transposeChars = ({ state, dispatch }) => { + if (state.readOnly) + return false; + let changes = state.changeByRange(range => { + if (!range.empty || range.from == 0 || range.from == state.doc.length) + return { range }; + let pos = range.from, line = state.doc.lineAt(pos); + let from = pos == line.from ? pos - 1 : findClusterBreak(line.text, pos - line.from, false) + line.from; + let to = pos == line.to ? pos + 1 : findClusterBreak(line.text, pos - line.from, true) + line.from; + return { changes: { from, to, insert: state.doc.slice(pos, to).append(state.doc.slice(from, pos)) }, + range: EditorSelection.cursor(to) }; + }); + if (changes.changes.empty) + return false; + dispatch(state.update(changes, { scrollIntoView: true, userEvent: "move.character" })); + return true; + }; + function selectedLineBlocks(state) { + let blocks = [], upto = -1; + for (let range of state.selection.ranges) { + let startLine = state.doc.lineAt(range.from), endLine = state.doc.lineAt(range.to); + if (!range.empty && range.to == endLine.from) + endLine = state.doc.lineAt(range.to - 1); + if (upto >= startLine.number) { + let prev = blocks[blocks.length - 1]; + prev.to = endLine.to; + prev.ranges.push(range); + } + else { + blocks.push({ from: startLine.from, to: endLine.to, ranges: [range] }); + } + upto = endLine.number + 1; + } + return blocks; + } + function moveLine(state, dispatch, forward) { + if (state.readOnly) + return false; + let changes = [], ranges = []; + for (let block of selectedLineBlocks(state)) { + if (forward ? block.to == state.doc.length : block.from == 0) + continue; + let nextLine = state.doc.lineAt(forward ? block.to + 1 : block.from - 1); + let size = nextLine.length + 1; + if (forward) { + changes.push({ from: block.to, to: nextLine.to }, { from: block.from, insert: nextLine.text + state.lineBreak }); + for (let r of block.ranges) + ranges.push(EditorSelection.range(Math.min(state.doc.length, r.anchor + size), Math.min(state.doc.length, r.head + size))); + } + else { + changes.push({ from: nextLine.from, to: block.from }, { from: block.to, insert: state.lineBreak + nextLine.text }); + for (let r of block.ranges) + ranges.push(EditorSelection.range(r.anchor - size, r.head - size)); + } + } + if (!changes.length) + return false; + dispatch(state.update({ + changes, + scrollIntoView: true, + selection: EditorSelection.create(ranges, state.selection.mainIndex), + userEvent: "move.line" + })); + return true; + } + /** + Move the selected lines up one line. + */ + const moveLineUp = ({ state, dispatch }) => moveLine(state, dispatch, false); + /** + Move the selected lines down one line. + */ + const moveLineDown = ({ state, dispatch }) => moveLine(state, dispatch, true); + function copyLine(state, dispatch, forward) { + if (state.readOnly) + return false; + let changes = []; + for (let block of selectedLineBlocks(state)) { + if (forward) + changes.push({ from: block.from, insert: state.doc.slice(block.from, block.to) + state.lineBreak }); + else + changes.push({ from: block.to, insert: state.lineBreak + state.doc.slice(block.from, block.to) }); + } + dispatch(state.update({ changes, scrollIntoView: true, userEvent: "input.copyline" })); + return true; + } + /** + Create a copy of the selected lines. Keep the selection in the top copy. + */ + const copyLineUp = ({ state, dispatch }) => copyLine(state, dispatch, false); + /** + Create a copy of the selected lines. Keep the selection in the bottom copy. + */ + const copyLineDown = ({ state, dispatch }) => copyLine(state, dispatch, true); + /** + Delete selected lines. + */ + const deleteLine = view => { + if (view.state.readOnly) + return false; + let { state } = view, changes = state.changes(selectedLineBlocks(state).map(({ from, to }) => { + if (from > 0) + from--; + else if (to < state.doc.length) + to++; + return { from, to }; + })); + let selection = updateSel(state.selection, range => view.moveVertically(range, true)).map(changes); + view.dispatch({ changes, selection, scrollIntoView: true, userEvent: "delete.line" }); + return true; + }; + function isBetweenBrackets(state, pos) { + if (/\(\)|\[\]|\{\}/.test(state.sliceDoc(pos - 1, pos + 1))) + return { from: pos, to: pos }; + let context = syntaxTree(state).resolveInner(pos); + let before = context.childBefore(pos), after = context.childAfter(pos), closedBy; + if (before && after && before.to <= pos && after.from >= pos && + (closedBy = before.type.prop(NodeProp.closedBy)) && closedBy.indexOf(after.name) > -1 && + state.doc.lineAt(before.to).from == state.doc.lineAt(after.from).from) + return { from: before.to, to: after.from }; + return null; + } + /** + Replace the selection with a newline and indent the newly created + line(s). If the current line consists only of whitespace, this + will also delete that whitespace. When the cursor is between + matching brackets, an additional newline will be inserted after + the cursor. + */ + const insertNewlineAndIndent = /*@__PURE__*/newlineAndIndent(false); + /** + Create a blank, indented line below the current line. + */ + const insertBlankLine = /*@__PURE__*/newlineAndIndent(true); + function newlineAndIndent(atEof) { + return ({ state, dispatch }) => { + if (state.readOnly) + return false; + let changes = state.changeByRange(range => { + let { from, to } = range, line = state.doc.lineAt(from); + let explode = !atEof && from == to && isBetweenBrackets(state, from); + if (atEof) + from = to = (to <= line.to ? line : state.doc.lineAt(to)).to; + let cx = new IndentContext(state, { simulateBreak: from, simulateDoubleBreak: !!explode }); + let indent = getIndentation(cx, from); + if (indent == null) + indent = /^\s*/.exec(state.doc.lineAt(from).text)[0].length; + while (to < line.to && /\s/.test(line.text[to - line.from])) + to++; + if (explode) + ({ from, to } = explode); + else if (from > line.from && from < line.from + 100 && !/\S/.test(line.text.slice(0, from))) + from = line.from; + let insert = ["", indentString(state, indent)]; + if (explode) + insert.push(indentString(state, cx.lineIndent(line.from, -1))); + return { changes: { from, to, insert: Text.of(insert) }, + range: EditorSelection.cursor(from + 1 + insert[1].length) }; + }); + dispatch(state.update(changes, { scrollIntoView: true, userEvent: "input" })); + return true; + }; + } + function changeBySelectedLine(state, f) { + let atLine = -1; + return state.changeByRange(range => { + let changes = []; + for (let pos = range.from; pos <= range.to;) { + let line = state.doc.lineAt(pos); + if (line.number > atLine && (range.empty || range.to > line.from)) { + f(line, changes, range); + atLine = line.number; + } + pos = line.to + 1; + } + let changeSet = state.changes(changes); + return { changes, + range: EditorSelection.range(changeSet.mapPos(range.anchor, 1), changeSet.mapPos(range.head, 1)) }; + }); + } + /** + Auto-indent the selected lines. This uses the [indentation service + facet](https://codemirror.net/6/docs/ref/#language.indentService) as source for auto-indent + information. + */ + const indentSelection = ({ state, dispatch }) => { + if (state.readOnly) + return false; + let updated = Object.create(null); + let context = new IndentContext(state, { overrideIndentation: start => { + let found = updated[start]; + return found == null ? -1 : found; + } }); + let changes = changeBySelectedLine(state, (line, changes, range) => { + let indent = getIndentation(context, line.from); + if (indent == null) + return; + if (!/\S/.test(line.text)) + indent = 0; + let cur = /^\s*/.exec(line.text)[0]; + let norm = indentString(state, indent); + if (cur != norm || range.from < line.from + cur.length) { + updated[line.from] = indent; + changes.push({ from: line.from, to: line.from + cur.length, insert: norm }); + } + }); + if (!changes.changes.empty) + dispatch(state.update(changes, { userEvent: "indent" })); + return true; + }; + /** + Add a [unit](https://codemirror.net/6/docs/ref/#language.indentUnit) of indentation to all selected + lines. + */ + const indentMore = ({ state, dispatch }) => { + if (state.readOnly) + return false; + dispatch(state.update(changeBySelectedLine(state, (line, changes) => { + changes.push({ from: line.from, insert: state.facet(indentUnit) }); + }), { userEvent: "input.indent" })); + return true; + }; + /** + Remove a [unit](https://codemirror.net/6/docs/ref/#language.indentUnit) of indentation from all + selected lines. + */ + const indentLess = ({ state, dispatch }) => { + if (state.readOnly) + return false; + dispatch(state.update(changeBySelectedLine(state, (line, changes) => { + let space = /^\s*/.exec(line.text)[0]; + if (!space) + return; + let col = countColumn(space, state.tabSize), keep = 0; + let insert = indentString(state, Math.max(0, col - getIndentUnit(state))); + while (keep < space.length && keep < insert.length && space.charCodeAt(keep) == insert.charCodeAt(keep)) + keep++; + changes.push({ from: line.from + keep, to: line.from + space.length, insert: insert.slice(keep) }); + }), { userEvent: "delete.dedent" })); + return true; + }; + /** + Array of key bindings containing the Emacs-style bindings that are + available on macOS by default. + + - Ctrl-b: [`cursorCharLeft`](https://codemirror.net/6/docs/ref/#commands.cursorCharLeft) ([`selectCharLeft`](https://codemirror.net/6/docs/ref/#commands.selectCharLeft) with Shift) + - Ctrl-f: [`cursorCharRight`](https://codemirror.net/6/docs/ref/#commands.cursorCharRight) ([`selectCharRight`](https://codemirror.net/6/docs/ref/#commands.selectCharRight) with Shift) + - Ctrl-p: [`cursorLineUp`](https://codemirror.net/6/docs/ref/#commands.cursorLineUp) ([`selectLineUp`](https://codemirror.net/6/docs/ref/#commands.selectLineUp) with Shift) + - Ctrl-n: [`cursorLineDown`](https://codemirror.net/6/docs/ref/#commands.cursorLineDown) ([`selectLineDown`](https://codemirror.net/6/docs/ref/#commands.selectLineDown) with Shift) + - Ctrl-a: [`cursorLineStart`](https://codemirror.net/6/docs/ref/#commands.cursorLineStart) ([`selectLineStart`](https://codemirror.net/6/docs/ref/#commands.selectLineStart) with Shift) + - Ctrl-e: [`cursorLineEnd`](https://codemirror.net/6/docs/ref/#commands.cursorLineEnd) ([`selectLineEnd`](https://codemirror.net/6/docs/ref/#commands.selectLineEnd) with Shift) + - Ctrl-d: [`deleteCharForward`](https://codemirror.net/6/docs/ref/#commands.deleteCharForward) + - Ctrl-h: [`deleteCharBackward`](https://codemirror.net/6/docs/ref/#commands.deleteCharBackward) + - Ctrl-k: [`deleteToLineEnd`](https://codemirror.net/6/docs/ref/#commands.deleteToLineEnd) + - Ctrl-Alt-h: [`deleteGroupBackward`](https://codemirror.net/6/docs/ref/#commands.deleteGroupBackward) + - Ctrl-o: [`splitLine`](https://codemirror.net/6/docs/ref/#commands.splitLine) + - Ctrl-t: [`transposeChars`](https://codemirror.net/6/docs/ref/#commands.transposeChars) + - Ctrl-v: [`cursorPageDown`](https://codemirror.net/6/docs/ref/#commands.cursorPageDown) + - Alt-v: [`cursorPageUp`](https://codemirror.net/6/docs/ref/#commands.cursorPageUp) + */ + const emacsStyleKeymap = [ + { key: "Ctrl-b", run: cursorCharLeft, shift: selectCharLeft, preventDefault: true }, + { key: "Ctrl-f", run: cursorCharRight, shift: selectCharRight }, + { key: "Ctrl-p", run: cursorLineUp, shift: selectLineUp }, + { key: "Ctrl-n", run: cursorLineDown, shift: selectLineDown }, + { key: "Ctrl-a", run: cursorLineStart, shift: selectLineStart }, + { key: "Ctrl-e", run: cursorLineEnd, shift: selectLineEnd }, + { key: "Ctrl-d", run: deleteCharForward }, + { key: "Ctrl-h", run: deleteCharBackward }, + { key: "Ctrl-k", run: deleteToLineEnd }, + { key: "Ctrl-Alt-h", run: deleteGroupBackward }, + { key: "Ctrl-o", run: splitLine }, + { key: "Ctrl-t", run: transposeChars }, + { key: "Ctrl-v", run: cursorPageDown }, + ]; + /** + An array of key bindings closely sticking to platform-standard or + widely used bindings. (This includes the bindings from + [`emacsStyleKeymap`](https://codemirror.net/6/docs/ref/#commands.emacsStyleKeymap), with their `key` + property changed to `mac`.) + + - ArrowLeft: [`cursorCharLeft`](https://codemirror.net/6/docs/ref/#commands.cursorCharLeft) ([`selectCharLeft`](https://codemirror.net/6/docs/ref/#commands.selectCharLeft) with Shift) + - ArrowRight: [`cursorCharRight`](https://codemirror.net/6/docs/ref/#commands.cursorCharRight) ([`selectCharRight`](https://codemirror.net/6/docs/ref/#commands.selectCharRight) with Shift) + - Ctrl-ArrowLeft (Alt-ArrowLeft on macOS): [`cursorGroupLeft`](https://codemirror.net/6/docs/ref/#commands.cursorGroupLeft) ([`selectGroupLeft`](https://codemirror.net/6/docs/ref/#commands.selectGroupLeft) with Shift) + - Ctrl-ArrowRight (Alt-ArrowRight on macOS): [`cursorGroupRight`](https://codemirror.net/6/docs/ref/#commands.cursorGroupRight) ([`selectGroupRight`](https://codemirror.net/6/docs/ref/#commands.selectGroupRight) with Shift) + - Cmd-ArrowLeft (on macOS): [`cursorLineStart`](https://codemirror.net/6/docs/ref/#commands.cursorLineStart) ([`selectLineStart`](https://codemirror.net/6/docs/ref/#commands.selectLineStart) with Shift) + - Cmd-ArrowRight (on macOS): [`cursorLineEnd`](https://codemirror.net/6/docs/ref/#commands.cursorLineEnd) ([`selectLineEnd`](https://codemirror.net/6/docs/ref/#commands.selectLineEnd) with Shift) + - ArrowUp: [`cursorLineUp`](https://codemirror.net/6/docs/ref/#commands.cursorLineUp) ([`selectLineUp`](https://codemirror.net/6/docs/ref/#commands.selectLineUp) with Shift) + - ArrowDown: [`cursorLineDown`](https://codemirror.net/6/docs/ref/#commands.cursorLineDown) ([`selectLineDown`](https://codemirror.net/6/docs/ref/#commands.selectLineDown) with Shift) + - Cmd-ArrowUp (on macOS): [`cursorDocStart`](https://codemirror.net/6/docs/ref/#commands.cursorDocStart) ([`selectDocStart`](https://codemirror.net/6/docs/ref/#commands.selectDocStart) with Shift) + - Cmd-ArrowDown (on macOS): [`cursorDocEnd`](https://codemirror.net/6/docs/ref/#commands.cursorDocEnd) ([`selectDocEnd`](https://codemirror.net/6/docs/ref/#commands.selectDocEnd) with Shift) + - Ctrl-ArrowUp (on macOS): [`cursorPageUp`](https://codemirror.net/6/docs/ref/#commands.cursorPageUp) ([`selectPageUp`](https://codemirror.net/6/docs/ref/#commands.selectPageUp) with Shift) + - Ctrl-ArrowDown (on macOS): [`cursorPageDown`](https://codemirror.net/6/docs/ref/#commands.cursorPageDown) ([`selectPageDown`](https://codemirror.net/6/docs/ref/#commands.selectPageDown) with Shift) + - PageUp: [`cursorPageUp`](https://codemirror.net/6/docs/ref/#commands.cursorPageUp) ([`selectPageUp`](https://codemirror.net/6/docs/ref/#commands.selectPageUp) with Shift) + - PageDown: [`cursorPageDown`](https://codemirror.net/6/docs/ref/#commands.cursorPageDown) ([`selectPageDown`](https://codemirror.net/6/docs/ref/#commands.selectPageDown) with Shift) + - Home: [`cursorLineBoundaryBackward`](https://codemirror.net/6/docs/ref/#commands.cursorLineBoundaryBackward) ([`selectLineBoundaryBackward`](https://codemirror.net/6/docs/ref/#commands.selectLineBoundaryBackward) with Shift) + - End: [`cursorLineBoundaryForward`](https://codemirror.net/6/docs/ref/#commands.cursorLineBoundaryForward) ([`selectLineBoundaryForward`](https://codemirror.net/6/docs/ref/#commands.selectLineBoundaryForward) with Shift) + - Ctrl-Home (Cmd-Home on macOS): [`cursorDocStart`](https://codemirror.net/6/docs/ref/#commands.cursorDocStart) ([`selectDocStart`](https://codemirror.net/6/docs/ref/#commands.selectDocStart) with Shift) + - Ctrl-End (Cmd-Home on macOS): [`cursorDocEnd`](https://codemirror.net/6/docs/ref/#commands.cursorDocEnd) ([`selectDocEnd`](https://codemirror.net/6/docs/ref/#commands.selectDocEnd) with Shift) + - Enter: [`insertNewlineAndIndent`](https://codemirror.net/6/docs/ref/#commands.insertNewlineAndIndent) + - Ctrl-a (Cmd-a on macOS): [`selectAll`](https://codemirror.net/6/docs/ref/#commands.selectAll) + - Backspace: [`deleteCharBackward`](https://codemirror.net/6/docs/ref/#commands.deleteCharBackward) + - Delete: [`deleteCharForward`](https://codemirror.net/6/docs/ref/#commands.deleteCharForward) + - Ctrl-Backspace (Alt-Backspace on macOS): [`deleteGroupBackward`](https://codemirror.net/6/docs/ref/#commands.deleteGroupBackward) + - Ctrl-Delete (Alt-Delete on macOS): [`deleteGroupForward`](https://codemirror.net/6/docs/ref/#commands.deleteGroupForward) + - Cmd-Backspace (macOS): [`deleteToLineStart`](https://codemirror.net/6/docs/ref/#commands.deleteToLineStart). + - Cmd-Delete (macOS): [`deleteToLineEnd`](https://codemirror.net/6/docs/ref/#commands.deleteToLineEnd). + */ + const standardKeymap = /*@__PURE__*/[ + { key: "ArrowLeft", run: cursorCharLeft, shift: selectCharLeft, preventDefault: true }, + { key: "Mod-ArrowLeft", mac: "Alt-ArrowLeft", run: cursorGroupLeft, shift: selectGroupLeft, preventDefault: true }, + { mac: "Cmd-ArrowLeft", run: cursorLineBoundaryLeft, shift: selectLineBoundaryLeft, preventDefault: true }, + { key: "ArrowRight", run: cursorCharRight, shift: selectCharRight, preventDefault: true }, + { key: "Mod-ArrowRight", mac: "Alt-ArrowRight", run: cursorGroupRight, shift: selectGroupRight, preventDefault: true }, + { mac: "Cmd-ArrowRight", run: cursorLineBoundaryRight, shift: selectLineBoundaryRight, preventDefault: true }, + { key: "ArrowUp", run: cursorLineUp, shift: selectLineUp, preventDefault: true }, + { mac: "Cmd-ArrowUp", run: cursorDocStart, shift: selectDocStart }, + { mac: "Ctrl-ArrowUp", run: cursorPageUp, shift: selectPageUp }, + { key: "ArrowDown", run: cursorLineDown, shift: selectLineDown, preventDefault: true }, + { mac: "Cmd-ArrowDown", run: cursorDocEnd, shift: selectDocEnd }, + { mac: "Ctrl-ArrowDown", run: cursorPageDown, shift: selectPageDown }, + { key: "PageUp", run: cursorPageUp, shift: selectPageUp }, + { key: "PageDown", run: cursorPageDown, shift: selectPageDown }, + { key: "Home", run: cursorLineBoundaryBackward, shift: selectLineBoundaryBackward, preventDefault: true }, + { key: "Mod-Home", run: cursorDocStart, shift: selectDocStart }, + { key: "End", run: cursorLineBoundaryForward, shift: selectLineBoundaryForward, preventDefault: true }, + { key: "Mod-End", run: cursorDocEnd, shift: selectDocEnd }, + { key: "Enter", run: insertNewlineAndIndent }, + { key: "Mod-a", run: selectAll }, + { key: "Backspace", run: deleteCharBackward, shift: deleteCharBackward }, + { key: "Delete", run: deleteCharForward }, + { key: "Mod-Backspace", mac: "Alt-Backspace", run: deleteGroupBackward }, + { key: "Mod-Delete", mac: "Alt-Delete", run: deleteGroupForward }, + { mac: "Mod-Backspace", run: deleteToLineStart }, + { mac: "Mod-Delete", run: deleteToLineEnd } + ].concat(/*@__PURE__*/emacsStyleKeymap.map(b => ({ mac: b.key, run: b.run, shift: b.shift }))); + /** + The default keymap. Includes all bindings from + [`standardKeymap`](https://codemirror.net/6/docs/ref/#commands.standardKeymap) plus the following: + + - Alt-ArrowLeft (Ctrl-ArrowLeft on macOS): [`cursorSyntaxLeft`](https://codemirror.net/6/docs/ref/#commands.cursorSyntaxLeft) ([`selectSyntaxLeft`](https://codemirror.net/6/docs/ref/#commands.selectSyntaxLeft) with Shift) + - Alt-ArrowRight (Ctrl-ArrowRight on macOS): [`cursorSyntaxRight`](https://codemirror.net/6/docs/ref/#commands.cursorSyntaxRight) ([`selectSyntaxRight`](https://codemirror.net/6/docs/ref/#commands.selectSyntaxRight) with Shift) + - Alt-ArrowUp: [`moveLineUp`](https://codemirror.net/6/docs/ref/#commands.moveLineUp) + - Alt-ArrowDown: [`moveLineDown`](https://codemirror.net/6/docs/ref/#commands.moveLineDown) + - Shift-Alt-ArrowUp: [`copyLineUp`](https://codemirror.net/6/docs/ref/#commands.copyLineUp) + - Shift-Alt-ArrowDown: [`copyLineDown`](https://codemirror.net/6/docs/ref/#commands.copyLineDown) + - Escape: [`simplifySelection`](https://codemirror.net/6/docs/ref/#commands.simplifySelection) + - Ctrl-Enter (Comd-Enter on macOS): [`insertBlankLine`](https://codemirror.net/6/docs/ref/#commands.insertBlankLine) + - Alt-l (Ctrl-l on macOS): [`selectLine`](https://codemirror.net/6/docs/ref/#commands.selectLine) + - Ctrl-i (Cmd-i on macOS): [`selectParentSyntax`](https://codemirror.net/6/docs/ref/#commands.selectParentSyntax) + - Ctrl-[ (Cmd-[ on macOS): [`indentLess`](https://codemirror.net/6/docs/ref/#commands.indentLess) + - Ctrl-] (Cmd-] on macOS): [`indentMore`](https://codemirror.net/6/docs/ref/#commands.indentMore) + - Ctrl-Alt-\\ (Cmd-Alt-\\ on macOS): [`indentSelection`](https://codemirror.net/6/docs/ref/#commands.indentSelection) + - Shift-Ctrl-k (Shift-Cmd-k on macOS): [`deleteLine`](https://codemirror.net/6/docs/ref/#commands.deleteLine) + - Shift-Ctrl-\\ (Shift-Cmd-\\ on macOS): [`cursorMatchingBracket`](https://codemirror.net/6/docs/ref/#commands.cursorMatchingBracket) + - Ctrl-/ (Cmd-/ on macOS): [`toggleComment`](https://codemirror.net/6/docs/ref/#commands.toggleComment). + - Shift-Alt-a: [`toggleBlockComment`](https://codemirror.net/6/docs/ref/#commands.toggleBlockComment). + */ + const defaultKeymap = /*@__PURE__*/[ + { key: "Alt-ArrowLeft", mac: "Ctrl-ArrowLeft", run: cursorSyntaxLeft, shift: selectSyntaxLeft }, + { key: "Alt-ArrowRight", mac: "Ctrl-ArrowRight", run: cursorSyntaxRight, shift: selectSyntaxRight }, + { key: "Alt-ArrowUp", run: moveLineUp }, + { key: "Shift-Alt-ArrowUp", run: copyLineUp }, + { key: "Alt-ArrowDown", run: moveLineDown }, + { key: "Shift-Alt-ArrowDown", run: copyLineDown }, + { key: "Escape", run: simplifySelection }, + { key: "Mod-Enter", run: insertBlankLine }, + { key: "Alt-l", mac: "Ctrl-l", run: selectLine }, + { key: "Mod-i", run: selectParentSyntax, preventDefault: true }, + { key: "Mod-[", run: indentLess }, + { key: "Mod-]", run: indentMore }, + { key: "Mod-Alt-\\", run: indentSelection }, + { key: "Shift-Mod-k", run: deleteLine }, + { key: "Shift-Mod-\\", run: cursorMatchingBracket }, + { key: "Mod-/", run: toggleComment }, + { key: "Alt-A", run: toggleBlockComment } + ].concat(standardKeymap); + + function crelt() { + var elt = arguments[0]; + if (typeof elt == "string") elt = document.createElement(elt); + var i = 1, next = arguments[1]; + if (next && typeof next == "object" && next.nodeType == null && !Array.isArray(next)) { + for (var name in next) if (Object.prototype.hasOwnProperty.call(next, name)) { + var value = next[name]; + if (typeof value == "string") elt.setAttribute(name, value); + else if (value != null) elt[name] = value; + } + i++; } + for (; i < arguments.length; i++) add(elt, arguments[i]); + return elt + } - - var loadAll_1 = loadAll$1; - var load_1 = load$1; - - var loader$2 = { - loadAll: loadAll_1, - load: load_1 - }; - var load = loader$2.load; - - const logger$9 = getLogger('py-env'); - // Premise used to connect to the first available runtime (can be pyodide or others) - let runtime; - runtimeLoaded.subscribe(value => { - runtime = value; - }); - class PyEnv extends HTMLElement { - shadow; - wrapper; - code; - environment; - runtime; - env; - paths; - constructor() { - super(); - this.shadow = this.attachShadow({ mode: 'open' }); - this.wrapper = document.createElement('slot'); - } - connectedCallback() { - logger$9.info("The <py-env> tag is deprecated, please use <py-config> instead."); - this.code = this.innerHTML; - this.innerHTML = ''; - const env = []; - const paths = []; - this.environment = load(this.code); - if (this.environment === undefined) - return; - for (const entry of Array.isArray(this.environment) ? this.environment : []) { - if (typeof entry == 'string') { - env.push(entry); - } - else if (entry && typeof entry === 'object') { - const obj = entry; - for (const path of Array.isArray(obj.paths) ? obj.paths : []) { - if (typeof path === 'string') { - paths.push(path); - } - } - } - } - this.env = env; - this.paths = paths; - async function loadEnv() { - logger$9.info("Loading env: ", env); - await runtime.installPackage(env); - } - async function loadPaths() { - logger$9.info("Paths to load: ", paths); - for (const singleFile of paths) { - logger$9.info(` loading path: ${singleFile}`); - try { - await runtime.loadFromFile(singleFile); - } - catch (e) { - //Should we still export full error contents to console? - handleFetchError(e, singleFile); - } - } - logger$9.info("All paths loaded"); - } - addInitializer(loadEnv); - addInitializer(loadPaths); - } + function add(elt, child) { + if (typeof child == "string") { + elt.appendChild(document.createTextNode(child)); + } else if (child == null) ; else if (child.nodeType != null) { + elt.appendChild(child); + } else if (Array.isArray(child)) { + for (var i = 0; i < child.length; i++) add(elt, child[i]); + } else { + throw new RangeError("Unsupported child node: " + child) } + } - const logger$8 = getLogger('py-loader'); - class PyLoader extends BaseEvalElement { - widths; - label; - mount_name; - details; - operation; - constructor() { - super(); - } - connectedCallback() { - this.innerHTML = `<div id="pyscript_loading_splash" class="py-overlay"> + const basicNormalize = typeof String.prototype.normalize == "function" + ? x => x.normalize("NFKD") : x => x; + /** + A search cursor provides an iterator over text matches in a + document. + */ + class SearchCursor { + /** + Create a text cursor. The query is the search string, `from` to + `to` provides the region to search. + + When `normalize` is given, it will be called, on both the query + string and the content it is matched against, before comparing. + You can, for example, create a case-insensitive search by + passing `s => s.toLowerCase()`. + + Text is always normalized with + [`.normalize("NFKD")`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/normalize) + (when supported). + */ + constructor(text, query, from = 0, to = text.length, normalize, test) { + this.test = test; + /** + The current match (only holds a meaningful value after + [`next`](https://codemirror.net/6/docs/ref/#search.SearchCursor.next) has been called and when + `done` is false). + */ + this.value = { from: 0, to: 0 }; + /** + Whether the end of the iterated region has been reached. + */ + this.done = false; + this.matches = []; + this.buffer = ""; + this.bufferPos = 0; + this.iter = text.iterRange(from, to); + this.bufferStart = from; + this.normalize = normalize ? x => normalize(basicNormalize(x)) : basicNormalize; + this.query = this.normalize(query); + } + peek() { + if (this.bufferPos == this.buffer.length) { + this.bufferStart += this.buffer.length; + this.iter.next(); + if (this.iter.done) + return -1; + this.bufferPos = 0; + this.buffer = this.iter.value; + } + return codePointAt(this.buffer, this.bufferPos); + } + /** + Look for the next match. Updates the iterator's + [`value`](https://codemirror.net/6/docs/ref/#search.SearchCursor.value) and + [`done`](https://codemirror.net/6/docs/ref/#search.SearchCursor.done) properties. Should be called + at least once before using the cursor. + */ + next() { + while (this.matches.length) + this.matches.pop(); + return this.nextOverlapping(); + } + /** + The `next` method will ignore matches that partially overlap a + previous match. This method behaves like `next`, but includes + such matches. + */ + nextOverlapping() { + for (;;) { + let next = this.peek(); + if (next < 0) { + this.done = true; + return this; + } + let str = fromCodePoint(next), start = this.bufferStart + this.bufferPos; + this.bufferPos += codePointSize(next); + let norm = this.normalize(str); + for (let i = 0, pos = start;; i++) { + let code = norm.charCodeAt(i); + let match = this.match(code, pos); + if (match) { + this.value = match; + return this; + } + if (i == norm.length - 1) + break; + if (pos == start && i < str.length && str.charCodeAt(i) == code) + pos++; + } + } + } + match(code, pos) { + let match = null; + for (let i = 0; i < this.matches.length; i += 2) { + let index = this.matches[i], keep = false; + if (this.query.charCodeAt(index) == code) { + if (index == this.query.length - 1) { + match = { from: this.matches[i + 1], to: pos + 1 }; + } + else { + this.matches[i]++; + keep = true; + } + } + if (!keep) { + this.matches.splice(i, 2); + i -= 2; + } + } + if (this.query.charCodeAt(0) == code) { + if (this.query.length == 1) + match = { from: pos, to: pos + 1 }; + else + this.matches.push(1, pos); + } + if (match && this.test && !this.test(match.from, match.to, this.buffer, this.bufferPos)) + match = null; + return match; + } + } + if (typeof Symbol != "undefined") + SearchCursor.prototype[Symbol.iterator] = function () { return this; }; + + const empty = { from: -1, to: -1, match: /*@__PURE__*//.*/.exec("") }; + const baseFlags = "gm" + (/x/.unicode == null ? "" : "u"); + /** + This class is similar to [`SearchCursor`](https://codemirror.net/6/docs/ref/#search.SearchCursor) + but searches for a regular expression pattern instead of a plain + string. + */ + class RegExpCursor { + /** + Create a cursor that will search the given range in the given + document. `query` should be the raw pattern (as you'd pass it to + `new RegExp`). + */ + constructor(text, query, options, from = 0, to = text.length) { + this.text = text; + this.to = to; + this.curLine = ""; + /** + Set to `true` when the cursor has reached the end of the search + range. + */ + this.done = false; + /** + Will contain an object with the extent of the match and the + match object when [`next`](https://codemirror.net/6/docs/ref/#search.RegExpCursor.next) + sucessfully finds a match. + */ + this.value = empty; + if (/\\[sWDnr]|\n|\r|\[\^/.test(query)) + return new MultilineRegExpCursor(text, query, options, from, to); + this.re = new RegExp(query, baseFlags + ((options === null || options === void 0 ? void 0 : options.ignoreCase) ? "i" : "")); + this.test = options === null || options === void 0 ? void 0 : options.test; + this.iter = text.iter(); + let startLine = text.lineAt(from); + this.curLineStart = startLine.from; + this.matchPos = toCharEnd(text, from); + this.getLine(this.curLineStart); + } + getLine(skip) { + this.iter.next(skip); + if (this.iter.lineBreak) { + this.curLine = ""; + } + else { + this.curLine = this.iter.value; + if (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; + if (this.curLineStart > this.to) + this.curLine = ""; + else + this.getLine(0); + } + /** + Move to the next match, if there is one. + */ + next() { + for (let off = this.matchPos - this.curLineStart;;) { + this.re.lastIndex = off; + let match = this.matchPos <= this.to && this.re.exec(this.curLine); + if (match) { + let from = this.curLineStart + match.index, to = from + match[0].length; + this.matchPos = toCharEnd(this.text, to + (from == to ? 1 : 0)); + if (from == this.curLine.length) + this.nextLine(); + if ((from < to || from > this.value.to) && (!this.test || this.test(from, to, match))) { + this.value = { from, to, match }; + return this; + } + off = this.matchPos - this.curLineStart; + } + else if (this.curLineStart + this.curLine.length < this.to) { + this.nextLine(); + off = 0; + } + else { + this.done = true; + return this; + } + } + } + } + const flattened = /*@__PURE__*/new WeakMap(); + // Reusable (partially) flattened document strings + class FlattenedDoc { + constructor(from, text) { + this.from = from; + this.text = text; + } + get to() { return this.from + this.text.length; } + static get(doc, from, to) { + let cached = flattened.get(doc); + if (!cached || cached.from >= to || cached.to <= from) { + let flat = new FlattenedDoc(from, doc.sliceString(from, to)); + flattened.set(doc, flat); + return flat; + } + if (cached.from == from && cached.to == to) + return cached; + let { text, from: cachedFrom } = cached; + if (cachedFrom > from) { + text = doc.sliceString(from, cachedFrom) + text; + cachedFrom = from; + } + if (cached.to < to) + text += doc.sliceString(cached.to, to); + flattened.set(doc, new FlattenedDoc(cachedFrom, text)); + return new FlattenedDoc(from, text.slice(from - cachedFrom, to - cachedFrom)); + } + } + class MultilineRegExpCursor { + constructor(text, query, options, from, to) { + this.text = text; + this.to = to; + this.done = false; + this.value = empty; + this.matchPos = toCharEnd(text, from); + this.re = new RegExp(query, baseFlags + ((options === null || options === void 0 ? void 0 : options.ignoreCase) ? "i" : "")); + this.test = options === null || options === void 0 ? void 0 : options.test; + this.flat = FlattenedDoc.get(text, from, this.chunkEnd(from + 5000 /* Chunk.Base */)); + } + chunkEnd(pos) { + return pos >= this.to ? this.to : this.text.lineAt(pos).to; + } + next() { + for (;;) { + let off = this.re.lastIndex = this.matchPos - this.flat.from; + let match = this.re.exec(this.flat.text); + // Skip empty matches directly after the last match + if (match && !match[0] && match.index == off) { + this.re.lastIndex = off + 1; + match = this.re.exec(this.flat.text); + } + if (match) { + let from = this.flat.from + match.index, to = from + match[0].length; + // If a match goes almost to the end of a noncomplete chunk, try + // again, since it'll likely be able to match more + if ((this.flat.to >= this.to || match.index + match[0].length <= this.flat.text.length - 10) && + (!this.test || this.test(from, to, match))) { + this.value = { from, to, match }; + this.matchPos = toCharEnd(this.text, to + (from == to ? 1 : 0)); + return this; + } + } + if (this.flat.to == this.to) { + this.done = true; + return this; + } + // Grow the flattened doc + this.flat = FlattenedDoc.get(this.text, this.flat.from, this.chunkEnd(this.flat.from + this.flat.text.length * 2)); + } + } + } + if (typeof Symbol != "undefined") { + RegExpCursor.prototype[Symbol.iterator] = MultilineRegExpCursor.prototype[Symbol.iterator] = + function () { return this; }; + } + function validRegExp(source) { + try { + new RegExp(source, baseFlags); + return true; + } + catch (_a) { + return false; + } + } + function toCharEnd(text, pos) { + if (pos >= text.length) + return pos; + let line = text.lineAt(pos), next; + while (pos < line.to && (next = line.text.charCodeAt(pos - line.from)) >= 0xDC00 && next < 0xE000) + pos++; + return pos; + } + + function createLineDialog(view) { + let input = crelt("input", { class: "cm-textfield", name: "line" }); + let dom = crelt("form", { + class: "cm-gotoLine", + onkeydown: (event) => { + if (event.keyCode == 27) { // Escape + event.preventDefault(); + view.dispatch({ effects: dialogEffect.of(false) }); + view.focus(); + } + else if (event.keyCode == 13) { // Enter + event.preventDefault(); + go(); + } + }, + onsubmit: (event) => { + event.preventDefault(); + go(); + } + }, crelt("label", view.state.phrase("Go to line"), ": ", input), " ", crelt("button", { class: "cm-button", type: "submit" }, view.state.phrase("go"))); + function go() { + let match = /^([+-])?(\d+)?(:\d+)?(%)?$/.exec(input.value); + if (!match) + return; + let { state } = view, startLine = state.doc.lineAt(state.selection.main.head); + let [, sign, ln, cl, percent] = match; + let col = cl ? +cl.slice(1) : 0; + let line = ln ? +ln : startLine.number; + if (ln && percent) { + let pc = line / 100; + if (sign) + pc = pc * (sign == "-" ? -1 : 1) + (startLine.number / state.doc.lines); + line = Math.round(state.doc.lines * pc); + } + else if (ln && sign) { + line = line * (sign == "-" ? -1 : 1) + startLine.number; + } + let docLine = state.doc.line(Math.max(1, Math.min(state.doc.lines, line))); + view.dispatch({ + effects: dialogEffect.of(false), + selection: EditorSelection.cursor(docLine.from + Math.max(0, Math.min(col, docLine.length))), + scrollIntoView: true + }); + view.focus(); + } + return { dom }; + } + const dialogEffect = /*@__PURE__*/StateEffect.define(); + const dialogField = /*@__PURE__*/StateField.define({ + create() { return true; }, + update(value, tr) { + for (let e of tr.effects) + if (e.is(dialogEffect)) + value = e.value; + return value; + }, + provide: f => showPanel.from(f, val => val ? createLineDialog : null) + }); + /** + Command that shows a dialog asking the user for a line number, and + when a valid position is provided, moves the cursor to that line. + + Supports line numbers, relative line offsets prefixed with `+` or + `-`, document percentages suffixed with `%`, and an optional + column position by adding `:` and a second number after the line + number. + + The dialog can be styled with the `panel.gotoLine` theme + selector. + */ + const gotoLine = view => { + let panel = getPanel(view, createLineDialog); + if (!panel) { + let effects = [dialogEffect.of(true)]; + if (view.state.field(dialogField, false) == null) + effects.push(StateEffect.appendConfig.of([dialogField, baseTheme$1$1])); + view.dispatch({ effects }); + panel = getPanel(view, createLineDialog); + } + if (panel) + panel.dom.querySelector("input").focus(); + return true; + }; + const baseTheme$1$1 = /*@__PURE__*/EditorView.baseTheme({ + ".cm-panel.cm-gotoLine": { + padding: "2px 6px 4px", + "& label": { fontSize: "80%" } + } + }); + + const defaultHighlightOptions = { + highlightWordAroundCursor: false, + minSelectionLength: 1, + maxMatches: 100, + wholeWords: false + }; + const highlightConfig = /*@__PURE__*/Facet.define({ + combine(options) { + return combineConfig(options, defaultHighlightOptions, { + highlightWordAroundCursor: (a, b) => a || b, + minSelectionLength: Math.min, + maxMatches: Math.min + }); + } + }); + /** + This extension highlights text that matches the selection. It uses + the `"cm-selectionMatch"` class for the highlighting. When + `highlightWordAroundCursor` is enabled, the word at the cursor + itself will be highlighted with `"cm-selectionMatch-main"`. + */ + function highlightSelectionMatches(options) { + let ext = [defaultTheme, matchHighlighter]; + if (options) + ext.push(highlightConfig.of(options)); + return ext; + } + const matchDeco = /*@__PURE__*/Decoration.mark({ class: "cm-selectionMatch" }); + const mainMatchDeco = /*@__PURE__*/Decoration.mark({ class: "cm-selectionMatch cm-selectionMatch-main" }); + // Whether the characters directly outside the given positions are non-word characters + function insideWordBoundaries(check, state, from, to) { + return (from == 0 || check(state.sliceDoc(from - 1, from)) != CharCategory.Word) && + (to == state.doc.length || check(state.sliceDoc(to, to + 1)) != CharCategory.Word); + } + // Whether the characters directly at the given positions are word characters + function insideWord(check, state, from, to) { + return check(state.sliceDoc(from, from + 1)) == CharCategory.Word + && check(state.sliceDoc(to - 1, to)) == CharCategory.Word; + } + const matchHighlighter = /*@__PURE__*/ViewPlugin.fromClass(class { + constructor(view) { + this.decorations = this.getDeco(view); + } + update(update) { + if (update.selectionSet || update.docChanged || update.viewportChanged) + this.decorations = this.getDeco(update.view); + } + getDeco(view) { + let conf = view.state.facet(highlightConfig); + let { state } = view, sel = state.selection; + if (sel.ranges.length > 1) + return Decoration.none; + let range = sel.main, query, check = null; + if (range.empty) { + if (!conf.highlightWordAroundCursor) + return Decoration.none; + let word = state.wordAt(range.head); + if (!word) + return Decoration.none; + check = state.charCategorizer(range.head); + query = state.sliceDoc(word.from, word.to); + } + else { + let len = range.to - range.from; + if (len < conf.minSelectionLength || len > 200) + return Decoration.none; + if (conf.wholeWords) { + query = state.sliceDoc(range.from, range.to); // TODO: allow and include leading/trailing space? + check = state.charCategorizer(range.head); + if (!(insideWordBoundaries(check, state, range.from, range.to) + && insideWord(check, state, range.from, range.to))) + return Decoration.none; + } + else { + query = state.sliceDoc(range.from, range.to).trim(); + if (!query) + return Decoration.none; + } + } + let deco = []; + for (let part of view.visibleRanges) { + let cursor = new SearchCursor(state.doc, query, part.from, part.to); + while (!cursor.next().done) { + let { from, to } = cursor.value; + if (!check || insideWordBoundaries(check, state, from, to)) { + if (range.empty && from <= range.from && to >= range.to) + deco.push(mainMatchDeco.range(from, to)); + else if (from >= range.to || to <= range.from) + deco.push(matchDeco.range(from, to)); + if (deco.length > conf.maxMatches) + return Decoration.none; + } + } + } + return Decoration.set(deco); + } + }, { + decorations: v => v.decorations + }); + const defaultTheme = /*@__PURE__*/EditorView.baseTheme({ + ".cm-selectionMatch": { backgroundColor: "#99ff7780" }, + ".cm-searchMatch .cm-selectionMatch": { backgroundColor: "transparent" } + }); + // Select the words around the cursors. + const selectWord = ({ state, dispatch }) => { + let { selection } = state; + let newSel = EditorSelection.create(selection.ranges.map(range => state.wordAt(range.head) || EditorSelection.cursor(range.head)), selection.mainIndex); + if (newSel.eq(selection)) + return false; + dispatch(state.update({ selection: newSel })); + return true; + }; + // Find next occurrence of query relative to last cursor. Wrap around + // the document if there are no more matches. + function findNextOccurrence(state, query) { + let { main, ranges } = state.selection; + let word = state.wordAt(main.head), fullWord = word && word.from == main.from && word.to == main.to; + for (let cycled = false, cursor = new SearchCursor(state.doc, query, ranges[ranges.length - 1].to);;) { + cursor.next(); + if (cursor.done) { + if (cycled) + return null; + cursor = new SearchCursor(state.doc, query, 0, Math.max(0, ranges[ranges.length - 1].from - 1)); + cycled = true; + } + else { + if (cycled && ranges.some(r => r.from == cursor.value.from)) + continue; + if (fullWord) { + let word = state.wordAt(cursor.value.from); + if (!word || word.from != cursor.value.from || word.to != cursor.value.to) + continue; + } + return cursor.value; + } + } + } + /** + Select next occurrence of the current selection. Expand selection + to the surrounding word when the selection is empty. + */ + const selectNextOccurrence = ({ state, dispatch }) => { + let { ranges } = state.selection; + if (ranges.some(sel => sel.from === sel.to)) + return selectWord({ state, dispatch }); + let searchedText = state.sliceDoc(ranges[0].from, ranges[0].to); + if (state.selection.ranges.some(r => state.sliceDoc(r.from, r.to) != searchedText)) + return false; + let range = findNextOccurrence(state, searchedText); + if (!range) + return false; + dispatch(state.update({ + selection: state.selection.addRange(EditorSelection.range(range.from, range.to), false), + effects: EditorView.scrollIntoView(range.to) + })); + return true; + }; + + const searchConfigFacet = /*@__PURE__*/Facet.define({ + combine(configs) { + return combineConfig(configs, { + top: false, + caseSensitive: false, + literal: false, + wholeWord: false, + createPanel: view => new SearchPanel(view) + }); + } + }); + /** + A search query. Part of the editor's search state. + */ + class SearchQuery { + /** + Create a query object. + */ + constructor(config) { + this.search = config.search; + this.caseSensitive = !!config.caseSensitive; + this.literal = !!config.literal; + this.regexp = !!config.regexp; + this.replace = config.replace || ""; + this.valid = !!this.search && (!this.regexp || validRegExp(this.search)); + this.unquoted = this.literal ? this.search : this.search.replace(/\\([nrt\\])/g, (_, ch) => ch == "n" ? "\n" : ch == "r" ? "\r" : ch == "t" ? "\t" : "\\"); + this.wholeWord = !!config.wholeWord; + } + /** + Compare this query to another query. + */ + eq(other) { + return this.search == other.search && this.replace == other.replace && + this.caseSensitive == other.caseSensitive && this.regexp == other.regexp && + this.wholeWord == other.wholeWord; + } + /** + @internal + */ + create() { + return this.regexp ? new RegExpQuery(this) : new StringQuery(this); + } + /** + Get a search cursor for this query, searching through the given + range in the given state. + */ + getCursor(state, from = 0, to) { + let st = state.doc ? state : EditorState.create({ doc: state }); + if (to == null) + to = st.doc.length; + return this.regexp ? regexpCursor(this, st, from, to) : stringCursor(this, st, from, to); + } + } + class QueryType { + constructor(spec) { + this.spec = spec; + } + } + function stringCursor(spec, state, from, to) { + return new SearchCursor(state.doc, spec.unquoted, from, to, spec.caseSensitive ? undefined : x => x.toLowerCase(), spec.wholeWord ? stringWordTest(state.doc, state.charCategorizer(state.selection.main.head)) : undefined); + } + function stringWordTest(doc, categorizer) { + return (from, to, buf, bufPos) => { + if (bufPos > from || bufPos + buf.length < to) { + bufPos = Math.max(0, from - 2); + buf = doc.sliceString(bufPos, Math.min(doc.length, to + 2)); + } + return (categorizer(charBefore(buf, from - bufPos)) != CharCategory.Word || + categorizer(charAfter(buf, from - bufPos)) != CharCategory.Word) && + (categorizer(charAfter(buf, to - bufPos)) != CharCategory.Word || + categorizer(charBefore(buf, to - bufPos)) != CharCategory.Word); + }; + } + class StringQuery extends QueryType { + constructor(spec) { + super(spec); + } + nextMatch(state, curFrom, curTo) { + let cursor = stringCursor(this.spec, state, curTo, state.doc.length).nextOverlapping(); + if (cursor.done) + cursor = stringCursor(this.spec, state, 0, curFrom).nextOverlapping(); + return cursor.done ? null : cursor.value; + } + // Searching in reverse is, rather than implementing inverted search + // cursor, done by scanning chunk after chunk forward. + prevMatchInRange(state, from, to) { + for (let pos = to;;) { + let start = Math.max(from, pos - 10000 /* FindPrev.ChunkSize */ - this.spec.unquoted.length); + let cursor = stringCursor(this.spec, state, start, pos), range = null; + while (!cursor.nextOverlapping().done) + range = cursor.value; + if (range) + return range; + if (start == from) + return null; + pos -= 10000 /* FindPrev.ChunkSize */; + } + } + prevMatch(state, curFrom, curTo) { + return this.prevMatchInRange(state, 0, curFrom) || + this.prevMatchInRange(state, curTo, state.doc.length); + } + getReplacement(_result) { return this.spec.replace; } + matchAll(state, limit) { + let cursor = stringCursor(this.spec, state, 0, state.doc.length), ranges = []; + while (!cursor.next().done) { + if (ranges.length >= limit) + return null; + ranges.push(cursor.value); + } + return ranges; + } + highlight(state, from, to, add) { + let cursor = stringCursor(this.spec, state, Math.max(0, from - this.spec.unquoted.length), Math.min(to + this.spec.unquoted.length, state.doc.length)); + while (!cursor.next().done) + add(cursor.value.from, cursor.value.to); + } + } + function regexpCursor(spec, state, from, to) { + return new RegExpCursor(state.doc, spec.search, { + ignoreCase: !spec.caseSensitive, + test: spec.wholeWord ? regexpWordTest(state.charCategorizer(state.selection.main.head)) : undefined + }, from, to); + } + function charBefore(str, index) { + return str.slice(findClusterBreak(str, index, false), index); + } + function charAfter(str, index) { + return str.slice(index, findClusterBreak(str, index)); + } + function regexpWordTest(categorizer) { + return (_from, _to, match) => !match[0].length || + (categorizer(charBefore(match.input, match.index)) != CharCategory.Word || + categorizer(charAfter(match.input, match.index)) != CharCategory.Word) && + (categorizer(charAfter(match.input, match.index + match[0].length)) != CharCategory.Word || + categorizer(charBefore(match.input, match.index + match[0].length)) != CharCategory.Word); + } + class RegExpQuery extends QueryType { + nextMatch(state, curFrom, curTo) { + let cursor = regexpCursor(this.spec, state, curTo, state.doc.length).next(); + if (cursor.done) + cursor = regexpCursor(this.spec, state, 0, curFrom).next(); + return cursor.done ? null : cursor.value; + } + prevMatchInRange(state, from, to) { + for (let size = 1;; size++) { + let start = Math.max(from, to - size * 10000 /* FindPrev.ChunkSize */); + let cursor = regexpCursor(this.spec, state, start, to), range = null; + while (!cursor.next().done) + range = cursor.value; + if (range && (start == from || range.from > start + 10)) + return range; + if (start == from) + return null; + } + } + prevMatch(state, curFrom, curTo) { + return this.prevMatchInRange(state, 0, curFrom) || + this.prevMatchInRange(state, curTo, state.doc.length); + } + getReplacement(result) { + return this.spec.replace.replace(/\$([$&\d+])/g, (m, i) => i == "$" ? "$" + : i == "&" ? result.match[0] + : i != "0" && +i < result.match.length ? result.match[i] + : m); + } + matchAll(state, limit) { + let cursor = regexpCursor(this.spec, state, 0, state.doc.length), ranges = []; + while (!cursor.next().done) { + if (ranges.length >= limit) + return null; + ranges.push(cursor.value); + } + return ranges; + } + highlight(state, from, to, add) { + let cursor = regexpCursor(this.spec, state, Math.max(0, from - 250 /* RegExp.HighlightMargin */), Math.min(to + 250 /* RegExp.HighlightMargin */, state.doc.length)); + while (!cursor.next().done) + add(cursor.value.from, cursor.value.to); + } + } + /** + A state effect that updates the current search query. Note that + this only has an effect if the search state has been initialized + (by including [`search`](https://codemirror.net/6/docs/ref/#search.search) in your configuration or + by running [`openSearchPanel`](https://codemirror.net/6/docs/ref/#search.openSearchPanel) at least + once). + */ + const setSearchQuery = /*@__PURE__*/StateEffect.define(); + const togglePanel$1 = /*@__PURE__*/StateEffect.define(); + const searchState = /*@__PURE__*/StateField.define({ + create(state) { + return new SearchState(defaultQuery(state).create(), null); + }, + update(value, tr) { + for (let effect of tr.effects) { + if (effect.is(setSearchQuery)) + value = new SearchState(effect.value.create(), value.panel); + else if (effect.is(togglePanel$1)) + value = new SearchState(value.query, effect.value ? createSearchPanel : null); + } + return value; + }, + provide: f => showPanel.from(f, val => val.panel) + }); + class SearchState { + constructor(query, panel) { + this.query = query; + this.panel = panel; + } + } + const matchMark = /*@__PURE__*/Decoration.mark({ class: "cm-searchMatch" }), selectedMatchMark = /*@__PURE__*/Decoration.mark({ class: "cm-searchMatch cm-searchMatch-selected" }); + const searchHighlighter = /*@__PURE__*/ViewPlugin.fromClass(class { + constructor(view) { + this.view = view; + this.decorations = this.highlight(view.state.field(searchState)); + } + update(update) { + let state = update.state.field(searchState); + if (state != update.startState.field(searchState) || update.docChanged || update.selectionSet || update.viewportChanged) + this.decorations = this.highlight(state); + } + highlight({ query, panel }) { + if (!panel || !query.spec.valid) + return Decoration.none; + let { view } = this; + let builder = new RangeSetBuilder(); + for (let i = 0, ranges = view.visibleRanges, l = ranges.length; i < l; i++) { + let { from, to } = ranges[i]; + while (i < l - 1 && to > ranges[i + 1].from - 2 * 250 /* RegExp.HighlightMargin */) + to = ranges[++i].to; + query.highlight(view.state, from, to, (from, to) => { + let selected = view.state.selection.ranges.some(r => r.from == from && r.to == to); + builder.add(from, to, selected ? selectedMatchMark : matchMark); + }); + } + return builder.finish(); + } + }, { + decorations: v => v.decorations + }); + function searchCommand(f) { + return view => { + let state = view.state.field(searchState, false); + return state && state.query.spec.valid ? f(view, state) : openSearchPanel(view); + }; + } + /** + Open the search panel if it isn't already open, and move the + selection to the first match after the current main selection. + Will wrap around to the start of the document when it reaches the + end. + */ + const findNext = /*@__PURE__*/searchCommand((view, { query }) => { + let { to } = view.state.selection.main; + let next = query.nextMatch(view.state, to, to); + if (!next) + return false; + view.dispatch({ + selection: { anchor: next.from, head: next.to }, + scrollIntoView: true, + effects: announceMatch(view, next), + userEvent: "select.search" + }); + return true; + }); + /** + Move the selection to the previous instance of the search query, + before the current main selection. Will wrap past the start + of the document to start searching at the end again. + */ + const findPrevious = /*@__PURE__*/searchCommand((view, { query }) => { + let { state } = view, { from } = state.selection.main; + let range = query.prevMatch(state, from, from); + if (!range) + return false; + view.dispatch({ + selection: { anchor: range.from, head: range.to }, + scrollIntoView: true, + effects: announceMatch(view, range), + userEvent: "select.search" + }); + return true; + }); + /** + Select all instances of the search query. + */ + const selectMatches = /*@__PURE__*/searchCommand((view, { query }) => { + let ranges = query.matchAll(view.state, 1000); + if (!ranges || !ranges.length) + return false; + view.dispatch({ + selection: EditorSelection.create(ranges.map(r => EditorSelection.range(r.from, r.to))), + userEvent: "select.search.matches" + }); + return true; + }); + /** + Select all instances of the currently selected text. + */ + const selectSelectionMatches = ({ state, dispatch }) => { + let sel = state.selection; + if (sel.ranges.length > 1 || sel.main.empty) + return false; + let { from, to } = sel.main; + let ranges = [], main = 0; + for (let cur = new SearchCursor(state.doc, state.sliceDoc(from, to)); !cur.next().done;) { + if (ranges.length > 1000) + return false; + if (cur.value.from == from) + main = ranges.length; + ranges.push(EditorSelection.range(cur.value.from, cur.value.to)); + } + dispatch(state.update({ + selection: EditorSelection.create(ranges, main), + userEvent: "select.search.matches" + })); + return true; + }; + /** + Replace the current match of the search query. + */ + const replaceNext = /*@__PURE__*/searchCommand((view, { query }) => { + let { state } = view, { from, to } = state.selection.main; + if (state.readOnly) + return false; + let next = query.nextMatch(state, from, from); + if (!next) + return false; + let changes = [], selection, replacement; + let announce = []; + if (next.from == from && next.to == to) { + replacement = state.toText(query.getReplacement(next)); + changes.push({ from: next.from, to: next.to, insert: replacement }); + next = query.nextMatch(state, next.from, next.to); + announce.push(EditorView.announce.of(state.phrase("replaced match on line $", state.doc.lineAt(from).number) + ".")); + } + if (next) { + let off = changes.length == 0 || changes[0].from >= next.to ? 0 : next.to - next.from - replacement.length; + selection = { anchor: next.from - off, head: next.to - off }; + announce.push(announceMatch(view, next)); + } + view.dispatch({ + changes, selection, + scrollIntoView: !!selection, + effects: announce, + userEvent: "input.replace" + }); + return true; + }); + /** + Replace all instances of the search query with the given + replacement. + */ + const replaceAll = /*@__PURE__*/searchCommand((view, { query }) => { + if (view.state.readOnly) + return false; + let changes = query.matchAll(view.state, 1e9).map(match => { + let { from, to } = match; + return { from, to, insert: query.getReplacement(match) }; + }); + if (!changes.length) + return false; + let announceText = view.state.phrase("replaced $ matches", changes.length) + "."; + view.dispatch({ + changes, + effects: EditorView.announce.of(announceText), + userEvent: "input.replace.all" + }); + return true; + }); + function createSearchPanel(view) { + return view.state.facet(searchConfigFacet).createPanel(view); + } + function defaultQuery(state, fallback) { + var _a, _b, _c, _d; + let sel = state.selection.main; + let selText = sel.empty || sel.to > sel.from + 100 ? "" : state.sliceDoc(sel.from, sel.to); + if (fallback && !selText) + return fallback; + let config = state.facet(searchConfigFacet); + return new SearchQuery({ + search: ((_a = fallback === null || fallback === void 0 ? void 0 : fallback.literal) !== null && _a !== void 0 ? _a : config.literal) ? selText : selText.replace(/\n/g, "\\n"), + caseSensitive: (_b = fallback === null || fallback === void 0 ? void 0 : fallback.caseSensitive) !== null && _b !== void 0 ? _b : config.caseSensitive, + literal: (_c = fallback === null || fallback === void 0 ? void 0 : fallback.literal) !== null && _c !== void 0 ? _c : config.literal, + wholeWord: (_d = fallback === null || fallback === void 0 ? void 0 : fallback.wholeWord) !== null && _d !== void 0 ? _d : config.wholeWord + }); + } + /** + Make sure the search panel is open and focused. + */ + const openSearchPanel = view => { + let state = view.state.field(searchState, false); + if (state && state.panel) { + let panel = getPanel(view, createSearchPanel); + if (!panel) + return false; + let searchInput = panel.dom.querySelector("[main-field]"); + if (searchInput && searchInput != view.root.activeElement) { + let query = defaultQuery(view.state, state.query.spec); + if (query.valid) + view.dispatch({ effects: setSearchQuery.of(query) }); + searchInput.focus(); + searchInput.select(); + } + } + else { + view.dispatch({ effects: [ + togglePanel$1.of(true), + state ? setSearchQuery.of(defaultQuery(view.state, state.query.spec)) : StateEffect.appendConfig.of(searchExtensions) + ] }); + } + return true; + }; + /** + Close the search panel. + */ + const closeSearchPanel = view => { + let state = view.state.field(searchState, false); + if (!state || !state.panel) + return false; + let panel = getPanel(view, createSearchPanel); + if (panel && panel.dom.contains(view.root.activeElement)) + view.focus(); + view.dispatch({ effects: togglePanel$1.of(false) }); + return true; + }; + /** + Default search-related key bindings. + + - Mod-f: [`openSearchPanel`](https://codemirror.net/6/docs/ref/#search.openSearchPanel) + - F3, Mod-g: [`findNext`](https://codemirror.net/6/docs/ref/#search.findNext) + - Shift-F3, Shift-Mod-g: [`findPrevious`](https://codemirror.net/6/docs/ref/#search.findPrevious) + - Alt-g: [`gotoLine`](https://codemirror.net/6/docs/ref/#search.gotoLine) + - Mod-d: [`selectNextOccurrence`](https://codemirror.net/6/docs/ref/#search.selectNextOccurrence) + */ + const searchKeymap = [ + { key: "Mod-f", run: openSearchPanel, scope: "editor search-panel" }, + { key: "F3", run: findNext, shift: findPrevious, scope: "editor search-panel", preventDefault: true }, + { key: "Mod-g", run: findNext, shift: findPrevious, scope: "editor search-panel", preventDefault: true }, + { key: "Escape", run: closeSearchPanel, scope: "editor search-panel" }, + { key: "Mod-Shift-l", run: selectSelectionMatches }, + { key: "Alt-g", run: gotoLine }, + { key: "Mod-d", run: selectNextOccurrence, preventDefault: true }, + ]; + class SearchPanel { + constructor(view) { + this.view = view; + let query = this.query = view.state.field(searchState).query.spec; + this.commit = this.commit.bind(this); + this.searchField = crelt("input", { + value: query.search, + placeholder: phrase(view, "Find"), + "aria-label": phrase(view, "Find"), + class: "cm-textfield", + name: "search", + "main-field": "true", + onchange: this.commit, + onkeyup: this.commit + }); + this.replaceField = crelt("input", { + value: query.replace, + placeholder: phrase(view, "Replace"), + "aria-label": phrase(view, "Replace"), + class: "cm-textfield", + name: "replace", + onchange: this.commit, + onkeyup: this.commit + }); + this.caseField = crelt("input", { + type: "checkbox", + name: "case", + checked: query.caseSensitive, + onchange: this.commit + }); + this.reField = crelt("input", { + type: "checkbox", + name: "re", + checked: query.regexp, + onchange: this.commit + }); + this.wordField = crelt("input", { + type: "checkbox", + name: "word", + checked: query.wholeWord, + onchange: this.commit + }); + function button(name, onclick, content) { + return crelt("button", { class: "cm-button", name, onclick, type: "button" }, content); + } + this.dom = crelt("div", { onkeydown: (e) => this.keydown(e), class: "cm-search" }, [ + this.searchField, + button("next", () => findNext(view), [phrase(view, "next")]), + button("prev", () => findPrevious(view), [phrase(view, "previous")]), + button("select", () => selectMatches(view), [phrase(view, "all")]), + crelt("label", null, [this.caseField, phrase(view, "match case")]), + crelt("label", null, [this.reField, phrase(view, "regexp")]), + crelt("label", null, [this.wordField, phrase(view, "by word")]), + ...view.state.readOnly ? [] : [ + crelt("br"), + this.replaceField, + button("replace", () => replaceNext(view), [phrase(view, "replace")]), + button("replaceAll", () => replaceAll(view), [phrase(view, "replace all")]), + crelt("button", { + name: "close", + onclick: () => closeSearchPanel(view), + "aria-label": phrase(view, "close"), + type: "button" + }, ["×"]) + ] + ]); + } + commit() { + let query = new SearchQuery({ + search: this.searchField.value, + caseSensitive: this.caseField.checked, + regexp: this.reField.checked, + wholeWord: this.wordField.checked, + replace: this.replaceField.value, + }); + if (!query.eq(this.query)) { + this.query = query; + this.view.dispatch({ effects: setSearchQuery.of(query) }); + } + } + keydown(e) { + if (runScopeHandlers(this.view, e, "search-panel")) { + e.preventDefault(); + } + else if (e.keyCode == 13 && e.target == this.searchField) { + e.preventDefault(); + (e.shiftKey ? findPrevious : findNext)(this.view); + } + else if (e.keyCode == 13 && e.target == this.replaceField) { + e.preventDefault(); + replaceNext(this.view); + } + } + update(update) { + for (let tr of update.transactions) + for (let effect of tr.effects) { + if (effect.is(setSearchQuery) && !effect.value.eq(this.query)) + this.setQuery(effect.value); + } + } + setQuery(query) { + this.query = query; + this.searchField.value = query.search; + this.replaceField.value = query.replace; + this.caseField.checked = query.caseSensitive; + this.reField.checked = query.regexp; + this.wordField.checked = query.wholeWord; + } + mount() { + this.searchField.select(); + } + get pos() { return 80; } + get top() { return this.view.state.facet(searchConfigFacet).top; } + } + function phrase(view, phrase) { return view.state.phrase(phrase); } + const AnnounceMargin = 30; + const Break = /[\s\.,:;?!]/; + function announceMatch(view, { from, to }) { + let line = view.state.doc.lineAt(from), lineEnd = view.state.doc.lineAt(to).to; + let start = Math.max(line.from, from - AnnounceMargin), end = Math.min(lineEnd, to + AnnounceMargin); + let text = view.state.sliceDoc(start, end); + if (start != line.from) { + for (let i = 0; i < AnnounceMargin; i++) + if (!Break.test(text[i + 1]) && Break.test(text[i])) { + text = text.slice(i); + break; + } + } + if (end != lineEnd) { + for (let i = text.length - 1; i > text.length - AnnounceMargin; i--) + if (!Break.test(text[i - 1]) && Break.test(text[i])) { + text = text.slice(0, i); + break; + } + } + return EditorView.announce.of(`${view.state.phrase("current match")}. ${text} ${view.state.phrase("on line")} ${line.number}.`); + } + const baseTheme$2 = /*@__PURE__*/EditorView.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" } + }); + const searchExtensions = [ + searchState, + /*@__PURE__*/Prec.lowest(searchHighlighter), + baseTheme$2 + ]; + + /** + An instance of this is passed to completion source functions. + */ + class CompletionContext { + /** + Create a new completion context. (Mostly useful for testing + completion sources—in the editor, the extension will create + these for you.) + */ + constructor( + /** + The editor state that the completion happens in. + */ + state, + /** + The position at which the completion is happening. + */ + pos, + /** + Indicates whether completion was activated explicitly, or + implicitly by typing. The usual way to respond to this is to + only return completions when either there is part of a + completable entity before the cursor, or `explicit` is true. + */ + explicit) { + this.state = state; + this.pos = pos; + this.explicit = explicit; + /** + @internal + */ + this.abortListeners = []; + } + /** + Get the extent, content, and (if there is a token) type of the + token before `this.pos`. + */ + tokenBefore(types) { + let token = syntaxTree(this.state).resolveInner(this.pos, -1); + while (token && types.indexOf(token.name) < 0) + token = token.parent; + return token ? { from: token.from, to: this.pos, + text: this.state.sliceDoc(token.from, this.pos), + type: token.type } : null; + } + /** + Get the match of the given expression directly before the + cursor. + */ + matchBefore(expr) { + let line = this.state.doc.lineAt(this.pos); + let start = Math.max(line.from, this.pos - 250); + let str = line.text.slice(start - line.from, this.pos - line.from); + let found = str.search(ensureAnchor(expr, false)); + return found < 0 ? null : { from: start + found, to: this.pos, text: str.slice(found) }; + } + /** + Yields true when the query has been aborted. Can be useful in + asynchronous queries to avoid doing work that will be ignored. + */ + get aborted() { return this.abortListeners == null; } + /** + Allows you to register abort handlers, which will be called when + the query is + [aborted](https://codemirror.net/6/docs/ref/#autocomplete.CompletionContext.aborted). + */ + addEventListener(type, listener) { + if (type == "abort" && this.abortListeners) + this.abortListeners.push(listener); + } + } + function toSet(chars) { + let flat = Object.keys(chars).join(""); + let words = /\w/.test(flat); + if (words) + flat = flat.replace(/\w/g, ""); + return `[${words ? "\\w" : ""}${flat.replace(/[^\w\s]/g, "\\$&")}]`; + } + function prefixMatch(options) { + let first = Object.create(null), rest = Object.create(null); + for (let { label } of options) { + first[label[0]] = true; + for (let i = 1; i < label.length; i++) + rest[label[i]] = true; + } + let source = toSet(first) + toSet(rest) + "*$"; + return [new RegExp("^" + source), new RegExp(source)]; + } + /** + Given a a fixed array of options, return an autocompleter that + completes them. + */ + function completeFromList(list) { + let options = list.map(o => typeof o == "string" ? { label: o } : o); + let [validFor, match] = options.every(o => /^\w+$/.test(o.label)) ? [/\w*$/, /\w+$/] : prefixMatch(options); + return (context) => { + let token = context.matchBefore(match); + return token || context.explicit ? { from: token ? token.from : context.pos, options, validFor } : null; + }; + } + class Option { + constructor(completion, source, match) { + this.completion = completion; + this.source = source; + this.match = match; + } + } + function cur(state) { return state.selection.main.head; } + // Make sure the given regexp has a $ at its end and, if `start` is + // true, a ^ at its start. + function ensureAnchor(expr, start) { + var _a; + let { source } = expr; + let addStart = start && source[0] != "^", addEnd = source[source.length - 1] != "$"; + if (!addStart && !addEnd) + return expr; + return new RegExp(`${addStart ? "^" : ""}(?:${source})${addEnd ? "$" : ""}`, (_a = expr.flags) !== null && _a !== void 0 ? _a : (expr.ignoreCase ? "i" : "")); + } + /** + Helper function that returns a transaction spec which inserts a + completion's text in the main selection range, and any other + selection range that has the same text in front of it. + */ + function insertCompletionText(state, text, from, to) { + return Object.assign(Object.assign({}, state.changeByRange(range => { + if (range == state.selection.main) + return { + changes: { from: from, to: to, insert: text }, + range: EditorSelection.cursor(from + text.length) + }; + let len = to - from; + if (!range.empty || + len && state.sliceDoc(range.from - len, range.from) != state.sliceDoc(from, to)) + return { range }; + return { + changes: { from: range.from - len, to: range.from, insert: text }, + range: EditorSelection.cursor(range.from - len + text.length) + }; + })), { userEvent: "input.complete" }); + } + function applyCompletion(view, option) { + const apply = option.completion.apply || option.completion.label; + let result = option.source; + if (typeof apply == "string") + view.dispatch(insertCompletionText(view.state, apply, result.from, result.to)); + else + apply(view, option.completion, result.from, result.to); + } + const SourceCache = /*@__PURE__*/new WeakMap(); + function asSource(source) { + if (!Array.isArray(source)) + return source; + let known = SourceCache.get(source); + if (!known) + SourceCache.set(source, known = completeFromList(source)); + return known; + } + + // A pattern matcher for fuzzy completion matching. Create an instance + // once for a pattern, and then use that to match any number of + // completions. + class FuzzyMatcher { + constructor(pattern) { + this.pattern = pattern; + this.chars = []; + this.folded = []; + // Buffers reused by calls to `match` to track matched character + // positions. + this.any = []; + this.precise = []; + this.byWord = []; + for (let p = 0; p < pattern.length;) { + let char = codePointAt(pattern, p), size = codePointSize(char); + this.chars.push(char); + let part = pattern.slice(p, p + size), upper = part.toUpperCase(); + this.folded.push(codePointAt(upper == part ? part.toLowerCase() : upper, 0)); + p += size; + } + this.astral = pattern.length != this.chars.length; + } + // Matches a given word (completion) against the pattern (input). + // Will return null for no match, and otherwise an array that starts + // with the match score, followed by any number of `from, to` pairs + // indicating the matched parts of `word`. + // + // The score is a number that is more negative the worse the match + // is. See `Penalty` above. + match(word) { + if (this.pattern.length == 0) + return [0]; + if (word.length < this.pattern.length) + return null; + let { chars, folded, any, precise, byWord } = this; + // For single-character queries, only match when they occur right + // at the start + if (chars.length == 1) { + let first = codePointAt(word, 0); + return first == chars[0] ? [0, 0, codePointSize(first)] + : first == folded[0] ? [-200 /* Penalty.CaseFold */, 0, codePointSize(first)] : null; + } + let direct = word.indexOf(this.pattern); + if (direct == 0) + return [0, 0, this.pattern.length]; + let len = chars.length, anyTo = 0; + if (direct < 0) { + for (let i = 0, e = Math.min(word.length, 200); i < e && anyTo < len;) { + let next = codePointAt(word, i); + if (next == chars[anyTo] || next == folded[anyTo]) + any[anyTo++] = i; + i += codePointSize(next); + } + // No match, exit immediately + if (anyTo < len) + return null; + } + // This tracks the extent of the precise (non-folded, not + // necessarily adjacent) match + let preciseTo = 0; + // Tracks whether there is a match that hits only characters that + // appear to be starting words. `byWordFolded` is set to true when + // a case folded character is encountered in such a match + let byWordTo = 0, byWordFolded = false; + // If we've found a partial adjacent match, these track its state + let adjacentTo = 0, adjacentStart = -1, adjacentEnd = -1; + let hasLower = /[a-z]/.test(word), wordAdjacent = true; + // Go over the option's text, scanning for the various kinds of matches + for (let i = 0, e = Math.min(word.length, 200), prevType = 0 /* Tp.NonWord */; i < e && byWordTo < len;) { + let next = codePointAt(word, i); + if (direct < 0) { + if (preciseTo < len && next == chars[preciseTo]) + precise[preciseTo++] = i; + if (adjacentTo < len) { + if (next == chars[adjacentTo] || next == folded[adjacentTo]) { + if (adjacentTo == 0) + adjacentStart = i; + adjacentEnd = i + 1; + adjacentTo++; + } + else { + adjacentTo = 0; + } + } + } + let ch, type = next < 0xff + ? (next >= 48 && next <= 57 || next >= 97 && next <= 122 ? 2 /* Tp.Lower */ : next >= 65 && next <= 90 ? 1 /* Tp.Upper */ : 0 /* Tp.NonWord */) + : ((ch = fromCodePoint(next)) != ch.toLowerCase() ? 1 /* Tp.Upper */ : ch != ch.toUpperCase() ? 2 /* Tp.Lower */ : 0 /* Tp.NonWord */); + if (!i || type == 1 /* Tp.Upper */ && hasLower || prevType == 0 /* Tp.NonWord */ && type != 0 /* Tp.NonWord */) { + if (chars[byWordTo] == next || (folded[byWordTo] == next && (byWordFolded = true))) + byWord[byWordTo++] = i; + else if (byWord.length) + wordAdjacent = false; + } + prevType = type; + i += codePointSize(next); + } + if (byWordTo == len && byWord[0] == 0 && wordAdjacent) + return this.result(-100 /* Penalty.ByWord */ + (byWordFolded ? -200 /* Penalty.CaseFold */ : 0), byWord, word); + if (adjacentTo == len && adjacentStart == 0) + return [-200 /* Penalty.CaseFold */ - word.length, 0, adjacentEnd]; + if (direct > -1) + return [-700 /* Penalty.NotStart */ - word.length, direct, direct + this.pattern.length]; + if (adjacentTo == len) + return [-200 /* Penalty.CaseFold */ + -700 /* Penalty.NotStart */ - word.length, adjacentStart, adjacentEnd]; + if (byWordTo == len) + return this.result(-100 /* Penalty.ByWord */ + (byWordFolded ? -200 /* Penalty.CaseFold */ : 0) + -700 /* Penalty.NotStart */ + + (wordAdjacent ? 0 : -1100 /* Penalty.Gap */), byWord, word); + return chars.length == 2 ? null : this.result((any[0] ? -700 /* Penalty.NotStart */ : 0) + -200 /* Penalty.CaseFold */ + -1100 /* Penalty.Gap */, any, word); + } + result(score, positions, word) { + let result = [score - word.length], i = 1; + for (let pos of positions) { + let to = pos + (this.astral ? codePointSize(codePointAt(word, pos)) : 1); + if (i > 1 && result[i - 1] == pos) + result[i - 1] = to; + else { + result[i++] = pos; + result[i++] = to; + } + } + return result; + } + } + + const completionConfig = /*@__PURE__*/Facet.define({ + combine(configs) { + return combineConfig(configs, { + activateOnTyping: true, + selectOnOpen: true, + override: null, + closeOnBlur: true, + maxRenderedOptions: 100, + defaultKeymap: true, + optionClass: () => "", + aboveCursor: false, + icons: true, + addToOptions: [], + compareCompletions: (a, b) => a.label.localeCompare(b.label), + interactionDelay: 75 + }, { + defaultKeymap: (a, b) => a && b, + closeOnBlur: (a, b) => a && b, + icons: (a, b) => a && b, + optionClass: (a, b) => c => joinClass(a(c), b(c)), + addToOptions: (a, b) => a.concat(b) + }); + } + }); + function joinClass(a, b) { + return a ? b ? a + " " + b : a : b; + } + + function optionContent(config) { + let content = config.addToOptions.slice(); + if (config.icons) + content.push({ + render(completion) { + let icon = document.createElement("div"); + icon.classList.add("cm-completionIcon"); + if (completion.type) + icon.classList.add(...completion.type.split(/\s+/g).map(cls => "cm-completionIcon-" + cls)); + icon.setAttribute("aria-hidden", "true"); + return icon; + }, + position: 20 + }); + content.push({ + render(completion, _s, match) { + let labelElt = document.createElement("span"); + labelElt.className = "cm-completionLabel"; + let { label } = completion, off = 0; + for (let j = 1; j < match.length;) { + let from = match[j++], to = match[j++]; + if (from > off) + labelElt.appendChild(document.createTextNode(label.slice(off, from))); + let span = labelElt.appendChild(document.createElement("span")); + span.appendChild(document.createTextNode(label.slice(from, to))); + span.className = "cm-completionMatchedText"; + off = to; + } + if (off < label.length) + labelElt.appendChild(document.createTextNode(label.slice(off))); + return labelElt; + }, + position: 50 + }, { + render(completion) { + if (!completion.detail) + return null; + let detailElt = document.createElement("span"); + detailElt.className = "cm-completionDetail"; + detailElt.textContent = completion.detail; + return detailElt; + }, + position: 80 + }); + return content.sort((a, b) => a.position - b.position).map(a => a.render); + } + function rangeAroundSelected(total, selected, max) { + if (total <= max) + return { from: 0, to: total }; + if (selected < 0) + selected = 0; + if (selected <= (total >> 1)) { + let off = Math.floor(selected / max); + return { from: off * max, to: (off + 1) * max }; + } + let off = Math.floor((total - selected) / max); + return { from: total - (off + 1) * max, to: total - off * max }; + } + class CompletionTooltip { + constructor(view, stateField) { + this.view = view; + this.stateField = stateField; + this.info = null; + this.placeInfo = { + read: () => this.measureInfo(), + write: (pos) => this.positionInfo(pos), + key: this + }; + let cState = view.state.field(stateField); + let { options, selected } = cState.open; + let config = view.state.facet(completionConfig); + this.optionContent = optionContent(config); + this.optionClass = config.optionClass; + this.range = rangeAroundSelected(options.length, selected, config.maxRenderedOptions); + this.dom = document.createElement("div"); + this.dom.className = "cm-tooltip-autocomplete"; + this.dom.addEventListener("mousedown", (e) => { + for (let dom = e.target, match; dom && dom != this.dom; dom = dom.parentNode) { + if (dom.nodeName == "LI" && (match = /-(\d+)$/.exec(dom.id)) && +match[1] < options.length) { + applyCompletion(view, options[+match[1]]); + e.preventDefault(); + return; + } + } + }); + this.list = this.dom.appendChild(this.createListBox(options, cState.id, this.range)); + this.list.addEventListener("scroll", () => { + if (this.info) + this.view.requestMeasure(this.placeInfo); + }); + } + mount() { this.updateSel(); } + update(update) { + if (update.state.field(this.stateField) != update.startState.field(this.stateField)) + this.updateSel(); + } + positioned() { + if (this.info) + this.view.requestMeasure(this.placeInfo); + } + updateSel() { + let cState = this.view.state.field(this.stateField), open = cState.open; + if (open.selected > -1 && open.selected < this.range.from || open.selected >= this.range.to) { + this.range = rangeAroundSelected(open.options.length, open.selected, this.view.state.facet(completionConfig).maxRenderedOptions); + this.list.remove(); + this.list = this.dom.appendChild(this.createListBox(open.options, cState.id, this.range)); + this.list.addEventListener("scroll", () => { + if (this.info) + this.view.requestMeasure(this.placeInfo); + }); + } + if (this.updateSelectedOption(open.selected)) { + if (this.info) { + this.info.remove(); + this.info = null; + } + let { completion } = open.options[open.selected]; + let { info } = completion; + if (!info) + return; + let infoResult = typeof info === 'string' ? document.createTextNode(info) : info(completion); + if (!infoResult) + return; + if ('then' in infoResult) { + infoResult.then(node => { + if (node && this.view.state.field(this.stateField, false) == cState) + this.addInfoPane(node); + }).catch(e => logException(this.view.state, e, "completion info")); + } + else { + this.addInfoPane(infoResult); + } + } + } + addInfoPane(content) { + let dom = this.info = document.createElement("div"); + dom.className = "cm-tooltip cm-completionInfo"; + dom.appendChild(content); + this.dom.appendChild(dom); + this.view.requestMeasure(this.placeInfo); + } + updateSelectedOption(selected) { + let set = null; + for (let opt = this.list.firstChild, i = this.range.from; opt; opt = opt.nextSibling, i++) { + if (i == selected) { + if (!opt.hasAttribute("aria-selected")) { + opt.setAttribute("aria-selected", "true"); + set = opt; + } + } + else { + if (opt.hasAttribute("aria-selected")) + opt.removeAttribute("aria-selected"); + } + } + if (set) + scrollIntoView(this.list, set); + return set; + } + measureInfo() { + let sel = this.dom.querySelector("[aria-selected]"); + if (!sel || !this.info) + return null; + let win = this.dom.ownerDocument.defaultView || window; + let listRect = this.dom.getBoundingClientRect(); + let infoRect = this.info.getBoundingClientRect(); + let selRect = sel.getBoundingClientRect(); + if (selRect.top > Math.min(win.innerHeight, listRect.bottom) - 10 || selRect.bottom < Math.max(0, listRect.top) + 10) + return null; + let rtl = this.view.textDirection == Direction.RTL, left = rtl, narrow = false, maxWidth; + let top = "", bottom = ""; + let spaceLeft = listRect.left, spaceRight = win.innerWidth - listRect.right; + if (left && spaceLeft < Math.min(infoRect.width, spaceRight)) + left = false; + else if (!left && spaceRight < Math.min(infoRect.width, spaceLeft)) + left = true; + if (infoRect.width <= (left ? spaceLeft : spaceRight)) { + top = (Math.max(0, Math.min(selRect.top, win.innerHeight - infoRect.height)) - listRect.top) + "px"; + maxWidth = Math.min(400 /* Info.Width */, left ? spaceLeft : spaceRight) + "px"; + } + else { + narrow = true; + maxWidth = Math.min(400 /* Info.Width */, (rtl ? listRect.right : win.innerWidth - listRect.left) - 30 /* Info.Margin */) + "px"; + let spaceBelow = win.innerHeight - listRect.bottom; + if (spaceBelow >= infoRect.height || spaceBelow > listRect.top) // Below the completion + top = (selRect.bottom - listRect.top) + "px"; + else // Above it + bottom = (listRect.bottom - selRect.top) + "px"; + } + return { + top, bottom, maxWidth, + class: narrow ? (rtl ? "left-narrow" : "right-narrow") : left ? "left" : "right", + }; + } + positionInfo(pos) { + if (this.info) { + if (pos) { + this.info.style.top = pos.top; + this.info.style.bottom = pos.bottom; + this.info.style.maxWidth = pos.maxWidth; + this.info.className = "cm-tooltip cm-completionInfo cm-completionInfo-" + pos.class; + } + else { + this.info.style.top = "-1e6px"; + } + } + } + createListBox(options, id, range) { + const ul = document.createElement("ul"); + ul.id = id; + ul.setAttribute("role", "listbox"); + ul.setAttribute("aria-expanded", "true"); + ul.setAttribute("aria-label", this.view.state.phrase("Completions")); + for (let i = range.from; i < range.to; i++) { + let { completion, match } = options[i]; + const li = ul.appendChild(document.createElement("li")); + li.id = id + "-" + i; + li.setAttribute("role", "option"); + let cls = this.optionClass(completion); + if (cls) + li.className = cls; + for (let source of this.optionContent) { + let node = source(completion, this.view.state, match); + if (node) + li.appendChild(node); + } + } + if (range.from) + ul.classList.add("cm-completionListIncompleteTop"); + if (range.to < options.length) + ul.classList.add("cm-completionListIncompleteBottom"); + return ul; + } + } + // We allocate a new function instance every time the completion + // changes to force redrawing/repositioning of the tooltip + function completionTooltip(stateField) { + return (view) => new CompletionTooltip(view, stateField); + } + function scrollIntoView(container, element) { + let parent = container.getBoundingClientRect(); + let self = element.getBoundingClientRect(); + if (self.top < parent.top) + container.scrollTop -= parent.top - self.top; + else if (self.bottom > parent.bottom) + container.scrollTop += self.bottom - parent.bottom; + } + + // Used to pick a preferred option when two options with the same + // label occur in the result. + function score(option) { + return (option.boost || 0) * 100 + (option.apply ? 10 : 0) + (option.info ? 5 : 0) + + (option.type ? 1 : 0); + } + function sortOptions(active, state) { + let options = [], i = 0; + for (let a of active) + if (a.hasResult()) { + if (a.result.filter === false) { + let getMatch = a.result.getMatch; + for (let option of a.result.options) { + let match = [1e9 - i++]; + if (getMatch) + for (let n of getMatch(option)) + match.push(n); + options.push(new Option(option, a, match)); + } + } + else { + let matcher = new FuzzyMatcher(state.sliceDoc(a.from, a.to)), match; + for (let option of a.result.options) + if (match = matcher.match(option.label)) { + if (option.boost != null) + match[0] += option.boost; + options.push(new Option(option, a, match)); + } + } + } + let result = [], prev = null; + let compare = state.facet(completionConfig).compareCompletions; + for (let opt of options.sort((a, b) => (b.match[0] - a.match[0]) || compare(a.completion, b.completion))) { + if (!prev || prev.label != opt.completion.label || prev.detail != opt.completion.detail || + (prev.type != null && opt.completion.type != null && prev.type != opt.completion.type) || + prev.apply != opt.completion.apply) + result.push(opt); + else if (score(opt.completion) > score(prev)) + result[result.length - 1] = opt; + prev = opt.completion; + } + return result; + } + class CompletionDialog { + constructor(options, attrs, tooltip, timestamp, selected) { + this.options = options; + this.attrs = attrs; + this.tooltip = tooltip; + this.timestamp = timestamp; + this.selected = selected; + } + setSelected(selected, id) { + return selected == this.selected || selected >= this.options.length ? this + : new CompletionDialog(this.options, makeAttrs(id, selected), this.tooltip, this.timestamp, selected); + } + static build(active, state, id, prev, conf) { + let options = sortOptions(active, state); + if (!options.length) + return null; + let selected = state.facet(completionConfig).selectOnOpen ? 0 : -1; + if (prev && prev.selected != selected && prev.selected != -1) { + let selectedValue = prev.options[prev.selected].completion; + for (let i = 0; i < options.length; i++) + if (options[i].completion == selectedValue) { + selected = i; + break; + } + } + return new CompletionDialog(options, makeAttrs(id, selected), { + pos: active.reduce((a, b) => b.hasResult() ? Math.min(a, b.from) : a, 1e8), + create: completionTooltip(completionState), + above: conf.aboveCursor, + }, prev ? prev.timestamp : Date.now(), selected); + } + map(changes) { + return new CompletionDialog(this.options, this.attrs, Object.assign(Object.assign({}, this.tooltip), { pos: changes.mapPos(this.tooltip.pos) }), this.timestamp, this.selected); + } + } + class CompletionState { + constructor(active, id, open) { + this.active = active; + this.id = id; + this.open = open; + } + static start() { + return new CompletionState(none, "cm-ac-" + Math.floor(Math.random() * 2e6).toString(36), null); + } + update(tr) { + let { state } = tr, conf = state.facet(completionConfig); + let sources = conf.override || + state.languageDataAt("autocomplete", cur(state)).map(asSource); + let active = sources.map(source => { + let value = this.active.find(s => s.source == source) || + new ActiveSource(source, this.active.some(a => a.state != 0 /* State.Inactive */) ? 1 /* State.Pending */ : 0 /* State.Inactive */); + return value.update(tr, conf); + }); + if (active.length == this.active.length && active.every((a, i) => a == this.active[i])) + active = this.active; + let open = tr.selection || active.some(a => a.hasResult() && tr.changes.touchesRange(a.from, a.to)) || + !sameResults(active, this.active) ? CompletionDialog.build(active, state, this.id, this.open, conf) + : this.open && tr.docChanged ? this.open.map(tr.changes) : this.open; + if (!open && active.every(a => a.state != 1 /* State.Pending */) && active.some(a => a.hasResult())) + active = active.map(a => a.hasResult() ? new ActiveSource(a.source, 0 /* State.Inactive */) : a); + for (let effect of tr.effects) + if (effect.is(setSelectedEffect)) + open = open && open.setSelected(effect.value, this.id); + return active == this.active && open == this.open ? this : new CompletionState(active, this.id, open); + } + get tooltip() { return this.open ? this.open.tooltip : null; } + get attrs() { return this.open ? this.open.attrs : baseAttrs; } + } + function sameResults(a, b) { + if (a == b) + return true; + for (let iA = 0, iB = 0;;) { + while (iA < a.length && !a[iA].hasResult) + iA++; + while (iB < b.length && !b[iB].hasResult) + iB++; + let endA = iA == a.length, endB = iB == b.length; + if (endA || endB) + return endA == endB; + if (a[iA++].result != b[iB++].result) + return false; + } + } + const baseAttrs = { + "aria-autocomplete": "list" + }; + function makeAttrs(id, selected) { + let result = { + "aria-autocomplete": "list", + "aria-haspopup": "listbox", + "aria-controls": id + }; + if (selected > -1) + result["aria-activedescendant"] = id + "-" + selected; + return result; + } + const none = []; + function getUserEvent(tr) { + return tr.isUserEvent("input.type") ? "input" : tr.isUserEvent("delete.backward") ? "delete" : null; + } + class ActiveSource { + constructor(source, state, explicitPos = -1) { + this.source = source; + this.state = state; + this.explicitPos = explicitPos; + } + hasResult() { return false; } + update(tr, conf) { + let event = getUserEvent(tr), value = this; + if (event) + value = value.handleUserEvent(tr, event, conf); + else if (tr.docChanged) + value = value.handleChange(tr); + else if (tr.selection && value.state != 0 /* State.Inactive */) + value = new ActiveSource(value.source, 0 /* State.Inactive */); + for (let effect of tr.effects) { + if (effect.is(startCompletionEffect)) + value = new ActiveSource(value.source, 1 /* State.Pending */, effect.value ? cur(tr.state) : -1); + else if (effect.is(closeCompletionEffect)) + value = new ActiveSource(value.source, 0 /* State.Inactive */); + else if (effect.is(setActiveEffect)) + for (let active of effect.value) + if (active.source == value.source) + value = active; + } + return value; + } + handleUserEvent(tr, type, conf) { + return type == "delete" || !conf.activateOnTyping ? this.map(tr.changes) : new ActiveSource(this.source, 1 /* State.Pending */); + } + handleChange(tr) { + return tr.changes.touchesRange(cur(tr.startState)) ? new ActiveSource(this.source, 0 /* State.Inactive */) : this.map(tr.changes); + } + map(changes) { + return changes.empty || this.explicitPos < 0 ? this : new ActiveSource(this.source, this.state, changes.mapPos(this.explicitPos)); + } + } + class ActiveResult extends ActiveSource { + constructor(source, explicitPos, result, from, to) { + super(source, 2 /* State.Result */, explicitPos); + this.result = result; + this.from = from; + this.to = to; + } + hasResult() { return true; } + handleUserEvent(tr, type, conf) { + var _a; + let from = tr.changes.mapPos(this.from), to = tr.changes.mapPos(this.to, 1); + let pos = cur(tr.state); + if ((this.explicitPos < 0 ? pos <= from : pos < this.from) || + pos > to || + type == "delete" && cur(tr.startState) == this.from) + return new ActiveSource(this.source, type == "input" && conf.activateOnTyping ? 1 /* State.Pending */ : 0 /* State.Inactive */); + let explicitPos = this.explicitPos < 0 ? -1 : tr.changes.mapPos(this.explicitPos), updated; + if (checkValid(this.result.validFor, tr.state, from, to)) + return new ActiveResult(this.source, explicitPos, this.result, from, to); + if (this.result.update && + (updated = this.result.update(this.result, from, to, new CompletionContext(tr.state, pos, explicitPos >= 0)))) + return new ActiveResult(this.source, explicitPos, updated, updated.from, (_a = updated.to) !== null && _a !== void 0 ? _a : cur(tr.state)); + return new ActiveSource(this.source, 1 /* State.Pending */, explicitPos); + } + handleChange(tr) { + return tr.changes.touchesRange(this.from, this.to) ? new ActiveSource(this.source, 0 /* State.Inactive */) : this.map(tr.changes); + } + map(mapping) { + return mapping.empty ? this : + new ActiveResult(this.source, this.explicitPos < 0 ? -1 : mapping.mapPos(this.explicitPos), this.result, mapping.mapPos(this.from), mapping.mapPos(this.to, 1)); + } + } + function checkValid(validFor, state, from, to) { + if (!validFor) + return false; + let text = state.sliceDoc(from, to); + return typeof validFor == "function" ? validFor(text, from, to, state) : ensureAnchor(validFor, true).test(text); + } + const startCompletionEffect = /*@__PURE__*/StateEffect.define(); + const closeCompletionEffect = /*@__PURE__*/StateEffect.define(); + const setActiveEffect = /*@__PURE__*/StateEffect.define({ + map(sources, mapping) { return sources.map(s => s.map(mapping)); } + }); + const setSelectedEffect = /*@__PURE__*/StateEffect.define(); + const completionState = /*@__PURE__*/StateField.define({ + create() { return CompletionState.start(); }, + update(value, tr) { return value.update(tr); }, + provide: f => [ + showTooltip.from(f, val => val.tooltip), + EditorView.contentAttributes.from(f, state => state.attrs) + ] + }); + + /** + Returns a command that moves the completion selection forward or + backward by the given amount. + */ + function moveCompletionSelection(forward, by = "option") { + return (view) => { + let cState = view.state.field(completionState, false); + if (!cState || !cState.open || + Date.now() - cState.open.timestamp < view.state.facet(completionConfig).interactionDelay) + return false; + let step = 1, tooltip; + if (by == "page" && (tooltip = getTooltip(view, cState.open.tooltip))) + step = Math.max(2, Math.floor(tooltip.dom.offsetHeight / + tooltip.dom.querySelector("li").offsetHeight) - 1); + let { length } = cState.open.options; + let selected = cState.open.selected > -1 ? cState.open.selected + step * (forward ? 1 : -1) : forward ? 0 : length - 1; + if (selected < 0) + selected = by == "page" ? 0 : length - 1; + else if (selected >= length) + selected = by == "page" ? length - 1 : 0; + view.dispatch({ effects: setSelectedEffect.of(selected) }); + return true; + }; + } + /** + Accept the current completion. + */ + const acceptCompletion = (view) => { + let cState = view.state.field(completionState, false); + if (view.state.readOnly || !cState || !cState.open || cState.open.selected < 0 || + Date.now() - cState.open.timestamp < view.state.facet(completionConfig).interactionDelay) + return false; + applyCompletion(view, cState.open.options[cState.open.selected]); + return true; + }; + /** + Explicitly start autocompletion. + */ + const startCompletion = (view) => { + let cState = view.state.field(completionState, false); + if (!cState) + return false; + view.dispatch({ effects: startCompletionEffect.of(true) }); + return true; + }; + /** + Close the currently active completion. + */ + const closeCompletion = (view) => { + let cState = view.state.field(completionState, false); + if (!cState || !cState.active.some(a => a.state != 0 /* State.Inactive */)) + return false; + view.dispatch({ effects: closeCompletionEffect.of(null) }); + return true; + }; + class RunningQuery { + constructor(active, context) { + this.active = active; + this.context = context; + this.time = Date.now(); + this.updates = []; + // Note that 'undefined' means 'not done yet', whereas 'null' means + // 'query returned null'. + this.done = undefined; + } + } + const DebounceTime = 50, MaxUpdateCount = 50, MinAbortTime = 1000; + const completionPlugin = /*@__PURE__*/ViewPlugin.fromClass(class { + constructor(view) { + this.view = view; + this.debounceUpdate = -1; + this.running = []; + this.debounceAccept = -1; + this.composing = 0 /* CompositionState.None */; + for (let active of view.state.field(completionState).active) + if (active.state == 1 /* State.Pending */) + this.startQuery(active); + } + update(update) { + let cState = update.state.field(completionState); + if (!update.selectionSet && !update.docChanged && update.startState.field(completionState) == cState) + return; + let doesReset = update.transactions.some(tr => { + return (tr.selection || tr.docChanged) && !getUserEvent(tr); + }); + for (let i = 0; i < this.running.length; i++) { + let query = this.running[i]; + if (doesReset || + query.updates.length + update.transactions.length > MaxUpdateCount && Date.now() - query.time > MinAbortTime) { + for (let handler of query.context.abortListeners) { + try { + handler(); + } + catch (e) { + logException(this.view.state, e); + } + } + query.context.abortListeners = null; + this.running.splice(i--, 1); + } + else { + query.updates.push(...update.transactions); + } + } + if (this.debounceUpdate > -1) + clearTimeout(this.debounceUpdate); + this.debounceUpdate = cState.active.some(a => a.state == 1 /* State.Pending */ && !this.running.some(q => q.active.source == a.source)) + ? setTimeout(() => this.startUpdate(), DebounceTime) : -1; + if (this.composing != 0 /* CompositionState.None */) + for (let tr of update.transactions) { + if (getUserEvent(tr) == "input") + this.composing = 2 /* CompositionState.Changed */; + else if (this.composing == 2 /* CompositionState.Changed */ && tr.selection) + this.composing = 3 /* CompositionState.ChangedAndMoved */; + } + } + startUpdate() { + this.debounceUpdate = -1; + let { state } = this.view, cState = state.field(completionState); + for (let active of cState.active) { + if (active.state == 1 /* State.Pending */ && !this.running.some(r => r.active.source == active.source)) + this.startQuery(active); + } + } + startQuery(active) { + let { state } = this.view, pos = cur(state); + let context = new CompletionContext(state, pos, active.explicitPos == pos); + let pending = new RunningQuery(active, context); + this.running.push(pending); + Promise.resolve(active.source(context)).then(result => { + if (!pending.context.aborted) { + pending.done = result || null; + this.scheduleAccept(); + } + }, err => { + this.view.dispatch({ effects: closeCompletionEffect.of(null) }); + logException(this.view.state, err); + }); + } + scheduleAccept() { + if (this.running.every(q => q.done !== undefined)) + this.accept(); + else if (this.debounceAccept < 0) + this.debounceAccept = setTimeout(() => this.accept(), DebounceTime); + } + // For each finished query in this.running, try to create a result + // or, if appropriate, restart the query. + accept() { + var _a; + if (this.debounceAccept > -1) + clearTimeout(this.debounceAccept); + this.debounceAccept = -1; + let updated = []; + let conf = this.view.state.facet(completionConfig); + for (let i = 0; i < this.running.length; i++) { + let query = this.running[i]; + if (query.done === undefined) + continue; + this.running.splice(i--, 1); + if (query.done) { + let active = new ActiveResult(query.active.source, query.active.explicitPos, query.done, query.done.from, (_a = query.done.to) !== null && _a !== void 0 ? _a : cur(query.updates.length ? query.updates[0].startState : this.view.state)); + // Replay the transactions that happened since the start of + // the request and see if that preserves the result + for (let tr of query.updates) + active = active.update(tr, conf); + if (active.hasResult()) { + updated.push(active); + continue; + } + } + let current = this.view.state.field(completionState).active.find(a => a.source == query.active.source); + if (current && current.state == 1 /* State.Pending */) { + if (query.done == null) { + // Explicitly failed. Should clear the pending status if it + // hasn't been re-set in the meantime. + let active = new ActiveSource(query.active.source, 0 /* State.Inactive */); + for (let tr of query.updates) + active = active.update(tr, conf); + if (active.state != 1 /* State.Pending */) + updated.push(active); + } + else { + // Cleared by subsequent transactions. Restart. + this.startQuery(current); + } + } + } + if (updated.length) + this.view.dispatch({ effects: setActiveEffect.of(updated) }); + } + }, { + eventHandlers: { + blur() { + let state = this.view.state.field(completionState, false); + if (state && state.tooltip && this.view.state.facet(completionConfig).closeOnBlur) + this.view.dispatch({ effects: closeCompletionEffect.of(null) }); + }, + compositionstart() { + this.composing = 1 /* CompositionState.Started */; + }, + compositionend() { + if (this.composing == 3 /* CompositionState.ChangedAndMoved */) { + // Safari fires compositionend events synchronously, possibly + // from inside an update, so dispatch asynchronously to avoid reentrancy + setTimeout(() => this.view.dispatch({ effects: startCompletionEffect.of(false) }), 20); + } + this.composing = 0 /* CompositionState.None */; + } + } + }); + + const baseTheme$1 = /*@__PURE__*/EditorView.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", + listStyle: "none", + margin: 0, + padding: 0, + "& > li": { + overflowX: "hidden", + textOverflow: "ellipsis", + cursor: "pointer", + padding: "1px 3px", + lineHeight: 1.2 + }, + } + }, + "&light .cm-tooltip-autocomplete ul li[aria-selected]": { + background: "#17c", + color: "white", + }, + "&dark .cm-tooltip-autocomplete ul li[aria-selected]": { + background: "#347", + color: "white", + }, + ".cm-completionListIncompleteTop:before, .cm-completionListIncompleteBottom:after": { + content: '"···"', + opacity: 0.5, + display: "block", + textAlign: "center" + }, + ".cm-tooltip.cm-completionInfo": { + position: "absolute", + padding: "3px 9px", + width: "max-content", + maxWidth: `${400 /* Info.Width */}px`, + boxSizing: "border-box" + }, + ".cm-completionInfo.cm-completionInfo-left": { right: "100%" }, + ".cm-completionInfo.cm-completionInfo-right": { left: "100%" }, + ".cm-completionInfo.cm-completionInfo-left-narrow": { right: `${30 /* Info.Margin */}px` }, + ".cm-completionInfo.cm-completionInfo-right-narrow": { left: `${30 /* Info.Margin */}px` }, + "&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" + }, + ".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: "'🔑\uFE0E'" } // Disable emoji rendering + }, + ".cm-completionIcon-namespace": { + "&:after": { content: "'▢'" } + }, + ".cm-completionIcon-text": { + "&:after": { content: "'abc'", fontSize: "50%", verticalAlign: "middle" } + } + }); + + const defaults = { + brackets: ["(", "[", "{", "'", '"'], + before: ")]}:;>", + stringPrefixes: [] + }; + const closeBracketEffect = /*@__PURE__*/StateEffect.define({ + map(value, mapping) { + let mapped = mapping.mapPos(value, -1, MapMode.TrackAfter); + return mapped == null ? undefined : mapped; + } + }); + const skipBracketEffect = /*@__PURE__*/StateEffect.define({ + map(value, mapping) { return mapping.mapPos(value); } + }); + const closedBracket = /*@__PURE__*/new class extends RangeValue { + }; + closedBracket.startSide = 1; + closedBracket.endSide = -1; + const bracketState = /*@__PURE__*/StateField.define({ + create() { return RangeSet.empty; }, + update(value, tr) { + if (tr.selection) { + let lineStart = tr.state.doc.lineAt(tr.selection.main.head).from; + let prevLineStart = tr.startState.doc.lineAt(tr.startState.selection.main.head).from; + if (lineStart != tr.changes.mapPos(prevLineStart, -1)) + value = RangeSet.empty; + } + value = value.map(tr.changes); + for (let effect of tr.effects) { + if (effect.is(closeBracketEffect)) + value = value.update({ add: [closedBracket.range(effect.value, effect.value + 1)] }); + else if (effect.is(skipBracketEffect)) + value = value.update({ filter: from => from != effect.value }); + } + return value; + } + }); + /** + Extension to enable bracket-closing behavior. When a closeable + bracket is typed, its closing bracket is immediately inserted + after the cursor. When closing a bracket directly in front of a + closing bracket inserted by the extension, the cursor moves over + that bracket. + */ + function closeBrackets() { + return [inputHandler, bracketState]; + } + const definedClosing = "()[]{}<>"; + function closing(ch) { + for (let i = 0; i < definedClosing.length; i += 2) + if (definedClosing.charCodeAt(i) == ch) + return definedClosing.charAt(i + 1); + return fromCodePoint(ch < 128 ? ch : ch + 1); + } + function config(state, pos) { + return state.languageDataAt("closeBrackets", pos)[0] || defaults; + } + const android = typeof navigator == "object" && /*@__PURE__*//Android\b/.test(navigator.userAgent); + const inputHandler = /*@__PURE__*/EditorView.inputHandler.of((view, from, to, insert) => { + if ((android ? view.composing : view.compositionStarted) || view.state.readOnly) + return false; + let sel = view.state.selection.main; + if (insert.length > 2 || insert.length == 2 && codePointSize(codePointAt(insert, 0)) == 1 || + from != sel.from || to != sel.to) + return false; + let tr = insertBracket(view.state, insert); + if (!tr) + return false; + view.dispatch(tr); + return true; + }); + /** + Command that implements deleting a pair of matching brackets when + the cursor is between them. + */ + const deleteBracketPair = ({ state, dispatch }) => { + if (state.readOnly) + return false; + let conf = config(state, state.selection.main.head); + let tokens = conf.brackets || defaults.brackets; + let dont = null, changes = state.changeByRange(range => { + if (range.empty) { + let before = prevChar(state.doc, range.head); + for (let token of tokens) { + if (token == before && nextChar(state.doc, range.head) == closing(codePointAt(token, 0))) + return { changes: { from: range.head - token.length, to: range.head + token.length }, + range: EditorSelection.cursor(range.head - token.length) }; + } + } + return { range: dont = range }; + }); + if (!dont) + dispatch(state.update(changes, { scrollIntoView: true, userEvent: "delete.backward" })); + return !dont; + }; + /** + Close-brackets related key bindings. Binds Backspace to + [`deleteBracketPair`](https://codemirror.net/6/docs/ref/#autocomplete.deleteBracketPair). + */ + const closeBracketsKeymap = [ + { key: "Backspace", run: deleteBracketPair } + ]; + /** + Implements the extension's behavior on text insertion. If the + given string counts as a bracket in the language around the + selection, and replacing the selection with it requires custom + behavior (inserting a closing version or skipping past a + previously-closed bracket), this function returns a transaction + representing that custom behavior. (You only need this if you want + to programmatically insert brackets—the + [`closeBrackets`](https://codemirror.net/6/docs/ref/#autocomplete.closeBrackets) extension will + take care of running this for user input.) + */ + function insertBracket(state, bracket) { + let conf = config(state, state.selection.main.head); + let tokens = conf.brackets || defaults.brackets; + for (let tok of tokens) { + let closed = closing(codePointAt(tok, 0)); + if (bracket == tok) + return closed == tok ? handleSame(state, tok, tokens.indexOf(tok + tok + tok) > -1, conf) + : handleOpen(state, tok, closed, conf.before || defaults.before); + if (bracket == closed && closedBracketAt(state, state.selection.main.from)) + return handleClose(state, tok, closed); + } + return null; + } + function closedBracketAt(state, pos) { + let found = false; + state.field(bracketState).between(0, state.doc.length, from => { + if (from == pos) + found = true; + }); + return found; + } + function nextChar(doc, pos) { + let next = doc.sliceString(pos, pos + 2); + return next.slice(0, codePointSize(codePointAt(next, 0))); + } + function prevChar(doc, pos) { + let prev = doc.sliceString(pos - 2, pos); + return codePointSize(codePointAt(prev, 0)) == prev.length ? prev : prev.slice(1); + } + function handleOpen(state, open, close, closeBefore) { + let dont = null, changes = state.changeByRange(range => { + if (!range.empty) + return { changes: [{ insert: open, from: range.from }, { insert: close, from: range.to }], + effects: closeBracketEffect.of(range.to + open.length), + range: EditorSelection.range(range.anchor + open.length, range.head + open.length) }; + let next = nextChar(state.doc, range.head); + if (!next || /\s/.test(next) || closeBefore.indexOf(next) > -1) + return { changes: { insert: open + close, from: range.head }, + effects: closeBracketEffect.of(range.head + open.length), + range: EditorSelection.cursor(range.head + open.length) }; + return { range: dont = range }; + }); + return dont ? null : state.update(changes, { + scrollIntoView: true, + userEvent: "input.type" + }); + } + function handleClose(state, _open, close) { + let dont = null, moved = state.selection.ranges.map(range => { + if (range.empty && nextChar(state.doc, range.head) == close) + return EditorSelection.cursor(range.head + close.length); + return dont = range; + }); + return dont ? null : state.update({ + selection: EditorSelection.create(moved, state.selection.mainIndex), + scrollIntoView: true, + effects: state.selection.ranges.map(({ from }) => skipBracketEffect.of(from)) + }); + } + // Handles cases where the open and close token are the same, and + // possibly triple quotes (as in `"""abc"""`-style quoting). + function handleSame(state, token, allowTriple, config) { + let stringPrefixes = config.stringPrefixes || defaults.stringPrefixes; + let dont = null, changes = state.changeByRange(range => { + if (!range.empty) + return { changes: [{ insert: token, from: range.from }, { insert: token, from: range.to }], + effects: closeBracketEffect.of(range.to + token.length), + range: EditorSelection.range(range.anchor + token.length, range.head + token.length) }; + let pos = range.head, next = nextChar(state.doc, pos), start; + if (next == token) { + if (nodeStart(state, pos)) { + return { changes: { insert: token + token, from: pos }, + effects: closeBracketEffect.of(pos + token.length), + range: EditorSelection.cursor(pos + token.length) }; + } + else if (closedBracketAt(state, pos)) { + let isTriple = allowTriple && state.sliceDoc(pos, pos + token.length * 3) == token + token + token; + return { range: EditorSelection.cursor(pos + token.length * (isTriple ? 3 : 1)), + effects: skipBracketEffect.of(pos) }; + } + } + else if (allowTriple && state.sliceDoc(pos - 2 * token.length, pos) == token + token && + (start = canStartStringAt(state, pos - 2 * token.length, stringPrefixes)) > -1 && + nodeStart(state, start)) { + return { changes: { insert: token + token + token + token, from: pos }, + effects: closeBracketEffect.of(pos + token.length), + range: EditorSelection.cursor(pos + token.length) }; + } + else if (state.charCategorizer(pos)(next) != CharCategory.Word) { + if (canStartStringAt(state, pos, stringPrefixes) > -1 && !probablyInString(state, pos, token, stringPrefixes)) + return { changes: { insert: token + token, from: pos }, + effects: closeBracketEffect.of(pos + token.length), + range: EditorSelection.cursor(pos + token.length) }; + } + return { range: dont = range }; + }); + return dont ? null : state.update(changes, { + scrollIntoView: true, + userEvent: "input.type" + }); + } + function nodeStart(state, pos) { + let tree = syntaxTree(state).resolveInner(pos + 1); + return tree.parent && tree.from == pos; + } + function probablyInString(state, pos, quoteToken, prefixes) { + let node = syntaxTree(state).resolveInner(pos, -1); + let maxPrefix = prefixes.reduce((m, p) => Math.max(m, p.length), 0); + for (let i = 0; i < 5; i++) { + let start = state.sliceDoc(node.from, Math.min(node.to, node.from + quoteToken.length + maxPrefix)); + let quotePos = start.indexOf(quoteToken); + if (!quotePos || quotePos > -1 && prefixes.indexOf(start.slice(0, quotePos)) > -1) { + let first = node.firstChild; + while (first && first.from == node.from && first.to - first.from > quoteToken.length + quotePos) { + if (state.sliceDoc(first.to - quoteToken.length, first.to) == quoteToken) + return false; + first = first.firstChild; + } + return true; + } + let parent = node.to == pos && node.parent; + if (!parent) + break; + node = parent; + } + return false; + } + function canStartStringAt(state, pos, prefixes) { + let charCat = state.charCategorizer(pos); + if (charCat(state.sliceDoc(pos - 1, pos)) != CharCategory.Word) + return pos; + for (let prefix of prefixes) { + let start = pos - prefix.length; + if (state.sliceDoc(start, pos) == prefix && charCat(state.sliceDoc(start - 1, start)) != CharCategory.Word) + return start; + } + return -1; + } + + /** + Returns an extension that enables autocompletion. + */ + function autocompletion(config = {}) { + return [ + completionState, + completionConfig.of(config), + completionPlugin, + completionKeymapExt, + baseTheme$1 + ]; + } + /** + Basic keybindings for autocompletion. + + - Ctrl-Space: [`startCompletion`](https://codemirror.net/6/docs/ref/#autocomplete.startCompletion) + - Escape: [`closeCompletion`](https://codemirror.net/6/docs/ref/#autocomplete.closeCompletion) + - ArrowDown: [`moveCompletionSelection`](https://codemirror.net/6/docs/ref/#autocomplete.moveCompletionSelection)`(true)` + - ArrowUp: [`moveCompletionSelection`](https://codemirror.net/6/docs/ref/#autocomplete.moveCompletionSelection)`(false)` + - PageDown: [`moveCompletionSelection`](https://codemirror.net/6/docs/ref/#autocomplete.moveCompletionSelection)`(true, "page")` + - PageDown: [`moveCompletionSelection`](https://codemirror.net/6/docs/ref/#autocomplete.moveCompletionSelection)`(true, "page")` + - Enter: [`acceptCompletion`](https://codemirror.net/6/docs/ref/#autocomplete.acceptCompletion) + */ + const completionKeymap = [ + { key: "Ctrl-Space", run: startCompletion }, + { key: "Escape", run: closeCompletion }, + { key: "ArrowDown", run: /*@__PURE__*/moveCompletionSelection(true) }, + { key: "ArrowUp", run: /*@__PURE__*/moveCompletionSelection(false) }, + { key: "PageDown", run: /*@__PURE__*/moveCompletionSelection(true, "page") }, + { key: "PageUp", run: /*@__PURE__*/moveCompletionSelection(false, "page") }, + { key: "Enter", run: acceptCompletion } + ]; + const completionKeymapExt = /*@__PURE__*/Prec.highest(/*@__PURE__*/keymap.computeN([completionConfig], state => state.facet(completionConfig).defaultKeymap ? [completionKeymap] : [])); + + class SelectedDiagnostic { + constructor(from, to, diagnostic) { + this.from = from; + this.to = to; + this.diagnostic = diagnostic; + } + } + class LintState { + constructor(diagnostics, panel, selected) { + this.diagnostics = diagnostics; + this.panel = panel; + this.selected = selected; + } + static init(diagnostics, panel, state) { + // Filter the list of diagnostics for which to create markers + let markedDiagnostics = diagnostics; + let diagnosticFilter = state.facet(lintConfig).markerFilter; + if (diagnosticFilter) + markedDiagnostics = diagnosticFilter(markedDiagnostics); + let ranges = Decoration.set(markedDiagnostics.map((d) => { + // For zero-length ranges or ranges covering only a line break, create a widget + return d.from == d.to || (d.from == d.to - 1 && state.doc.lineAt(d.from).to == d.from) + ? Decoration.widget({ + widget: new DiagnosticWidget(d), + diagnostic: d + }).range(d.from) + : Decoration.mark({ + attributes: { class: "cm-lintRange cm-lintRange-" + d.severity }, + diagnostic: d + }).range(d.from, d.to); + }), true); + return new LintState(ranges, panel, findDiagnostic(ranges)); + } + } + function findDiagnostic(diagnostics, diagnostic = null, after = 0) { + let found = null; + diagnostics.between(after, 1e9, (from, to, { spec }) => { + if (diagnostic && spec.diagnostic != diagnostic) + return; + found = new SelectedDiagnostic(from, to, spec.diagnostic); + return false; + }); + return found; + } + function hideTooltip(tr, tooltip) { + return !!(tr.effects.some(e => e.is(setDiagnosticsEffect)) || tr.changes.touchesRange(tooltip.pos)); + } + function maybeEnableLint(state, effects) { + return state.field(lintState, false) ? effects : effects.concat(StateEffect.appendConfig.of([ + lintState, + EditorView.decorations.compute([lintState], state => { + let { selected, panel } = state.field(lintState); + return !selected || !panel || selected.from == selected.to ? Decoration.none : Decoration.set([ + activeMark.range(selected.from, selected.to) + ]); + }), + hoverTooltip(lintTooltip, { hideOn: hideTooltip }), + baseTheme + ])); + } + /** + Returns a transaction spec which updates the current set of + diagnostics, and enables the lint extension if if wasn't already + active. + */ + function setDiagnostics(state, diagnostics) { + return { + effects: maybeEnableLint(state, [setDiagnosticsEffect.of(diagnostics)]) + }; + } + /** + The state effect that updates the set of active diagnostics. Can + be useful when writing an extension that needs to track these. + */ + const setDiagnosticsEffect = /*@__PURE__*/StateEffect.define(); + const togglePanel = /*@__PURE__*/StateEffect.define(); + const movePanelSelection = /*@__PURE__*/StateEffect.define(); + const lintState = /*@__PURE__*/StateField.define({ + create() { + return new LintState(Decoration.none, null, null); + }, + update(value, tr) { + if (tr.docChanged) { + let mapped = value.diagnostics.map(tr.changes), selected = null; + if (value.selected) { + let selPos = tr.changes.mapPos(value.selected.from, 1); + selected = findDiagnostic(mapped, value.selected.diagnostic, selPos) || findDiagnostic(mapped, null, selPos); + } + value = new LintState(mapped, value.panel, selected); + } + for (let effect of tr.effects) { + if (effect.is(setDiagnosticsEffect)) { + value = LintState.init(effect.value, value.panel, tr.state); + } + else if (effect.is(togglePanel)) { + value = new LintState(value.diagnostics, effect.value ? LintPanel.open : null, value.selected); + } + else if (effect.is(movePanelSelection)) { + value = new LintState(value.diagnostics, value.panel, effect.value); + } + } + return value; + }, + provide: f => [showPanel.from(f, val => val.panel), + EditorView.decorations.from(f, s => s.diagnostics)] + }); + const activeMark = /*@__PURE__*/Decoration.mark({ class: "cm-lintRange cm-lintRange-active" }); + function lintTooltip(view, pos, side) { + let { diagnostics } = view.state.field(lintState); + let found = [], stackStart = 2e8, stackEnd = 0; + diagnostics.between(pos - (side < 0 ? 1 : 0), pos + (side > 0 ? 1 : 0), (from, to, { spec }) => { + if (pos >= from && pos <= to && + (from == to || ((pos > from || side > 0) && (pos < to || side < 0)))) { + found.push(spec.diagnostic); + stackStart = Math.min(from, stackStart); + stackEnd = Math.max(to, stackEnd); + } + }); + let diagnosticFilter = view.state.facet(lintConfig).tooltipFilter; + if (diagnosticFilter) + found = diagnosticFilter(found); + if (!found.length) + return null; + return { + pos: stackStart, + end: stackEnd, + above: view.state.doc.lineAt(stackStart).to < stackEnd, + create() { + return { dom: diagnosticsTooltip(view, found) }; + } + }; + } + function diagnosticsTooltip(view, diagnostics) { + return crelt("ul", { class: "cm-tooltip-lint" }, diagnostics.map(d => renderDiagnostic(view, d, false))); + } + /** + Command to open and focus the lint panel. + */ + const openLintPanel = (view) => { + let field = view.state.field(lintState, false); + if (!field || !field.panel) + view.dispatch({ effects: maybeEnableLint(view.state, [togglePanel.of(true)]) }); + let panel = getPanel(view, LintPanel.open); + if (panel) + panel.dom.querySelector(".cm-panel-lint ul").focus(); + return true; + }; + /** + Command to close the lint panel, when open. + */ + const closeLintPanel = (view) => { + let field = view.state.field(lintState, false); + if (!field || !field.panel) + return false; + view.dispatch({ effects: togglePanel.of(false) }); + return true; + }; + /** + Move the selection to the next diagnostic. + */ + const nextDiagnostic = (view) => { + let field = view.state.field(lintState, false); + if (!field) + return false; + let sel = view.state.selection.main, next = field.diagnostics.iter(sel.to + 1); + if (!next.value) { + next = field.diagnostics.iter(0); + if (!next.value || next.from == sel.from && next.to == sel.to) + return false; + } + view.dispatch({ selection: { anchor: next.from, head: next.to }, scrollIntoView: true }); + return true; + }; + /** + A set of default key bindings for the lint functionality. + + - Ctrl-Shift-m (Cmd-Shift-m on macOS): [`openLintPanel`](https://codemirror.net/6/docs/ref/#lint.openLintPanel) + - F8: [`nextDiagnostic`](https://codemirror.net/6/docs/ref/#lint.nextDiagnostic) + */ + const lintKeymap = [ + { key: "Mod-Shift-m", run: openLintPanel }, + { key: "F8", run: nextDiagnostic } + ]; + const lintPlugin = /*@__PURE__*/ViewPlugin.fromClass(class { + constructor(view) { + this.view = view; + this.timeout = -1; + this.set = true; + let { delay } = view.state.facet(lintConfig); + this.lintTime = Date.now() + delay; + this.run = this.run.bind(this); + this.timeout = setTimeout(this.run, delay); + } + run() { + let now = Date.now(); + if (now < this.lintTime - 10) { + setTimeout(this.run, this.lintTime - now); + } + else { + this.set = false; + let { state } = this.view, { sources } = state.facet(lintConfig); + Promise.all(sources.map(source => Promise.resolve(source(this.view)))).then(annotations => { + let all = annotations.reduce((a, b) => a.concat(b)); + if (this.view.state.doc == state.doc) + this.view.dispatch(setDiagnostics(this.view.state, all)); + }, error => { logException(this.view.state, error); }); + } + } + update(update) { + let config = update.state.facet(lintConfig); + if (update.docChanged || config != update.startState.facet(lintConfig)) { + this.lintTime = Date.now() + config.delay; + if (!this.set) { + this.set = true; + this.timeout = setTimeout(this.run, config.delay); + } + } + } + force() { + if (this.set) { + this.lintTime = Date.now(); + this.run(); + } + } + destroy() { + clearTimeout(this.timeout); + } + }); + const lintConfig = /*@__PURE__*/Facet.define({ + combine(input) { + return Object.assign({ sources: input.map(i => i.source) }, combineConfig(input.map(i => i.config), { + delay: 750, + markerFilter: null, + tooltipFilter: null + })); + }, + enables: lintPlugin + }); + function assignKeys(actions) { + let assigned = []; + if (actions) + actions: for (let { name } of actions) { + for (let i = 0; i < name.length; i++) { + let ch = name[i]; + if (/[a-zA-Z]/.test(ch) && !assigned.some(c => c.toLowerCase() == ch.toLowerCase())) { + assigned.push(ch); + continue actions; + } + } + assigned.push(""); + } + return assigned; + } + function renderDiagnostic(view, diagnostic, inPanel) { + var _a; + let keys = inPanel ? assignKeys(diagnostic.actions) : []; + return crelt("li", { class: "cm-diagnostic cm-diagnostic-" + diagnostic.severity }, crelt("span", { class: "cm-diagnosticText" }, diagnostic.renderMessage ? diagnostic.renderMessage() : diagnostic.message), (_a = diagnostic.actions) === null || _a === void 0 ? void 0 : _a.map((action, i) => { + let click = (e) => { + e.preventDefault(); + let found = findDiagnostic(view.state.field(lintState).diagnostics, diagnostic); + if (found) + action.apply(view, found.from, found.to); + }; + let { name } = action, keyIndex = keys[i] ? name.indexOf(keys[i]) : -1; + let nameElt = keyIndex < 0 ? name : [name.slice(0, keyIndex), + crelt("u", name.slice(keyIndex, keyIndex + 1)), + name.slice(keyIndex + 1)]; + return crelt("button", { + type: "button", + class: "cm-diagnosticAction", + onclick: click, + onmousedown: click, + "aria-label": ` Action: ${name}${keyIndex < 0 ? "" : ` (access key "${keys[i]})"`}.` + }, nameElt); + }), diagnostic.source && crelt("div", { class: "cm-diagnosticSource" }, diagnostic.source)); + } + class DiagnosticWidget extends WidgetType { + constructor(diagnostic) { + super(); + this.diagnostic = diagnostic; + } + eq(other) { return other.diagnostic == this.diagnostic; } + toDOM() { + return crelt("span", { class: "cm-lintPoint cm-lintPoint-" + this.diagnostic.severity }); + } + } + class PanelItem { + constructor(view, diagnostic) { + this.diagnostic = diagnostic; + this.id = "item_" + Math.floor(Math.random() * 0xffffffff).toString(16); + this.dom = renderDiagnostic(view, diagnostic, true); + this.dom.id = this.id; + this.dom.setAttribute("role", "option"); + } + } + class LintPanel { + constructor(view) { + this.view = view; + this.items = []; + let onkeydown = (event) => { + if (event.keyCode == 27) { // Escape + closeLintPanel(this.view); + this.view.focus(); + } + else if (event.keyCode == 38 || event.keyCode == 33) { // ArrowUp, PageUp + this.moveSelection((this.selectedIndex - 1 + this.items.length) % this.items.length); + } + else if (event.keyCode == 40 || event.keyCode == 34) { // ArrowDown, PageDown + this.moveSelection((this.selectedIndex + 1) % this.items.length); + } + else if (event.keyCode == 36) { // Home + this.moveSelection(0); + } + else if (event.keyCode == 35) { // End + this.moveSelection(this.items.length - 1); + } + else if (event.keyCode == 13) { // Enter + this.view.focus(); + } + else if (event.keyCode >= 65 && event.keyCode <= 90 && this.selectedIndex >= 0) { // A-Z + let { diagnostic } = this.items[this.selectedIndex], keys = assignKeys(diagnostic.actions); + for (let i = 0; i < keys.length; i++) + if (keys[i].toUpperCase().charCodeAt(0) == event.keyCode) { + let found = findDiagnostic(this.view.state.field(lintState).diagnostics, diagnostic); + if (found) + diagnostic.actions[i].apply(view, found.from, found.to); + } + } + else { + return; + } + event.preventDefault(); + }; + let onclick = (event) => { + for (let i = 0; i < this.items.length; i++) { + if (this.items[i].dom.contains(event.target)) + this.moveSelection(i); + } + }; + this.list = crelt("ul", { + tabIndex: 0, + role: "listbox", + "aria-label": this.view.state.phrase("Diagnostics"), + onkeydown, + onclick + }); + this.dom = crelt("div", { class: "cm-panel-lint" }, this.list, crelt("button", { + type: "button", + name: "close", + "aria-label": this.view.state.phrase("close"), + onclick: () => closeLintPanel(this.view) + }, "×")); + this.update(); + } + get selectedIndex() { + let selected = this.view.state.field(lintState).selected; + if (!selected) + return -1; + for (let i = 0; i < this.items.length; i++) + if (this.items[i].diagnostic == selected.diagnostic) + return i; + return -1; + } + update() { + let { diagnostics, selected } = this.view.state.field(lintState); + let i = 0, needsSync = false, newSelectedItem = null; + diagnostics.between(0, this.view.state.doc.length, (_start, _end, { spec }) => { + let found = -1, item; + for (let j = i; j < this.items.length; j++) + if (this.items[j].diagnostic == spec.diagnostic) { + found = j; + break; + } + if (found < 0) { + item = new PanelItem(this.view, spec.diagnostic); + this.items.splice(i, 0, item); + needsSync = true; + } + else { + item = this.items[found]; + if (found > i) { + this.items.splice(i, found - i); + needsSync = true; + } + } + if (selected && item.diagnostic == selected.diagnostic) { + if (!item.dom.hasAttribute("aria-selected")) { + item.dom.setAttribute("aria-selected", "true"); + newSelectedItem = item; + } + } + else if (item.dom.hasAttribute("aria-selected")) { + item.dom.removeAttribute("aria-selected"); + } + i++; + }); + while (i < this.items.length && !(this.items.length == 1 && this.items[0].diagnostic.from < 0)) { + needsSync = true; + this.items.pop(); + } + if (this.items.length == 0) { + this.items.push(new PanelItem(this.view, { + from: -1, to: -1, + severity: "info", + message: this.view.state.phrase("No diagnostics") + })); + needsSync = true; + } + if (newSelectedItem) { + this.list.setAttribute("aria-activedescendant", newSelectedItem.id); + this.view.requestMeasure({ + key: this, + read: () => ({ sel: newSelectedItem.dom.getBoundingClientRect(), panel: this.list.getBoundingClientRect() }), + write: ({ sel, panel }) => { + if (sel.top < panel.top) + this.list.scrollTop -= panel.top - sel.top; + else if (sel.bottom > panel.bottom) + this.list.scrollTop += sel.bottom - panel.bottom; + } + }); + } + else if (this.selectedIndex < 0) { + this.list.removeAttribute("aria-activedescendant"); + } + if (needsSync) + this.sync(); + } + sync() { + let domPos = this.list.firstChild; + function rm() { + let prev = domPos; + domPos = prev.nextSibling; + prev.remove(); + } + for (let item of this.items) { + if (item.dom.parentNode == this.list) { + while (domPos != item.dom) + rm(); + domPos = item.dom.nextSibling; + } + else { + this.list.insertBefore(item.dom, domPos); + } + } + while (domPos) + rm(); + } + moveSelection(selectedIndex) { + if (this.selectedIndex < 0) + return; + let field = this.view.state.field(lintState); + let selection = findDiagnostic(field.diagnostics, this.items[selectedIndex].diagnostic); + if (!selection) + return; + this.view.dispatch({ + selection: { anchor: selection.from, head: selection.to }, + scrollIntoView: true, + effects: movePanelSelection.of(selection) + }); + } + static open(view) { return new LintPanel(view); } + } + function svg(content, attrs = `viewBox="0 0 40 40"`) { + return `url('data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" ${attrs}>${encodeURIComponent(content)}</svg>')`; + } + function underline(color) { + return svg(`<path d="m0 2.5 l2 -1.5 l1 0 l2 1.5 l1 0" stroke="${color}" fill="none" stroke-width=".7"/>`, `width="6" height="3"`); + } + const baseTheme = /*@__PURE__*/EditorView.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-diagnosticAction": { + font: "inherit", + border: "none", + padding: "2px 4px", + backgroundColor: "#444", + color: "white", + borderRadius: "3px", + marginLeft: "8px" + }, + ".cm-diagnosticSource": { + fontSize: "70%", + opacity: .7 + }, + ".cm-lintRange": { + backgroundPosition: "left bottom", + backgroundRepeat: "repeat-x", + paddingBottom: "0.7px", + }, + ".cm-lintRange-error": { backgroundImage: /*@__PURE__*/underline("#d11") }, + ".cm-lintRange-warning": { backgroundImage: /*@__PURE__*/underline("orange") }, + ".cm-lintRange-info": { backgroundImage: /*@__PURE__*/underline("#999") }, + ".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-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 + } + } + }); + + // (The superfluous function calls around the list of extensions work + // around current limitations in tree-shaking software.) + /** + This is an extension value that just pulls together a number of + extensions that you might want in a basic editor. It is meant as a + convenient helper to quickly set up CodeMirror without installing + and importing a lot of separate packages. + + Specifically, it includes... + + - [the default command bindings](https://codemirror.net/6/docs/ref/#commands.defaultKeymap) + - [line numbers](https://codemirror.net/6/docs/ref/#view.lineNumbers) + - [special character highlighting](https://codemirror.net/6/docs/ref/#view.highlightSpecialChars) + - [the undo history](https://codemirror.net/6/docs/ref/#commands.history) + - [a fold gutter](https://codemirror.net/6/docs/ref/#language.foldGutter) + - [custom selection drawing](https://codemirror.net/6/docs/ref/#view.drawSelection) + - [drop cursor](https://codemirror.net/6/docs/ref/#view.dropCursor) + - [multiple selections](https://codemirror.net/6/docs/ref/#state.EditorState^allowMultipleSelections) + - [reindentation on input](https://codemirror.net/6/docs/ref/#language.indentOnInput) + - [the default highlight style](https://codemirror.net/6/docs/ref/#language.defaultHighlightStyle) (as fallback) + - [bracket matching](https://codemirror.net/6/docs/ref/#language.bracketMatching) + - [bracket closing](https://codemirror.net/6/docs/ref/#autocomplete.closeBrackets) + - [autocompletion](https://codemirror.net/6/docs/ref/#autocomplete.autocompletion) + - [rectangular selection](https://codemirror.net/6/docs/ref/#view.rectangularSelection) and [crosshair cursor](https://codemirror.net/6/docs/ref/#view.crosshairCursor) + - [active line highlighting](https://codemirror.net/6/docs/ref/#view.highlightActiveLine) + - [active line gutter highlighting](https://codemirror.net/6/docs/ref/#view.highlightActiveLineGutter) + - [selection match highlighting](https://codemirror.net/6/docs/ref/#search.highlightSelectionMatches) + - [search](https://codemirror.net/6/docs/ref/#search.searchKeymap) + - [linting](https://codemirror.net/6/docs/ref/#lint.lintKeymap) + + (You'll probably want to add some language package to your setup + too.) + + This extension does not allow customization. The idea is that, + once you decide you want to configure your editor more precisely, + you take this package's source (which is just a bunch of imports + and an array literal), copy it into your own code, and adjust it + as desired. + */ + const basicSetup = /*@__PURE__*/(() => [ + lineNumbers(), + highlightActiveLineGutter(), + highlightSpecialChars(), + history(), + foldGutter(), + drawSelection(), + dropCursor(), + EditorState.allowMultipleSelections.of(true), + indentOnInput(), + syntaxHighlighting(defaultHighlightStyle, { fallback: true }), + bracketMatching(), + closeBrackets(), + autocompletion(), + rectangularSelection(), + crosshairCursor(), + highlightActiveLine(), + highlightSelectionMatches(), + keymap.of([ + ...closeBracketsKeymap, + ...defaultKeymap, + ...searchKeymap, + ...historyKeymap, + ...foldKeymap, + ...completionKeymap, + ...lintKeymap + ]) + ])(); + + /// A parse stack. These are used internally by the parser to track + /// parsing progress. They also provide some properties and methods + /// that external code such as a tokenizer can use to get information + /// about the parse state. + class Stack { + /// @internal + constructor( + /// The parse that this stack is part of @internal + p, + /// Holds state, input pos, buffer index triplets for all but the + /// top state @internal + stack, + /// The current parse state @internal + state, + // The position at which the next reduce should take place. This + // can be less than `this.pos` when skipped expressions have been + // added to the stack (which should be moved outside of the next + // reduction) + /// @internal + reducePos, + /// The input position up to which this stack has parsed. + pos, + /// The dynamic score of the stack, including dynamic precedence + /// and error-recovery penalties + /// @internal + score, + // The output buffer. Holds (type, start, end, size) quads + // representing nodes created by the parser, where `size` is + // amount of buffer array entries covered by this node. + /// @internal + buffer, + // The base offset of the buffer. When stacks are split, the split + // instance shared the buffer history with its parent up to + // `bufferBase`, which is the absolute offset (including the + // offset of previous splits) into the buffer at which this stack + // starts writing. + /// @internal + bufferBase, + /// @internal + curContext, + /// @internal + lookAhead = 0, + // A parent stack from which this was split off, if any. This is + // set up so that it always points to a stack that has some + // additional buffer content, never to a stack with an equal + // `bufferBase`. + /// @internal + parent) { + this.p = p; + this.stack = stack; + this.state = state; + this.reducePos = reducePos; + this.pos = pos; + this.score = score; + this.buffer = buffer; + this.bufferBase = bufferBase; + this.curContext = curContext; + this.lookAhead = lookAhead; + this.parent = parent; + } + /// @internal + toString() { + return `[${this.stack.filter((_, i) => i % 3 == 0).concat(this.state)}]@${this.pos}${this.score ? "!" + this.score : ""}`; + } + // Start an empty stack + /// @internal + static start(p, state, pos = 0) { + let cx = p.parser.context; + return new Stack(p, [], state, pos, pos, 0, [], 0, cx ? new StackContext(cx, cx.start) : null, 0, null); + } + /// The stack's current [context](#lr.ContextTracker) value, if + /// any. Its type will depend on the context tracker's type + /// parameter, or it will be `null` if there is no context + /// tracker. + get context() { return this.curContext ? this.curContext.context : null; } + // Push a state onto the stack, tracking its start position as well + // as the buffer base at that point. + /// @internal + pushState(state, start) { + this.stack.push(this.state, start, this.bufferBase + this.buffer.length); + this.state = state; + } + // Apply a reduce action + /// @internal + reduce(action) { + let depth = action >> 19 /* ReduceDepthShift */, type = action & 65535 /* ValueMask */; + let { parser } = this.p; + let dPrec = parser.dynamicPrecedence(type); + if (dPrec) + this.score += dPrec; + if (depth == 0) { + this.pushState(parser.getGoto(this.state, type, true), this.reducePos); + // Zero-depth reductions are a special case—they add stuff to + // the stack without popping anything off. + if (type < parser.minRepeatTerm) + this.storeNode(type, this.reducePos, this.reducePos, 4, true); + this.reduceContext(type, this.reducePos); + return; + } + // Find the base index into `this.stack`, content after which will + // be dropped. Note that with `StayFlag` reductions we need to + // consume two extra frames (the dummy parent node for the skipped + // expression and the state that we'll be staying in, which should + // be moved to `this.state`). + let base = this.stack.length - ((depth - 1) * 3) - (action & 262144 /* StayFlag */ ? 6 : 0); + let start = this.stack[base - 2]; + let bufferBase = this.stack[base - 1], count = this.bufferBase + this.buffer.length - bufferBase; + // Store normal terms or `R -> R R` repeat reductions + if (type < parser.minRepeatTerm || (action & 131072 /* RepeatFlag */)) { + let pos = parser.stateFlag(this.state, 1 /* Skipped */) ? this.pos : this.reducePos; + this.storeNode(type, start, pos, count + 4, true); + } + if (action & 262144 /* StayFlag */) { + this.state = this.stack[base]; + } + else { + let baseStateID = this.stack[base - 3]; + this.state = parser.getGoto(baseStateID, type, true); + } + while (this.stack.length > base) + this.stack.pop(); + this.reduceContext(type, start); + } + // Shift a value into the buffer + /// @internal + storeNode(term, start, end, size = 4, isReduce = false) { + if (term == 0 /* Err */ && + (!this.stack.length || this.stack[this.stack.length - 1] < this.buffer.length + this.bufferBase)) { + // Try to omit/merge adjacent error nodes + let cur = this, top = this.buffer.length; + if (top == 0 && cur.parent) { + top = cur.bufferBase - cur.parent.bufferBase; + cur = cur.parent; + } + if (top > 0 && cur.buffer[top - 4] == 0 /* Err */ && cur.buffer[top - 1] > -1) { + if (start == end) + return; + if (cur.buffer[top - 2] >= start) { + cur.buffer[top - 2] = end; + return; + } + } + } + if (!isReduce || this.pos == end) { // Simple case, just append + this.buffer.push(term, start, end, size); + } + else { // There may be skipped nodes that have to be moved forward + let index = this.buffer.length; + if (index > 0 && this.buffer[index - 4] != 0 /* Err */) + while (index > 0 && this.buffer[index - 2] > end) { + // Move this record forward + this.buffer[index] = this.buffer[index - 4]; + this.buffer[index + 1] = this.buffer[index - 3]; + this.buffer[index + 2] = this.buffer[index - 2]; + this.buffer[index + 3] = this.buffer[index - 1]; + index -= 4; + if (size > 4) + size -= 4; + } + this.buffer[index] = term; + this.buffer[index + 1] = start; + this.buffer[index + 2] = end; + this.buffer[index + 3] = size; + } + } + // Apply a shift action + /// @internal + shift(action, next, nextEnd) { + let start = this.pos; + if (action & 131072 /* GotoFlag */) { + this.pushState(action & 65535 /* ValueMask */, this.pos); + } + else if ((action & 262144 /* StayFlag */) == 0) { // Regular shift + let nextState = action, { parser } = this.p; + if (nextEnd > this.pos || next <= parser.maxNode) { + this.pos = nextEnd; + if (!parser.stateFlag(nextState, 1 /* Skipped */)) + this.reducePos = nextEnd; + } + this.pushState(nextState, start); + this.shiftContext(next, start); + if (next <= parser.maxNode) + this.buffer.push(next, start, nextEnd, 4); + } + else { // Shift-and-stay, which means this is a skipped token + this.pos = nextEnd; + this.shiftContext(next, start); + if (next <= this.p.parser.maxNode) + this.buffer.push(next, start, nextEnd, 4); + } + } + // Apply an action + /// @internal + apply(action, next, nextEnd) { + if (action & 65536 /* ReduceFlag */) + this.reduce(action); + else + this.shift(action, next, nextEnd); + } + // Add a prebuilt (reused) node into the buffer. + /// @internal + useNode(value, next) { + let index = this.p.reused.length - 1; + if (index < 0 || this.p.reused[index] != value) { + this.p.reused.push(value); + index++; + } + let start = this.pos; + this.reducePos = this.pos = start + value.length; + this.pushState(next, start); + this.buffer.push(index, start, this.reducePos, -1 /* size == -1 means this is a reused value */); + if (this.curContext) + this.updateContext(this.curContext.tracker.reuse(this.curContext.context, value, this, this.p.stream.reset(this.pos - value.length))); + } + // Split the stack. Due to the buffer sharing and the fact + // that `this.stack` tends to stay quite shallow, this isn't very + // expensive. + /// @internal + split() { + let parent = this; + let off = parent.buffer.length; + // Because the top of the buffer (after this.pos) may be mutated + // to reorder reductions and skipped tokens, and shared buffers + // should be immutable, this copies any outstanding skipped tokens + // to the new buffer, and puts the base pointer before them. + while (off > 0 && parent.buffer[off - 2] > parent.reducePos) + off -= 4; + let buffer = parent.buffer.slice(off), base = parent.bufferBase + off; + // Make sure parent points to an actual parent with content, if there is such a parent. + while (parent && base == parent.bufferBase) + parent = parent.parent; + return new Stack(this.p, this.stack.slice(), this.state, this.reducePos, this.pos, this.score, buffer, base, this.curContext, this.lookAhead, parent); + } + // Try to recover from an error by 'deleting' (ignoring) one token. + /// @internal + recoverByDelete(next, nextEnd) { + let isNode = next <= this.p.parser.maxNode; + if (isNode) + this.storeNode(next, this.pos, nextEnd, 4); + this.storeNode(0 /* Err */, this.pos, nextEnd, isNode ? 8 : 4); + this.pos = this.reducePos = nextEnd; + this.score -= 190 /* Delete */; + } + /// Check if the given term would be able to be shifted (optionally + /// after some reductions) on this stack. This can be useful for + /// external tokenizers that want to make sure they only provide a + /// given token when it applies. + canShift(term) { + for (let sim = new SimulatedStack(this);;) { + let action = this.p.parser.stateSlot(sim.state, 4 /* DefaultReduce */) || this.p.parser.hasAction(sim.state, term); + if ((action & 65536 /* ReduceFlag */) == 0) + return true; + if (action == 0) + return false; + sim.reduce(action); + } + } + // Apply up to Recover.MaxNext recovery actions that conceptually + // inserts some missing token or rule. + /// @internal + recoverByInsert(next) { + if (this.stack.length >= 300 /* MaxInsertStackDepth */) + return []; + let nextStates = this.p.parser.nextStates(this.state); + if (nextStates.length > 4 /* MaxNext */ << 1 || this.stack.length >= 120 /* DampenInsertStackDepth */) { + let best = []; + for (let i = 0, s; i < nextStates.length; i += 2) { + if ((s = nextStates[i + 1]) != this.state && this.p.parser.hasAction(s, next)) + best.push(nextStates[i], s); + } + if (this.stack.length < 120 /* DampenInsertStackDepth */) + for (let i = 0; best.length < 4 /* MaxNext */ << 1 && i < nextStates.length; i += 2) { + let s = nextStates[i + 1]; + if (!best.some((v, i) => (i & 1) && v == s)) + best.push(nextStates[i], s); + } + nextStates = best; + } + let result = []; + for (let i = 0; i < nextStates.length && result.length < 4 /* MaxNext */; i += 2) { + let s = nextStates[i + 1]; + if (s == this.state) + continue; + let stack = this.split(); + stack.pushState(s, this.pos); + stack.storeNode(0 /* Err */, stack.pos, stack.pos, 4, true); + stack.shiftContext(nextStates[i], this.pos); + stack.score -= 200 /* Insert */; + result.push(stack); + } + return result; + } + // Force a reduce, if possible. Return false if that can't + // be done. + /// @internal + forceReduce() { + let reduce = this.p.parser.stateSlot(this.state, 5 /* ForcedReduce */); + if ((reduce & 65536 /* ReduceFlag */) == 0) + return false; + let { parser } = this.p; + if (!parser.validAction(this.state, reduce)) { + let depth = reduce >> 19 /* ReduceDepthShift */, term = reduce & 65535 /* ValueMask */; + let target = this.stack.length - depth * 3; + if (target < 0 || parser.getGoto(this.stack[target], term, false) < 0) + return false; + this.storeNode(0 /* Err */, this.reducePos, this.reducePos, 4, true); + this.score -= 100 /* Reduce */; + } + this.reducePos = this.pos; + this.reduce(reduce); + return true; + } + /// @internal + forceAll() { + while (!this.p.parser.stateFlag(this.state, 2 /* Accepting */)) { + if (!this.forceReduce()) { + this.storeNode(0 /* Err */, this.pos, this.pos, 4, true); + break; + } + } + return this; + } + /// Check whether this state has no further actions (assumed to be a direct descendant of the + /// top state, since any other states must be able to continue + /// somehow). @internal + get deadEnd() { + if (this.stack.length != 3) + return false; + let { parser } = this.p; + return parser.data[parser.stateSlot(this.state, 1 /* Actions */)] == 65535 /* End */ && + !parser.stateSlot(this.state, 4 /* DefaultReduce */); + } + /// Restart the stack (put it back in its start state). Only safe + /// when this.stack.length == 3 (state is directly below the top + /// state). @internal + restart() { + this.state = this.stack[0]; + this.stack.length = 0; + } + /// @internal + sameState(other) { + if (this.state != other.state || this.stack.length != other.stack.length) + return false; + for (let i = 0; i < this.stack.length; i += 3) + if (this.stack[i] != other.stack[i]) + return false; + return true; + } + /// Get the parser used by this stack. + get parser() { return this.p.parser; } + /// Test whether a given dialect (by numeric ID, as exported from + /// the terms file) is enabled. + dialectEnabled(dialectID) { return this.p.parser.dialect.flags[dialectID]; } + shiftContext(term, start) { + if (this.curContext) + this.updateContext(this.curContext.tracker.shift(this.curContext.context, term, this, this.p.stream.reset(start))); + } + reduceContext(term, start) { + if (this.curContext) + this.updateContext(this.curContext.tracker.reduce(this.curContext.context, term, this, this.p.stream.reset(start))); + } + /// @internal + emitContext() { + let last = this.buffer.length - 1; + if (last < 0 || this.buffer[last] != -3) + this.buffer.push(this.curContext.hash, this.reducePos, this.reducePos, -3); + } + /// @internal + emitLookAhead() { + let last = this.buffer.length - 1; + if (last < 0 || this.buffer[last] != -4) + this.buffer.push(this.lookAhead, this.reducePos, this.reducePos, -4); + } + updateContext(context) { + if (context != this.curContext.context) { + let newCx = new StackContext(this.curContext.tracker, context); + if (newCx.hash != this.curContext.hash) + this.emitContext(); + this.curContext = newCx; + } + } + /// @internal + setLookAhead(lookAhead) { + if (lookAhead > this.lookAhead) { + this.emitLookAhead(); + this.lookAhead = lookAhead; + } + } + /// @internal + close() { + if (this.curContext && this.curContext.tracker.strict) + this.emitContext(); + if (this.lookAhead > 0) + this.emitLookAhead(); + } + } + class StackContext { + constructor(tracker, context) { + this.tracker = tracker; + this.context = context; + this.hash = tracker.strict ? tracker.hash(context) : 0; + } + } + var Recover; + (function (Recover) { + Recover[Recover["Insert"] = 200] = "Insert"; + Recover[Recover["Delete"] = 190] = "Delete"; + Recover[Recover["Reduce"] = 100] = "Reduce"; + Recover[Recover["MaxNext"] = 4] = "MaxNext"; + Recover[Recover["MaxInsertStackDepth"] = 300] = "MaxInsertStackDepth"; + Recover[Recover["DampenInsertStackDepth"] = 120] = "DampenInsertStackDepth"; + })(Recover || (Recover = {})); + // Used to cheaply run some reductions to scan ahead without mutating + // an entire stack + class SimulatedStack { + constructor(start) { + this.start = start; + this.state = start.state; + this.stack = start.stack; + this.base = this.stack.length; + } + reduce(action) { + let term = action & 65535 /* ValueMask */, depth = action >> 19 /* ReduceDepthShift */; + if (depth == 0) { + if (this.stack == this.start.stack) + this.stack = this.stack.slice(); + this.stack.push(this.state, 0, 0); + this.base += 3; + } + else { + this.base -= (depth - 1) * 3; + } + let goto = this.start.p.parser.getGoto(this.stack[this.base - 3], term, true); + this.state = goto; + } + } + // This is given to `Tree.build` to build a buffer, and encapsulates + // the parent-stack-walking necessary to read the nodes. + class StackBufferCursor { + constructor(stack, pos, index) { + this.stack = stack; + this.pos = pos; + this.index = index; + this.buffer = stack.buffer; + if (this.index == 0) + this.maybeNext(); + } + static create(stack, pos = stack.bufferBase + stack.buffer.length) { + return new StackBufferCursor(stack, pos, pos - stack.bufferBase); + } + maybeNext() { + let next = this.stack.parent; + if (next != null) { + this.index = this.stack.bufferBase - next.bufferBase; + this.stack = next; + this.buffer = next.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; + if (this.index == 0) + this.maybeNext(); + } + fork() { + return new StackBufferCursor(this.stack, this.pos, this.index); + } + } + + class CachedToken { + constructor() { + this.start = -1; + this.value = -1; + this.end = -1; + this.extended = -1; + this.lookAhead = 0; + this.mask = 0; + this.context = 0; + } + } + const nullToken = new CachedToken; + /// [Tokenizers](#lr.ExternalTokenizer) interact with the input + /// through this interface. It presents the input as a stream of + /// characters, tracking lookahead and hiding the complexity of + /// [ranges](#common.Parser.parse^ranges) from tokenizer code. + class InputStream { + /// @internal + constructor( + /// @internal + input, + /// @internal + ranges) { + this.input = input; + this.ranges = ranges; + /// @internal + this.chunk = ""; + /// @internal + this.chunkOff = 0; + /// Backup chunk + this.chunk2 = ""; + this.chunk2Pos = 0; + /// The character code of the next code unit in the input, or -1 + /// when the stream is at the end of the input. + this.next = -1; + /// @internal + this.token = nullToken; + this.rangeIndex = 0; + this.pos = this.chunkPos = ranges[0].from; + this.range = ranges[0]; + this.end = ranges[ranges.length - 1].to; + this.readNext(); + } + /// @internal + resolveOffset(offset, assoc) { + let range = this.range, index = this.rangeIndex; + let pos = this.pos + offset; + while (pos < range.from) { + if (!index) + return null; + let next = this.ranges[--index]; + pos -= range.from - next.to; + range = next; + } + while (assoc < 0 ? pos > range.to : pos >= range.to) { + if (index == this.ranges.length - 1) + return null; + let next = this.ranges[++index]; + pos += next.from - range.to; + range = next; + } + return pos; + } + /// @internal + clipPos(pos) { + if (pos >= this.range.from && pos < this.range.to) + return pos; + for (let range of this.ranges) + if (range.to > pos) + return Math.max(pos, range.from); + return this.end; + } + /// Look at a code unit near the stream position. `.peek(0)` equals + /// `.next`, `.peek(-1)` gives you the previous character, and so + /// on. + /// + /// Note that looking around during tokenizing creates dependencies + /// on potentially far-away content, which may reduce the + /// effectiveness incremental parsing—when looking forward—or even + /// cause invalid reparses when looking backward more than 25 code + /// units, since the library does not track lookbehind. + peek(offset) { + let idx = this.chunkOff + offset, pos, result; + if (idx >= 0 && idx < this.chunk.length) { + pos = this.pos + offset; + result = this.chunk.charCodeAt(idx); + } + else { + let resolved = this.resolveOffset(offset, 1); + if (resolved == null) + return -1; + pos = resolved; + if (pos >= this.chunk2Pos && pos < this.chunk2Pos + this.chunk2.length) { + result = this.chunk2.charCodeAt(pos - this.chunk2Pos); + } + else { + let i = this.rangeIndex, range = this.range; + while (range.to <= pos) + range = this.ranges[++i]; + this.chunk2 = this.input.chunk(this.chunk2Pos = pos); + if (pos + this.chunk2.length > range.to) + this.chunk2 = this.chunk2.slice(0, range.to - pos); + result = this.chunk2.charCodeAt(0); + } + } + if (pos >= this.token.lookAhead) + this.token.lookAhead = pos + 1; + return result; + } + /// Accept a token. By default, the end of the token is set to the + /// current stream position, but you can pass an offset (relative to + /// the stream position) to change that. + acceptToken(token, endOffset = 0) { + let end = endOffset ? this.resolveOffset(endOffset, -1) : this.pos; + if (end == null || end < this.token.start) + throw new RangeError("Token end out of bounds"); + this.token.value = token; + this.token.end = end; + } + getChunk() { + if (this.pos >= this.chunk2Pos && this.pos < this.chunk2Pos + this.chunk2.length) { + let { chunk, chunkPos } = this; + this.chunk = this.chunk2; + this.chunkPos = this.chunk2Pos; + this.chunk2 = chunk; + this.chunk2Pos = chunkPos; + this.chunkOff = this.pos - this.chunkPos; + } + else { + this.chunk2 = this.chunk; + this.chunk2Pos = this.chunkPos; + let nextChunk = this.input.chunk(this.pos); + let end = this.pos + nextChunk.length; + this.chunk = end > this.range.to ? nextChunk.slice(0, this.range.to - this.pos) : nextChunk; + this.chunkPos = this.pos; + this.chunkOff = 0; + } + } + readNext() { + if (this.chunkOff >= this.chunk.length) { + this.getChunk(); + if (this.chunkOff == this.chunk.length) + return this.next = -1; + } + return this.next = this.chunk.charCodeAt(this.chunkOff); + } + /// Move the stream forward N (defaults to 1) code units. Returns + /// the new value of [`next`](#lr.InputStream.next). + advance(n = 1) { + this.chunkOff += n; + while (this.pos + n >= this.range.to) { + if (this.rangeIndex == this.ranges.length - 1) + return this.setDone(); + n -= this.range.to - this.pos; + this.range = this.ranges[++this.rangeIndex]; + this.pos = this.range.from; + } + this.pos += n; + if (this.pos >= this.token.lookAhead) + this.token.lookAhead = this.pos + 1; + return this.readNext(); + } + setDone() { + this.pos = this.chunkPos = this.end; + this.range = this.ranges[this.rangeIndex = this.ranges.length - 1]; + this.chunk = ""; + return this.next = -1; + } + /// @internal + reset(pos, token) { + if (token) { + this.token = token; + token.start = pos; + token.lookAhead = pos + 1; + token.value = token.extended = -1; + } + else { + this.token = nullToken; + } + if (this.pos != pos) { + this.pos = pos; + if (pos == this.end) { + this.setDone(); + return this; + } + while (pos < this.range.from) + this.range = this.ranges[--this.rangeIndex]; + while (pos >= this.range.to) + this.range = this.ranges[++this.rangeIndex]; + if (pos >= this.chunkPos && pos < this.chunkPos + this.chunk.length) { + this.chunkOff = pos - this.chunkPos; + } + else { + this.chunk = ""; + this.chunkOff = 0; + } + this.readNext(); + } + return this; + } + /// @internal + read(from, to) { + if (from >= this.chunkPos && to <= this.chunkPos + this.chunk.length) + return this.chunk.slice(from - this.chunkPos, to - this.chunkPos); + if (from >= this.chunk2Pos && to <= this.chunk2Pos + this.chunk2.length) + return this.chunk2.slice(from - this.chunk2Pos, to - this.chunk2Pos); + if (from >= this.range.from && to <= this.range.to) + return this.input.read(from, to); + let result = ""; + for (let r of this.ranges) { + if (r.from >= to) + break; + if (r.to > from) + result += this.input.read(Math.max(r.from, from), Math.min(r.to, to)); + } + return result; + } + } + /// @internal + class TokenGroup { + constructor(data, id) { + this.data = data; + this.id = id; + } + token(input, stack) { readToken(this.data, input, stack, this.id); } + } + TokenGroup.prototype.contextual = TokenGroup.prototype.fallback = TokenGroup.prototype.extend = false; + /// `@external tokens` declarations in the grammar should resolve to + /// an instance of this class. + class ExternalTokenizer { + /// Create a tokenizer. The first argument is the function that, + /// given an input stream, scans for the types of tokens it + /// recognizes at the stream's position, and calls + /// [`acceptToken`](#lr.InputStream.acceptToken) when it finds + /// one. + constructor( + /// @internal + token, options = {}) { + this.token = token; + this.contextual = !!options.contextual; + this.fallback = !!options.fallback; + this.extend = !!options.extend; + } + } + // Tokenizer data is stored a big uint16 array containing, for each + // state: + // + // - A group bitmask, indicating what token groups are reachable from + // this state, so that paths that can only lead to tokens not in + // any of the current groups can be cut off early. + // + // - The position of the end of the state's sequence of accepting + // tokens + // + // - The number of outgoing edges for the state + // + // - The accepting tokens, as (token id, group mask) pairs + // + // - The outgoing edges, as (start character, end character, state + // index) triples, with end character being exclusive + // + // This function interprets that data, running through a stream as + // long as new states with the a matching group mask can be reached, + // and updating `input.token` when it matches a token. + function readToken(data, input, stack, group) { + let state = 0, groupMask = 1 << group, { parser } = stack.p, { dialect } = parser; + scan: for (;;) { + if ((groupMask & data[state]) == 0) + break; + let accEnd = data[state + 1]; + // Check whether this state can lead to a token in the current group + // Accept tokens in this state, possibly overwriting + // lower-precedence / shorter tokens + for (let i = state + 3; i < accEnd; i += 2) + if ((data[i + 1] & groupMask) > 0) { + let term = data[i]; + if (dialect.allows(term) && + (input.token.value == -1 || input.token.value == term || parser.overrides(term, input.token.value))) { + input.acceptToken(term); + break; + } + } + let next = input.next, low = 0, high = data[state + 2]; + // Special case for EOF + if (input.next < 0 && high > low && data[accEnd + high * 3 - 3] == 65535 /* End */) { + state = data[accEnd + high * 3 - 1]; + continue scan; + } + // Do a binary search on the state's edges + for (; low < high;) { + let mid = (low + high) >> 1; + let index = accEnd + mid + (mid << 1); + let from = data[index], to = data[index + 1]; + if (next < from) + high = mid; + else if (next >= to) + low = mid + 1; + else { + state = data[index + 2]; + input.advance(); + continue scan; + } + } + break; + } + } + + // See lezer-generator/src/encode.ts for comments about the encoding + // used here + function decodeArray(input, Type = Uint16Array) { + if (typeof input != "string") + return input; + let array = null; + for (let pos = 0, out = 0; pos < input.length;) { + let value = 0; + for (;;) { + let next = input.charCodeAt(pos++), stop = false; + if (next == 126 /* BigValCode */) { + value = 65535 /* BigVal */; + break; + } + if (next >= 92 /* Gap2 */) + next--; + if (next >= 34 /* Gap1 */) + next--; + let digit = next - 32 /* Start */; + if (digit >= 46 /* Base */) { + digit -= 46 /* Base */; + stop = true; + } + value += digit; + if (stop) + break; + value *= 46 /* Base */; + } + if (array) + array[out++] = value; + else + array = new Type(value); + } + return array; + } + + // Environment variable used to control console output + const verbose = typeof process != "undefined" && process.env && /\bparse\b/.test(process.env.LOG); + let stackIDs = null; + var Safety; + (function (Safety) { + Safety[Safety["Margin"] = 25] = "Margin"; + })(Safety || (Safety = {})); + function cutAt(tree, pos, side) { + let cursor = tree.cursor(IterMode.IncludeAnonymous); + cursor.moveTo(pos); + for (;;) { + if (!(side < 0 ? cursor.childBefore(pos) : cursor.childAfter(pos))) + for (;;) { + if ((side < 0 ? cursor.to < pos : cursor.from > pos) && !cursor.type.isError) + return side < 0 ? Math.max(0, Math.min(cursor.to - 1, pos - 25 /* Margin */)) + : Math.min(tree.length, Math.max(cursor.from + 1, pos + 25 /* Margin */)); + if (side < 0 ? cursor.prevSibling() : cursor.nextSibling()) + break; + if (!cursor.parent()) + return side < 0 ? 0 : tree.length; + } + } + } + class FragmentCursor { + constructor(fragments, nodeSet) { + this.fragments = fragments; + this.nodeSet = nodeSet; + this.i = 0; + this.fragment = null; + this.safeFrom = -1; + this.safeTo = -1; + this.trees = []; + this.start = []; + this.index = []; + this.nextFragment(); + } + nextFragment() { + let fr = this.fragment = this.i == this.fragments.length ? null : this.fragments[this.i++]; + if (fr) { + this.safeFrom = fr.openStart ? cutAt(fr.tree, fr.from + fr.offset, 1) - fr.offset : fr.from; + this.safeTo = fr.openEnd ? cutAt(fr.tree, fr.to + fr.offset, -1) - fr.offset : fr.to; + while (this.trees.length) { + this.trees.pop(); + this.start.pop(); + this.index.pop(); + } + this.trees.push(fr.tree); + this.start.push(-fr.offset); + this.index.push(0); + this.nextStart = this.safeFrom; + } + else { + this.nextStart = 1e9; + } + } + // `pos` must be >= any previously given `pos` for this cursor + nodeAt(pos) { + if (pos < this.nextStart) + return null; + while (this.fragment && this.safeTo <= pos) + this.nextFragment(); + if (!this.fragment) + return null; + for (;;) { + let last = this.trees.length - 1; + if (last < 0) { // End of tree + this.nextFragment(); + return null; + } + let top = this.trees[last], index = this.index[last]; + if (index == top.children.length) { + this.trees.pop(); + this.start.pop(); + this.index.pop(); + continue; + } + let next = top.children[index]; + let start = this.start[last] + top.positions[index]; + if (start > pos) { + this.nextStart = start; + return null; + } + if (next instanceof Tree) { + if (start == pos) { + if (start < this.safeFrom) + return null; + let end = start + next.length; + if (end <= this.safeTo) { + let lookAhead = next.prop(NodeProp.lookAhead); + if (!lookAhead || end + lookAhead < this.fragment.to) + return next; + } + } + this.index[last]++; + if (start + next.length >= Math.max(this.safeFrom, pos)) { // Enter this node + this.trees.push(next); + this.start.push(start); + this.index.push(0); + } + } + else { + this.index[last]++; + this.nextStart = start + next.length; + } + } + } + } + class TokenCache { + constructor(parser, stream) { + this.stream = stream; + this.tokens = []; + this.mainToken = null; + this.actions = []; + this.tokens = parser.tokenizers.map(_ => new CachedToken); + } + getActions(stack) { + let actionIndex = 0; + let main = null; + let { parser } = stack.p, { tokenizers } = parser; + let mask = parser.stateSlot(stack.state, 3 /* TokenizerMask */); + let context = stack.curContext ? stack.curContext.hash : 0; + let lookAhead = 0; + for (let i = 0; i < tokenizers.length; i++) { + if (((1 << i) & mask) == 0) + continue; + let tokenizer = tokenizers[i], token = this.tokens[i]; + if (main && !tokenizer.fallback) + continue; + if (tokenizer.contextual || token.start != stack.pos || token.mask != mask || token.context != context) { + this.updateCachedToken(token, tokenizer, stack); + token.mask = mask; + token.context = context; + } + if (token.lookAhead > token.end + 25 /* Margin */) + lookAhead = Math.max(token.lookAhead, lookAhead); + if (token.value != 0 /* Err */) { + let startIndex = actionIndex; + if (token.extended > -1) + actionIndex = this.addActions(stack, token.extended, token.end, actionIndex); + actionIndex = this.addActions(stack, token.value, token.end, actionIndex); + if (!tokenizer.extend) { + main = token; + if (actionIndex > startIndex) + break; + } + } + } + while (this.actions.length > actionIndex) + this.actions.pop(); + if (lookAhead) + stack.setLookAhead(lookAhead); + if (!main && stack.pos == this.stream.end) { + main = new CachedToken; + main.value = stack.p.parser.eofTerm; + main.start = main.end = stack.pos; + actionIndex = this.addActions(stack, main.value, main.end, actionIndex); + } + this.mainToken = main; + return this.actions; + } + getMainToken(stack) { + if (this.mainToken) + return this.mainToken; + let main = new CachedToken, { pos, p } = stack; + main.start = pos; + main.end = Math.min(pos + 1, p.stream.end); + main.value = pos == p.stream.end ? p.parser.eofTerm : 0 /* Err */; + return main; + } + updateCachedToken(token, tokenizer, stack) { + let start = this.stream.clipPos(stack.pos); + tokenizer.token(this.stream.reset(start, token), stack); + if (token.value > -1) { + let { parser } = stack.p; + for (let i = 0; i < parser.specialized.length; i++) + if (parser.specialized[i] == token.value) { + let result = parser.specializers[i](this.stream.read(token.start, token.end), stack); + if (result >= 0 && stack.p.parser.dialect.allows(result >> 1)) { + if ((result & 1) == 0 /* Specialize */) + token.value = result >> 1; + else + token.extended = result >> 1; + break; + } + } + } + else { + token.value = 0 /* Err */; + token.end = this.stream.clipPos(start + 1); + } + } + putAction(action, token, end, index) { + // Don't add duplicate actions + for (let i = 0; i < index; i += 3) + if (this.actions[i] == action) + return index; + this.actions[index++] = action; + this.actions[index++] = token; + this.actions[index++] = end; + return index; + } + addActions(stack, token, end, index) { + let { state } = stack, { parser } = stack.p, { data } = parser; + for (let set = 0; set < 2; set++) { + for (let i = parser.stateSlot(state, set ? 2 /* Skip */ : 1 /* Actions */);; i += 3) { + if (data[i] == 65535 /* End */) { + if (data[i + 1] == 1 /* Next */) { + i = pair(data, i + 2); + } + else { + if (index == 0 && data[i + 1] == 2 /* Other */) + index = this.putAction(pair(data, i + 2), token, end, index); + break; + } + } + if (data[i] == token) + index = this.putAction(pair(data, i + 1), token, end, index); + } + } + return index; + } + } + var Rec; + (function (Rec) { + Rec[Rec["Distance"] = 5] = "Distance"; + Rec[Rec["MaxRemainingPerStep"] = 3] = "MaxRemainingPerStep"; + // When two stacks have been running independently long enough to + // add this many elements to their buffers, prune one. + Rec[Rec["MinBufferLengthPrune"] = 500] = "MinBufferLengthPrune"; + Rec[Rec["ForceReduceLimit"] = 10] = "ForceReduceLimit"; + // Once a stack reaches this depth (in .stack.length) force-reduce + // it back to CutTo to avoid creating trees that overflow the stack + // on recursive traversal. + Rec[Rec["CutDepth"] = 15000] = "CutDepth"; + Rec[Rec["CutTo"] = 9000] = "CutTo"; + })(Rec || (Rec = {})); + class Parse { + constructor(parser, input, fragments, ranges) { + this.parser = parser; + this.input = input; + this.ranges = ranges; + this.recovering = 0; + this.nextStackID = 0x2654; // ♔, ♕, ♖, ♗, ♘, ♙, ♠, ♡, ♢, ♣, ♤, ♥, ♦, ♧ + this.minStackPos = 0; + this.reused = []; + this.stoppedAt = null; + this.stream = new InputStream(input, ranges); + this.tokens = new TokenCache(parser, this.stream); + this.topTerm = parser.top[1]; + let { from } = ranges[0]; + this.stacks = [Stack.start(this, parser.top[0], from)]; + this.fragments = fragments.length && this.stream.end - from > parser.bufferLength * 4 + ? new FragmentCursor(fragments, parser.nodeSet) : null; + } + get parsedPos() { + return this.minStackPos; + } + // Move the parser forward. This will process all parse stacks at + // `this.pos` and try to advance them to a further position. If no + // stack for such a position is found, it'll start error-recovery. + // + // When the parse is finished, this will return a syntax tree. When + // not, it returns `null`. + advance() { + let stacks = this.stacks, pos = this.minStackPos; + // This will hold stacks beyond `pos`. + let newStacks = this.stacks = []; + let stopped, stoppedTokens; + // Keep advancing any stacks at `pos` until they either move + // forward or can't be advanced. Gather stacks that can't be + // advanced further in `stopped`. + for (let i = 0; i < stacks.length; i++) { + let stack = stacks[i]; + for (;;) { + this.tokens.mainToken = null; + if (stack.pos > pos) { + newStacks.push(stack); + } + else if (this.advanceStack(stack, newStacks, stacks)) { + continue; + } + else { + if (!stopped) { + stopped = []; + stoppedTokens = []; + } + stopped.push(stack); + let tok = this.tokens.getMainToken(stack); + stoppedTokens.push(tok.value, tok.end); + } + break; + } + } + if (!newStacks.length) { + let finished = stopped && findFinished(stopped); + if (finished) + return this.stackToTree(finished); + if (this.parser.strict) { + if (verbose && stopped) + console.log("Stuck with token " + (this.tokens.mainToken ? this.parser.getName(this.tokens.mainToken.value) : "none")); + throw new SyntaxError("No parse at " + pos); + } + if (!this.recovering) + this.recovering = 5 /* Distance */; + } + if (this.recovering && stopped) { + let finished = this.stoppedAt != null && stopped[0].pos > this.stoppedAt ? stopped[0] + : this.runRecovery(stopped, stoppedTokens, newStacks); + if (finished) + return this.stackToTree(finished.forceAll()); + } + if (this.recovering) { + let maxRemaining = this.recovering == 1 ? 1 : this.recovering * 3 /* MaxRemainingPerStep */; + if (newStacks.length > maxRemaining) { + newStacks.sort((a, b) => b.score - a.score); + while (newStacks.length > maxRemaining) + newStacks.pop(); + } + if (newStacks.some(s => s.reducePos > pos)) + this.recovering--; + } + else if (newStacks.length > 1) { + // Prune stacks that are in the same state, or that have been + // running without splitting for a while, to avoid getting stuck + // with multiple successful stacks running endlessly on. + outer: for (let i = 0; i < newStacks.length - 1; i++) { + let stack = newStacks[i]; + for (let j = i + 1; j < newStacks.length; j++) { + let other = newStacks[j]; + if (stack.sameState(other) || + stack.buffer.length > 500 /* MinBufferLengthPrune */ && other.buffer.length > 500 /* MinBufferLengthPrune */) { + if (((stack.score - other.score) || (stack.buffer.length - other.buffer.length)) > 0) { + newStacks.splice(j--, 1); + } + else { + newStacks.splice(i--, 1); + continue outer; + } + } + } + } + } + this.minStackPos = newStacks[0].pos; + for (let i = 1; i < newStacks.length; i++) + if (newStacks[i].pos < this.minStackPos) + this.minStackPos = newStacks[i].pos; + return null; + } + stopAt(pos) { + if (this.stoppedAt != null && this.stoppedAt < pos) + throw new RangeError("Can't move stoppedAt forward"); + this.stoppedAt = pos; + } + // Returns an updated version of the given stack, or null if the + // stack can't advance normally. When `split` and `stacks` are + // given, stacks split off by ambiguous operations will be pushed to + // `split`, or added to `stacks` if they move `pos` forward. + advanceStack(stack, stacks, split) { + let start = stack.pos, { parser } = this; + let base = verbose ? this.stackID(stack) + " -> " : ""; + if (this.stoppedAt != null && start > this.stoppedAt) + return stack.forceReduce() ? stack : null; + if (this.fragments) { + let strictCx = stack.curContext && stack.curContext.tracker.strict, cxHash = strictCx ? stack.curContext.hash : 0; + for (let cached = this.fragments.nodeAt(start); cached;) { + let match = this.parser.nodeSet.types[cached.type.id] == cached.type ? parser.getGoto(stack.state, cached.type.id) : -1; + if (match > -1 && cached.length && (!strictCx || (cached.prop(NodeProp.contextHash) || 0) == cxHash)) { + stack.useNode(cached, match); + if (verbose) + console.log(base + this.stackID(stack) + ` (via reuse of ${parser.getName(cached.type.id)})`); + return true; + } + if (!(cached instanceof Tree) || cached.children.length == 0 || cached.positions[0] > 0) + break; + let inner = cached.children[0]; + if (inner instanceof Tree && cached.positions[0] == 0) + cached = inner; + else + break; + } + } + let defaultReduce = parser.stateSlot(stack.state, 4 /* DefaultReduce */); + if (defaultReduce > 0) { + stack.reduce(defaultReduce); + if (verbose) + console.log(base + this.stackID(stack) + ` (via always-reduce ${parser.getName(defaultReduce & 65535 /* ValueMask */)})`); + return true; + } + if (stack.stack.length >= 15000 /* CutDepth */) { + while (stack.stack.length > 9000 /* CutTo */ && stack.forceReduce()) { } + } + let actions = this.tokens.getActions(stack); + for (let i = 0; i < actions.length;) { + let action = actions[i++], term = actions[i++], end = actions[i++]; + let last = i == actions.length || !split; + let localStack = last ? stack : stack.split(); + localStack.apply(action, term, end); + if (verbose) + console.log(base + this.stackID(localStack) + ` (via ${(action & 65536 /* ReduceFlag */) == 0 ? "shift" + : `reduce of ${parser.getName(action & 65535 /* ValueMask */)}`} for ${parser.getName(term)} @ ${start}${localStack == stack ? "" : ", split"})`); + if (last) + return true; + else if (localStack.pos > start) + stacks.push(localStack); + else + split.push(localStack); + } + return false; + } + // Advance a given stack forward as far as it will go. Returns the + // (possibly updated) stack if it got stuck, or null if it moved + // forward and was given to `pushStackDedup`. + advanceFully(stack, newStacks) { + let pos = stack.pos; + for (;;) { + if (!this.advanceStack(stack, null, null)) + return false; + if (stack.pos > pos) { + pushStackDedup(stack, newStacks); + return true; + } + } + } + runRecovery(stacks, tokens, newStacks) { + let finished = null, restarted = false; + for (let i = 0; i < stacks.length; i++) { + let stack = stacks[i], token = tokens[i << 1], tokenEnd = tokens[(i << 1) + 1]; + let base = verbose ? this.stackID(stack) + " -> " : ""; + if (stack.deadEnd) { + if (restarted) + continue; + restarted = true; + stack.restart(); + if (verbose) + console.log(base + this.stackID(stack) + " (restarted)"); + let done = this.advanceFully(stack, newStacks); + if (done) + continue; + } + let force = stack.split(), forceBase = base; + for (let j = 0; force.forceReduce() && j < 10 /* ForceReduceLimit */; j++) { + if (verbose) + console.log(forceBase + this.stackID(force) + " (via force-reduce)"); + let done = this.advanceFully(force, newStacks); + if (done) + break; + if (verbose) + forceBase = this.stackID(force) + " -> "; + } + for (let insert of stack.recoverByInsert(token)) { + if (verbose) + console.log(base + this.stackID(insert) + " (via recover-insert)"); + this.advanceFully(insert, newStacks); + } + if (this.stream.end > stack.pos) { + if (tokenEnd == stack.pos) { + tokenEnd++; + token = 0 /* Err */; + } + stack.recoverByDelete(token, tokenEnd); + if (verbose) + console.log(base + this.stackID(stack) + ` (via recover-delete ${this.parser.getName(token)})`); + pushStackDedup(stack, newStacks); + } + else if (!finished || finished.score < stack.score) { + finished = stack; + } + } + return finished; + } + // Convert the stack's buffer to a syntax tree. + stackToTree(stack) { + stack.close(); + return Tree.build({ buffer: StackBufferCursor.create(stack), + nodeSet: this.parser.nodeSet, + topID: this.topTerm, + maxBufferLength: this.parser.bufferLength, + reused: this.reused, + start: this.ranges[0].from, + length: stack.pos - this.ranges[0].from, + minRepeatType: this.parser.minRepeatTerm }); + } + stackID(stack) { + let id = (stackIDs || (stackIDs = new WeakMap)).get(stack); + if (!id) + stackIDs.set(stack, id = String.fromCodePoint(this.nextStackID++)); + return id + stack; + } + } + function pushStackDedup(stack, newStacks) { + for (let i = 0; i < newStacks.length; i++) { + let other = newStacks[i]; + if (other.pos == stack.pos && other.sameState(stack)) { + if (newStacks[i].score < stack.score) + newStacks[i] = stack; + return; + } + } + newStacks.push(stack); + } + class Dialect { + constructor(source, flags, disabled) { + this.source = source; + this.flags = flags; + this.disabled = disabled; + } + allows(term) { return !this.disabled || this.disabled[term] == 0; } + } + const id = x => x; + /// Context trackers are used to track stateful context (such as + /// indentation in the Python grammar, or parent elements in the XML + /// grammar) needed by external tokenizers. You declare them in a + /// grammar file as `@context exportName from "module"`. + /// + /// Context values should be immutable, and can be updated (replaced) + /// on shift or reduce actions. + /// + /// The export used in a `@context` declaration should be of this + /// type. + class ContextTracker { + /// Define a context tracker. + constructor(spec) { + this.start = spec.start; + this.shift = spec.shift || id; + this.reduce = spec.reduce || id; + this.reuse = spec.reuse || id; + this.hash = spec.hash || (() => 0); + this.strict = spec.strict !== false; + } + } + /// Holds the parse tables for a given grammar, as generated by + /// `lezer-generator`, and provides [methods](#common.Parser) to parse + /// content with. + class LRParser extends Parser { + /// @internal + constructor(spec) { + super(); + /// @internal + this.wrappers = []; + if (spec.version != 14 /* Version */) + throw new RangeError(`Parser version (${spec.version}) doesn't match runtime version (${14 /* Version */})`); + let nodeNames = spec.nodeNames.split(" "); + this.minRepeatTerm = nodeNames.length; + for (let i = 0; i < spec.repeatNodeCount; i++) + nodeNames.push(""); + let topTerms = Object.keys(spec.topRules).map(r => spec.topRules[r][1]); + let nodeProps = []; + for (let i = 0; i < nodeNames.length; i++) + nodeProps.push([]); + function setProp(nodeID, prop, value) { + nodeProps[nodeID].push([prop, prop.deserialize(String(value))]); + } + if (spec.nodeProps) + for (let propSpec of spec.nodeProps) { + let prop = propSpec[0]; + if (typeof prop == "string") + prop = NodeProp[prop]; + for (let i = 1; i < propSpec.length;) { + let next = propSpec[i++]; + if (next >= 0) { + setProp(next, prop, propSpec[i++]); + } + else { + let value = propSpec[i + -next]; + for (let j = -next; j > 0; j--) + setProp(propSpec[i++], prop, value); + i++; + } + } + } + this.nodeSet = new NodeSet(nodeNames.map((name, i) => NodeType.define({ + name: i >= this.minRepeatTerm ? undefined : name, + id: i, + props: nodeProps[i], + top: topTerms.indexOf(i) > -1, + error: i == 0, + skipped: spec.skippedNodes && spec.skippedNodes.indexOf(i) > -1 + }))); + if (spec.propSources) + this.nodeSet = this.nodeSet.extend(...spec.propSources); + this.strict = false; + this.bufferLength = DefaultBufferLength; + let tokenArray = decodeArray(spec.tokenData); + this.context = spec.context; + this.specializerSpecs = spec.specialized || []; + this.specialized = new Uint16Array(this.specializerSpecs.length); + for (let i = 0; i < this.specializerSpecs.length; i++) + this.specialized[i] = this.specializerSpecs[i].term; + this.specializers = this.specializerSpecs.map(getSpecializer); + this.states = decodeArray(spec.states, Uint32Array); + this.data = decodeArray(spec.stateData); + this.goto = decodeArray(spec.goto); + this.maxTerm = spec.maxTerm; + this.tokenizers = spec.tokenizers.map(value => typeof value == "number" ? new TokenGroup(tokenArray, value) : value); + this.topRules = spec.topRules; + this.dialects = spec.dialects || {}; + this.dynamicPrecedences = spec.dynamicPrecedences || null; + this.tokenPrecTable = spec.tokenPrec; + this.termNames = spec.termNames || null; + this.maxNode = this.nodeSet.types.length - 1; + this.dialect = this.parseDialect(); + this.top = this.topRules[Object.keys(this.topRules)[0]]; + } + createParse(input, fragments, ranges) { + let parse = new Parse(this, input, fragments, ranges); + for (let w of this.wrappers) + parse = w(parse, input, fragments, ranges); + return parse; + } + /// Get a goto table entry @internal + getGoto(state, term, loose = false) { + let table = this.goto; + if (term >= table[0]) + return -1; + for (let pos = table[term + 1];;) { + let groupTag = table[pos++], last = groupTag & 1; + let target = table[pos++]; + if (last && loose) + return target; + for (let end = pos + (groupTag >> 1); pos < end; pos++) + if (table[pos] == state) + return target; + if (last) + return -1; + } + } + /// Check if this state has an action for a given terminal @internal + hasAction(state, terminal) { + let data = this.data; + for (let set = 0; set < 2; set++) { + for (let i = this.stateSlot(state, set ? 2 /* Skip */ : 1 /* Actions */), next;; i += 3) { + if ((next = data[i]) == 65535 /* End */) { + if (data[i + 1] == 1 /* Next */) + next = data[i = pair(data, i + 2)]; + else if (data[i + 1] == 2 /* Other */) + return pair(data, i + 2); + else + break; + } + if (next == terminal || next == 0 /* Err */) + return pair(data, i + 1); + } + } + return 0; + } + /// @internal + stateSlot(state, slot) { + return this.states[(state * 6 /* Size */) + slot]; + } + /// @internal + stateFlag(state, flag) { + return (this.stateSlot(state, 0 /* Flags */) & flag) > 0; + } + /// @internal + validAction(state, action) { + if (action == this.stateSlot(state, 4 /* DefaultReduce */)) + return true; + for (let i = this.stateSlot(state, 1 /* Actions */);; i += 3) { + if (this.data[i] == 65535 /* End */) { + if (this.data[i + 1] == 1 /* Next */) + i = pair(this.data, i + 2); + else + return false; + } + if (action == pair(this.data, i + 1)) + return true; + } + } + /// Get the states that can follow this one through shift actions or + /// goto jumps. @internal + nextStates(state) { + let result = []; + for (let i = this.stateSlot(state, 1 /* Actions */);; i += 3) { + if (this.data[i] == 65535 /* End */) { + if (this.data[i + 1] == 1 /* Next */) + i = pair(this.data, i + 2); + else + break; + } + if ((this.data[i + 2] & (65536 /* ReduceFlag */ >> 16)) == 0) { + let value = this.data[i + 1]; + if (!result.some((v, i) => (i & 1) && v == value)) + result.push(this.data[i], value); + } + } + return result; + } + /// @internal + overrides(token, prev) { + let iPrev = findOffset(this.data, this.tokenPrecTable, prev); + return iPrev < 0 || findOffset(this.data, this.tokenPrecTable, token) < iPrev; + } + /// Configure the parser. Returns a new parser instance that has the + /// given settings modified. Settings not provided in `config` are + /// kept from the original parser. + configure(config) { + // Hideous reflection-based kludge to make it easy to create a + // slightly modified copy of a parser. + let copy = Object.assign(Object.create(LRParser.prototype), this); + if (config.props) + copy.nodeSet = this.nodeSet.extend(...config.props); + if (config.top) { + let info = this.topRules[config.top]; + if (!info) + throw new RangeError(`Invalid top rule name ${config.top}`); + copy.top = info; + } + if (config.tokenizers) + copy.tokenizers = this.tokenizers.map(t => { + let found = config.tokenizers.find(r => r.from == t); + return found ? found.to : t; + }); + if (config.specializers) { + copy.specializers = this.specializers.slice(); + copy.specializerSpecs = this.specializerSpecs.map((s, i) => { + let found = config.specializers.find(r => r.from == s.external); + if (!found) + return s; + let spec = Object.assign(Object.assign({}, s), { external: found.to }); + copy.specializers[i] = getSpecializer(spec); + return spec; + }); + } + if (config.contextTracker) + copy.context = config.contextTracker; + if (config.dialect) + copy.dialect = this.parseDialect(config.dialect); + if (config.strict != null) + copy.strict = config.strict; + if (config.wrap) + copy.wrappers = copy.wrappers.concat(config.wrap); + if (config.bufferLength != null) + copy.bufferLength = config.bufferLength; + return copy; + } + /// Tells you whether any [parse wrappers](#lr.ParserConfig.wrap) + /// are registered for this parser. + hasWrappers() { + return this.wrappers.length > 0; + } + /// Returns the name associated with a given term. This will only + /// work for all terms when the parser was generated with the + /// `--names` option. By default, only the names of tagged terms are + /// stored. + getName(term) { + return this.termNames ? this.termNames[term] : String(term <= this.maxNode && this.nodeSet.types[term].name || term); + } + /// The eof term id is always allocated directly after the node + /// types. @internal + get eofTerm() { return this.maxNode + 1; } + /// The type of top node produced by the parser. + get topNode() { return this.nodeSet.types[this.top[1]]; } + /// @internal + dynamicPrecedence(term) { + let prec = this.dynamicPrecedences; + return prec == null ? 0 : prec[term] || 0; + } + /// @internal + parseDialect(dialect) { + let values = Object.keys(this.dialects), flags = values.map(() => false); + if (dialect) + for (let part of dialect.split(" ")) { + let id = values.indexOf(part); + if (id >= 0) + flags[id] = true; + } + let disabled = null; + for (let i = 0; i < values.length; i++) + if (!flags[i]) { + for (let j = this.dialects[values[i]], id; (id = this.data[j++]) != 65535 /* End */;) + (disabled || (disabled = new Uint8Array(this.maxTerm + 1)))[id] = 1; + } + return new Dialect(dialect, flags, disabled); + } + /// Used by the output of the parser generator. Not available to + /// user code. + static deserialize(spec) { + return new LRParser(spec); + } + } + function pair(data, off) { return data[off] | (data[off + 1] << 16); } + function findOffset(data, start, term) { + for (let i = start, next; (next = data[i]) != 65535 /* End */; i++) + if (next == term) + return i - start; + return -1; + } + function findFinished(stacks) { + let best = null; + for (let stack of stacks) { + let stopped = stack.p.stoppedAt; + if ((stack.pos == stack.p.stream.end || stopped != null && stack.pos > stopped) && + stack.p.parser.stateFlag(stack.state, 2 /* Accepting */) && + (!best || best.score < stack.score)) + best = stack; + } + return best; + } + function getSpecializer(spec) { + if (spec.external) { + let mask = spec.extend ? 1 /* Extend */ : 0 /* Specialize */; + return (value, stack) => (spec.external(value, stack) << 1) | mask; + } + return spec.get; + } + + // This file was generated by lezer-generator. You probably shouldn't edit it. + const printKeyword = 1, + indent = 189, + dedent = 190, + newline$1 = 191, + newlineBracketed = 192, + newlineEmpty = 193, + eof = 194, + ParenL = 22, + ParenthesizedExpression = 23, + TupleExpression = 47, + ComprehensionExpression = 48, + BracketL = 53, + ArrayExpression = 54, + ArrayComprehensionExpression = 55, + BraceL = 57, + DictionaryExpression = 58, + DictionaryComprehensionExpression = 59, + SetExpression = 60, + SetComprehensionExpression = 61, + ArgList = 63, + subscript = 230, + FormatReplacement = 71, + importList = 255, + ParamList = 121, + SequencePattern = 142, + MappingPattern = 143, + PatternArgList = 146; + + const newline = 10, carriageReturn = 13, space = 32, tab = 9, hash = 35, parenOpen = 40, dot = 46; + + const bracketed = new Set([ + ParenthesizedExpression, TupleExpression, ComprehensionExpression, importList, ArgList, ParamList, + ArrayExpression, ArrayComprehensionExpression, subscript, + SetExpression, SetComprehensionExpression, + DictionaryExpression, DictionaryComprehensionExpression, FormatReplacement, + SequencePattern, MappingPattern, PatternArgList + ]); + + const newlines = new ExternalTokenizer((input, stack) => { + if (input.next < 0) { + input.acceptToken(eof); + } else if (input.next != newline && input.next != carriageReturn) ; else if (stack.context.depth < 0) { + input.acceptToken(newlineBracketed, 1); + } else { + input.advance(); + let spaces = 0; + while (input.next == space || input.next == tab) { input.advance(); spaces++; } + let empty = input.next == newline || input.next == carriageReturn || input.next == hash; + input.acceptToken(empty ? newlineEmpty : newline$1, -spaces); + } + }, {contextual: true, fallback: true}); + + const indentation = new ExternalTokenizer((input, stack) => { + let cDepth = stack.context.depth; + if (cDepth < 0) return + let prev = input.peek(-1); + if ((prev == newline || prev == carriageReturn) && stack.context.depth >= 0) { + let depth = 0, chars = 0; + for (;;) { + if (input.next == space) depth++; + else if (input.next == tab) depth += 8 - (depth % 8); + else break + input.advance(); + chars++; + } + if (depth != cDepth && + input.next != newline && input.next != carriageReturn && input.next != hash) { + if (depth < cDepth) input.acceptToken(dedent, -chars); + else input.acceptToken(indent); + } + } + }); + + function IndentLevel(parent, depth) { + this.parent = parent; + // -1 means this is not an actual indent level but a set of brackets + this.depth = depth; + this.hash = (parent ? parent.hash + parent.hash << 8 : 0) + depth + (depth << 4); + } + + const topIndent = new IndentLevel(null, 0); + + function countIndent(space) { + let depth = 0; + for (let i = 0; i < space.length; i++) + depth += space.charCodeAt(i) == tab ? 8 - (depth % 8) : 1; + return depth + } + + const trackIndent = new ContextTracker({ + start: topIndent, + reduce(context, term) { + return context.depth < 0 && bracketed.has(term) ? context.parent : context + }, + shift(context, term, stack, input) { + if (term == indent) return new IndentLevel(context, countIndent(input.read(input.pos, stack.pos))) + if (term == dedent) return context.parent + if (term == ParenL || term == BracketL || term == BraceL) return new IndentLevel(context, -1) + return context + }, + hash(context) { return context.hash } + }); + + const legacyPrint = new ExternalTokenizer(input => { + for (let i = 0; i < 5; i++) { + if (input.next != "print".charCodeAt(i)) return + input.advance(); + } + if (/\w/.test(String.fromCharCode(input.next))) return + for (let off = 0;; off++) { + let next = input.peek(off); + if (next == space || next == tab) continue + if (next != parenOpen && next != dot && next != newline && next != carriageReturn && next != hash) + input.acceptToken(printKeyword); + return + } + }); + + const pythonHighlighting = styleTags({ + "async \"*\" \"**\" FormatConversion FormatSpec": tags.modifier, + "for while if elif else try except finally return raise break continue with pass assert await yield": tags.controlKeyword, + "in not and or is del": tags.operatorKeyword, + "from def class global nonlocal lambda": tags.definitionKeyword, + import: tags.moduleKeyword, + "with as print": tags.keyword, + Boolean: tags.bool, + None: tags.null, + VariableName: tags.variableName, + "CallExpression/VariableName": tags.function(tags.variableName), + "FunctionDefinition/VariableName": tags.function(tags.definition(tags.variableName)), + "ClassDefinition/VariableName": tags.definition(tags.className), + PropertyName: tags.propertyName, + "CallExpression/MemberExpression/PropertyName": tags.function(tags.propertyName), + Comment: tags.lineComment, + Number: tags.number, + String: tags.string, + FormatString: tags.special(tags.string), + UpdateOp: tags.updateOperator, + ArithOp: tags.arithmeticOperator, + BitOp: tags.bitwiseOperator, + CompareOp: tags.compareOperator, + AssignOp: tags.definitionOperator, + Ellipsis: tags.punctuation, + At: tags.meta, + "( )": tags.paren, + "[ ]": tags.squareBracket, + "{ }": tags.brace, + ".": tags.derefOperator, + ", ;": tags.separator + }); + + // This file was generated by lezer-generator. You probably shouldn't edit it. + const spec_identifier = {__proto__:null,await:40, or:50, and:52, in:56, not:58, is:60, if:66, else:68, lambda:72, yield:90, from:92, async:98, for:100, None:152, True:154, False:154, del:168, pass:172, break:176, continue:180, return:184, raise:192, import:196, as:198, global:202, nonlocal:204, assert:208, elif:218, while:222, try:228, except:230, finally:232, with:236, def:240, class:250, match:261, case:267}; + const parser = LRParser.deserialize({ + version: 14, + states: "!L`O`Q$IXOOO%fQ$I[O'#G|OOQ$IS'#Cm'#CmOOQ$IS'#Cn'#CnO'UQ$IWO'#ClO(wQ$I[O'#G{OOQ$IS'#G|'#G|OOQ$IS'#DS'#DSOOQ$IS'#G{'#G{O)eQ$IWO'#CsO)uQ$IWO'#DdO*VQ$IWO'#DhOOQ$IS'#Ds'#DsO*jO`O'#DsO*rOpO'#DsO*zO!bO'#DtO+VO#tO'#DtO+bO&jO'#DtO+mO,UO'#DtO-oQ$I[O'#GmOOQ$IS'#Gm'#GmO'UQ$IWO'#GlO/RQ$I[O'#GlOOQ$IS'#E]'#E]O/jQ$IWO'#E^OOQ$IS'#Gk'#GkO/tQ$IWO'#GjOOQ$IV'#Gj'#GjO0PQ$IWO'#FPOOQ$IS'#GX'#GXO0UQ$IWO'#FOOOQ$IV'#Hx'#HxOOQ$IV'#Gi'#GiOOQ$IT'#Fh'#FhQ`Q$IXOOO'UQ$IWO'#CoO0dQ$IWO'#C{O0kQ$IWO'#DPO0yQ$IWO'#HQO1ZQ$I[O'#EQO'UQ$IWO'#EROOQ$IS'#ET'#ETOOQ$IS'#EV'#EVOOQ$IS'#EX'#EXO1oQ$IWO'#EZO2VQ$IWO'#E_O0PQ$IWO'#EaO2jQ$I[O'#EaO0PQ$IWO'#EdO/jQ$IWO'#EgO/jQ$IWO'#EkO/jQ$IWO'#EnO2uQ$IWO'#EpO2|Q$IWO'#EuO3XQ$IWO'#EqO/jQ$IWO'#EuO0PQ$IWO'#EwO0PQ$IWO'#E|O3^Q$IWO'#FROOQ$IS'#Cc'#CcOOQ$IS'#Cd'#CdOOQ$IS'#Ce'#CeOOQ$IS'#Cf'#CfOOQ$IS'#Cg'#CgOOQ$IS'#Ch'#ChOOQ$IS'#Cj'#CjO'UQ$IWO,58|O'UQ$IWO,58|O'UQ$IWO,58|O'UQ$IWO,58|O'UQ$IWO,58|O'UQ$IWO,58|O3eQ$IWO'#DmOOQ$IS,5:W,5:WO3xQ$IWO'#H[OOQ$IS,5:Z,5:ZO4VQ%1`O,5:ZO4[Q$I[O,59WO0dQ$IWO,59`O0dQ$IWO,59`O0dQ$IWO,59`O6zQ$IWO,59`O7PQ$IWO,59`O7WQ$IWO,59hO7_Q$IWO'#G{O8eQ$IWO'#GzOOQ$IS'#Gz'#GzOOQ$IS'#DY'#DYO8|Q$IWO,59_O'UQ$IWO,59_O9[Q$IWO,59_O9aQ$IWO,5:PO'UQ$IWO,5:POOQ$IS,5:O,5:OO9oQ$IWO,5:OO9tQ$IWO,5:VO'UQ$IWO,5:VO'UQ$IWO,5:TOOQ$IS,5:S,5:SO:VQ$IWO,5:SO:[Q$IWO,5:UOOOO'#Fp'#FpO:aO`O,5:_OOQ$IS,5:_,5:_OOOO'#Fq'#FqO:iOpO,5:_O:qQ$IWO'#DuOOOO'#Fr'#FrO;RO!bO,5:`OOQ$IS,5:`,5:`OOOO'#Fu'#FuO;^O#tO,5:`OOOO'#Fv'#FvO;iO&jO,5:`OOOO'#Fw'#FwO;tO,UO,5:`OOQ$IS'#Fx'#FxO<PQ$I[O,5:dO>qQ$I[O,5=WO?[Q%GlO,5=WO?{Q$I[O,5=WOOQ$IS,5:x,5:xO@dQ$IXO'#GQOAsQ$IWO,5;TOOQ$IV,5=U,5=UOBOQ$I[O'#HtOBgQ$IWO,5;kOOQ$IS-E:V-E:VOOQ$IV,5;j,5;jO3SQ$IWO'#EwOOQ$IT-E9f-E9fOBoQ$I[O,59ZODvQ$I[O,59gOEaQ$IWO'#G}OElQ$IWO'#G}O0PQ$IWO'#G}OEwQ$IWO'#DROFPQ$IWO,59kOFUQ$IWO'#HRO'UQ$IWO'#HRO/jQ$IWO,5=lOOQ$IS,5=l,5=lO/jQ$IWO'#D|OOQ$IS'#D}'#D}OFsQ$IWO'#FzOGTQ$IWO,58zOGTQ$IWO,58zO)hQ$IWO,5:jOGcQ$I[O'#HTOOQ$IS,5:m,5:mOOQ$IS,5:u,5:uOGvQ$IWO,5:yOHXQ$IWO,5:{OOQ$IS'#F}'#F}OHgQ$I[O,5:{OHuQ$IWO,5:{OHzQ$IWO'#HwOOQ$IS,5;O,5;OOIYQ$IWO'#HsOOQ$IS,5;R,5;RO3XQ$IWO,5;VO3XQ$IWO,5;YOIkQ$I[O'#HyO'UQ$IWO'#HyOIuQ$IWO,5;[O2uQ$IWO,5;[O/jQ$IWO,5;aO0PQ$IWO,5;cOIzQ$IXO'#ElOKTQ$IZO,5;]ONiQ$IWO'#HzO3XQ$IWO,5;aONtQ$IWO,5;cONyQ$IWO,5;hO! RQ$I[O,5;mO'UQ$IWO,5;mO!#uQ$I[O1G.hO!#|Q$I[O1G.hO!&mQ$I[O1G.hO!&wQ$I[O1G.hO!)bQ$I[O1G.hO!)uQ$I[O1G.hO!*YQ$IWO'#HZO!*hQ$I[O'#GmO/jQ$IWO'#HZO!*rQ$IWO'#HYOOQ$IS,5:X,5:XO!*zQ$IWO,5:XO!+PQ$IWO'#H]O!+[Q$IWO'#H]O!+oQ$IWO,5=vOOQ$IS'#Dq'#DqOOQ$IS1G/u1G/uOOQ$IS1G.z1G.zO!,oQ$I[O1G.zO!,vQ$I[O1G.zO0dQ$IWO1G.zO!-cQ$IWO1G/SOOQ$IS'#DX'#DXO/jQ$IWO,59rOOQ$IS1G.y1G.yO!-jQ$IWO1G/cO!-zQ$IWO1G/cO!.SQ$IWO1G/dO'UQ$IWO'#HSO!.XQ$IWO'#HSO!.^Q$I[O1G.yO!.nQ$IWO,59gO!/tQ$IWO,5=rO!0UQ$IWO,5=rO!0^Q$IWO1G/kO!0cQ$I[O1G/kOOQ$IS1G/j1G/jO!0sQ$IWO,5=mO!1jQ$IWO,5=mO/jQ$IWO1G/oO!2XQ$IWO1G/qO!2^Q$I[O1G/qO!2nQ$I[O1G/oOOQ$IS1G/n1G/nOOQ$IS1G/p1G/pOOOO-E9n-E9nOOQ$IS1G/y1G/yOOOO-E9o-E9oO!3OQ$IWO'#HhO/jQ$IWO'#HhO!3^Q$IWO,5:aOOOO-E9p-E9pOOQ$IS1G/z1G/zOOOO-E9s-E9sOOOO-E9t-E9tOOOO-E9u-E9uOOQ$IS-E9v-E9vO!3iQ%GlO1G2rO!4YQ$I[O1G2rO'UQ$IWO,5<eOOQ$IS,5<e,5<eOOQ$IS-E9w-E9wOOQ$IS,5<l,5<lOOQ$IS-E:O-E:OOOQ$IV1G0o1G0oO0PQ$IWO'#F|O!4qQ$I[O,5>`OOQ$IS1G1V1G1VO!5YQ$IWO1G1VOOQ$IS'#DT'#DTO/jQ$IWO,5=iOOQ$IS,5=i,5=iO!5_Q$IWO'#FiO!5jQ$IWO,59mO!5rQ$IWO1G/VO!5|Q$I[O,5=mOOQ$IS1G3W1G3WOOQ$IS,5:h,5:hO!6mQ$IWO'#GlOOQ$IS,5<f,5<fOOQ$IS-E9x-E9xO!7OQ$IWO1G.fOOQ$IS1G0U1G0UO!7^Q$IWO,5=oO!7nQ$IWO,5=oO/jQ$IWO1G0eO/jQ$IWO1G0eO0PQ$IWO1G0gOOQ$IS-E9{-E9{O!8PQ$IWO1G0gO!8[Q$IWO1G0gO!8aQ$IWO,5>cO!8oQ$IWO,5>cO!8}Q$IWO,5>_O!9eQ$IWO,5>_O!9vQ$IZO1G0qO!=XQ$IZO1G0tO!@gQ$IWO,5>eO!@qQ$IWO,5>eO!@yQ$I[O,5>eO/jQ$IWO1G0vO!ATQ$IWO1G0vO3XQ$IWO1G0{ONtQ$IWO1G0}OOQ$IV,5;W,5;WO!AYQ$IYO,5;WO!A_Q$IZO1G0wO!DsQ$IWO'#GUO3XQ$IWO1G0wO3XQ$IWO1G0wO!EQQ$IWO,5>fO!E_Q$IWO,5>fO0PQ$IWO,5>fOOQ$IV1G0{1G0{O!EgQ$IWO'#EyO!ExQ%1`O1G0}OOQ$IV1G1S1G1SO3XQ$IWO1G1SO!FQQ$IWO'#FTOOQ$IV1G1X1G1XO! RQ$I[O1G1XOOQ$IS,5=u,5=uOOQ$IS'#Dn'#DnO/jQ$IWO,5=uO!FVQ$IWO,5=tO!FjQ$IWO,5=tOOQ$IS1G/s1G/sO!FrQ$IWO,5=wO!GSQ$IWO,5=wO!G[Q$IWO,5=wO!GoQ$IWO,5=wO!HPQ$IWO,5=wOOQ$IS1G3b1G3bOOQ$IS7+$f7+$fO!5rQ$IWO7+$nO!IrQ$IWO1G.zO!IyQ$IWO1G.zOOQ$IS1G/^1G/^OOQ$IS,5<V,5<VO'UQ$IWO,5<VOOQ$IS7+$}7+$}O!JQQ$IWO7+$}OOQ$IS-E9i-E9iOOQ$IS7+%O7+%OO!JbQ$IWO,5=nO'UQ$IWO,5=nOOQ$IS7+$e7+$eO!JgQ$IWO7+$}O!JoQ$IWO7+%OO!JtQ$IWO1G3^OOQ$IS7+%V7+%VO!KUQ$IWO1G3^O!K^Q$IWO7+%VOOQ$IS,5<U,5<UO'UQ$IWO,5<UO!KcQ$IWO1G3XOOQ$IS-E9h-E9hO!LYQ$IWO7+%ZOOQ$IS7+%]7+%]O!LhQ$IWO1G3XO!MVQ$IWO7+%]O!M[Q$IWO1G3_O!MlQ$IWO1G3_O!MtQ$IWO7+%ZO!MyQ$IWO,5>SO!NaQ$IWO,5>SO!NaQ$IWO,5>SO!NoO!LQO'#DwO!NzOSO'#HiOOOO1G/{1G/{O# PQ$IWO1G/{O# XQ%GlO7+(^O# xQ$I[O1G2PP#!cQ$IWO'#FyOOQ$IS,5<h,5<hOOQ$IS-E9z-E9zOOQ$IS7+&q7+&qOOQ$IS1G3T1G3TOOQ$IS,5<T,5<TOOQ$IS-E9g-E9gOOQ$IS7+$q7+$qO#!pQ$IWO,5=WO##ZQ$IWO,5=WO##lQ$I[O,5<WO#$PQ$IWO1G3ZOOQ$IS-E9j-E9jOOQ$IS7+&P7+&PO#$aQ$IWO7+&POOQ$IS7+&R7+&RO#$oQ$IWO'#HvO0PQ$IWO'#HuO#%TQ$IWO7+&ROOQ$IS,5<k,5<kO#%`Q$IWO1G3}OOQ$IS-E9}-E9}OOQ$IS,5<g,5<gO#%nQ$IWO1G3yOOQ$IS-E9y-E9yO#&UQ$IZO7+&]O!DsQ$IWO'#GSO3XQ$IWO7+&]O3XQ$IWO7+&`O#)gQ$I[O,5<oO'UQ$IWO,5<oO#)qQ$IWO1G4POOQ$IS-E:R-E:RO#){Q$IWO1G4PO3XQ$IWO7+&bO/jQ$IWO7+&bOOQ$IV7+&g7+&gO!ExQ%1`O7+&iO#*TQ$IXO1G0rOOQ$IV-E:S-E:SO3XQ$IWO7+&cO3XQ$IWO7+&cOOQ$IV,5<p,5<pO#+yQ$IWO,5<pOOQ$IV7+&c7+&cO#,UQ$IZO7+&cO#/dQ$IWO,5<qO#/oQ$IWO1G4QOOQ$IS-E:T-E:TO#/|Q$IWO1G4QO#0UQ$IWO'#H|O#0dQ$IWO'#H|O0PQ$IWO'#H|OOQ$IS'#H|'#H|O#0oQ$IWO'#H{OOQ$IS,5;e,5;eO#0wQ$IWO,5;eO/jQ$IWO'#E{OOQ$IV7+&i7+&iO3XQ$IWO7+&iOOQ$IV7+&n7+&nO#0|Q$IYO,5;oOOQ$IV7+&s7+&sOOQ$IS1G3a1G3aOOQ$IS,5<Y,5<YO#1RQ$IWO1G3`OOQ$IS-E9l-E9lO#1fQ$IWO,5<ZO#1qQ$IWO,5<ZO#2UQ$IWO1G3cOOQ$IS-E9m-E9mO#2fQ$IWO1G3cO#2nQ$IWO1G3cO#3OQ$IWO1G3cO#2fQ$IWO1G3cOOQ$IS<<HY<<HYO#3ZQ$I[O1G1qOOQ$IS<<Hi<<HiP#3hQ$IWO'#FkO7WQ$IWO1G3YO#3uQ$IWO1G3YO#3zQ$IWO<<HiOOQ$IS<<Hj<<HjO#4[Q$IWO7+(xOOQ$IS<<Hq<<HqO#4lQ$I[O1G1pP#5]Q$IWO'#FjO#5jQ$IWO7+(yO#5zQ$IWO7+(yO#6SQ$IWO<<HuO#6XQ$IWO7+(sOOQ$IS<<Hw<<HwO#7OQ$IWO,5<XO'UQ$IWO,5<XOOQ$IS-E9k-E9kOOQ$IS<<Hu<<HuOOQ$IS,5<_,5<_O/jQ$IWO,5<_O#7TQ$IWO1G3nOOQ$IS-E9q-E9qO#7kQ$IWO1G3nOOOO'#Ft'#FtO#7yO!LQO,5:cOOOO,5>T,5>TOOOO7+%g7+%gO#8UQ$IWO1G2rO#8oQ$IWO1G2rP'UQ$IWO'#FlO/jQ$IWO<<IkO#9QQ$IWO,5>bO#9cQ$IWO,5>bO0PQ$IWO,5>bO#9tQ$IWO,5>aOOQ$IS<<Im<<ImP0PQ$IWO'#GPP/jQ$IWO'#F{OOQ$IV-E:Q-E:QO3XQ$IWO<<IwOOQ$IV,5<n,5<nO3XQ$IWO,5<nOOQ$IV<<Iw<<IwOOQ$IV<<Iz<<IzO#9yQ$I[O1G2ZP#:TQ$IWO'#GTO#:[Q$IWO7+)kO#:fQ$IZO<<I|O3XQ$IWO<<I|OOQ$IV<<JT<<JTO3XQ$IWO<<JTOOQ$IV'#GR'#GRO#=tQ$IZO7+&^OOQ$IV<<I}<<I}O#?pQ$IZO<<I}OOQ$IV1G2[1G2[O0PQ$IWO1G2[O3XQ$IWO<<I}O0PQ$IWO1G2]P/jQ$IWO'#GVO#COQ$IWO7+)lO#C]Q$IWO7+)lOOQ$IS'#Ez'#EzO/jQ$IWO,5>hO#CeQ$IWO,5>hOOQ$IS,5>h,5>hO#CpQ$IWO,5>gO#DRQ$IWO,5>gOOQ$IS1G1P1G1POOQ$IS,5;g,5;gO#DZQ$IWO1G1ZP#D`Q$IWO'#FnO#DpQ$IWO1G1uO#ETQ$IWO1G1uO#EeQ$IWO1G1uP#EpQ$IWO'#FoO#E}Q$IWO7+(}O#F_Q$IWO7+(}O#F_Q$IWO7+(}O#FgQ$IWO7+(}O#FwQ$IWO7+(tO7WQ$IWO7+(tOOQ$ISAN>TAN>TO#GbQ$IWO<<LeOOQ$ISAN>aAN>aO/jQ$IWO1G1sO#GrQ$I[O1G1sP#G|Q$IWO'#FmOOQ$IS1G1y1G1yP#HZQ$IWO'#FsO#HhQ$IWO7+)YOOOO-E9r-E9rO#IOQ$IWO7+(^OOQ$ISAN?VAN?VO#IiQ$IWO,5<jO#I}Q$IWO1G3|OOQ$IS-E9|-E9|O#J`Q$IWO1G3|OOQ$IS1G3{1G3{OOQ$IVAN?cAN?cOOQ$IV1G2Y1G2YO3XQ$IWOAN?hO#JqQ$IZOAN?hOOQ$IVAN?oAN?oOOQ$IV-E:P-E:POOQ$IV<<Ix<<IxO3XQ$IWOAN?iO3XQ$IWO7+'vOOQ$IVAN?iAN?iOOQ$IS7+'w7+'wO#NPQ$IWO<<MWOOQ$IS1G4S1G4SO/jQ$IWO1G4SOOQ$IS,5<r,5<rO#N^Q$IWO1G4ROOQ$IS-E:U-E:UOOQ$IU'#GY'#GYO#NoQ$IYO7+&uO#NzQ$IWO'#FUO$ rQ$IWO7+'aO$!SQ$IWO7+'aOOQ$IS7+'a7+'aO$!_Q$IWO<<LiO$!oQ$IWO<<LiO$!oQ$IWO<<LiO$!wQ$IWO'#HUOOQ$IS<<L`<<L`O$#RQ$IWO<<L`OOQ$IS7+'_7+'_O0PQ$IWO1G2UP0PQ$IWO'#GOO$#lQ$IWO7+)hO$#}Q$IWO7+)hOOQ$IVG25SG25SO3XQ$IWOG25SOOQ$IVG25TG25TOOQ$IV<<Kb<<KbOOQ$IS7+)n7+)nP$$`Q$IWO'#GWOOQ$IU-E:W-E:WOOQ$IV<<Ja<<JaO$%SQ$I[O'#FWOOQ$IS'#FY'#FYO$%dQ$IWO'#FXO$&UQ$IWO'#FXOOQ$IS'#FX'#FXO$&ZQ$IWO'#IOO#NzQ$IWO'#F`O#NzQ$IWO'#F`O$&rQ$IWO'#FaO#NzQ$IWO'#FbO$&yQ$IWO'#IPOOQ$IS'#IP'#IPO$'hQ$IWO,5;pOOQ$IS<<J{<<J{O$'pQ$IWO<<J{O$(QQ$IWOANBTO$(bQ$IWOANBTO$(jQ$IWO'#HVOOQ$IS'#HV'#HVO0kQ$IWO'#DaO$)TQ$IWO,5=pOOQ$ISANAzANAzOOQ$IS7+'p7+'pO$)lQ$IWO<<MSOOQ$IVLD*nLD*nO4VQ%1`O'#G[O$)}Q$I[O,5;yO#NzQ$IWO'#FdOOQ$IS,5;},5;}OOQ$IS'#FZ'#FZO$*oQ$IWO,5;sO$*tQ$IWO,5;sOOQ$IS'#F^'#F^O#NzQ$IWO'#GZO$+fQ$IWO,5;wO$,QQ$IWO,5>jO$,bQ$IWO,5>jO0PQ$IWO,5;vO$,sQ$IWO,5;zO$,xQ$IWO,5;zO#NzQ$IWO'#IQO$,}Q$IWO'#IQO$-SQ$IWO,5;{OOQ$IS,5;|,5;|O'UQ$IWO'#FgOOQ$IU1G1[1G1[O3XQ$IWO1G1[OOQ$ISAN@gAN@gO$-XQ$IWOG27oO$-iQ$IWO,59{OOQ$IS1G3[1G3[OOQ$IS,5<v,5<vOOQ$IS-E:Y-E:YO$-nQ$I[O'#FWO$-uQ$IWO'#IRO$.TQ$IWO'#IRO$.]Q$IWO,5<OOOQ$IS1G1_1G1_O$.bQ$IWO1G1_O$.gQ$IWO,5<uOOQ$IS-E:X-E:XO$/RQ$IWO,5<yO$/jQ$IWO1G4UOOQ$IS-E:]-E:]OOQ$IS1G1b1G1bOOQ$IS1G1f1G1fO$/zQ$IWO,5>lO#NzQ$IWO,5>lOOQ$IS1G1g1G1gO$0YQ$I[O,5<ROOQ$IU7+&v7+&vO$!wQ$IWO1G/gO#NzQ$IWO,5<PO$0aQ$IWO,5>mO$0hQ$IWO,5>mOOQ$IS1G1j1G1jOOQ$IS7+&y7+&yP#NzQ$IWO'#G_O$0pQ$IWO1G4WO$0zQ$IWO1G4WO$1SQ$IWO1G4WOOQ$IS7+%R7+%RO$1bQ$IWO1G1kO$1pQ$I[O'#FWO$1wQ$IWO,5<xOOQ$IS,5<x,5<xO$2VQ$IWO1G4XOOQ$IS-E:[-E:[O#NzQ$IWO,5<wO$2^Q$IWO,5<wO$2cQ$IWO7+)rOOQ$IS-E:Z-E:ZO$2mQ$IWO7+)rO#NzQ$IWO,5<QP#NzQ$IWO'#G^O$2uQ$IWO1G2cO#NzQ$IWO1G2cP$3TQ$IWO'#G]O$3[Q$IWO<<M^O$3fQ$IWO1G1lO$3tQ$IWO7+'}O7WQ$IWO'#C{O7WQ$IWO,59`O7WQ$IWO,59`O7WQ$IWO,59`O$4SQ$I[O,5=WO7WQ$IWO1G.zO/jQ$IWO1G/VO/jQ$IWO7+$nP$4gQ$IWO'#FyO'UQ$IWO'#GlO$4tQ$IWO,59`O$4yQ$IWO,59`O$5QQ$IWO,59kO$5VQ$IWO1G/SO0kQ$IWO'#DPO7WQ$IWO,59h", + stateData: "$5m~O%[OS%XOS%WOSQOS~OPhOTeOdsOfXOmtOq!SOtuO}vO!O!PO!R!VO!S!UO!VYO!ZZO!fdO!mdO!ndO!odO!vxO!xyO!zzO!|{O#O|O#S}O#U!OO#X!QO#Y!QO#[!RO#c!TO#f!WO#j!XO#l!YO#q!ZO#tlO#v![O%VqO%gQO%hQO%lRO%mVO&R[O&S]O&V^O&Y_O&``O&caO&ebO~OT!bO]!bO_!cOf!jO!V!lO!d!nO%b!]O%c!^O%d!_O%e!`O%f!`O%g!aO%h!aO%i!bO%j!bO%k!bO~Oi%pXj%pXk%pXl%pXm%pXn%pXq%pXx%pXy%pX!s%pX#^%pX%V%pX%Y%pX%r%pXe%pX!R%pX!S%pX%s%pX!U%pX!Y%pX!O%pX#V%pXr%pX!j%pX~P$bOdsOfXO!VYO!ZZO!fdO!mdO!ndO!odO%gQO%hQO%lRO%mVO&R[O&S]O&V^O&Y_O&``O&caO&ebO~Ox%oXy%oX#^%oX%V%oX%Y%oX%r%oX~Oi!qOj!rOk!pOl!pOm!sOn!tOq!uO!s%oX~P(cOT!{Om/iOt/wO}vO~P'UOT#OOm/iOt/wO!U#PO~P'UOT#SO_#TOm/iOt/wO!Y#UO~P'UO&T#XO&U#ZO~O&W#[O&X#ZO~O!Z#^O&Z#_O&_#aO~O!Z#^O&a#bO&b#aO~O!Z#^O&U#aO&d#dO~O!Z#^O&X#aO&f#fO~OT%aX]%aX_%aXf%aXi%aXj%aXk%aXl%aXm%aXn%aXq%aXx%aX!V%aX!d%aX%b%aX%c%aX%d%aX%e%aX%f%aX%g%aX%h%aX%i%aX%j%aX%k%aXe%aX!R%aX!S%aX~O&R[O&S]O&V^O&Y_O&``O&caO&ebOy%aX!s%aX#^%aX%V%aX%Y%aX%r%aX%s%aX!U%aX!Y%aX!O%aX#V%aXr%aX!j%aX~P+xOx#kOy%`X!s%`X#^%`X%V%`X%Y%`X%r%`X~Om/iOt/wO~P'UO#^#nO%V#pO%Y#pO~O%mVO~O!R#uO#l!YO#q!ZO#tlO~OmtO~P'UOT#zO_#{O%mVOyuP~OT$POm/iOt/wO!O$QO~P'UOy$SO!s$XO%r$TO#^!tX%V!tX%Y!tX~OT$POm/iOt/wO#^!}X%V!}X%Y!}X~P'UOm/iOt/wO#^#RX%V#RX%Y#RX~P'UO!d$_O!m$_O%mVO~OT$iO~P'UO!S$kO#j$lO#l$mO~Oy$nO~OT$uO~P'UOT%OO_%OOe%QOm/iOt/wO~P'UOm/iOt/wOy%TO~P'UO&Q%VO~O_!cOf!jO!V!lO!d!nOT`a]`ai`aj`ak`al`am`an`aq`ax`ay`a!s`a#^`a%V`a%Y`a%b`a%c`a%d`a%e`a%f`a%g`a%h`a%i`a%j`a%k`a%r`ae`a!R`a!S`a%s`a!U`a!Y`a!O`a#V`ar`a!j`a~Ol%[O~Om%[O~P'UOm/iO~P'UOi/kOj/lOk/jOl/jOm/sOn/tOq/xOe%oX!R%oX!S%oX%s%oX!U%oX!Y%oX!O%oX#V%oX!j%oX~P(cO%s%^Oe%nXx%nX!R%nX!S%nX!U%nXy%nX~Oe%`Ox%aO!R%eO!S%dO~Oe%`O~Ox%hO!R%eO!S%dO!U%zX~O!U%lO~Ox%mOy%oO!R%eO!S%dO!Y%uX~O!Y%sO~O!Y%tO~O&T#XO&U%vO~O&W#[O&X%vO~OT%yOm/iOt/wO}vO~P'UO!Z#^O&Z#_O&_%|O~O!Z#^O&a#bO&b%|O~O!Z#^O&U%|O&d#dO~O!Z#^O&X%|O&f#fO~OT!la]!la_!laf!lai!laj!lak!lal!lam!lan!laq!lax!lay!la!V!la!d!la!s!la#^!la%V!la%Y!la%b!la%c!la%d!la%e!la%f!la%g!la%h!la%i!la%j!la%k!la%r!lae!la!R!la!S!la%s!la!U!la!Y!la!O!la#V!lar!la!j!la~P#yOx&ROy%`a!s%`a#^%`a%V%`a%Y%`a%r%`a~P$bOT&TOmtOtuOy%`a!s%`a#^%`a%V%`a%Y%`a%r%`a~P'UOx&ROy%`a!s%`a#^%`a%V%`a%Y%`a%r%`a~OPhOTeOmtOtuO}vO!O!PO!vxO!xyO!zzO!|{O#O|O#S}O#U!OO#X!QO#Y!QO#[!RO#^$tX%V$tX%Y$tX~P'UO#^#nO%V&YO%Y&YO~O!d&ZOf&hX%V&hX#V&hX#^&hX%Y&hX#U&hX~Of!jO%V&]O~Oicajcakcalcamcancaqcaxcayca!sca#^ca%Vca%Yca%rcaeca!Rca!Sca%sca!Uca!Yca!Oca#Vcarca!jca~P$bOqoaxoayoa#^oa%Voa%Yoa%roa~Oi!qOj!rOk!pOl!pOm!sOn!tO!soa~PD_O%r&_Ox%qXy%qX~O%mVOx%qXy%qX~Ox&bOyuX~Oy&dO~Ox%mO#^%uX%V%uX%Y%uXe%uXy%uX!Y%uX!j%uX%r%uX~OT/rOm/iOt/wO}vO~P'UO%r$TO#^Sa%VSa%YSa~Ox&mO#^%wX%V%wX%Y%wXl%wX~P$bOx&pO!O&oO#^#Ra%V#Ra%Y#Ra~O#V&qO#^#Ta%V#Ta%Y#Ta~O!d$_O!m$_O#U&sO%mVO~O#U&sO~Ox&uO#^&kX%V&kX%Y&kX~Ox&wO#^&gX%V&gX%Y&gXy&gX~Ox&{Ol&mX~P$bOl'OO~OPhOTeOmtOtuO}vO!O!PO!vxO!xyO!zzO!|{O#O|O#S}O#U!OO#X!QO#Y!QO#[!RO%V'TO~P'UOr'XO#g'VO#h'WOP#eaT#ead#eaf#eam#eaq#eat#ea}#ea!O#ea!R#ea!S#ea!V#ea!Z#ea!f#ea!m#ea!n#ea!o#ea!v#ea!x#ea!z#ea!|#ea#O#ea#S#ea#U#ea#X#ea#Y#ea#[#ea#c#ea#f#ea#j#ea#l#ea#q#ea#t#ea#v#ea%S#ea%V#ea%g#ea%h#ea%l#ea%m#ea&R#ea&S#ea&V#ea&Y#ea&`#ea&c#ea&e#ea%U#ea%Y#ea~Ox'YO#V'[Oy&nX~Of'^O~Of!jOy$nO~Oy'bO~P$bOT!bO]!bO_!cOf!jO!V!lO!d!nO%d!_O%e!`O%f!`O%g!aO%h!aO%i!bO%j!bO%k!bOiUijUikUilUimUinUiqUixUiyUi!sUi#^Ui%VUi%YUi%bUi%rUieUi!RUi!SUi%sUi!UUi!YUi!OUi#VUirUi!jUi~O%c!^O~P! YO%cUi~P! YOT!bO]!bO_!cOf!jO!V!lO!d!nO%g!aO%h!aO%i!bO%j!bO%k!bOiUijUikUilUimUinUiqUixUiyUi!sUi#^Ui%VUi%YUi%bUi%cUi%dUi%rUieUi!RUi!SUi%sUi!UUi!YUi!OUi#VUirUi!jUi~O%e!`O%f!`O~P!$TO%eUi%fUi~P!$TO_!cOf!jO!V!lO!d!nOiUijUikUilUimUinUiqUixUiyUi!sUi#^Ui%VUi%YUi%bUi%cUi%dUi%eUi%fUi%gUi%hUi%rUieUi!RUi!SUi%sUi!UUi!YUi!OUi#VUirUi!jUi~OT!bO]!bO%i!bO%j!bO%k!bO~P!'ROTUi]Ui%iUi%jUi%kUi~P!'RO!R%eO!S%dOe%}Xx%}X~O%r'fO%s'fO~P+xOx'hOe%|X~Oe'jO~Ox'kOy'mO!U&PX~Om/iOt/wOx'kOy'nO!U&PX~P'UO!U'pO~Ok!pOl!pOm!sOn!tOihiqhixhiyhi!shi#^hi%Vhi%Yhi%rhi~Oj!rO~P!+tOjhi~P!+tOi/kOj/lOk/jOl/jOm/sOn/tO~Or'rO~P!,}OT'wOe'xOm/iOt/wO~P'UOe'xOx'yO~Oe'{O~O!S'}O~Oe(OOx'yO!R%eO!S%dO~P$bOi/kOj/lOk/jOl/jOm/sOn/tOeoa!Roa!Soa%soa!Uoa!Yoa!Ooa#Voaroa!joa~PD_OT'wOm/iOt/wO!U%za~P'UOx(RO!U%za~O!U(SO~Ox(RO!R%eO!S%dO!U%za~P$bOT(WOm/iOt/wO!Y%ua#^%ua%V%ua%Y%uae%uay%ua!j%ua%r%ua~P'UOx(XO!Y%ua#^%ua%V%ua%Y%uae%uay%ua!j%ua%r%ua~O!Y([O~Ox(XO!R%eO!S%dO!Y%ua~P$bOx(_O!R%eO!S%dO!Y%{a~P$bOx(bOy&[X!Y&[X!j&[X~Oy(eO!Y(gO!j(hO~OT&TOmtOtuOy%`i!s%`i#^%`i%V%`i%Y%`i%r%`i~P'UOx(iOy%`i!s%`i#^%`i%V%`i%Y%`i%r%`i~O!d&ZOf&ha%V&ha#V&ha#^&ha%Y&ha#U&ha~O%V(nO~OT#zO_#{O%mVO~Ox&bOyua~OmtOtuO~P'UOx(XO#^%ua%V%ua%Y%uae%uay%ua!Y%ua!j%ua%r%ua~P$bOx(sO#^%`X%V%`X%Y%`X%r%`X~O%r$TO#^Si%VSi%YSi~O#^%wa%V%wa%Y%wal%wa~P'UOx(vO#^%wa%V%wa%Y%wal%wa~OT(zOf(|O%mVO~O#U(}O~O%mVO#^&ka%V&ka%Y&ka~Ox)PO#^&ka%V&ka%Y&ka~Om/iOt/wO#^&ga%V&ga%Y&gay&ga~P'UOx)SO#^&ga%V&ga%Y&gay&ga~Or)WO#a)VOP#_iT#_id#_if#_im#_iq#_it#_i}#_i!O#_i!R#_i!S#_i!V#_i!Z#_i!f#_i!m#_i!n#_i!o#_i!v#_i!x#_i!z#_i!|#_i#O#_i#S#_i#U#_i#X#_i#Y#_i#[#_i#c#_i#f#_i#j#_i#l#_i#q#_i#t#_i#v#_i%S#_i%V#_i%g#_i%h#_i%l#_i%m#_i&R#_i&S#_i&V#_i&Y#_i&`#_i&c#_i&e#_i%U#_i%Y#_i~Or)XOP#biT#bid#bif#bim#biq#bit#bi}#bi!O#bi!R#bi!S#bi!V#bi!Z#bi!f#bi!m#bi!n#bi!o#bi!v#bi!x#bi!z#bi!|#bi#O#bi#S#bi#U#bi#X#bi#Y#bi#[#bi#c#bi#f#bi#j#bi#l#bi#q#bi#t#bi#v#bi%S#bi%V#bi%g#bi%h#bi%l#bi%m#bi&R#bi&S#bi&V#bi&Y#bi&`#bi&c#bi&e#bi%U#bi%Y#bi~OT)ZOl&ma~P'UOx)[Ol&ma~Ox)[Ol&ma~P$bOl)`O~O%T)cO~Or)fO#g'VO#h)eOP#eiT#eid#eif#eim#eiq#eit#ei}#ei!O#ei!R#ei!S#ei!V#ei!Z#ei!f#ei!m#ei!n#ei!o#ei!v#ei!x#ei!z#ei!|#ei#O#ei#S#ei#U#ei#X#ei#Y#ei#[#ei#c#ei#f#ei#j#ei#l#ei#q#ei#t#ei#v#ei%S#ei%V#ei%g#ei%h#ei%l#ei%m#ei&R#ei&S#ei&V#ei&Y#ei&`#ei&c#ei&e#ei%U#ei%Y#ei~Om/iOt/wOy$nO~P'UOm/iOt/wOy&na~P'UOx)lOy&na~OT)pO_)qOe)tO%i)rO%mVO~Oy$nO&q)vO~O%V)zO~OT%OO_%OOm/iOt/wOe%|a~P'UOx*OOe%|a~Om/iOt/wOy*RO!U&Pa~P'UOx*SO!U&Pa~Om/iOt/wOx*SOy*VO!U&Pa~P'UOm/iOt/wOx*SO!U&Pa~P'UOx*SOy*VO!U&Pa~Ok/jOl/jOm/sOn/tOehiihiqhixhi!Rhi!Shi%shi!Uhiyhi!Yhi#^hi%Vhi%Yhi!Ohi#Vhirhi!jhi%rhi~Oj/lO~P!H[Ojhi~P!H[OT'wOe*[Om/iOt/wO~P'UOl*^O~Oe*[Ox*`O~Oe*aO~OT'wOm/iOt/wO!U%zi~P'UOx*bO!U%zi~O!U*cO~OT(WOm/iOt/wO!Y%ui#^%ui%V%ui%Y%uie%uiy%ui!j%ui%r%ui~P'UOx*fO!R%eO!S%dO!Y%{i~Ox*iO!Y%ui#^%ui%V%ui%Y%uie%uiy%ui!j%ui%r%ui~O!Y*jO~O_*lOm/iOt/wO!Y%{i~P'UOx*fO!Y%{i~O!Y*nO~OT*pOm/iOt/wOy&[a!Y&[a!j&[a~P'UOx*qOy&[a!Y&[a!j&[a~O!Z#^O&^*tO!Y!kX~O!Y*vO~Oy(eO!Y*wO~OT&TOmtOtuOy%`q!s%`q#^%`q%V%`q%Y%`q%r%`q~P'UOx$miy$mi!s$mi#^$mi%V$mi%Y$mi%r$mi~P$bOT&TOmtOtuO~P'UOT&TOm/iOt/wO#^%`a%V%`a%Y%`a%r%`a~P'UOx*xO#^%`a%V%`a%Y%`a%r%`a~Ox$`a#^$`a%V$`a%Y$`al$`a~P$bO#^%wi%V%wi%Y%wil%wi~P'UOx*{O#^#Rq%V#Rq%Y#Rq~Ox*|O#V+OO#^&jX%V&jX%Y&jXe&jX~OT+QOf(|O%mVO~O%mVO#^&ki%V&ki%Y&ki~Om/iOt/wO#^&gi%V&gi%Y&giy&gi~P'UOr+UO#a)VOP#_qT#_qd#_qf#_qm#_qq#_qt#_q}#_q!O#_q!R#_q!S#_q!V#_q!Z#_q!f#_q!m#_q!n#_q!o#_q!v#_q!x#_q!z#_q!|#_q#O#_q#S#_q#U#_q#X#_q#Y#_q#[#_q#c#_q#f#_q#j#_q#l#_q#q#_q#t#_q#v#_q%S#_q%V#_q%g#_q%h#_q%l#_q%m#_q&R#_q&S#_q&V#_q&Y#_q&`#_q&c#_q&e#_q%U#_q%Y#_q~Ol$wax$wa~P$bOT)ZOl&mi~P'UOx+]Ol&mi~OPhOTeOmtOq!SOtuO}vO!O!PO!R!VO!S!UO!vxO!xyO!zzO!|{O#O|O#S}O#U!OO#X!QO#Y!QO#[!RO#c!TO#f!WO#j!XO#l!YO#q!ZO#tlO#v![O~P'UOx+gOy$nO#V+gO~O#h+hOP#eqT#eqd#eqf#eqm#eqq#eqt#eq}#eq!O#eq!R#eq!S#eq!V#eq!Z#eq!f#eq!m#eq!n#eq!o#eq!v#eq!x#eq!z#eq!|#eq#O#eq#S#eq#U#eq#X#eq#Y#eq#[#eq#c#eq#f#eq#j#eq#l#eq#q#eq#t#eq#v#eq%S#eq%V#eq%g#eq%h#eq%l#eq%m#eq&R#eq&S#eq&V#eq&Y#eq&`#eq&c#eq&e#eq%U#eq%Y#eq~O#V+iOx$yay$ya~Om/iOt/wOy&ni~P'UOx+kOy&ni~Oy$SO%r+mOe&pXx&pX~O%mVOe&pXx&pX~Ox+qOe&oX~Oe+sO~O%T+uO~OT%OO_%OOm/iOt/wOe%|i~P'UOy+wOx$ca!U$ca~Om/iOt/wOy+xOx$ca!U$ca~P'UOm/iOt/wOy*RO!U&Pi~P'UOx+{O!U&Pi~Om/iOt/wOx+{O!U&Pi~P'UOx+{Oy,OO!U&Pi~Oe$_ix$_i!U$_i~P$bOT'wOm/iOt/wO~P'UOl,QO~OT'wOe,ROm/iOt/wO~P'UOT'wOm/iOt/wO!U%zq~P'UOx$^i!Y$^i#^$^i%V$^i%Y$^ie$^iy$^i!j$^i%r$^i~P$bOT(WOm/iOt/wO~P'UO_*lOm/iOt/wO!Y%{q~P'UOx,SO!Y%{q~O!Y,TO~OT(WOm/iOt/wO!Y%uq#^%uq%V%uq%Y%uqe%uqy%uq!j%uq%r%uq~P'UOy,UO~OT*pOm/iOt/wOy&[i!Y&[i!j&[i~P'UOx,ZOy&[i!Y&[i!j&[i~O!Z#^O&^*tO!Y!ka~OT&TOm/iOt/wO#^%`i%V%`i%Y%`i%r%`i~P'UOx,]O#^%`i%V%`i%Y%`i%r%`i~O%mVO#^&ja%V&ja%Y&jae&ja~Ox,`O#^&ja%V&ja%Y&jae&ja~Oe,cO~Ol$wix$wi~P$bOT)ZO~P'UOT)ZOl&mq~P'UOr,fOP#dyT#dyd#dyf#dym#dyq#dyt#dy}#dy!O#dy!R#dy!S#dy!V#dy!Z#dy!f#dy!m#dy!n#dy!o#dy!v#dy!x#dy!z#dy!|#dy#O#dy#S#dy#U#dy#X#dy#Y#dy#[#dy#c#dy#f#dy#j#dy#l#dy#q#dy#t#dy#v#dy%S#dy%V#dy%g#dy%h#dy%l#dy%m#dy&R#dy&S#dy&V#dy&Y#dy&`#dy&c#dy&e#dy%U#dy%Y#dy~OPhOTeOmtOq!SOtuO}vO!O!PO!R!VO!S!UO!vxO!xyO!zzO!|{O#O|O#S}O#U!OO#X!QO#Y!QO#[!RO#c!TO#f!WO#j!XO#l!YO#q!ZO#tlO#v![O%U,jO%Y,jO~P'UO#h,kOP#eyT#eyd#eyf#eym#eyq#eyt#ey}#ey!O#ey!R#ey!S#ey!V#ey!Z#ey!f#ey!m#ey!n#ey!o#ey!v#ey!x#ey!z#ey!|#ey#O#ey#S#ey#U#ey#X#ey#Y#ey#[#ey#c#ey#f#ey#j#ey#l#ey#q#ey#t#ey#v#ey%S#ey%V#ey%g#ey%h#ey%l#ey%m#ey&R#ey&S#ey&V#ey&Y#ey&`#ey&c#ey&e#ey%U#ey%Y#ey~Om/iOt/wOy&nq~P'UOx,oOy&nq~O%r+mOe&pax&pa~OT)pO_)qO%i)rO%mVOe&oa~Ox,sOe&oa~O#y,wO~OT%OO_%OOm/iOt/wO~P'UOm/iOt/wOy,xOx$ci!U$ci~P'UOm/iOt/wOx$ci!U$ci~P'UOy,xOx$ci!U$ci~Om/iOt/wOy*RO~P'UOm/iOt/wOy*RO!U&Pq~P'UOx,{O!U&Pq~Om/iOt/wOx,{O!U&Pq~P'UOq-OO!R%eO!S%dOe%vq!U%vq!Y%vqx%vq~P!,}O_*lOm/iOt/wO!Y%{y~P'UOx$ai!Y$ai~P$bO_*lOm/iOt/wO~P'UOT*pOm/iOt/wO~P'UOT*pOm/iOt/wOy&[q!Y&[q!j&[q~P'UOT&TOm/iOt/wO#^%`q%V%`q%Y%`q%r%`q~P'UO#V-SOx$ra#^$ra%V$ra%Y$rae$ra~O%mVO#^&ji%V&ji%Y&jie&ji~Ox-UO#^&ji%V&ji%Y&jie&ji~Or-XOP#d!RT#d!Rd#d!Rf#d!Rm#d!Rq#d!Rt#d!R}#d!R!O#d!R!R#d!R!S#d!R!V#d!R!Z#d!R!f#d!R!m#d!R!n#d!R!o#d!R!v#d!R!x#d!R!z#d!R!|#d!R#O#d!R#S#d!R#U#d!R#X#d!R#Y#d!R#[#d!R#c#d!R#f#d!R#j#d!R#l#d!R#q#d!R#t#d!R#v#d!R%S#d!R%V#d!R%g#d!R%h#d!R%l#d!R%m#d!R&R#d!R&S#d!R&V#d!R&Y#d!R&`#d!R&c#d!R&e#d!R%U#d!R%Y#d!R~Om/iOt/wOy&ny~P'UOT)pO_)qO%i)rO%mVOe&oi~O#y,wO%U-_O%Y-_O~OT-iOf-gO!V-fO!Z-hO!f-bO!n-dO!o-dO%h-aO%mVO&R[O&S]O&V^O~Om/iOt/wOx$cq!U$cq~P'UOy-nOx$cq!U$cq~Om/iOt/wOy*RO!U&Py~P'UOx-oO!U&Py~Om/iOt-sO~P'UOq-OO!R%eO!S%dOe%vy!U%vy!Y%vyx%vy~P!,}O%mVO#^&jq%V&jq%Y&jqe&jq~Ox-wO#^&jq%V&jq%Y&jqe&jq~OT)pO_)qO%i)rO%mVO~Of-{O!d-yOx#zX#V#zX%b#zXe#zX~Oq#zXy#zX!U#zX!Y#zX~P$$nO%g-}O%h-}Oq#{Xx#{Xy#{X#V#{X%b#{X!U#{Xe#{X!Y#{X~O!f.PO~Ox.TO#V.VO%b.QOq&rXy&rX!U&rXe&rX~O_.YO~P$ WOf-{Oq&sXx&sXy&sX#V&sX%b&sX!U&sXe&sX!Y&sX~Oq.^Oy$nO~Om/iOt/wOx$cy!U$cy~P'UOm/iOt/wOy*RO!U&P!R~P'UOx.bO!U&P!R~Oe%yXq%yX!R%yX!S%yX!U%yX!Y%yXx%yX~P!,}Oq-OO!R%eO!S%dOe%xa!U%xa!Y%xax%xa~O%mVO#^&jy%V&jy%Y&jye&jy~O!d-yOf$Raq$Rax$Ray$Ra#V$Ra%b$Ra!U$Rae$Ra!Y$Ra~O!f.kO~O%g-}O%h-}Oq#{ax#{ay#{a#V#{a%b#{a!U#{ae#{a!Y#{a~O%b.QOq$Pax$Pay$Pa#V$Pa!U$Pae$Pa!Y$Pa~Oq&ray&ra!U&rae&ra~P#NzOx.pOq&ray&ra!U&rae&ra~O!U.sO~Oe.sO~Oy.uO~O!Y.vO~Om/iOt/wOy*RO!U&P!Z~P'UOy.yO~O%r.zO~P$$nOx.{O#V.VO%b.QOe&uX~Ox.{Oe&uX~Oe.}O~O!f/OO~O#V.VOq$}ax$}ay$}a%b$}a!U$}ae$}a!Y$}a~O#V.VO%b.QOq%Rax%Ray%Ra!U%Rae%Ra~Oq&riy&ri!U&rie&ri~P#NzOx/QO#V.VO%b.QO!Y&ta~Oy$Za~P$bOe&ua~P#NzOx/YOe&ua~O_/[O!Y&ti~P$ WOx/^O!Y&ti~Ox/^O#V.VO%b.QO!Y&ti~O#V.VO%b.QOe$Xix$Xi~O%r/aO~P$$nO#V.VO%b.QOe%Qax%Qa~Oe&ui~P#NzOy/dO~O_/[O!Y&tq~P$ WOx/fO!Y&tq~O#V.VO%b.QOx%Pi!Y%Pi~O_/[O~P$ WO_/[O!Y&ty~P$ WO#V.VO%b.QOe$Yix$Yi~O#V.VO%b.QOx%Pq!Y%Pq~Ox*xO#^%`a%V%`a%Y%`a%r%`a~P$bOT&TOm/iOt/wO~P'UOl/nO~Om/nO~P'UOy/oO~Or/pO~P!,}O&S&V&c&e&R!Z&Z&a&d&f&Y&`&Y%m~", + goto: "!9p&vPPPP&wP'P*e*}+h,S,o-]P-zP'P.k.k'PPPP'P2PPPPPPP2P4oPP4oP6{7U=QPP=T=c=fPP'P'PPP=rPP'P'PPP'P'P'P'P'P=v>m'PP>pP>vByFcPFw'PPPPF{GR&wP&w&wP&wP&wP&wP&wP&w&w&wP&wPP&wPP&wPGXPG`GfPG`PG`G`PPPG`PIePInItIzIePG`JQPG`PJXJ_PJcJwKfLPJcJcLVLdJcJcJcJcLxMOMRMWMZMaMgMsNVN]NgNm! Z! a! g! m! w! }!!T!!Z!!a!!g!!y!#T!#Z!#a!#g!#q!#w!#}!$T!$Z!$e!$k!$u!${!%U!%[!%k!%s!%}!&UPPPPPPPPP!&[!&d!&m!&w!'SPPPPPPPPPPPP!+r!,[!0j!3vPP!4O!4^!4g!5]!5S!5f!5l!5o!5r!5u!5}!6nPPPPPPPPPP!6q!6tPPPPPPPPP!6z!7W!7d!7j!7s!7v!7|!8S!8Y!8]P!8e!8n!9j!9m]iOr#n$n)c+c'udOSXYZehrstvx|}!R!S!T!U!X![!d!e!f!g!h!i!j!l!p!q!r!t!u!{#O#S#T#^#k#n$P$Q$S$U$X$i$k$l$n$u%O%T%[%_%a%d%h%m%o%y&R&T&`&d&m&o&p&w&{'O'V'Y'g'h'k'm'n'r'w'y'}(R(W(X(_(b(i(k(s(v)S)V)Z)[)`)c)l)v*O*R*S*V*]*^*`*b*e*f*i*l*p*q*x*z*{+S+[+]+c+j+k+n+v+w+x+z+{,O,Q,S,U,W,Y,Z,],o,q,x,{-O-n-o.^.b.y/i/j/k/l/n/o/p/q/r/t/x}!dP#j#w$Y$h$t%f%k%q%r&e&}'d(j(u)Y*Z*d+Z,V.w/m!P!eP#j#w$Y$h$t$v%f%k%q%r&e&}'d(j(u)Y*Z*d+Z,V.w/m!R!fP#j#w$Y$h$t$v$w%f%k%q%r&e&}'d(j(u)Y*Z*d+Z,V.w/m!T!gP#j#w$Y$h$t$v$w$x%f%k%q%r&e&}'d(j(u)Y*Z*d+Z,V.w/m!V!hP#j#w$Y$h$t$v$w$x$y%f%k%q%r&e&}'d(j(u)Y*Z*d+Z,V.w/m!X!iP#j#w$Y$h$t$v$w$x$y$z%f%k%q%r&e&}'d(j(u)Y*Z*d+Z,V.w/m!]!iP!o#j#w$Y$h$t$v$w$x$y$z${%f%k%q%r&e&}'d(j(u)Y*Z*d+Z,V.w/m'uSOSXYZehrstvx|}!R!S!T!U!X![!d!e!f!g!h!i!j!l!p!q!r!t!u!{#O#S#T#^#k#n$P$Q$S$U$X$i$k$l$n$u%O%T%[%_%a%d%h%m%o%y&R&T&`&d&m&o&p&w&{'O'V'Y'g'h'k'm'n'r'w'y'}(R(W(X(_(b(i(k(s(v)S)V)Z)[)`)c)l)v*O*R*S*V*]*^*`*b*e*f*i*l*p*q*x*z*{+S+[+]+c+j+k+n+v+w+x+z+{,O,Q,S,U,W,Y,Z,],o,q,x,{-O-n-o.^.b.y/i/j/k/l/n/o/p/q/r/t/x&ZUOXYZhrtv|}!R!S!T!X!j!l!p!q!r!t!u#^#k#n$Q$S$U$X$l$n%O%T%[%_%a%h%m%o%y&R&`&d&o&p&w'O'V'Y'g'h'k'm'n'r'y(R(X(_(b(i(k(s)S)V)`)c)l)v*O*R*S*V*]*^*`*b*e*f*i*p*q*x*{+S+c+j+k+n+v+w+x+z+{,O,Q,S,U,W,Y,Z,],o,q,x,{-O-n-o.b.y/i/j/k/l/n/o/p/q/t/x%eWOXYZhrv|}!R!S!T!X!j!l#^#k#n$Q$S$U$X$l$n%O%T%_%a%h%m%o%y&R&`&d&o&p&w'O'V'Y'g'h'k'm'n'r'y(R(X(_(b(i(k(s)S)V)`)c)l)v*O*R*S*V*]*`*b*e*f*i*p*q*x*{+S+c+j+k+n+v+w+x+z+{,O,S,U,W,Y,Z,],o,q,x,{-n-o.b/o/p/qQ#}uQ.c-sR/u/w'ldOSXYZehrstvx|}!R!S!T!U!X![!d!e!f!g!h!i!l!p!q!r!t!u!{#O#S#T#^#k#n$P$Q$S$U$X$i$k$l$n$u%O%T%[%_%a%d%h%m%o%y&R&T&`&d&m&o&p&w&{'O'V'Y'g'k'm'n'r'w'y'}(R(W(X(_(b(i(k(s(v)S)V)Z)[)`)c)l)v*R*S*V*]*^*`*b*e*f*i*l*p*q*x*z*{+S+[+]+c+j+k+n+w+x+z+{,O,Q,S,U,W,Y,Z,],o,q,x,{-O-n-o.^.b.y/i/j/k/l/n/o/p/q/r/t/xW#ql!O!P$`W#yu&b-s/wQ$b!QQ$r!YQ$s!ZW$}!j'h*O+vS&a#z#{Q'R$mQ(l&ZQ(z&qU({&s(|(}U)O&u)P+RQ)n'[W)o'^+q,s-]S+p)p)qY,_*|,`-T-U-wQ,b+OQ,l+gQ,n+il-`,w-f-g-i.R.T.Y.p.u.z/P/[/a/dQ-v-SQ.Z-hQ.g-{Q.r.VU/V.{/Y/bX/]/Q/^/e/fR&`#yi!xXY!S!T%a%h'y(R)V*]*`*bR%_!wQ!|XQ%z#^Q&i$UR&l$XT-r-O.y![!kP!o#j#w$Y$h$t$v$w$x$y$z${%f%k%q%r&e&}'d(j(u)Y*Z*d+Z,V.w/mQ&^#rR'a$sR'g$}Q%W!nR.e-y'tcOSXYZehrstvx|}!R!S!T!U!X![!d!e!f!g!h!i!j!l!p!q!r!t!u!{#O#S#T#^#k#n$P$Q$S$U$X$i$k$l$n$u%O%T%[%_%a%d%h%m%o%y&R&T&`&d&m&o&p&w&{'O'V'Y'g'h'k'm'n'r'w'y'}(R(W(X(_(b(i(k(s(v)S)V)Z)[)`)c)l)v*O*R*S*V*]*^*`*b*e*f*i*l*p*q*x*z*{+S+[+]+c+j+k+n+v+w+x+z+{,O,Q,S,U,W,Y,Z,],o,q,x,{-O-n-o.^.b.y/i/j/k/l/n/o/p/q/r/t/xS#hc#i!P-d,w-f-g-h-i-{.R.T.Y.p.u.z.{/P/Q/Y/[/^/a/b/d/e/f'tcOSXYZehrstvx|}!R!S!T!U!X![!d!e!f!g!h!i!j!l!p!q!r!t!u!{#O#S#T#^#k#n$P$Q$S$U$X$i$k$l$n$u%O%T%[%_%a%d%h%m%o%y&R&T&`&d&m&o&p&w&{'O'V'Y'g'h'k'm'n'r'w'y'}(R(W(X(_(b(i(k(s(v)S)V)Z)[)`)c)l)v*O*R*S*V*]*^*`*b*e*f*i*l*p*q*x*z*{+S+[+]+c+j+k+n+v+w+x+z+{,O,Q,S,U,W,Y,Z,],o,q,x,{-O-n-o.^.b.y/i/j/k/l/n/o/p/q/r/t/xT#hc#iS#__#`S#b`#cS#da#eS#fb#gT*t(e*uT(f%z(hQ$WwR+o)oX$Uw$V$W&kZkOr$n)c+cXoOr)c+cQ$o!WQ&y$fQ&z$gQ']$qQ'`$sQ)a'QQ)g'VQ)i'WQ)j'XQ)w'_Q)y'aQ+V)VQ+X)WQ+Y)XQ+^)_S+`)b)xQ+d)eQ+e)fQ+f)hQ,d+UQ,e+WQ,g+_Q,h+aQ,m+hQ-W,fQ-Y,kQ-Z,lQ-x-XQ._-lR.x.`WoOr)c+cR#tnQ'_$rR)b'RQ+n)oR,q+oQ)x'_R+a)bZmOnr)c+cQ'c$tR){'dT,u+u,vu-k,w-f-g-i-{.R.T.Y.p.u.z.{/P/Y/[/a/b/dt-k,w-f-g-i-{.R.T.Y.p.u.z.{/P/Y/[/a/b/dQ.Z-hX/]/Q/^/e/f!P-c,w-f-g-h-i-{.R.T.Y.p.u.z.{/P/Q/Y/[/^/a/b/d/e/fQ.O-bR.l.Pg.R-e.S.h.o.t/S/U/W/c/g/hu-j,w-f-g-i-{.R.T.Y.p.u.z.{/P/Y/[/a/b/dX-|-`-j.g/VR.i-{V/X.{/Y/bR.`-lQrOR#vrQ&c#|R(q&cS%n#R$OS(Y%n(]T(]%q&eQ%b!zQ%i!}W'z%b%i(P(TQ(P%fR(T%kQ&n$YR(w&nQ(`%rQ*g(ZT*m(`*gQ'i%PR*P'iS'l%S%TY*T'l*U+|,|-pU*U'm'n'oU+|*V*W*XS,|+},OR-p,}Q#Y]R%u#YQ#]^R%w#]Q#`_R%{#`Q(c%xS*r(c*sR*s(dQ*u(eR,[*uQ#c`R%}#cQ#eaR&O#eQ#gbR&P#gQ#icR&Q#iQ#lfQ&S#jW&V#l&S(t*yQ(t&hR*y/mQ$VwS&j$V&kR&k$WQ&x$dR)T&xQ&[#qR(m&[Q$`!PR&r$`Q*}({S,a*}-VR-V,bQ&v$bR)Q&vQ#ojR&X#oQ+c)cR,i+cQ)U&yR+T)UQ&|$hS)]&|)^R)^&}Q'U$oR)d'UQ'Z$pS)m'Z+lR+l)nQ+r)sR,t+rWnOr)c+cR#snQ,v+uR-^,vd.S-e.h.o.t/S/U/W/c/g/hR.n.SU-z-`.g/VR.f-zQ/R.tS/_/R/`R/`/SS.|.h.iR/Z.|Q.U-eR.q.USqOrT+b)c+cWpOr)c+cR'S$nYjOr$n)c+cR&W#n[wOr#n$n)c+cR&i$U&YPOXYZhrtv|}!R!S!T!X!j!l!p!q!r!t!u#^#k#n$Q$S$U$X$l$n%O%T%[%_%a%h%m%o%y&R&`&d&o&p&w'O'V'Y'g'h'k'm'n'r'y(R(X(_(b(i(k(s)S)V)`)c)l)v*O*R*S*V*]*^*`*b*e*f*i*p*q*x*{+S+c+j+k+n+v+w+x+z+{,O,Q,S,U,W,Y,Z,],o,q,x,{-O-n-o.b.y/i/j/k/l/n/o/p/q/t/xQ!oSQ#jeQ#wsU$Yx%d'}S$h!U$kQ$t![Q$v!dQ$w!eQ$x!fQ$y!gQ$z!hQ${!iQ%f!{Q%k#OQ%q#SQ%r#TQ&e$PQ&}$iQ'd$uQ(j&TU(u&m(v*zW)Y&{)[+[+]Q*Z'wQ*d(WQ+Z)ZQ,V*lQ.w.^R/m/rQ!zXQ!}YQ$f!SQ$g!T^'v%a%h'y(R*]*`*bR+W)V[fOr#n$n)c+ch!wXY!S!T%a%h'y(R)V*]*`*bQ#RZQ#mhS$Ov|Q$]}W$d!R$X'O)`S$p!X$lW$|!j'h*O+vQ%S!lQ%x#^`&U#k&R(i(k(s*x,]/qQ&f$QQ&g$SQ&h$UQ'e%OQ'o%TQ'u%_W(V%m(X*e*iQ(Z%oQ(d%yQ(o&`S(r&d/oQ(x&oQ(y&pU)R&w)S+SQ)h'VY)k'Y)l+j+k,oQ)|'g^*Q'k*S+z+{,{-o.bQ*W'mQ*X'nS*Y'r/pW*k(_*f,S,WW*o(b*q,Y,ZQ+t)vQ+y*RQ+}*VQ,X*pQ,^*{Q,p+nQ,y+wQ,z+xQ,},OQ-R,UQ-[,qQ-m,xR.a-nhTOr#k#n$n&R&d'r(i(k)c+c$z!vXYZhv|}!R!S!T!X!j!l#^$Q$S$U$X$l%O%T%_%a%h%m%o%y&`&o&p&w'O'V'Y'g'h'k'm'n'y(R(X(_(b(s)S)V)`)l)v*O*R*S*V*]*`*b*e*f*i*p*q*x*{+S+j+k+n+v+w+x+z+{,O,S,U,W,Y,Z,],o,q,x,{-n-o.b/o/p/qQ#xtW%X!p!t/j/tQ%Y!qQ%Z!rQ%]!uQ%g/iS'q%[/nQ's/kQ't/lQ,P*^Q-Q,QS-q-O.yR/v/xU#|u-s/wR(p&b[gOr#n$n)c+cX!yX#^$U$XQ#WZQ$RvR$[|Q%c!zQ%j!}Q%p#RQ'e$|Q(Q%fQ(U%kQ(^%qQ(a%rQ*h(ZQ-P,PQ-u-QR.d-tQ$ZxQ'|%dR*_'}Q-t-OR/T.yR#QYR#VZR%R!jQ%P!jV)}'h*O+v!]!mP!o#j#w$Y$h$t$v$w$x$y$z${%f%k%q%r&e&}'d(j(u)Y*Z*d+Z,V.w/mR%U!lR%z#^Q(g%zR*w(hQ$e!RQ&l$XQ)_'OR+_)`Q#rlQ$^!OQ$a!PR&t$`Q(z&sR+Q(}Q(z&sQ+P(|R+Q(}R$c!QXpOr)c+cQ$j!UR'P$kQ$q!XR'Q$lR)u'^Q)s'^V,r+q,s-]Q-l,wQ.W-fR.X-gU-e,w-f-gQ.]-iQ.h-{Q.m.RU.o.T.p/PQ.t.YQ/S.uQ/U.zU/W.{/Y/bQ/c/[Q/g/aR/h/dR.[-hR.j-{", + nodeNames: "⚠ print Comment Script AssignStatement * BinaryExpression BitOp BitOp BitOp BitOp ArithOp ArithOp @ ArithOp ** UnaryExpression ArithOp BitOp AwaitExpression await ) ( ParenthesizedExpression BinaryExpression or and CompareOp in not is UnaryExpression ConditionalExpression if else LambdaExpression lambda ParamList VariableName AssignOp , : NamedExpression AssignOp YieldExpression yield from TupleExpression ComprehensionExpression async for LambdaExpression ] [ ArrayExpression ArrayComprehensionExpression } { DictionaryExpression DictionaryComprehensionExpression SetExpression SetComprehensionExpression CallExpression ArgList AssignOp MemberExpression . PropertyName Number String FormatString FormatReplacement FormatConversion FormatSpec ContinuedString Ellipsis None Boolean TypeDef AssignOp UpdateStatement UpdateOp ExpressionStatement DeleteStatement del PassStatement pass BreakStatement break ContinueStatement continue ReturnStatement return YieldStatement PrintStatement RaiseStatement raise ImportStatement import as ScopeStatement global nonlocal AssertStatement assert StatementGroup ; IfStatement Body elif WhileStatement while ForStatement TryStatement try except finally WithStatement with FunctionDefinition def ParamList AssignOp TypeDef ClassDefinition class DecoratedStatement Decorator At MatchStatement match MatchBody MatchClause case CapturePattern LiteralPattern ArithOp ArithOp AsPattern OrPattern LogicOp AttributePattern SequencePattern MappingPattern StarPattern ClassPattern PatternArgList KeywordPattern KeywordPattern Guard", + maxTerm: 267, + context: trackIndent, + nodeProps: [ + ["group", -14,4,80,82,83,85,87,89,91,93,94,95,97,100,103,"Statement Statement",-22,6,16,19,23,38,47,48,54,55,58,59,60,61,62,65,68,69,70,74,75,76,77,"Expression",-10,105,107,110,112,113,117,119,124,126,129,"Statement",-9,134,135,138,139,141,142,143,144,145,"Pattern"], + ["openedBy", 21,"(",52,"[",56,"{"], + ["closedBy", 22,")",53,"]",57,"}"] + ], + propSources: [pythonHighlighting], + skippedNodes: [0,2], + repeatNodeCount: 38, + tokenData: "&JdMgR!^OX$}XY!&]Y[$}[]!&]]p$}pq!&]qr!(grs!,^st!IYtu$}uv$5[vw$7nwx$8zxy%'vyz%(|z{%*S{|%,r|}%.O}!O%/U!O!P%1k!P!Q%<q!Q!R%?a!R![%Cc![!]%N_!]!^&!q!^!_&#w!_!`&&g!`!a&'s!a!b$}!b!c&*`!c!d&+n!d!e&-`!e!h&+n!h!i&7[!i!t&+n!t!u&@j!u!w&+n!w!x&5j!x!}&+n!}#O&Bt#O#P!'u#P#Q&Cz#Q#R&EQ#R#S&+n#S#T$}#T#U&+n#U#V&-`#V#Y&+n#Y#Z&7[#Z#f&+n#f#g&@j#g#i&+n#i#j&5j#j#o&+n#o#p&F^#p#q&GS#q#r&H`#r#s&I^#s$g$}$g~&+n<r%`Z&^7[&TS&WW&Z`&ap&d!b&f#tOr$}rs&Rsw$}wxHsx#O$}#O#P!$R#P#o$}#o#p!%i#p#q$}#q#r!$g#r~$}<Q&^Z&^7[&TS&Z`&d!bOr'PrsFisw'Pwx(Rx#O'P#O#PAe#P#o'P#o#pEu#p#q'P#q#rAy#r~'P<Q'`Z&^7[&TS&WW&Z`&d!b&f#tOr'Prs&Rsw'Pwx(Rx#O'P#O#PAe#P#o'P#o#pEu#p#q'P#q#rAy#r~'P;p([Z&^7[&WW&f#tOr(}rs)}sw(}wx={x#O(}#O#P2]#P#o(}#o#p:X#p#q(}#q#r2q#r~(};p)[Z&^7[&TS&WW&d!b&f#tOr(}rs)}sw(}wx(Rx#O(}#O#P2]#P#o(}#o#p:X#p#q(}#q#r2q#r~(};p*WZ&^7[&TS&d!bOr(}rs*ysw(}wx(Rx#O(}#O#P2]#P#o(}#o#p:X#p#q(}#q#r2q#r~(};p+SZ&^7[&TS&d!bOr(}rs+usw(}wx(Rx#O(}#O#P2]#P#o(}#o#p:X#p#q(}#q#r2q#r~(}8r,OX&^7[&TS&d!bOw+uwx,kx#O+u#O#P.]#P#o+u#o#p0d#p#q+u#q#r.q#r~+u8r,pX&^7[Ow+uwx-]x#O+u#O#P.]#P#o+u#o#p0d#p#q+u#q#r.q#r~+u8r-bX&^7[Ow+uwx-}x#O+u#O#P.]#P#o+u#o#p0d#p#q+u#q#r.q#r~+u7[.SR&^7[O#o-}#p#q-}#r~-}8r.bT&^7[O#o+u#o#p.q#p#q+u#q#r.q#r~+u!f.xV&TS&d!bOw.qwx/_x#O.q#O#P0^#P#o.q#o#p0d#p~.q!f/bVOw.qwx/wx#O.q#O#P0^#P#o.q#o#p0d#p~.q!f/zUOw.qx#O.q#O#P0^#P#o.q#o#p0d#p~.q!f0aPO~.q!f0iV&TSOw1Owx1dx#O1O#O#P2V#P#o1O#o#p.q#p~1OS1TT&TSOw1Owx1dx#O1O#O#P2V#P~1OS1gTOw1Owx1vx#O1O#O#P2V#P~1OS1ySOw1Ox#O1O#O#P2V#P~1OS2YPO~1O;p2bT&^7[O#o(}#o#p2q#p#q(}#q#r2q#r~(}%d2|X&TS&WW&d!b&f#tOr2qrs3isw2qwx5Px#O2q#O#P:R#P#o2q#o#p:X#p~2q%d3pX&TS&d!bOr2qrs4]sw2qwx5Px#O2q#O#P:R#P#o2q#o#p:X#p~2q%d4dX&TS&d!bOr2qrs.qsw2qwx5Px#O2q#O#P:R#P#o2q#o#p:X#p~2q%d5WX&WW&f#tOr2qrs3isw2qwx5sx#O2q#O#P:R#P#o2q#o#p:X#p~2q%d5zX&WW&f#tOr2qrs3isw2qwx6gx#O2q#O#P:R#P#o2q#o#p:X#p~2q#|6nV&WW&f#tOr6grs7Ts#O6g#O#P8S#P#o6g#o#p8Y#p~6g#|7WVOr6grs7ms#O6g#O#P8S#P#o6g#o#p8Y#p~6g#|7pUOr6gs#O6g#O#P8S#P#o6g#o#p8Y#p~6g#|8VPO~6g#|8_V&WWOr8trs9Ys#O8t#O#P9{#P#o8t#o#p6g#p~8tW8yT&WWOr8trs9Ys#O8t#O#P9{#P~8tW9]TOr8trs9ls#O8t#O#P9{#P~8tW9oSOr8ts#O8t#O#P9{#P~8tW:OPO~8t%d:UPO~2q%d:`X&TS&WWOr:{rs;isw:{wx<ox#O:{#O#P=u#P#o:{#o#p2q#p~:{[;SV&TS&WWOr:{rs;isw:{wx<ox#O:{#O#P=u#P~:{[;nV&TSOr:{rs<Tsw:{wx<ox#O:{#O#P=u#P~:{[<YV&TSOr:{rs1Osw:{wx<ox#O:{#O#P=u#P~:{[<tV&WWOr:{rs;isw:{wx=Zx#O:{#O#P=u#P~:{[=`V&WWOr:{rs;isw:{wx8tx#O:{#O#P=u#P~:{[=xPO~:{;p>UZ&^7[&WW&f#tOr(}rs)}sw(}wx>wx#O(}#O#P2]#P#o(}#o#p:X#p#q(}#q#r2q#r~(}:Y?QX&^7[&WW&f#tOr>wrs?ms#O>w#O#PAP#P#o>w#o#p8Y#p#q>w#q#r6g#r~>w:Y?rX&^7[Or>wrs@_s#O>w#O#PAP#P#o>w#o#p8Y#p#q>w#q#r6g#r~>w:Y@dX&^7[Or>wrs-}s#O>w#O#PAP#P#o>w#o#p8Y#p#q>w#q#r6g#r~>w:YAUT&^7[O#o>w#o#p6g#p#q>w#q#r6g#r~>w<QAjT&^7[O#o'P#o#pAy#p#q'P#q#rAy#r~'P%tBWX&TS&WW&Z`&d!b&f#tOrAyrsBsswAywx5Px#OAy#O#PEo#P#oAy#o#pEu#p~Ay%tB|X&TS&Z`&d!bOrAyrsCiswAywx5Px#OAy#O#PEo#P#oAy#o#pEu#p~Ay%tCrX&TS&Z`&d!bOrAyrsD_swAywx5Px#OAy#O#PEo#P#oAy#o#pEu#p~Ay!vDhV&TS&Z`&d!bOwD_wx/_x#OD_#O#PD}#P#oD_#o#pET#p~D_!vEQPO~D_!vEYV&TSOw1Owx1dx#O1O#O#P2V#P#o1O#o#pD_#p~1O%tErPO~Ay%tE|X&TS&WWOr:{rs;isw:{wx<ox#O:{#O#P=u#P#o:{#o#pAy#p~:{<QFtZ&^7[&TS&Z`&d!bOr'PrsGgsw'Pwx(Rx#O'P#O#PAe#P#o'P#o#pEu#p#q'P#q#rAy#r~'P9SGrX&^7[&TS&Z`&d!bOwGgwx,kx#OGg#O#PH_#P#oGg#o#pET#p#qGg#q#rD_#r~Gg9SHdT&^7[O#oGg#o#pD_#p#qGg#q#rD_#r~Gg<bIOZ&^7[&WW&ap&f#tOrIqrs)}swIqwx! wx#OIq#O#PJs#P#oIq#o#p! T#p#qIq#q#rKX#r~Iq<bJQZ&^7[&TS&WW&ap&d!b&f#tOrIqrs)}swIqwxHsx#OIq#O#PJs#P#oIq#o#p! T#p#qIq#q#rKX#r~Iq<bJxT&^7[O#oIq#o#pKX#p#qIq#q#rKX#r~Iq&UKfX&TS&WW&ap&d!b&f#tOrKXrs3iswKXwxLRx#OKX#O#PN}#P#oKX#o#p! T#p~KX&UL[X&WW&ap&f#tOrKXrs3iswKXwxLwx#OKX#O#PN}#P#oKX#o#p! T#p~KX&UMQX&WW&ap&f#tOrKXrs3iswKXwxMmx#OKX#O#PN}#P#oKX#o#p! T#p~KX$nMvV&WW&ap&f#tOrMmrs7Ts#OMm#O#PN]#P#oMm#o#pNc#p~Mm$nN`PO~Mm$nNhV&WWOr8trs9Ys#O8t#O#P9{#P#o8t#o#pMm#p~8t&U! QPO~KX&U! [X&TS&WWOr:{rs;isw:{wx<ox#O:{#O#P=u#P#o:{#o#pKX#p~:{<b!!SZ&^7[&WW&ap&f#tOrIqrs)}swIqwx!!ux#OIq#O#PJs#P#oIq#o#p! T#p#qIq#q#rKX#r~Iq:z!#QX&^7[&WW&ap&f#tOr!!urs?ms#O!!u#O#P!#m#P#o!!u#o#pNc#p#q!!u#q#rMm#r~!!u:z!#rT&^7[O#o!!u#o#pMm#p#q!!u#q#rMm#r~!!u<r!$WT&^7[O#o$}#o#p!$g#p#q$}#q#r!$g#r~$}&f!$vX&TS&WW&Z`&ap&d!b&f#tOr!$grsBssw!$gwxLRx#O!$g#O#P!%c#P#o!$g#o#p!%i#p~!$g&f!%fPO~!$g&f!%pX&TS&WWOr:{rs;isw:{wx<ox#O:{#O#P=u#P#o:{#o#p!$g#p~:{Mg!&pa&^7[&TS&WW%[1s&Z`&ap&d!b&f#tOX$}XY!&]Y[$}[]!&]]p$}pq!&]qr$}rs&Rsw$}wxHsx#O$}#O#P!'u#P#o$}#o#p!%i#p#q$}#q#r!$g#r~$}Mg!'zX&^7[OY$}YZ!&]Z]$}]^!&]^#o$}#o#p!$g#p#q$}#q#r!$g#r~$}<u!(xb&^7[&TS&WW&Z`&ap&d!b&f#tOr$}rs&Rsw$}wxHsx!_$}!_!`!*Q!`#O$}#O#P!$R#P#T$}#T#U!+W#U#f$}#f#g!+W#g#h!+W#h#o$}#o#p!%i#p#q$}#q#r!$g#r~$}<u!*eZkR&^7[&TS&WW&Z`&ap&d!b&f#tOr$}rs&Rsw$}wxHsx#O$}#O#P!$R#P#o$}#o#p!%i#p#q$}#q#r!$g#r~$}<u!+kZ!jR&^7[&TS&WW&Z`&ap&d!b&f#tOr$}rs&Rsw$}wxHsx#O$}#O#P!$R#P#o$}#o#p!%i#p#q$}#q#r!$g#r~$}G{!,m_&bp&^7[&TS&R,X&Z`&d!bOY!-lYZ'PZ]!-l]^'P^r!-lrs!G^sw!-lwx!/|x#O!-l#O#P!Cp#P#o!-l#o#p!F[#p#q!-l#q#r!DU#r~!-lGZ!-}_&^7[&TS&WW&R,X&Z`&d!b&f#tOY!-lYZ'PZ]!-l]^'P^r!-lrs!.|sw!-lwx!/|x#O!-l#O#P!Cp#P#o!-l#o#p!F[#p#q!-l#q#r!DU#r~!-lGZ!/ZZ&^7[&TS&R,X&Z`&d!bOr'PrsFisw'Pwx(Rx#O'P#O#PAe#P#o'P#o#pEu#p#q'P#q#rAy#r~'PFy!0X_&^7[&WW&R,X&f#tOY!1WYZ(}Z]!1W]^(}^r!1Wrs!2fsw!1Wwx!@Yx#O!1W#O#P!3d#P#o!1W#o#p!;t#p#q!1W#q#r!3x#r~!1WFy!1g_&^7[&TS&WW&R,X&d!b&f#tOY!1WYZ(}Z]!1W]^(}^r!1Wrs!2fsw!1Wwx!/|x#O!1W#O#P!3d#P#o!1W#o#p!;t#p#q!1W#q#r!3x#r~!1WFy!2qZ&^7[&TS&R,X&d!bOr(}rs*ysw(}wx(Rx#O(}#O#P2]#P#o(}#o#p:X#p#q(}#q#r2q#r~(}Fy!3iT&^7[O#o!1W#o#p!3x#p#q!1W#q#r!3x#r~!1W0m!4V]&TS&WW&R,X&d!b&f#tOY!3xYZ2qZ]!3x]^2q^r!3xrs!5Osw!3xwx!5tx#O!3x#O#P!;n#P#o!3x#o#p!;t#p~!3x0m!5XX&TS&R,X&d!bOr2qrs4]sw2qwx5Px#O2q#O#P:R#P#o2q#o#p:X#p~2q0m!5}]&WW&R,X&f#tOY!3xYZ2qZ]!3x]^2q^r!3xrs!5Osw!3xwx!6vx#O!3x#O#P!;n#P#o!3x#o#p!;t#p~!3x0m!7P]&WW&R,X&f#tOY!3xYZ2qZ]!3x]^2q^r!3xrs!5Osw!3xwx!7xx#O!3x#O#P!;n#P#o!3x#o#p!;t#p~!3x/V!8RZ&WW&R,X&f#tOY!7xYZ6gZ]!7x]^6g^r!7xrs!8ts#O!7x#O#P!9`#P#o!7x#o#p!9f#p~!7x/V!8yV&R,XOr6grs7ms#O6g#O#P8S#P#o6g#o#p8Y#p~6g/V!9cPO~!7x/V!9mZ&WW&R,XOY!:`YZ8tZ]!:`]^8t^r!:`rs!;Ss#O!:`#O#P!;h#P#o!:`#o#p!7x#p~!:`,a!:gX&WW&R,XOY!:`YZ8tZ]!:`]^8t^r!:`rs!;Ss#O!:`#O#P!;h#P~!:`,a!;XT&R,XOr8trs9ls#O8t#O#P9{#P~8t,a!;kPO~!:`0m!;qPO~!3x0m!;}]&TS&WW&R,XOY!<vYZ:{Z]!<v]^:{^r!<vrs!=rsw!<vwx!>`x#O!<v#O#P!@S#P#o!<v#o#p!3x#p~!<v,e!=PZ&TS&WW&R,XOY!<vYZ:{Z]!<v]^:{^r!<vrs!=rsw!<vwx!>`x#O!<v#O#P!@S#P~!<v,e!=yV&TS&R,XOr:{rs<Tsw:{wx<ox#O:{#O#P=u#P~:{,e!>gZ&WW&R,XOY!<vYZ:{Z]!<v]^:{^r!<vrs!=rsw!<vwx!?Yx#O!<v#O#P!@S#P~!<v,e!?aZ&WW&R,XOY!<vYZ:{Z]!<v]^:{^r!<vrs!=rsw!<vwx!:`x#O!<v#O#P!@S#P~!<v,e!@VPO~!<vFy!@e_&^7[&WW&R,X&f#tOY!1WYZ(}Z]!1W]^(}^r!1Wrs!2fsw!1Wwx!Adx#O!1W#O#P!3d#P#o!1W#o#p!;t#p#q!1W#q#r!3x#r~!1WEc!Ao]&^7[&WW&R,X&f#tOY!AdYZ>wZ]!Ad]^>w^r!Adrs!Bhs#O!Ad#O#P!C[#P#o!Ad#o#p!9f#p#q!Ad#q#r!7x#r~!AdEc!BoX&^7[&R,XOr>wrs@_s#O>w#O#PAP#P#o>w#o#p8Y#p#q>w#q#r6g#r~>wEc!CaT&^7[O#o!Ad#o#p!7x#p#q!Ad#q#r!7x#r~!AdGZ!CuT&^7[O#o!-l#o#p!DU#p#q!-l#q#r!DU#r~!-l0}!De]&TS&WW&R,X&Z`&d!b&f#tOY!DUYZAyZ]!DU]^Ay^r!DUrs!E^sw!DUwx!5tx#O!DU#O#P!FU#P#o!DU#o#p!F[#p~!DU0}!EiX&TS&R,X&Z`&d!bOrAyrsCiswAywx5Px#OAy#O#PEo#P#oAy#o#pEu#p~Ay0}!FXPO~!DU0}!Fe]&TS&WW&R,XOY!<vYZ:{Z]!<v]^:{^r!<vrs!=rsw!<vwx!>`x#O!<v#O#P!@S#P#o!<v#o#p!DU#p~!<vGZ!GkZ&^7[&TS&R,X&Z`&d!bOr'Prs!H^sw'Pwx(Rx#O'P#O#PAe#P#o'P#o#pEu#p#q'P#q#rAy#r~'PGZ!HmX&X#|&^7[&TS&V,X&Z`&d!bOwGgwx,kx#OGg#O#PH_#P#oGg#o#pET#p#qGg#q#rD_#r~GgMg!Im_Q1s&^7[&TS&WW&Z`&ap&d!b&f#tOY!IYYZ$}Z]!IY]^$}^r!IYrs!Jlsw!IYwx$$[x#O!IY#O#P$1v#P#o!IY#o#p$4Y#p#q!IY#q#r$2j#r~!IYLu!Jy_Q1s&^7[&TS&Z`&d!bOY!KxYZ'PZ]!Kx]^'P^r!Kxrs$ Usw!Kxwx!MYx#O!Kx#O#P#G^#P#o!Kx#o#p#NS#p#q!Kx#q#r#HQ#r~!KxLu!LZ_Q1s&^7[&TS&WW&Z`&d!b&f#tOY!KxYZ'PZ]!Kx]^'P^r!Kxrs!Jlsw!Kxwx!MYx#O!Kx#O#P#G^#P#o!Kx#o#p#NS#p#q!Kx#q#r#HQ#r~!KxLe!Me_Q1s&^7[&WW&f#tOY!NdYZ(}Z]!Nd]^(}^r!Ndrs# rsw!Ndwx#B[x#O!Nd#O#P#/f#P#o!Nd#o#p#<b#p#q!Nd#q#r#0Y#r~!NdLe!Ns_Q1s&^7[&TS&WW&d!b&f#tOY!NdYZ(}Z]!Nd]^(}^r!Ndrs# rsw!Ndwx!MYx#O!Nd#O#P#/f#P#o!Nd#o#p#<b#p#q!Nd#q#r#0Y#r~!NdLe# }_Q1s&^7[&TS&d!bOY!NdYZ(}Z]!Nd]^(}^r!Ndrs#!|sw!Ndwx!MYx#O!Nd#O#P#/f#P#o!Nd#o#p#<b#p#q!Nd#q#r#0Y#r~!NdLe##X_Q1s&^7[&TS&d!bOY!NdYZ(}Z]!Nd]^(}^r!Ndrs#$Wsw!Ndwx!MYx#O!Nd#O#P#/f#P#o!Nd#o#p#<b#p#q!Nd#q#r#0Y#r~!NdIg#$c]Q1s&^7[&TS&d!bOY#$WYZ+uZ]#$W]^+u^w#$Wwx#%[x#O#$W#O#P#(^#P#o#$W#o#p#,Q#p#q#$W#q#r#)Q#r~#$WIg#%c]Q1s&^7[OY#$WYZ+uZ]#$W]^+u^w#$Wwx#&[x#O#$W#O#P#(^#P#o#$W#o#p#,Q#p#q#$W#q#r#)Q#r~#$WIg#&c]Q1s&^7[OY#$WYZ+uZ]#$W]^+u^w#$Wwx#'[x#O#$W#O#P#(^#P#o#$W#o#p#,Q#p#q#$W#q#r#)Q#r~#$WHP#'cXQ1s&^7[OY#'[YZ-}Z]#'[]^-}^#o#'[#o#p#(O#p#q#'[#q#r#(O#r~#'[1s#(TRQ1sOY#(OZ]#(O^~#(OIg#(eXQ1s&^7[OY#$WYZ+uZ]#$W]^+u^#o#$W#o#p#)Q#p#q#$W#q#r#)Q#r~#$W3Z#)ZZQ1s&TS&d!bOY#)QYZ.qZ]#)Q]^.q^w#)Qwx#)|x#O#)Q#O#P#+l#P#o#)Q#o#p#,Q#p~#)Q3Z#*RZQ1sOY#)QYZ.qZ]#)Q]^.q^w#)Qwx#*tx#O#)Q#O#P#+l#P#o#)Q#o#p#,Q#p~#)Q3Z#*yZQ1sOY#)QYZ.qZ]#)Q]^.q^w#)Qwx#(Ox#O#)Q#O#P#+l#P#o#)Q#o#p#,Q#p~#)Q3Z#+qTQ1sOY#)QYZ.qZ]#)Q]^.q^~#)Q3Z#,XZQ1s&TSOY#,zYZ1OZ]#,z]^1O^w#,zwx#-nx#O#,z#O#P#/Q#P#o#,z#o#p#)Q#p~#,z1w#-RXQ1s&TSOY#,zYZ1OZ]#,z]^1O^w#,zwx#-nx#O#,z#O#P#/Q#P~#,z1w#-sXQ1sOY#,zYZ1OZ]#,z]^1O^w#,zwx#.`x#O#,z#O#P#/Q#P~#,z1w#.eXQ1sOY#,zYZ1OZ]#,z]^1O^w#,zwx#(Ox#O#,z#O#P#/Q#P~#,z1w#/VTQ1sOY#,zYZ1OZ]#,z]^1O^~#,zLe#/mXQ1s&^7[OY!NdYZ(}Z]!Nd]^(}^#o!Nd#o#p#0Y#p#q!Nd#q#r#0Y#r~!Nd6X#0g]Q1s&TS&WW&d!b&f#tOY#0YYZ2qZ]#0Y]^2q^r#0Yrs#1`sw#0Ywx#3dx#O#0Y#O#P#;|#P#o#0Y#o#p#<b#p~#0Y6X#1i]Q1s&TS&d!bOY#0YYZ2qZ]#0Y]^2q^r#0Yrs#2bsw#0Ywx#3dx#O#0Y#O#P#;|#P#o#0Y#o#p#<b#p~#0Y6X#2k]Q1s&TS&d!bOY#0YYZ2qZ]#0Y]^2q^r#0Yrs#)Qsw#0Ywx#3dx#O#0Y#O#P#;|#P#o#0Y#o#p#<b#p~#0Y6X#3m]Q1s&WW&f#tOY#0YYZ2qZ]#0Y]^2q^r#0Yrs#1`sw#0Ywx#4fx#O#0Y#O#P#;|#P#o#0Y#o#p#<b#p~#0Y6X#4o]Q1s&WW&f#tOY#0YYZ2qZ]#0Y]^2q^r#0Yrs#1`sw#0Ywx#5hx#O#0Y#O#P#;|#P#o#0Y#o#p#<b#p~#0Y4q#5qZQ1s&WW&f#tOY#5hYZ6gZ]#5h]^6g^r#5hrs#6ds#O#5h#O#P#8S#P#o#5h#o#p#8h#p~#5h4q#6iZQ1sOY#5hYZ6gZ]#5h]^6g^r#5hrs#7[s#O#5h#O#P#8S#P#o#5h#o#p#8h#p~#5h4q#7aZQ1sOY#5hYZ6gZ]#5h]^6g^r#5hrs#(Os#O#5h#O#P#8S#P#o#5h#o#p#8h#p~#5h4q#8XTQ1sOY#5hYZ6gZ]#5h]^6g^~#5h4q#8oZQ1s&WWOY#9bYZ8tZ]#9b]^8t^r#9brs#:Us#O#9b#O#P#;h#P#o#9b#o#p#5h#p~#9b1{#9iXQ1s&WWOY#9bYZ8tZ]#9b]^8t^r#9brs#:Us#O#9b#O#P#;h#P~#9b1{#:ZXQ1sOY#9bYZ8tZ]#9b]^8t^r#9brs#:vs#O#9b#O#P#;h#P~#9b1{#:{XQ1sOY#9bYZ8tZ]#9b]^8t^r#9brs#(Os#O#9b#O#P#;h#P~#9b1{#;mTQ1sOY#9bYZ8tZ]#9b]^8t^~#9b6X#<RTQ1sOY#0YYZ2qZ]#0Y]^2q^~#0Y6X#<k]Q1s&TS&WWOY#=dYZ:{Z]#=d]^:{^r#=drs#>`sw#=dwx#@Sx#O#=d#O#P#Av#P#o#=d#o#p#0Y#p~#=d2P#=mZQ1s&TS&WWOY#=dYZ:{Z]#=d]^:{^r#=drs#>`sw#=dwx#@Sx#O#=d#O#P#Av#P~#=d2P#>gZQ1s&TSOY#=dYZ:{Z]#=d]^:{^r#=drs#?Ysw#=dwx#@Sx#O#=d#O#P#Av#P~#=d2P#?aZQ1s&TSOY#=dYZ:{Z]#=d]^:{^r#=drs#,zsw#=dwx#@Sx#O#=d#O#P#Av#P~#=d2P#@ZZQ1s&WWOY#=dYZ:{Z]#=d]^:{^r#=drs#>`sw#=dwx#@|x#O#=d#O#P#Av#P~#=d2P#ATZQ1s&WWOY#=dYZ:{Z]#=d]^:{^r#=drs#>`sw#=dwx#9bx#O#=d#O#P#Av#P~#=d2P#A{TQ1sOY#=dYZ:{Z]#=d]^:{^~#=dLe#Bg_Q1s&^7[&WW&f#tOY!NdYZ(}Z]!Nd]^(}^r!Ndrs# rsw!Ndwx#Cfx#O!Nd#O#P#/f#P#o!Nd#o#p#<b#p#q!Nd#q#r#0Y#r~!NdJ}#Cq]Q1s&^7[&WW&f#tOY#CfYZ>wZ]#Cf]^>w^r#Cfrs#Djs#O#Cf#O#P#Fj#P#o#Cf#o#p#8h#p#q#Cf#q#r#5h#r~#CfJ}#Dq]Q1s&^7[OY#CfYZ>wZ]#Cf]^>w^r#Cfrs#Ejs#O#Cf#O#P#Fj#P#o#Cf#o#p#8h#p#q#Cf#q#r#5h#r~#CfJ}#Eq]Q1s&^7[OY#CfYZ>wZ]#Cf]^>w^r#Cfrs#'[s#O#Cf#O#P#Fj#P#o#Cf#o#p#8h#p#q#Cf#q#r#5h#r~#CfJ}#FqXQ1s&^7[OY#CfYZ>wZ]#Cf]^>w^#o#Cf#o#p#5h#p#q#Cf#q#r#5h#r~#CfLu#GeXQ1s&^7[OY!KxYZ'PZ]!Kx]^'P^#o!Kx#o#p#HQ#p#q!Kx#q#r#HQ#r~!Kx6i#Ha]Q1s&TS&WW&Z`&d!b&f#tOY#HQYZAyZ]#HQ]^Ay^r#HQrs#IYsw#HQwx#3dx#O#HQ#O#P#Mn#P#o#HQ#o#p#NS#p~#HQ6i#Ie]Q1s&TS&Z`&d!bOY#HQYZAyZ]#HQ]^Ay^r#HQrs#J^sw#HQwx#3dx#O#HQ#O#P#Mn#P#o#HQ#o#p#NS#p~#HQ6i#Ji]Q1s&TS&Z`&d!bOY#HQYZAyZ]#HQ]^Ay^r#HQrs#Kbsw#HQwx#3dx#O#HQ#O#P#Mn#P#o#HQ#o#p#NS#p~#HQ3k#KmZQ1s&TS&Z`&d!bOY#KbYZD_Z]#Kb]^D_^w#Kbwx#)|x#O#Kb#O#P#L`#P#o#Kb#o#p#Lt#p~#Kb3k#LeTQ1sOY#KbYZD_Z]#Kb]^D_^~#Kb3k#L{ZQ1s&TSOY#,zYZ1OZ]#,z]^1O^w#,zwx#-nx#O#,z#O#P#/Q#P#o#,z#o#p#Kb#p~#,z6i#MsTQ1sOY#HQYZAyZ]#HQ]^Ay^~#HQ6i#N]]Q1s&TS&WWOY#=dYZ:{Z]#=d]^:{^r#=drs#>`sw#=dwx#@Sx#O#=d#O#P#Av#P#o#=d#o#p#HQ#p~#=dLu$ c_Q1s&^7[&TS&Z`&d!bOY!KxYZ'PZ]!Kx]^'P^r!Kxrs$!bsw!Kxwx!MYx#O!Kx#O#P#G^#P#o!Kx#o#p#NS#p#q!Kx#q#r#HQ#r~!KxIw$!o]Q1s&^7[&TS&Z`&d!bOY$!bYZGgZ]$!b]^Gg^w$!bwx#%[x#O$!b#O#P$#h#P#o$!b#o#p#Lt#p#q$!b#q#r#Kb#r~$!bIw$#oXQ1s&^7[OY$!bYZGgZ]$!b]^Gg^#o$!b#o#p#Kb#p#q$!b#q#r#Kb#r~$!bMV$$i_Q1s&^7[&WW&ap&f#tOY$%hYZIqZ]$%h]^Iq^r$%hrs# rsw$%hwx$.px#O$%h#O#P$&x#P#o$%h#o#p$-n#p#q$%h#q#r$'l#r~$%hMV$%y_Q1s&^7[&TS&WW&ap&d!b&f#tOY$%hYZIqZ]$%h]^Iq^r$%hrs# rsw$%hwx$$[x#O$%h#O#P$&x#P#o$%h#o#p$-n#p#q$%h#q#r$'l#r~$%hMV$'PXQ1s&^7[OY$%hYZIqZ]$%h]^Iq^#o$%h#o#p$'l#p#q$%h#q#r$'l#r~$%h6y$'{]Q1s&TS&WW&ap&d!b&f#tOY$'lYZKXZ]$'l]^KX^r$'lrs#1`sw$'lwx$(tx#O$'l#O#P$-Y#P#o$'l#o#p$-n#p~$'l6y$)P]Q1s&WW&ap&f#tOY$'lYZKXZ]$'l]^KX^r$'lrs#1`sw$'lwx$)xx#O$'l#O#P$-Y#P#o$'l#o#p$-n#p~$'l6y$*T]Q1s&WW&ap&f#tOY$'lYZKXZ]$'l]^KX^r$'lrs#1`sw$'lwx$*|x#O$'l#O#P$-Y#P#o$'l#o#p$-n#p~$'l5c$+XZQ1s&WW&ap&f#tOY$*|YZMmZ]$*|]^Mm^r$*|rs#6ds#O$*|#O#P$+z#P#o$*|#o#p$,`#p~$*|5c$,PTQ1sOY$*|YZMmZ]$*|]^Mm^~$*|5c$,gZQ1s&WWOY#9bYZ8tZ]#9b]^8t^r#9brs#:Us#O#9b#O#P#;h#P#o#9b#o#p$*|#p~#9b6y$-_TQ1sOY$'lYZKXZ]$'l]^KX^~$'l6y$-w]Q1s&TS&WWOY#=dYZ:{Z]#=d]^:{^r#=drs#>`sw#=dwx#@Sx#O#=d#O#P#Av#P#o#=d#o#p$'l#p~#=dMV$.}_Q1s&^7[&WW&ap&f#tOY$%hYZIqZ]$%h]^Iq^r$%hrs# rsw$%hwx$/|x#O$%h#O#P$&x#P#o$%h#o#p$-n#p#q$%h#q#r$'l#r~$%hKo$0Z]Q1s&^7[&WW&ap&f#tOY$/|YZ!!uZ]$/|]^!!u^r$/|rs#Djs#O$/|#O#P$1S#P#o$/|#o#p$,`#p#q$/|#q#r$*|#r~$/|Ko$1ZXQ1s&^7[OY$/|YZ!!uZ]$/|]^!!u^#o$/|#o#p$*|#p#q$/|#q#r$*|#r~$/|Mg$1}XQ1s&^7[OY!IYYZ$}Z]!IY]^$}^#o!IY#o#p$2j#p#q!IY#q#r$2j#r~!IY7Z$2{]Q1s&TS&WW&Z`&ap&d!b&f#tOY$2jYZ!$gZ]$2j]^!$g^r$2jrs#IYsw$2jwx$(tx#O$2j#O#P$3t#P#o$2j#o#p$4Y#p~$2j7Z$3yTQ1sOY$2jYZ!$gZ]$2j]^!$g^~$2j7Z$4c]Q1s&TS&WWOY#=dYZ:{Z]#=d]^:{^r#=drs#>`sw#=dwx#@Sx#O#=d#O#P#Av#P#o#=d#o#p$2j#p~#=dGz$5o]%jQ&^7[&TS&WW&Z`&ap&d!b&f#tOr$}rs&Rsw$}wxHsx!_$}!_!`$6h!`#O$}#O#P!$R#P#o$}#o#p!%i#p#q$}#q#r!$g#r~$}Gz$6{Z!s,W&^7[&TS&WW&Z`&ap&d!b&f#tOr$}rs&Rsw$}wxHsx#O$}#O#P!$R#P#o$}#o#p!%i#p#q$}#q#r!$g#r~$}Gz$8R]%dQ&^7[&TS&WW&Z`&ap&d!b&f#tOr$}rs&Rsw$}wxHsx!_$}!_!`$6h!`#O$}#O#P!$R#P#o$}#o#p!%i#p#q$}#q#r!$g#r~$}G{$9Z_&_`&^7[&WW&R,X&ap&f#tOY$:YYZIqZ]$:Y]^Iq^r$:Yrs$;jsw$:Ywx%%zx#O$:Y#O#P%!^#P#o$:Y#o#p%$x#p#q$:Y#q#r%!r#r~$:YGk$:k_&^7[&TS&WW&R,X&ap&d!b&f#tOY$:YYZIqZ]$:Y]^Iq^r$:Yrs$;jsw$:Ywx% ^x#O$:Y#O#P%!^#P#o$:Y#o#p%$x#p#q$:Y#q#r%!r#r~$:YFy$;u_&^7[&TS&R,X&d!bOY$<tYZ(}Z]$<t]^(}^r$<trs$Kvsw$<twx$>Sx#O$<t#O#P$?Q#P#o$<t#o#p$Gb#p#q$<t#q#r$?f#r~$<tFy$=T_&^7[&TS&WW&R,X&d!b&f#tOY$<tYZ(}Z]$<t]^(}^r$<trs$;jsw$<twx$>Sx#O$<t#O#P$?Q#P#o$<t#o#p$Gb#p#q$<t#q#r$?f#r~$<tFy$>_Z&^7[&WW&R,X&f#tOr(}rs)}sw(}wx={x#O(}#O#P2]#P#o(}#o#p:X#p#q(}#q#r2q#r~(}Fy$?VT&^7[O#o$<t#o#p$?f#p#q$<t#q#r$?f#r~$<t0m$?s]&TS&WW&R,X&d!b&f#tOY$?fYZ2qZ]$?f]^2q^r$?frs$@lsw$?fwx$Ffx#O$?f#O#P$G[#P#o$?f#o#p$Gb#p~$?f0m$@u]&TS&R,X&d!bOY$?fYZ2qZ]$?f]^2q^r$?frs$Answ$?fwx$Ffx#O$?f#O#P$G[#P#o$?f#o#p$Gb#p~$?f0m$Aw]&TS&R,X&d!bOY$?fYZ2qZ]$?f]^2q^r$?frs$Bpsw$?fwx$Ffx#O$?f#O#P$G[#P#o$?f#o#p$Gb#p~$?f-o$ByZ&TS&R,X&d!bOY$BpYZ.qZ]$Bp]^.q^w$Bpwx$Clx#O$Bp#O#P$DW#P#o$Bp#o#p$D^#p~$Bp-o$CqV&R,XOw.qwx/wx#O.q#O#P0^#P#o.q#o#p0d#p~.q-o$DZPO~$Bp-o$DeZ&TS&R,XOY$EWYZ1OZ]$EW]^1O^w$EWwx$Ezx#O$EW#O#P$F`#P#o$EW#o#p$Bp#p~$EW,]$E_X&TS&R,XOY$EWYZ1OZ]$EW]^1O^w$EWwx$Ezx#O$EW#O#P$F`#P~$EW,]$FPT&R,XOw1Owx1vx#O1O#O#P2V#P~1O,]$FcPO~$EW0m$FoX&WW&R,X&f#tOr2qrs3isw2qwx5sx#O2q#O#P:R#P#o2q#o#p:X#p~2q0m$G_PO~$?f0m$Gk]&TS&WW&R,XOY$HdYZ:{Z]$Hd]^:{^r$Hdrs$I`sw$Hdwx$KSx#O$Hd#O#P$Kp#P#o$Hd#o#p$?f#p~$Hd,e$HmZ&TS&WW&R,XOY$HdYZ:{Z]$Hd]^:{^r$Hdrs$I`sw$Hdwx$KSx#O$Hd#O#P$Kp#P~$Hd,e$IgZ&TS&R,XOY$HdYZ:{Z]$Hd]^:{^r$Hdrs$JYsw$Hdwx$KSx#O$Hd#O#P$Kp#P~$Hd,e$JaZ&TS&R,XOY$HdYZ:{Z]$Hd]^:{^r$Hdrs$EWsw$Hdwx$KSx#O$Hd#O#P$Kp#P~$Hd,e$KZV&WW&R,XOr:{rs;isw:{wx=Zx#O:{#O#P=u#P~:{,e$KsPO~$HdFy$LR_&^7[&TS&R,X&d!bOY$<tYZ(}Z]$<t]^(}^r$<trs$MQsw$<twx$>Sx#O$<t#O#P$?Q#P#o$<t#o#p$Gb#p#q$<t#q#r$?f#r~$<tC{$M]]&^7[&TS&R,X&d!bOY$MQYZ+uZ]$MQ]^+u^w$MQwx$NUx#O$MQ#O#P$Nx#P#o$MQ#o#p$D^#p#q$MQ#q#r$Bp#r~$MQC{$N]X&^7[&R,XOw+uwx-]x#O+u#O#P.]#P#o+u#o#p0d#p#q+u#q#r.q#r~+uC{$N}T&^7[O#o$MQ#o#p$Bp#p#q$MQ#q#r$Bp#r~$MQGk% kZ&^7[&WW&R,X&ap&f#tOrIqrs)}swIqwx! wx#OIq#O#PJs#P#oIq#o#p! T#p#qIq#q#rKX#r~IqGk%!cT&^7[O#o$:Y#o#p%!r#p#q$:Y#q#r%!r#r~$:Y1_%#R]&TS&WW&R,X&ap&d!b&f#tOY%!rYZKXZ]%!r]^KX^r%!rrs$@lsw%!rwx%#zx#O%!r#O#P%$r#P#o%!r#o#p%$x#p~%!r1_%$VX&WW&R,X&ap&f#tOrKXrs3iswKXwxLwx#OKX#O#PN}#P#oKX#o#p! T#p~KX1_%$uPO~%!r1_%%R]&TS&WW&R,XOY$HdYZ:{Z]$Hd]^:{^r$Hdrs$I`sw$Hdwx$KSx#O$Hd#O#P$Kp#P#o$Hd#o#p%!r#p~$HdGk%&XZ&^7[&WW&R,X&ap&f#tOrIqrs)}swIqwx%&zx#OIq#O#PJs#P#oIq#o#p! T#p#qIq#q#rKX#r~IqGk%'ZX&U!f&^7[&WW&S,X&ap&f#tOr!!urs?ms#O!!u#O#P!#m#P#o!!u#o#pNc#p#q!!u#q#rMm#r~!!uG{%(ZZf,X&^7[&TS&WW&Z`&ap&d!b&f#tOr$}rs&Rsw$}wxHsx#O$}#O#P!$R#P#o$}#o#p!%i#p#q$}#q#r!$g#r~$}<u%)aZeR&^7[&TS&WW&Z`&ap&d!b&f#tOr$}rs&Rsw$}wxHsx#O$}#O#P!$R#P#o$}#o#p!%i#p#q$}#q#r!$g#r~$}G{%*g_T,X&^7[&TS&WW&Z`&ap&d!b&f#tOr$}rs&Rsw$}wxHsxz$}z{%+f{!_$}!_!`$6h!`#O$}#O#P!$R#P#o$}#o#p!%i#p#q$}#q#r!$g#r~$}G{%+y]_R&^7[&TS&WW&Z`&ap&d!b&f#tOr$}rs&Rsw$}wxHsx!_$}!_!`$6h!`#O$}#O#P!$R#P#o$}#o#p!%i#p#q$}#q#r!$g#r~$}G{%-V]%g,X&^7[&TS&WW&Z`&ap&d!b&f#tOr$}rs&Rsw$}wxHsx!_$}!_!`$6h!`#O$}#O#P!$R#P#o$}#o#p!%i#p#q$}#q#r!$g#r~$}<u%.cZxR&^7[&TS&WW&Z`&ap&d!b&f#tOr$}rs&Rsw$}wxHsx#O$}#O#P!$R#P#o$}#o#p!%i#p#q$}#q#r!$g#r~$}Mg%/i^%h,X&^7[&TS&WW&Z`&ap&d!b&f#tOr$}rs&Rsw$}wxHsx!_$}!_!`$6h!`!a%0e!a#O$}#O#P!$R#P#o$}#o#p!%i#p#q$}#q#r!$g#r~$}B^%0xZ&q&j&^7[&TS&WW&Z`&ap&d!b&f#tOr$}rs&Rsw$}wxHsx#O$}#O#P!$R#P#o$}#o#p!%i#p#q$}#q#r!$g#r~$}G{%2O_!dQ&^7[&TS&WW&Z`&ap&d!b&f#tOr$}rs&Rsw$}wxHsx!O$}!O!P%2}!P!Q$}!Q![%5_![#O$}#O#P!$R#P#o$}#o#p!%i#p#q$}#q#r!$g#r~$}G{%3`]&^7[&TS&WW&Z`&ap&d!b&f#tOr$}rs&Rsw$}wxHsx!O$}!O!P%4X!P#O$}#O#P!$R#P#o$}#o#p!%i#p#q$}#q#r!$g#r~$}G{%4lZ!m,X&^7[&TS&WW&Z`&ap&d!b&f#tOr$}rs&Rsw$}wxHsx#O$}#O#P!$R#P#o$}#o#p!%i#p#q$}#q#r!$g#r~$}Gy%5rg!f,V&^7[&TS&WW&Z`&ap&d!b&f#tOr$}rs&Rsw$}wxHsx!Q$}!Q![%5_![!g$}!g!h%7Z!h!l$}!l!m%;k!m#O$}#O#P!$R#P#R$}#R#S%5_#S#X$}#X#Y%7Z#Y#^$}#^#_%;k#_#o$}#o#p!%i#p#q$}#q#r!$g#r~$}Gy%7la&^7[&TS&WW&Z`&ap&d!b&f#tOr$}rs&Rsw$}wxHsx{$}{|%8q|}$}}!O%8q!O!Q$}!Q![%9{![#O$}#O#P!$R#P#o$}#o#p!%i#p#q$}#q#r!$g#r~$}Gy%9S]&^7[&TS&WW&Z`&ap&d!b&f#tOr$}rs&Rsw$}wxHsx!Q$}!Q![%9{![#O$}#O#P!$R#P#o$}#o#p!%i#p#q$}#q#r!$g#r~$}Gy%:`c!f,V&^7[&TS&WW&Z`&ap&d!b&f#tOr$}rs&Rsw$}wxHsx!Q$}!Q![%9{![!l$}!l!m%;k!m#O$}#O#P!$R#P#R$}#R#S%9{#S#^$}#^#_%;k#_#o$}#o#p!%i#p#q$}#q#r!$g#r~$}Gy%<OZ!f,V&^7[&TS&WW&Z`&ap&d!b&f#tOr$}rs&Rsw$}wxHsx#O$}#O#P!$R#P#o$}#o#p!%i#p#q$}#q#r!$g#r~$}G{%=U_%iR&^7[&TS&WW&Z`&ap&d!b&f#tOr$}rs&Rsw$}wxHsx!P$}!P!Q%>T!Q!_$}!_!`$6h!`#O$}#O#P!$R#P#o$}#o#p!%i#p#q$}#q#r!$g#r~$}Gz%>h]%kQ&^7[&TS&WW&Z`&ap&d!b&f#tOr$}rs&Rsw$}wxHsx!_$}!_!`$6h!`#O$}#O#P!$R#P#o$}#o#p!%i#p#q$}#q#r!$g#r~$}Gy%?tu!f,V&^7[&TS&WW&Z`&ap&d!b&f#tOr$}rs&Rsw$}wxHsx!O$}!O!P%BX!P!Q$}!Q![%Cc![!d$}!d!e%Ee!e!g$}!g!h%7Z!h!l$}!l!m%;k!m!q$}!q!r%H_!r!z$}!z!{%KR!{#O$}#O#P!$R#P#R$}#R#S%Cc#S#U$}#U#V%Ee#V#X$}#X#Y%7Z#Y#^$}#^#_%;k#_#c$}#c#d%H_#d#l$}#l#m%KR#m#o$}#o#p!%i#p#q$}#q#r!$g#r~$}Gy%Bj]&^7[&TS&WW&Z`&ap&d!b&f#tOr$}rs&Rsw$}wxHsx!Q$}!Q![%5_![#O$}#O#P!$R#P#o$}#o#p!%i#p#q$}#q#r!$g#r~$}Gy%Cvi!f,V&^7[&TS&WW&Z`&ap&d!b&f#tOr$}rs&Rsw$}wxHsx!O$}!O!P%BX!P!Q$}!Q![%Cc![!g$}!g!h%7Z!h!l$}!l!m%;k!m#O$}#O#P!$R#P#R$}#R#S%Cc#S#X$}#X#Y%7Z#Y#^$}#^#_%;k#_#o$}#o#p!%i#p#q$}#q#r!$g#r~$}Gy%Ev`&^7[&TS&WW&Z`&ap&d!b&f#tOr$}rs&Rsw$}wxHsx!Q$}!Q!R%Fx!R!S%Fx!S#O$}#O#P!$R#P#R$}#R#S%Fx#S#o$}#o#p!%i#p#q$}#q#r!$g#r~$}Gy%G]`!f,V&^7[&TS&WW&Z`&ap&d!b&f#tOr$}rs&Rsw$}wxHsx!Q$}!Q!R%Fx!R!S%Fx!S#O$}#O#P!$R#P#R$}#R#S%Fx#S#o$}#o#p!%i#p#q$}#q#r!$g#r~$}Gy%Hp_&^7[&TS&WW&Z`&ap&d!b&f#tOr$}rs&Rsw$}wxHsx!Q$}!Q!Y%Io!Y#O$}#O#P!$R#P#R$}#R#S%Io#S#o$}#o#p!%i#p#q$}#q#r!$g#r~$}Gy%JS_!f,V&^7[&TS&WW&Z`&ap&d!b&f#tOr$}rs&Rsw$}wxHsx!Q$}!Q!Y%Io!Y#O$}#O#P!$R#P#R$}#R#S%Io#S#o$}#o#p!%i#p#q$}#q#r!$g#r~$}Gy%Kdc&^7[&TS&WW&Z`&ap&d!b&f#tOr$}rs&Rsw$}wxHsx!Q$}!Q![%Lo![!c$}!c!i%Lo!i#O$}#O#P!$R#P#R$}#R#S%Lo#S#T$}#T#Z%Lo#Z#o$}#o#p!%i#p#q$}#q#r!$g#r~$}Gy%MSc!f,V&^7[&TS&WW&Z`&ap&d!b&f#tOr$}rs&Rsw$}wxHsx!Q$}!Q![%Lo![!c$}!c!i%Lo!i#O$}#O#P!$R#P#R$}#R#S%Lo#S#T$}#T#Z%Lo#Z#o$}#o#p!%i#p#q$}#q#r!$g#r~$}Mg%Nr]y1s&^7[&TS&WW&Z`&ap&d!b&f#tOr$}rs&Rsw$}wxHsx!_$}!_!`& k!`#O$}#O#P!$R#P#o$}#o#p!%i#p#q$}#q#r!$g#r~$}<u&!OZ%sR&^7[&TS&WW&Z`&ap&d!b&f#tOr$}rs&Rsw$}wxHsx#O$}#O#P!$R#P#o$}#o#p!%i#p#q$}#q#r!$g#r~$}G{&#UZ#^,X&^7[&TS&WW&Z`&ap&d!b&f#tOr$}rs&Rsw$}wxHsx#O$}#O#P!$R#P#o$}#o#p!%i#p#q$}#q#r!$g#r~$}G{&$[_kR&^7[&TS&WW&Z`&ap&d!b&f#tOr$}rs&Rsw$}wxHsx!^$}!^!_&%Z!_!`!*Q!`!a!*Q!a#O$}#O#P!$R#P#o$}#o#p!%i#p#q$}#q#r!$g#r~$}Gz&%n]%eQ&^7[&TS&WW&Z`&ap&d!b&f#tOr$}rs&Rsw$}wxHsx!_$}!_!`$6h!`#O$}#O#P!$R#P#o$}#o#p!%i#p#q$}#q#r!$g#r~$}G{&&z]%r,X&^7[&TS&WW&Z`&ap&d!b&f#tOr$}rs&Rsw$}wxHsx!_$}!_!`!*Q!`#O$}#O#P!$R#P#o$}#o#p!%i#p#q$}#q#r!$g#r~$}G{&(W^kR&^7[&TS&WW&Z`&ap&d!b&f#tOr$}rs&Rsw$}wxHsx!_$}!_!`!*Q!`!a&)S!a#O$}#O#P!$R#P#o$}#o#p!%i#p#q$}#q#r!$g#r~$}Gz&)g]%fQ&^7[&TS&WW&Z`&ap&d!b&f#tOr$}rs&Rsw$}wxHsx!_$}!_!`$6h!`#O$}#O#P!$R#P#o$}#o#p!%i#p#q$}#q#r!$g#r~$}G{&*u]]Q#tP&^7[&TS&WW&Z`&ap&d!b&f#tOr$}rs&Rsw$}wxHsx!_$}!_!`$6h!`#O$}#O#P!$R#P#o$}#o#p!%i#p#q$}#q#r!$g#r~$}Mg&,Tc&^7[&TS&WW&Q&j&Z`&ap&d!b&f#t%m,XOr$}rs&Rsw$}wxHsx!Q$}!Q![&+n![!c$}!c!}&+n!}#O$}#O#P!$R#P#R$}#R#S&+n#S#T$}#T#o&+n#o#p!%i#p#q$}#q#r!$g#r$g$}$g~&+nMg&-ug&^7[&TS&WW&Q&j&Z`&ap&d!b&f#t%m,XOr$}rs&/^sw$}wx&2dx!Q$}!Q![&+n![!c$}!c!t&+n!t!u&5j!u!}&+n!}#O$}#O#P!$R#P#R$}#R#S&+n#S#T$}#T#f&+n#f#g&5j#g#o&+n#o#p!%i#p#q$}#q#r!$g#r$g$}$g~&+nGZ&/k_&^7[&TS&R,X&Z`&d!bOY!-lYZ'PZ]!-l]^'P^r!-lrs&0jsw!-lwx!/|x#O!-l#O#P!Cp#P#o!-l#o#p!F[#p#q!-l#q#r!DU#r~!-lGZ&0wZ&^7[&TS&R,X&Z`&d!bOr'Prs&1jsw'Pwx(Rx#O'P#O#PAe#P#o'P#o#pEu#p#q'P#q#rAy#r~'PD]&1wX&^7[&TS&V,X&Z`&d!bOwGgwx,kx#OGg#O#PH_#P#oGg#o#pET#p#qGg#q#rD_#r~GgGk&2q_&^7[&WW&R,X&ap&f#tOY$:YYZIqZ]$:Y]^Iq^r$:Yrs$;jsw$:Ywx&3px#O$:Y#O#P%!^#P#o$:Y#o#p%$x#p#q$:Y#q#r%!r#r~$:YGk&3}Z&^7[&WW&R,X&ap&f#tOrIqrs)}swIqwx&4px#OIq#O#PJs#P#oIq#o#p! T#p#qIq#q#rKX#r~IqFT&4}X&^7[&WW&S,X&ap&f#tOr!!urs?ms#O!!u#O#P!#m#P#o!!u#o#pNc#p#q!!u#q#rMm#r~!!uMg&6Pc&^7[&TS&WW&Q&j&Z`&ap&d!b&f#t%m,XOr$}rs&/^sw$}wx&2dx!Q$}!Q![&+n![!c$}!c!}&+n!}#O$}#O#P!$R#P#R$}#R#S&+n#S#T$}#T#o&+n#o#p!%i#p#q$}#q#r!$g#r$g$}$g~&+nMg&7qg&^7[&TS&WW&Q&j&Z`&ap&d!b&f#t%m,XOr$}rs&9Ysw$}wx&<Qx!Q$}!Q![&+n![!c$}!c!t&+n!t!u&>x!u!}&+n!}#O$}#O#P!$R#P#R$}#R#S&+n#S#T$}#T#f&+n#f#g&>x#g#o&+n#o#p!%i#p#q$}#q#r!$g#r$g$}$g~&+nGZ&9gZ&^7[&TS&Z`&d!b&`,XOr'Prs&:Ysw'Pwx(Rx#O'P#O#PAe#P#o'P#o#pEu#p#q'P#q#rAy#r~'PGZ&:eZ&^7[&TS&Z`&d!bOr'Prs&;Wsw'Pwx(Rx#O'P#O#PAe#P#o'P#o#pEu#p#q'P#q#rAy#r~'PD]&;eX&^7[&TS&e,X&Z`&d!bOwGgwx,kx#OGg#O#PH_#P#oGg#o#pET#p#qGg#q#rD_#r~GgGk&<_Z&^7[&WW&ap&f#t&Y,XOrIqrs)}swIqwx&=Qx#OIq#O#PJs#P#oIq#o#p! T#p#qIq#q#rKX#r~IqGk&=]Z&^7[&WW&ap&f#tOrIqrs)}swIqwx&>Ox#OIq#O#PJs#P#oIq#o#p! T#p#qIq#q#rKX#r~IqFT&>]X&^7[&WW&c,X&ap&f#tOr!!urs?ms#O!!u#O#P!#m#P#o!!u#o#pNc#p#q!!u#q#rMm#r~!!uMg&?_c&^7[&TS&WW&Q&j&Z`&ap&d!b&f#t%m,XOr$}rs&9Ysw$}wx&<Qx!Q$}!Q![&+n![!c$}!c!}&+n!}#O$}#O#P!$R#P#R$}#R#S&+n#S#T$}#T#o&+n#o#p!%i#p#q$}#q#r!$g#r$g$}$g~&+nMg&APk&^7[&TS&WW&Q&j&Z`&ap&d!b&f#t%m,XOr$}rs&/^sw$}wx&2dx!Q$}!Q![&+n![!c$}!c!h&+n!h!i&>x!i!t&+n!t!u&5j!u!}&+n!}#O$}#O#P!$R#P#R$}#R#S&+n#S#T$}#T#U&+n#U#V&5j#V#Y&+n#Y#Z&>x#Z#o&+n#o#p!%i#p#q$}#q#r!$g#r$g$}$g~&+nG{&CXZ!V,X&^7[&TS&WW&Z`&ap&d!b&f#tOr$}rs&Rsw$}wxHsx#O$}#O#P!$R#P#o$}#o#p!%i#p#q$}#q#r!$g#r~$}<u&D_Z!UR&^7[&TS&WW&Z`&ap&d!b&f#tOr$}rs&Rsw$}wxHsx#O$}#O#P!$R#P#o$}#o#p!%i#p#q$}#q#r!$g#r~$}Gz&Ee]%cQ&^7[&TS&WW&Z`&ap&d!b&f#tOr$}rs&Rsw$}wxHsx!_$}!_!`$6h!`#O$}#O#P!$R#P#o$}#o#p!%i#p#q$}#q#r!$g#r~$}Gy&FgX&TS&WW!ZGmOr:{rs;isw:{wx<ox#O:{#O#P=u#P#o:{#o#p!$g#p~:{G{&Gg]%bR&^7[&TS&WW&Z`&ap&d!b&f#tOr$}rs&Rsw$}wxHsx!_$}!_!`$6h!`#O$}#O#P!$R#P#o$}#o#p!%i#p#q$}#q#r!$g#r~$}<u&HqX!Y7_&TS&WW&Z`&ap&d!b&f#tOr!$grsBssw!$gwxLRx#O!$g#O#P!%c#P#o!$g#o#p!%i#p~!$gGy&IqZ%l,V&^7[&TS&WW&Z`&ap&d!b&f#tOr$}rs&Rsw$}wxHsx#O$}#O#P!$R#P#o$}#o#p!%i#p#q$}#q#r!$g#r~$}", + tokenizers: [legacyPrint, indentation, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, newlines], + topRules: {"Script":[0,3]}, + specialized: [{term: 213, get: value => spec_identifier[value] || -1}], + tokenPrec: 7282 + }); + + function indentBody(context, node) { + let base = context.lineIndent(node.from); + let line = context.lineAt(context.pos, -1), to = line.from + line.text.length; + // Don't consider blank, deindented lines at the end of the + // block part of the block + if (!/\S/.test(line.text) && + context.node.to < to + 100 && + !/\S/.test(context.state.sliceDoc(to, context.node.to)) && + context.lineIndent(context.pos, -1) <= base) + return null; + // A normally deindenting keyword that appears at a higher + // indentation than the block should probably be handled by the next + // level + if (/^\s*(else:|elif |except |finally:)/.test(context.textAfter) && context.lineIndent(context.pos, -1) > base) + return null; + return base + context.unit; + } + /** + A language provider based on the [Lezer Python + parser](https://github.com/lezer-parser/python), extended with + highlighting and indentation information. + */ + const pythonLanguage = /*@__PURE__*/LRLanguage.define({ + parser: /*@__PURE__*/parser.configure({ + props: [ + /*@__PURE__*/indentNodeProp.add({ + Body: context => { var _a; return (_a = indentBody(context, context.node)) !== null && _a !== void 0 ? _a : context.continue(); }, + IfStatement: cx => /^\s*(else:|elif )/.test(cx.textAfter) ? cx.baseIndent : cx.continue(), + TryStatement: cx => /^\s*(except |finally:)/.test(cx.textAfter) ? cx.baseIndent : cx.continue(), + "TupleExpression ComprehensionExpression ParamList ArgList ParenthesizedExpression": /*@__PURE__*/delimitedIndent({ closing: ")" }), + "DictionaryExpression DictionaryComprehensionExpression SetExpression SetComprehensionExpression": /*@__PURE__*/delimitedIndent({ closing: "}" }), + "ArrayExpression ArrayComprehensionExpression": /*@__PURE__*/delimitedIndent({ closing: "]" }), + "String FormatString": () => null, + Script: context => { + if (context.pos + /\s*/.exec(context.textAfter)[0].length >= context.node.to) { + let endBody = null; + for (let cur = context.node, to = cur.to;;) { + cur = cur.lastChild; + if (!cur || cur.to != to) + break; + if (cur.type.name == "Body") + endBody = cur; + } + if (endBody) { + let bodyIndent = indentBody(context, endBody); + if (bodyIndent != null) + return bodyIndent; + } + } + return context.continue(); + } + }), + /*@__PURE__*/foldNodeProp.add({ + "ArrayExpression DictionaryExpression SetExpression TupleExpression": foldInside, + Body: (node, state) => ({ from: node.from + 1, to: node.to - (node.to == state.doc.length ? 0 : 1) }) + }) + ], + }), + languageData: { + closeBrackets: { + brackets: ["(", "[", "{", "'", '"', "'''", '"""'], + stringPrefixes: ["f", "fr", "rf", "r", "u", "b", "br", "rb", + "F", "FR", "RF", "R", "U", "B", "BR", "RB"] + }, + commentTokens: { line: "#" }, + indentOnInput: /^\s*([\}\]\)]|else:|elif |except |finally:)$/ + } + }); + /** + Python language support. + */ + function python() { + return new LanguageSupport(pythonLanguage); + } + + // Using https://github.com/one-dark/vscode-one-dark-theme/ as reference for the colors + const ivory = "#abb2bf", stone = "#7d8799", // Brightened compared to original to increase contrast + darkBackground = "#21252b", highlightBackground = "#2c313a", background = "#282c34", tooltipBackground = "#353a42", selection = "#3E4451", cursor = "#528bff"; + /** + The editor theme styles for One Dark. + */ + const oneDarkTheme = /*@__PURE__*/EditorView.theme({ + "&": { + color: ivory, + backgroundColor: background + }, + ".cm-content": { + caretColor: cursor + }, + ".cm-cursor, .cm-dropCursor": { borderLeftColor: cursor }, + "&.cm-focused .cm-selectionBackground, .cm-selectionBackground, .cm-content ::selection": { backgroundColor: selection }, + ".cm-panels": { backgroundColor: darkBackground, color: ivory }, + ".cm-panels.cm-panels-top": { borderBottom: "2px solid black" }, + ".cm-panels.cm-panels-bottom": { borderTop: "2px solid black" }, + ".cm-searchMatch": { + backgroundColor: "#72a1ff59", + outline: "1px solid #457dff" + }, + ".cm-searchMatch.cm-searchMatch-selected": { + backgroundColor: "#6199ff2f" + }, + ".cm-activeLine": { backgroundColor: "#6699ff0b" }, + ".cm-selectionMatch": { backgroundColor: "#aafe661a" }, + "&.cm-focused .cm-matchingBracket, &.cm-focused .cm-nonmatchingBracket": { + backgroundColor: "#bad0f847", + outline: "1px solid #515a6b" + }, + ".cm-gutters": { + backgroundColor: background, + color: stone, + border: "none" + }, + ".cm-activeLineGutter": { + backgroundColor: highlightBackground + }, + ".cm-foldPlaceholder": { + backgroundColor: "transparent", + border: "none", + color: "#ddd" + }, + ".cm-tooltip": { + border: "none", + backgroundColor: tooltipBackground + }, + ".cm-tooltip .cm-tooltip-arrow:before": { + borderTopColor: "transparent", + borderBottomColor: "transparent" + }, + ".cm-tooltip .cm-tooltip-arrow:after": { + borderTopColor: tooltipBackground, + borderBottomColor: tooltipBackground + }, + ".cm-tooltip-autocomplete": { + "& > ul > li[aria-selected]": { + backgroundColor: highlightBackground, + color: ivory + } + } + }, { dark: true }); + + const logger$5 = getLogger('py-repl'); + const RUNBUTTON = `<svg style="height:20px;width:20px;vertical-align:-.125em;transform-origin:center;overflow:visible;color:green" viewBox="0 0 384 512" aria-hidden="true" role="img" xmlns="http://www.w3.org/2000/svg"><g transform="translate(192 256)" transform-origin="96 0"><g transform="translate(0,0) scale(1,1)"><path d="M361 215C375.3 223.8 384 239.3 384 256C384 272.7 375.3 288.2 361 296.1L73.03 472.1C58.21 482 39.66 482.4 24.52 473.9C9.377 465.4 0 449.4 0 432V80C0 62.64 9.377 46.63 24.52 38.13C39.66 29.64 58.21 29.99 73.03 39.04L361 215z" fill="currentColor" transform="translate(-192 -256)"></path></g></g></svg>`; + function make_PyRepl(interpreter) { + /* High level structure of py-repl DOM, and the corresponding JS names. + + this <py-repl> + shadow #shadow-root + <slot></slot> + boxDiv <div class='py-repl-box'> + editorLabel <label>...</label> + editorDiv <div class="py-repl-editor"></div> + outDiv <div class="py-repl-output"></div> + </div> + </py-repl> + */ + class PyRepl extends HTMLElement { + constructor() { + super(); + } + connectedCallback() { + ensureUniqueId(this); + this.shadow = this.attachShadow({ mode: 'open' }); + const slot = document.createElement('slot'); + this.shadow.appendChild(slot); + if (!this.hasAttribute('exec-id')) { + this.setAttribute('exec-id', '0'); + } + if (!this.hasAttribute('root')) { + this.setAttribute('root', this.id); + } + const pySrc = htmlDecode(this.innerHTML).trim(); + this.innerHTML = ''; + this.editor = this.makeEditor(pySrc); + const boxDiv = this.makeBoxDiv(); + this.appendChild(boxDiv); + this.editor.focus(); + logger$5.debug(`element ${this.id} successfully connected`); + } + /** Create and configure the codemirror editor + */ + makeEditor(pySrc) { + const languageConf = new Compartment(); + const extensions = [ + indentUnit.of(' '), + basicSetup, + languageConf.of(python()), + keymap.of([ + ...defaultKeymap, + { key: 'Ctrl-Enter', run: this.execute.bind(this), preventDefault: true }, + { key: 'Shift-Enter', run: this.execute.bind(this), preventDefault: true }, + ]), + ]; + if (getAttribute(this, 'theme') === 'dark') { + extensions.push(oneDarkTheme); + } + return new EditorView({ + doc: pySrc, + extensions, + }); + } + // ******** main entry point for py-repl DOM building ********** + // + // The following functions are written in a top-down, depth-first + // order (so that the order of code roughly matches the order of + // execution) + makeBoxDiv() { + const boxDiv = document.createElement('div'); + boxDiv.className = 'py-repl-box'; + const editorDiv = this.makeEditorDiv(); + const editorLabel = this.makeLabel('Python Script Area', editorDiv); + this.outDiv = this.makeOutDiv(); + boxDiv.append(editorLabel); + boxDiv.appendChild(editorDiv); + boxDiv.appendChild(this.outDiv); + return boxDiv; + } + makeEditorDiv() { + const editorDiv = document.createElement('div'); + editorDiv.id = 'code-editor'; + editorDiv.className = 'py-repl-editor'; + editorDiv.appendChild(this.editor.dom); + const runButton = this.makeRunButton(); + const runLabel = this.makeLabel('Python Script Run Button', runButton); + editorDiv.appendChild(runLabel); + editorDiv.appendChild(runButton); + return editorDiv; + } + makeLabel(text, elementFor) { + ensureUniqueId(elementFor); + const lbl = document.createElement('label'); + lbl.innerHTML = text; + lbl.htmlFor = elementFor.id; + // XXX this should be a CSS class + // Styles that we use to hide the labels whilst also keeping it accessible for screen readers + const labelStyle = 'overflow:hidden; display:block; width:1px; height:1px'; + lbl.setAttribute('style', labelStyle); + return lbl; + } + makeRunButton() { + const runButton = document.createElement('button'); + runButton.id = 'runButton'; + runButton.className = 'absolute py-repl-run-button'; + runButton.innerHTML = RUNBUTTON; + runButton.addEventListener('click', this.execute.bind(this)); + return runButton; + } + makeOutDiv() { + const outDiv = document.createElement('div'); + outDiv.className = 'py-repl-output'; + outDiv.id = this.id + '-repl-output'; + return outDiv; + } + // ********************* execution logic ********************* + /** Execute the python code written in the editor, and automatically + * display() the last evaluated expression + */ + async execute() { + const pySrc = this.getPySrc(); + // determine the output element + const outEl = this.getOutputElement(); + if (outEl === undefined) { + // this happens if we specified output="..." but we couldn't + // find the ID. We already displayed an error message inside + // getOutputElement, stop the execution. + return; + } + // clear the old output before executing the new code + outEl.innerHTML = ''; + // execute the python code + const pyResult = (await pyExec(interpreter, pySrc, outEl)).result; + // display the value of the last evaluated expression (REPL-style) + if (pyResult !== undefined) { + pyDisplay(interpreter, pyResult, { target: outEl.id }); + } + this.autogenerateMaybe(); + } + getPySrc() { + return this.editor.state.doc.toString(); + } + getOutputElement() { + const outputID = getAttribute(this, 'output'); + if (outputID !== null) { + const el = document.getElementById(outputID); + if (el === null) { + const err = `py-repl ERROR: cannot find the output element #${outputID} in the DOM`; + this.outDiv.innerText = err; + return undefined; + } + return el; + } + else { + return this.outDiv; + } + } + // XXX the autogenerate logic is very messy. We should redo it, and it + // should be the default. + autogenerateMaybe() { + if (this.hasAttribute('auto-generate')) { + const allPyRepls = document.querySelectorAll(`py-repl[root='${this.getAttribute('root')}'][exec-id]`); + const lastRepl = allPyRepls[allPyRepls.length - 1]; + const lastExecId = lastRepl.getAttribute('exec-id'); + const nextExecId = parseInt(lastExecId) + 1; + const newPyRepl = document.createElement('py-repl'); + newPyRepl.setAttribute('root', this.getAttribute('root')); + newPyRepl.id = this.getAttribute('root') + '-' + nextExecId.toString(); + if (this.hasAttribute('auto-generate')) { + newPyRepl.setAttribute('auto-generate', ''); + this.removeAttribute('auto-generate'); + } + const outputMode = getAttribute(this, 'output-mode'); + if (outputMode) { + newPyRepl.setAttribute('output-mode', outputMode); + } + const addReplAttribute = (attribute) => { + const attr = getAttribute(this, attribute); + if (attr) { + newPyRepl.setAttribute(attribute, attr); + } + }; + addReplAttribute('output'); + newPyRepl.setAttribute('exec-id', nextExecId.toString()); + if (this.parentElement) { + this.parentElement.appendChild(newPyRepl); + } + } + } + } + return PyRepl; + } + + const logger$4 = getLogger('py-register-widget'); + function createWidget(interpreter, name, code, klass) { + class CustomWidget extends HTMLElement { + constructor() { + super(); + this.name = name; + this.klass = klass; + this.code = code; + // attach shadow so we can preserve the element original innerHtml content + this.shadow = this.attachShadow({ mode: 'open' }); + this.wrapper = document.createElement('slot'); + this.shadow.appendChild(this.wrapper); + } + async connectedCallback() { + await interpreter.runButDontRaise(this.code); + this.proxyClass = interpreter.globals.get(this.klass); + this.proxy = this.proxyClass(this); + this.proxy.connect(); + this.registerWidget(); + } + registerWidget() { + logger$4.info('new widget registered:', this.name); + interpreter.globals.set(this.id, this.proxy); + } + } + /* eslint-disable @typescript-eslint/no-unused-vars */ + customElements.define(name, CustomWidget); + /* eslint-enable @typescript-eslint/no-unused-vars */ + } + function make_PyWidget(interpreter) { + class PyWidget extends HTMLElement { + constructor() { + super(); + // attach shadow so we can preserve the element original innerHtml content + this.shadow = this.attachShadow({ mode: 'open' }); + this.wrapper = document.createElement('slot'); + this.shadow.appendChild(this.wrapper); + this.addAttributes('src', 'name', 'klass'); + } + addAttributes(...attrs) { + for (const each of attrs) { + const property = each === 'src' ? 'source' : each; + if (this.hasAttribute(each)) { + this[property] = this.getAttribute(each); + } + } + } + async connectedCallback() { + if (this.id === undefined) { + throw new ReferenceError(`No id specified for component. Components must have an explicit id. Please use id="" to specify your component id.`); + } + const mainDiv = document.createElement('div'); + mainDiv.id = this.id + '-main'; + this.appendChild(mainDiv); + logger$4.debug('PyWidget: reading source', this.source); + this.code = await this.getSourceFromFile(this.source); + createWidget(interpreter, this.name, this.code, this.klass); + } + async getSourceFromFile(s) { + const response = await robustFetch(s); + return await response.text(); + } + } + return PyWidget; + } + + function createCustomElements(interpreter) { + const PyWidget = make_PyWidget(interpreter); + const PyRepl = make_PyRepl(interpreter); + /* eslint-disable @typescript-eslint/no-unused-vars */ + customElements.define('py-repl', PyRepl); + customElements.define('py-register-widget', PyWidget); + /* eslint-enable @typescript-eslint/no-unused-vars */ + } + + /** Default implementation of Stdio: stdout and stderr are both sent to the + * console + */ + const DEFAULT_STDIO = { + stdout_writeline: console.log, + stderr_writeline: console.log, + }; + /** Stdio provider for sending output to DOM element + * specified by ID. Used with "output" keyword. + * + */ + class TargetedStdio { + constructor(source_element, source_attribute, capture_stdout = true, capture_stderr = true) { + this.source_element = source_element; + this.source_attribute = source_attribute; + this.capture_stdout = capture_stdout; + this.capture_stderr = capture_stderr; + } + /** Writes the given msg to an element with a given ID. The ID is the value an attribute + * of the source_element specified by source_attribute. + * Both the element to be targeted and the ID of the element to write to + * are determined at write-time, not when the TargetdStdio object is + * created. This way, if either the 'output' attribute of the HTML tag + * or the ID of the target element changes during execution of the Python + * code, the output is still routed (or not) as expected + * + * @param msg The output to be written + */ + writeline_by_attribute(msg) { + const target_id = this.source_element.getAttribute(this.source_attribute); + const target = document.getElementById(target_id); + if (target === null) { + // No matching ID + createSingularWarning(`${this.source_attribute} = "${target_id}" does not match the id of any element on the page.`); + } + else { + msg = escape(msg).replace('\n', '<br>'); + if (!msg.endsWith('<br/>') && !msg.endsWith('<br>')) { + msg = msg + '<br>'; + } + target.innerHTML += msg; + } + } + stdout_writeline(msg) { + if (this.capture_stdout) { + this.writeline_by_attribute(msg); + } + } + stderr_writeline(msg) { + if (this.capture_stderr) { + this.writeline_by_attribute(msg); + } + } + } + /** Redirect stdio streams to multiple listeners + */ + class StdioMultiplexer { + constructor() { + this._listeners = []; + } + addListener(obj) { + this._listeners.push(obj); + } + removeListener(obj) { + const index = this._listeners.indexOf(obj); + if (index > -1) { + this._listeners.splice(index, 1); + } + } + stdout_writeline(msg) { + for (const obj of this._listeners) + obj.stdout_writeline(msg); + } + stderr_writeline(msg) { + for (const obj of this._listeners) + obj.stderr_writeline(msg); + } + } + + const logger$3 = getLogger('py-terminal'); + class PyTerminalPlugin extends Plugin { + constructor(app) { + super(); + this.app = app; + } + configure(config) { + // validate the terminal config and handle default values + const t = config.terminal; + if (t !== undefined && t !== true && t !== false && t !== 'auto') { + const got = JSON.stringify(t); + throw new UserError(ErrorCode.BAD_CONFIG, 'Invalid value for config.terminal: the only accepted' + + `values are true, false and "auto", got "${got}".`); + } + if (t === undefined) { + config.terminal = 'auto'; // default value + } + } + beforeLaunch(config) { + // if config.terminal is "yes" or "auto", let's add a <py-terminal> to + // the document, unless it's already present. + const t = config.terminal; + if (t === true || t === 'auto') { + if (document.querySelector('py-terminal') === null) { + logger$3.info('No <py-terminal> found, adding one'); + const termElem = document.createElement('py-terminal'); + if (t === 'auto') + termElem.setAttribute('auto', ''); + document.body.appendChild(termElem); + } + } + } + afterSetup(interpreter) { + // the Python interpreter has been initialized and we are ready to + // execute user code: + // + // 1. define the "py-terminal" custom element + // + // 2. if there is a <py-terminal> tag on the page, it will register + // a Stdio listener just before the user code executes, ensuring + // that we capture all the output + // + // 3. everything which was written to stdout BEFORE this moment will + // NOT be shown on the py-terminal; in particular, pyodide + // startup messages will not be shown (but they will go to the + // console as usual). This is by design, else we would display + // e.g. "Python initialization complete" on every page, which we + // don't want. + // + // 4. (in the future we might want to add an option to start the + // capture earlier, but I don't think it's important now). + const PyTerminal = make_PyTerminal(this.app); + customElements.define('py-terminal', PyTerminal); + } + } + function make_PyTerminal(app) { + /** The <py-terminal> custom element, which automatically register a stdio + * listener to capture and display stdout/stderr + */ + class PyTerminal extends HTMLElement { + connectedCallback() { + // should we use a shadowRoot instead? It looks unnecessarily + // complicated to me, but I'm not really sure about the + // implications + this.outElem = document.createElement('pre'); + this.outElem.className = 'py-terminal'; + this.appendChild(this.outElem); + if (this.isAuto()) { + this.classList.add('py-terminal-hidden'); + this.autoShowOnNextLine = true; + } + else { + this.autoShowOnNextLine = false; + } + logger$3.info('Registering stdio listener'); + app.registerStdioListener(this); + } + isAuto() { + return this.hasAttribute('auto'); + } + // implementation of the Stdio interface + stdout_writeline(msg) { + this.outElem.innerText += msg + '\n'; + if (this.autoShowOnNextLine) { + this.classList.remove('py-terminal-hidden'); + this.autoShowOnNextLine = false; + } + } + stderr_writeline(msg) { + this.stdout_writeline(msg); + } + } + return PyTerminal; + } + + const logger$2 = getLogger('py-splashscreen'); + const AUTOCLOSE_LOADER_DEPRECATED = ` +The setting autoclose_loader is deprecated. Please use the +following instead:<br> +<pre> +<py-config> +[splashscreen] +autoclose = false +</py-config> +</pre>`; + class SplashscreenPlugin extends Plugin { + configure(config) { + // the officially supported setting is config.splashscreen.autoclose, + // but we still also support the old config.autoclose_loader (with a + // deprecation warning) + this.autoclose = true; + this.enabled = true; + if ('autoclose_loader' in config) { + this.autoclose = config.autoclose_loader; + showWarning(AUTOCLOSE_LOADER_DEPRECATED, 'html'); + } + if (config.splashscreen) { + this.autoclose = config.splashscreen.autoclose ?? true; + this.enabled = config.splashscreen.enabled ?? true; + } + } + beforeLaunch(config) { + if (!this.enabled) { + return; + } + // add the splashscreen to the DOM + logger$2.info('add py-splashscreen'); + customElements.define('py-splashscreen', PySplashscreen); + this.elem = document.createElement('py-splashscreen'); + document.body.append(this.elem); + document.addEventListener('py-status-message', (e) => { + const msg = e.detail; + this.elem.log(msg); + }); + } + afterStartup(interpreter) { + if (this.autoclose && this.enabled) { + this.elem.close(); + } + } + onUserError(error) { + if (this.elem !== undefined && this.enabled) { + // Remove the splashscreen so users can see the banner better + this.elem.close(); + } + } + } + class PySplashscreen extends HTMLElement { + constructor() { + super(); + } + connectedCallback() { + this.innerHTML = `<div id="pyscript_loading_splash" class="py-overlay"> <div class="py-pop-up"> <div class="smooth spinner"></div> <div id="pyscript-loading-label" class="label"> @@ -4170,23687 +28474,434 @@ </div> </div> </div>`; - this.mount_name = this.id.split('-').join('_'); - this.operation = document.getElementById('pyscript-operation'); - this.details = document.getElementById('pyscript-operation-details'); - } - log(msg) { - // loader messages are showed both in the HTML and in the console - logger$8.info(msg); - const newLog = document.createElement('p'); - newLog.innerText = msg; - this.details.appendChild(newLog); - } - close() { - logger$8.info('Closing'); - this.remove(); - } - } + this.mount_name = this.id.split('-').join('_'); + this.operation = document.getElementById('pyscript-operation'); + this.details = document.getElementById('pyscript-operation-details'); + } + log(msg) { + const newLog = document.createElement('p'); + newLog.innerText = msg; + this.details.appendChild(newLog); + } + close() { + logger$2.info('Closing'); + this.remove(); + } + } - // Compressed representation of the Grapheme_Cluster_Break=Extend - // information from - // http://www.unicode.org/Public/13.0.0/ucd/auxiliary/GraphemeBreakProperty.txt. - // Each pair of elements represents a range, as an offet from the - // previous range and a length. Numbers are in base-36, with the empty - // string being a shorthand for 1. - let extend = /*@__PURE__*/"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(s => s ? parseInt(s, 36) : 1); - // Convert offsets into absolute values - for (let i = 1; i < extend.length; i++) - extend[i] += extend[i - 1]; - function isExtendingChar(code) { - for (let i = 1; i < extend.length; i += 2) - if (extend[i] > code) - return extend[i - 1] <= code; - return false; - } - function isRegionalIndicator(code) { - return code >= 0x1F1E6 && code <= 0x1F1FF; - } - const ZWJ = 0x200d; - /** - Returns a next grapheme cluster break _after_ (not equal to) - `pos`, if `forward` is true, or before otherwise. Returns `pos` - itself if no further cluster break is available in the string. - Moves across surrogate pairs, extending characters (when - `includeExtending` is true), characters joined with zero-width - joiners, and flag emoji. - */ - function findClusterBreak(str, pos, forward = true, includeExtending = true) { - return (forward ? nextClusterBreak : prevClusterBreak)(str, pos, includeExtending); - } - function nextClusterBreak(str, pos, includeExtending) { - if (pos == str.length) - return pos; - // If pos is in the middle of a surrogate pair, move to its start - if (pos && surrogateLow(str.charCodeAt(pos)) && surrogateHigh(str.charCodeAt(pos - 1))) - pos--; - let prev = codePointAt(str, pos); - pos += codePointSize(prev); - while (pos < str.length) { - let next = codePointAt(str, pos); - if (prev == ZWJ || next == ZWJ || includeExtending && isExtendingChar(next)) { - pos += codePointSize(next); - prev = next; - } - else if (isRegionalIndicator(next)) { - let countBefore = 0, i = pos - 2; - while (i >= 0 && isRegionalIndicator(codePointAt(str, i))) { - countBefore++; - i -= 2; - } - if (countBefore % 2 == 0) - break; - else - pos += 2; - } - else { - break; - } - } - return pos; - } - function prevClusterBreak(str, pos, includeExtending) { - while (pos > 0) { - let found = nextClusterBreak(str, pos - 2, includeExtending); - if (found < pos) - return found; - pos--; - } - return 0; - } - function surrogateLow(ch) { return ch >= 0xDC00 && ch < 0xE000; } - function surrogateHigh(ch) { return ch >= 0xD800 && ch < 0xDC00; } - /** - Find the code point at the given position in a string (like the - [`codePointAt`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/codePointAt) - string method). - */ - function codePointAt(str, pos) { - let code0 = str.charCodeAt(pos); - if (!surrogateHigh(code0) || pos + 1 == str.length) - return code0; - let code1 = str.charCodeAt(pos + 1); - if (!surrogateLow(code1)) - return code0; - return ((code0 - 0xd800) << 10) + (code1 - 0xdc00) + 0x10000; - } - /** - Given a Unicode codepoint, return the JavaScript string that - respresents it (like - [`String.fromCodePoint`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/fromCodePoint)). - */ - function fromCodePoint(code) { - if (code <= 0xffff) - return String.fromCharCode(code); - code -= 0x10000; - return String.fromCharCode((code >> 10) + 0xd800, (code & 1023) + 0xdc00); - } - /** - The first character that takes up two positions in a JavaScript - string. It is often useful to compare with this after calling - `codePointAt`, to figure out whether your character takes up 1 or - 2 index positions. - */ - function codePointSize(code) { return code < 0x10000 ? 1 : 2; } + const logger$1 = getLogger('plugins/importmap'); + class ImportmapPlugin extends Plugin { + async afterSetup(interpreter) { + // make importmap ES modules available from python using 'import'. + // + // XXX: this code can probably be improved because errors are silently + // ignored. + // + // Moreover, it's also wrong because it's async and currently we don't + // await the module to be fully registered before executing the code + // inside py-script. It's also unclear whether we want to wait or not + // (or maybe only wait only if we do an actual 'import'?) + for (const node of document.querySelectorAll("script[type='importmap']")) { + const importmap = (() => { + try { + return JSON.parse(node.textContent); + } + catch (error) { + showWarning('Failed to parse import map: ' + error.message); + } + })(); + if (importmap?.imports == null) + continue; + for (const [name, url] of Object.entries(importmap.imports)) { + if (typeof name != 'string' || typeof url != 'string') + continue; + let exports; + try { + // XXX: pyodide doesn't like Module(), failing with + // "can't read 'name' of undefined" at import time + exports = { ...(await import(url)) }; + } + catch { + logger$1.warn(`failed to fetch '${url}' for '${name}'`); + continue; + } + logger$1.info('Registering JS module', name); + interpreter._remote.registerJsModule(name, exports); + } + } + } + } - /** - Count the column position at the given offset into the string, - taking extending characters and tab size into account. - */ - function countColumn(string, tabSize, to = string.length) { - let n = 0; - for (let i = 0; i < to;) { - if (string.charCodeAt(i) == 9) { - n += tabSize - (n % tabSize); - i++; - } - else { - n++; - i = findClusterBreak(string, i); - } - } - return n; - } - /** - Find the offset that corresponds to the given column position in a - string, taking extending characters and tab size into account. By - default, the string length is returned when it is too short to - reach the column. Pass `strict` true to make it return -1 in that - situation. - */ - function findColumn(string, col, tabSize, strict) { - for (let i = 0, n = 0;;) { - if (n >= col) - return i; - if (i == string.length) - break; - n += string.charCodeAt(i) == 9 ? tabSize - (n % tabSize) : 1; - i = findClusterBreak(string, i); - } - return strict === true ? -1 : string.length; - } + /** + * The StdioDirector plugin captures the output to Python's sys.stdio and + * sys.stderr and writes it to a specific element in the DOM. It does this by + * creating a new TargetedStdio manager and adding it to the global stdioMultiplexer's + * list of listeners prior to executing the Python in a specific tag. Following + * execution of the Python in that tag, it removes the TargetedStdio as a listener + * + */ + class StdioDirector extends Plugin { + constructor(stdio) { + super(); + this._stdioMultiplexer = stdio; + } + /** Prior to a <py-script> tag being evaluated, if that tag itself has + * an 'output' attribute, a new TargetedStdio object is created and added + * to the stdioMultiplexer to route sys.stdout and sys.stdout to the DOM object + * with that ID for the duration of the evaluation. + * + */ + beforePyScriptExec(options) { + if (options.pyScriptTag.hasAttribute('output')) { + const targeted_io = new TargetedStdio(options.pyScriptTag, 'output', true, true); + options.pyScriptTag.stdout_manager = targeted_io; + this._stdioMultiplexer.addListener(targeted_io); + } + if (options.pyScriptTag.hasAttribute('stderr')) { + const targeted_io = new TargetedStdio(options.pyScriptTag, 'stderr', false, true); + options.pyScriptTag.stderr_manager = targeted_io; + this._stdioMultiplexer.addListener(targeted_io); + } + } + /** After a <py-script> tag is evaluated, if that tag has a 'stdout_manager' + * (presumably TargetedStdio, or some other future IO handler), it is removed. + */ + afterPyScriptExec(options) { + if (options.pyScriptTag.stdout_manager != null) { + this._stdioMultiplexer.removeListener(options.pyScriptTag.stdout_manager); + options.pyScriptTag.stdout_manager = null; + } + if (options.pyScriptTag.stderr_manager != null) { + this._stdioMultiplexer.removeListener(options.pyScriptTag.stderr_manager); + options.pyScriptTag.stderr_manager = null; + } + } + } - /** - The data structure for documents. - */ - class Text { - /** - @internal - */ - constructor() { } - /** - Get the line description around the given position. - */ - lineAt(pos) { - if (pos < 0 || pos > this.length) - throw new RangeError(`Invalid position ${pos} in document of length ${this.length}`); - return this.lineInner(pos, false, 1, 0); - } - /** - Get the description for the given (1-based) line number. - */ - line(n) { - if (n < 1 || n > this.lines) - throw new RangeError(`Invalid line number ${n} in ${this.lines}-line document`); - return this.lineInner(n, true, 1, 0); - } - /** - Replace a range of the text with the given content. - */ - replace(from, to, text) { - let parts = []; - this.decompose(0, from, parts, 2 /* To */); - if (text.length) - text.decompose(0, text.length, parts, 1 /* From */ | 2 /* To */); - this.decompose(to, this.length, parts, 1 /* From */); - return TextNode.from(parts, this.length - (to - from) + text.length); - } - /** - Append another document to this one. - */ - append(other) { - return this.replace(this.length, this.length, other); - } - /** - Retrieve the text between the given points. - */ - slice(from, to = this.length) { - let parts = []; - this.decompose(from, to, parts, 0); - return TextNode.from(parts, to - from); - } - /** - Test whether this text is equal to another instance. - */ - eq(other) { - if (other == this) - return true; - if (other.length != this.length || other.lines != this.lines) - return false; - let start = this.scanIdentical(other, 1), end = this.length - this.scanIdentical(other, -1); - let a = new RawTextCursor(this), b = new RawTextCursor(other); - for (let skip = start, pos = start;;) { - a.next(skip); - b.next(skip); - skip = 0; - if (a.lineBreak != b.lineBreak || a.done != b.done || a.value != b.value) - return false; - pos += a.value.length; - if (a.done || pos >= end) - return true; - } - } - /** - Iterate over the text. When `dir` is `-1`, iteration happens - from end to start. This will return lines and the breaks between - them as separate strings, and for long lines, might split lines - themselves into multiple chunks as well. - */ - iter(dir = 1) { return new RawTextCursor(this, dir); } - /** - Iterate over a range of the text. When `from` > `to`, the - iterator will run in reverse. - */ - iterRange(from, to = this.length) { return new PartialTextCursor(this, from, to); } - /** - Return a cursor that iterates over the given range of lines, - _without_ returning the line breaks between, and yielding empty - strings for empty lines. - - When `from` and `to` are given, they should be 1-based line numbers. - */ - iterLines(from, to) { - let inner; - if (from == null) { - inner = this.iter(); - } - else { - if (to == null) - to = this.lines + 1; - let start = this.line(from).from; - inner = this.iterRange(start, Math.max(start, to == this.lines + 1 ? this.length : to <= 1 ? 0 : this.line(to - 1).to)); - } - return new LineCursor(inner); - } - /** - @internal - */ - toString() { return this.sliceString(0); } - /** - Convert the document to an array of lines (which can be - deserialized again via [`Text.of`](https://codemirror.net/6/docs/ref/#text.Text^of)). - */ - toJSON() { - let lines = []; - this.flatten(lines); - return lines; - } - /** - Create a `Text` instance for the given array of lines. - */ - static of(text) { - if (text.length == 0) - throw new RangeError("A document must have at least one line"); - if (text.length == 1 && !text[0]) - return Text.empty; - return text.length <= 32 /* Branch */ ? new TextLeaf(text) : TextNode.from(TextLeaf.split(text, [])); - } - } - // Leaves store an array of line strings. There are always line breaks - // between these strings. Leaves are limited in size and have to be - // contained in TextNode instances for bigger documents. - class TextLeaf extends Text { - constructor(text, length = textLength(text)) { - super(); - this.text = text; - this.length = length; - } - get lines() { return this.text.length; } - get children() { return null; } - lineInner(target, isLine, line, offset) { - for (let i = 0;; i++) { - let string = this.text[i], end = offset + string.length; - if ((isLine ? line : end) >= target) - return new Line(offset, end, line, string); - offset = end + 1; - line++; - } - } - decompose(from, to, target, open) { - let text = from <= 0 && to >= this.length ? this - : new TextLeaf(sliceText(this.text, from, to), Math.min(to, this.length) - Math.max(0, from)); - if (open & 1 /* From */) { - let prev = target.pop(); - let joined = appendText(text.text, prev.text.slice(), 0, text.length); - if (joined.length <= 32 /* Branch */) { - target.push(new TextLeaf(joined, prev.length + text.length)); - } - else { - let mid = joined.length >> 1; - target.push(new TextLeaf(joined.slice(0, mid)), new TextLeaf(joined.slice(mid))); - } - } - else { - target.push(text); - } - } - replace(from, to, text) { - if (!(text instanceof TextLeaf)) - return super.replace(from, to, text); - let lines = appendText(this.text, appendText(text.text, sliceText(this.text, 0, from)), to); - let newLen = this.length + text.length - (to - from); - if (lines.length <= 32 /* Branch */) - return new TextLeaf(lines, newLen); - return TextNode.from(TextLeaf.split(lines, []), newLen); - } - sliceString(from, to = this.length, lineSep = "\n") { - let result = ""; - for (let pos = 0, i = 0; pos <= to && i < this.text.length; i++) { - let line = this.text[i], end = pos + line.length; - if (pos > from && i) - result += lineSep; - if (from < end && to > pos) - result += line.slice(Math.max(0, from - pos), to - pos); - pos = end + 1; - } - return result; - } - flatten(target) { - for (let line of this.text) - target.push(line); - } - scanIdentical() { return 0; } - static split(text, target) { - let part = [], len = -1; - for (let line of text) { - part.push(line); - len += line.length + 1; - if (part.length == 32 /* Branch */) { - target.push(new TextLeaf(part, len)); - part = []; - len = -1; - } - } - if (len > -1) - target.push(new TextLeaf(part, len)); - return target; - } - } - // Nodes provide the tree structure of the `Text` type. They store a - // number of other nodes or leaves, taking care to balance themselves - // on changes. There are implied line breaks _between_ the children of - // a node (but not before the first or after the last child). - class TextNode extends Text { - constructor(children, length) { - super(); - this.children = children; - this.length = length; - this.lines = 0; - for (let child of children) - this.lines += child.lines; - } - lineInner(target, isLine, line, offset) { - for (let i = 0;; i++) { - let child = this.children[i], end = offset + child.length, endLine = line + child.lines - 1; - if ((isLine ? endLine : end) >= target) - return child.lineInner(target, isLine, line, offset); - offset = end + 1; - line = endLine + 1; - } - } - decompose(from, to, target, open) { - for (let i = 0, pos = 0; pos <= to && i < this.children.length; i++) { - let child = this.children[i], end = pos + child.length; - if (from <= end && to >= pos) { - let childOpen = open & ((pos <= from ? 1 /* From */ : 0) | (end >= to ? 2 /* To */ : 0)); - if (pos >= from && end <= to && !childOpen) - target.push(child); - else - child.decompose(from - pos, to - pos, target, childOpen); - } - pos = end + 1; - } - } - replace(from, to, text) { - if (text.lines < this.lines) - for (let i = 0, pos = 0; i < this.children.length; i++) { - let child = this.children[i], end = pos + child.length; - // Fast path: if the change only affects one child and the - // child's size remains in the acceptable range, only update - // that child - if (from >= pos && to <= end) { - let updated = child.replace(from - pos, to - pos, text); - let totalLines = this.lines - child.lines + updated.lines; - if (updated.lines < (totalLines >> (5 /* BranchShift */ - 1)) && - updated.lines > (totalLines >> (5 /* BranchShift */ + 1))) { - let copy = this.children.slice(); - copy[i] = updated; - return new TextNode(copy, this.length - (to - from) + text.length); - } - return super.replace(pos, end, updated); - } - pos = end + 1; - } - return super.replace(from, to, text); - } - sliceString(from, to = this.length, lineSep = "\n") { - let result = ""; - for (let i = 0, pos = 0; i < this.children.length && pos <= to; i++) { - let child = this.children[i], end = pos + child.length; - if (pos > from && i) - result += lineSep; - if (from < end && to > pos) - result += child.sliceString(from - pos, to - pos, lineSep); - pos = end + 1; - } - return result; - } - flatten(target) { - for (let child of this.children) - child.flatten(target); - } - scanIdentical(other, dir) { - if (!(other instanceof TextNode)) - return 0; - let length = 0; - let [iA, iB, eA, eB] = dir > 0 ? [0, 0, this.children.length, other.children.length] - : [this.children.length - 1, other.children.length - 1, -1, -1]; - for (;; iA += dir, iB += dir) { - if (iA == eA || iB == eB) - return length; - let chA = this.children[iA], chB = other.children[iB]; - if (chA != chB) - return length + chA.scanIdentical(chB, dir); - length += chA.length + 1; - } - } - static from(children, length = children.reduce((l, ch) => l + ch.length + 1, -1)) { - let lines = 0; - for (let ch of children) - lines += ch.lines; - if (lines < 32 /* Branch */) { - let flat = []; - for (let ch of children) - ch.flatten(flat); - return new TextLeaf(flat, length); - } - let chunk = Math.max(32 /* Branch */, lines >> 5 /* BranchShift */), maxChunk = chunk << 1, minChunk = chunk >> 1; - let chunked = [], currentLines = 0, currentLen = -1, currentChunk = []; - function add(child) { - let last; - if (child.lines > maxChunk && child instanceof TextNode) { - for (let node of child.children) - add(node); - } - else if (child.lines > minChunk && (currentLines > minChunk || !currentLines)) { - flush(); - chunked.push(child); - } - else if (child instanceof TextLeaf && currentLines && - (last = currentChunk[currentChunk.length - 1]) instanceof TextLeaf && - child.lines + last.lines <= 32 /* Branch */) { - currentLines += child.lines; - currentLen += child.length + 1; - currentChunk[currentChunk.length - 1] = new TextLeaf(last.text.concat(child.text), last.length + 1 + child.length); - } - else { - if (currentLines + child.lines > chunk) - flush(); - currentLines += child.lines; - currentLen += child.length + 1; - currentChunk.push(child); - } - } - function flush() { - if (currentLines == 0) - return; - chunked.push(currentChunk.length == 1 ? currentChunk[0] : TextNode.from(currentChunk, currentLen)); - currentLen = -1; - currentLines = currentChunk.length = 0; - } - for (let child of children) - add(child); - flush(); - return chunked.length == 1 ? chunked[0] : new TextNode(chunked, length); - } - } - Text.empty = /*@__PURE__*/new TextLeaf([""], 0); - function textLength(text) { - let length = -1; - for (let line of text) - length += line.length + 1; - return length; - } - function appendText(text, target, from = 0, to = 1e9) { - for (let pos = 0, i = 0, first = true; i < text.length && pos <= to; i++) { - let line = text[i], end = pos + line.length; - if (end >= from) { - if (end > to) - line = line.slice(0, to - pos); - if (pos < from) - line = line.slice(from - pos); - if (first) { - target[target.length - 1] += line; - first = false; - } - else - target.push(line); - } - pos = end + 1; - } - return target; - } - function sliceText(text, from, to) { - return appendText(text, [""], from, to); - } - class RawTextCursor { - constructor(text, dir = 1) { - this.dir = dir; - this.done = false; - this.lineBreak = false; - this.value = ""; - this.nodes = [text]; - this.offsets = [dir > 0 ? 1 : (text instanceof TextLeaf ? text.text.length : text.children.length) << 1]; - } - nextInner(skip, dir) { - this.done = this.lineBreak = false; - for (;;) { - let last = this.nodes.length - 1; - let top = this.nodes[last], offsetValue = this.offsets[last], offset = offsetValue >> 1; - let size = top instanceof TextLeaf ? top.text.length : top.children.length; - if (offset == (dir > 0 ? size : 0)) { - if (last == 0) { - this.done = true; - this.value = ""; - return this; - } - if (dir > 0) - this.offsets[last - 1]++; - this.nodes.pop(); - this.offsets.pop(); - } - else if ((offsetValue & 1) == (dir > 0 ? 0 : 1)) { - this.offsets[last] += dir; - if (skip == 0) { - this.lineBreak = true; - this.value = "\n"; - return this; - } - skip--; - } - else if (top instanceof TextLeaf) { - // Move to the next string - let next = top.text[offset + (dir < 0 ? -1 : 0)]; - this.offsets[last] += dir; - if (next.length > Math.max(0, skip)) { - this.value = skip == 0 ? next : dir > 0 ? next.slice(skip) : next.slice(0, next.length - skip); - return this; - } - skip -= next.length; - } - else { - let next = top.children[offset + (dir < 0 ? -1 : 0)]; - if (skip > next.length) { - skip -= next.length; - this.offsets[last] += dir; - } - else { - if (dir < 0) - this.offsets[last]--; - this.nodes.push(next); - this.offsets.push(dir > 0 ? 1 : (next instanceof TextLeaf ? next.text.length : next.children.length) << 1); - } - } - } - } - next(skip = 0) { - if (skip < 0) { - this.nextInner(-skip, (-this.dir)); - skip = this.value.length; - } - return this.nextInner(skip, this.dir); - } - } - class PartialTextCursor { - constructor(text, start, end) { - this.value = ""; - this.done = false; - this.cursor = new RawTextCursor(text, start > end ? -1 : 1); - this.pos = start > end ? text.length : 0; - this.from = Math.min(start, end); - this.to = Math.max(start, end); - } - nextInner(skip, dir) { - if (dir < 0 ? this.pos <= this.from : this.pos >= this.to) { - this.value = ""; - this.done = true; - return this; - } - skip += Math.max(0, dir < 0 ? this.pos - this.to : this.from - this.pos); - let limit = dir < 0 ? this.pos - this.from : this.to - this.pos; - if (skip > limit) - skip = limit; - limit -= skip; - let { value } = this.cursor.next(skip); - this.pos += (value.length + skip) * dir; - this.value = value.length <= limit ? value : dir < 0 ? value.slice(value.length - limit) : value.slice(0, limit); - this.done = !this.value; - return this; - } - next(skip = 0) { - if (skip < 0) - skip = Math.max(skip, this.from - this.pos); - else if (skip > 0) - skip = Math.min(skip, this.to - this.pos); - return this.nextInner(skip, this.cursor.dir); - } - get lineBreak() { return this.cursor.lineBreak && this.value != ""; } - } - class LineCursor { - constructor(inner) { - this.inner = inner; - this.afterBreak = true; - this.value = ""; - this.done = false; - } - next(skip = 0) { - let { done, lineBreak, value } = this.inner.next(skip); - if (done) { - this.done = true; - this.value = ""; - } - else if (lineBreak) { - if (this.afterBreak) { - this.value = ""; - } - else { - this.afterBreak = true; - this.next(); - } - } - else { - this.value = value; - this.afterBreak = false; - } - return this; - } - get lineBreak() { return false; } - } - if (typeof Symbol != "undefined") { - Text.prototype[Symbol.iterator] = function () { return this.iter(); }; - RawTextCursor.prototype[Symbol.iterator] = PartialTextCursor.prototype[Symbol.iterator] = - LineCursor.prototype[Symbol.iterator] = function () { return this; }; - } - /** - This type describes a line in the document. It is created - on-demand when lines are [queried](https://codemirror.net/6/docs/ref/#text.Text.lineAt). - */ - class Line { - /** - @internal - */ - constructor( - /** - The position of the start of the line. - */ - from, - /** - The position at the end of the line (_before_ the line break, - or at the end of document for the last line). - */ - to, - /** - This line's line number (1-based). - */ - number, - /** - The line's content. - */ - text) { - this.from = from; - this.to = to; - this.number = number; - this.text = text; - } - /** - The length of the line (not including any line break after it). - */ - get length() { return this.to - this.from; } - } + var pyscript = "import ast\nimport asyncio\nimport base64\nimport html\nimport io\nimport re\nimport time\nfrom collections import namedtuple\nfrom textwrap import dedent\n\nimport js\n\ntry:\n from pyodide.ffi import create_proxy\nexcept ImportError:\n from pyodide import create_proxy\n\nloop = asyncio.get_event_loop()\n\nMIME_METHODS = {\n \"__repr__\": \"text/plain\",\n \"_repr_html_\": \"text/html\",\n \"_repr_markdown_\": \"text/markdown\",\n \"_repr_svg_\": \"image/svg+xml\",\n \"_repr_png_\": \"image/png\",\n \"_repr_pdf_\": \"application/pdf\",\n \"_repr_jpeg_\": \"image/jpeg\",\n \"_repr_latex\": \"text/latex\",\n \"_repr_json_\": \"application/json\",\n \"_repr_javascript_\": \"application/javascript\",\n \"savefig\": \"image/png\",\n}\n\n\ndef render_image(mime, value, meta):\n # If the image value is using bytes we should convert it to base64\n # otherwise it will return raw bytes and the browser will not be able to\n # render it.\n if isinstance(value, bytes):\n value = base64.b64encode(value).decode(\"utf-8\")\n\n # This is the pattern of base64 strings\n base64_pattern = re.compile(\n r\"^([A-Za-z0-9+/]{4})*([A-Za-z0-9+/]{3}=|[A-Za-z0-9+/]{2}==)?$\"\n )\n # If value doesn't match the base64 pattern we should encode it to base64\n if len(value) > 0 and not base64_pattern.match(value):\n value = base64.b64encode(value.encode(\"utf-8\")).decode(\"utf-8\")\n\n data = f\"data:{mime};charset=utf-8;base64,{value}\"\n attrs = \" \".join(['{k}=\"{v}\"' for k, v in meta.items()])\n return f'<img src=\"{data}\" {attrs}></img>'\n\n\ndef identity(value, meta):\n return value\n\n\nMIME_RENDERERS = {\n \"text/plain\": html.escape,\n \"text/html\": identity,\n \"image/png\": lambda value, meta: render_image(\"image/png\", value, meta),\n \"image/jpeg\": lambda value, meta: render_image(\"image/jpeg\", value, meta),\n \"image/svg+xml\": identity,\n \"application/json\": identity,\n \"application/javascript\": lambda value, meta: f\"<script>{value}</script>\",\n}\n\n\n# these are set by _set_version_info\n__version__ = None\nversion_info = None\n\n\ndef _set_version_info(version_from_interpreter: str):\n \"\"\"Sets the __version__ and version_info properties from provided JSON data\n Args:\n version_from_interpreter (str): A \"dotted\" representation of the version:\n YYYY.MM.m(m).releaselevel\n Year, Month, and Minor should be integers; releaselevel can be any string\n \"\"\"\n global __version__\n global version_info\n\n __version__ = version_from_interpreter\n\n version_parts = version_from_interpreter.split(\".\")\n year = int(version_parts[0])\n month = int(version_parts[1])\n minor = int(version_parts[2])\n if len(version_parts) > 3:\n releaselevel = version_parts[3]\n else:\n releaselevel = \"\"\n\n VersionInfo = namedtuple(\"version_info\", (\"year\", \"month\", \"minor\", \"releaselevel\"))\n version_info = VersionInfo(year, month, minor, releaselevel)\n\n # we ALSO set PyScript.__version__ and version_info for backwards\n # compatibility. Should be killed eventually.\n PyScript.__version__ = __version__\n PyScript.version_info = version_info\n\n\nclass HTML:\n \"\"\"\n Wrap a string so that display() can render it as plain HTML\n \"\"\"\n\n def __init__(self, html):\n self._html = html\n\n def _repr_html_(self):\n return self._html\n\n\ndef eval_formatter(obj, print_method):\n \"\"\"\n Evaluates a formatter method.\n \"\"\"\n if print_method == \"__repr__\":\n return repr(obj)\n elif hasattr(obj, print_method):\n if print_method == \"savefig\":\n buf = io.BytesIO()\n obj.savefig(buf, format=\"png\")\n buf.seek(0)\n return base64.b64encode(buf.read()).decode(\"utf-8\")\n return getattr(obj, print_method)()\n elif print_method == \"_repr_mimebundle_\":\n return {}, {}\n return None\n\n\ndef format_mime(obj):\n \"\"\"\n Formats object using _repr_x_ methods.\n \"\"\"\n if isinstance(obj, str):\n return html.escape(obj), \"text/plain\"\n\n mimebundle = eval_formatter(obj, \"_repr_mimebundle_\")\n if isinstance(mimebundle, tuple):\n format_dict, _ = mimebundle\n else:\n format_dict = mimebundle\n\n output, not_available = None, []\n for method, mime_type in reversed(MIME_METHODS.items()):\n if mime_type in format_dict:\n output = format_dict[mime_type]\n else:\n output = eval_formatter(obj, method)\n\n if output is None:\n continue\n elif mime_type not in MIME_RENDERERS:\n not_available.append(mime_type)\n continue\n break\n if output is None:\n if not_available:\n js.console.warn(\n f\"Rendered object requested unavailable MIME renderers: {not_available}\"\n )\n output = repr(output)\n mime_type = \"text/plain\"\n elif isinstance(output, tuple):\n output, meta = output\n else:\n meta = {}\n return MIME_RENDERERS[mime_type](output, meta), mime_type\n\n\ndef run_until_complete(f):\n _ = loop.run_until_complete(f)\n\n\ndef write(element_id, value, append=False, exec_id=0):\n \"\"\"Writes value to the element with id \"element_id\"\"\"\n Element(element_id).write(value=value, append=append)\n js.console.warn(\n dedent(\n \"\"\"PyScript Deprecation Warning: PyScript.write is\n marked as deprecated and will be removed sometime soon. Please, use\n Element(<id>).write instead.\"\"\"\n )\n )\n\n\ndef set_current_display_target(target_id):\n get_current_display_target._id = target_id\n\n\ndef get_current_display_target():\n return get_current_display_target._id\n\n\nget_current_display_target._id = None\n\n\ndef display(*values, target=None, append=True):\n default_target = get_current_display_target()\n if default_target is None and target is None:\n raise Exception(\n \"Implicit target not allowed here. Please use display(..., target=...)\"\n )\n if target is not None:\n for v in values:\n Element(target).write(v, append=append)\n else:\n for v in values:\n Element(default_target).write(v, append=append)\n\n\nclass Element:\n def __init__(self, element_id, element=None):\n self._id = element_id\n self._element = element\n\n @property\n def id(self):\n return self._id\n\n @property\n def element(self):\n \"\"\"Return the dom element\"\"\"\n if not self._element:\n self._element = js.document.querySelector(f\"#{self._id}\")\n return self._element\n\n @property\n def value(self):\n return self.element.value\n\n @property\n def innerHtml(self):\n return self.element.innerHTML\n\n def write(self, value, append=False):\n html, mime_type = format_mime(value)\n if html == \"\\n\":\n return\n\n if append:\n child = js.document.createElement(\"div\")\n self.element.appendChild(child)\n\n if append and self.element.children:\n out_element = self.element.children[-1]\n else:\n out_element = self.element\n\n if mime_type in (\"application/javascript\", \"text/html\"):\n script_element = js.document.createRange().createContextualFragment(html)\n out_element.appendChild(script_element)\n else:\n out_element.innerHTML = html\n\n def clear(self):\n if hasattr(self.element, \"value\"):\n self.element.value = \"\"\n else:\n self.write(\"\", append=False)\n\n def select(self, query, from_content=False):\n el = self.element\n\n if from_content:\n el = el.content\n\n _el = el.querySelector(query)\n if _el:\n return Element(_el.id, _el)\n else:\n js.console.warn(f\"WARNING: can't find element matching query {query}\")\n\n def clone(self, new_id=None, to=None):\n if new_id is None:\n new_id = self.element.id\n\n clone = self.element.cloneNode(True)\n clone.id = new_id\n\n if to:\n to.element.appendChild(clone)\n # Inject it into the DOM\n to.element.after(clone)\n else:\n # Inject it into the DOM\n self.element.after(clone)\n\n return Element(clone.id, clone)\n\n def remove_class(self, classname):\n if isinstance(classname, list):\n for cl in classname:\n self.remove_class(cl)\n else:\n self.element.classList.remove(classname)\n\n def add_class(self, classname):\n if isinstance(classname, list):\n for cl in classname:\n self.element.classList.add(cl)\n else:\n self.element.classList.add(classname)\n\n\ndef add_classes(element, class_list):\n for klass in class_list.split(\" \"):\n element.classList.add(klass)\n\n\ndef create(what, id_=None, classes=\"\"):\n element = js.document.createElement(what)\n if id_:\n element.id = id_\n add_classes(element, classes)\n return Element(id_, element)\n\n\nclass PyWidgetTheme:\n def __init__(self, main_style_classes):\n self.main_style_classes = main_style_classes\n\n def theme_it(self, widget):\n for klass in self.main_style_classes.split(\" \"):\n widget.classList.add(klass)\n\n\nclass PyItemTemplate(Element):\n label_fields = None\n\n def __init__(self, data, labels=None, state_key=None, parent=None):\n self.data = data\n\n self.register_parent(parent)\n\n if not labels:\n labels = list(self.data.keys())\n self.labels = labels\n\n self.state_key = state_key\n\n super().__init__(self._id)\n\n def register_parent(self, parent):\n self._parent = parent\n if parent:\n self._id = f\"{self._parent._id}-c-{len(self._parent._children)}\"\n self.data[\"id\"] = self._id\n else:\n self._id = None\n\n def create(self):\n new_child = create(\"div\", self._id, \"py-li-element\")\n new_child._element.innerHTML = dedent(\n f\"\"\"\n <label id=\"{self._id}\" for=\"flex items-center p-2 \">\n <input class=\"mr-2\" type=\"checkbox\" class=\"task-check\">\n <p>{self.render_content()}</p>\n </label>\n \"\"\"\n )\n return new_child\n\n def on_click(self, evt):\n pass\n\n def pre_append(self):\n pass\n\n def post_append(self):\n self.element.click = self.on_click\n self.element.onclick = self.on_click\n\n self._post_append()\n\n def _post_append(self):\n pass\n\n def strike(self, value, extra=None):\n if value:\n self.add_class(\"line-through\")\n else:\n self.remove_class(\"line-through\")\n\n def render_content(self):\n return \" - \".join([self.data[f] for f in self.labels])\n\n\nclass PyListTemplate:\n theme = PyWidgetTheme(\"py-li-element\")\n item_class = PyItemTemplate\n\n def __init__(self, parent):\n self.parent = parent\n self._children = []\n self._id = self.parent.id\n\n @property\n def children(self):\n return self._children\n\n @property\n def data(self):\n return [c.data for c in self._children]\n\n def render_children(self):\n binds = {}\n for i, c in enumerate(self._children):\n txt = c.element.innerHTML\n rnd = str(time.time()).replace(\".\", \"\")[-5:]\n new_id = f\"{c.element.id}-{i}-{rnd}\"\n binds[new_id] = c.element.id\n txt = txt.replace(\">\", f\" id='{new_id}'>\")\n print(txt)\n\n def foo(evt):\n evtEl = evt.srcElement\n srcEl = Element(binds[evtEl.id])\n srcEl.element.onclick()\n evtEl.classList = srcEl.element.classList\n\n for new_id in binds:\n Element(new_id).element.onclick = foo\n\n def connect(self):\n self.md = main_div = js.document.createElement(\"div\")\n main_div.id = self._id + \"-list-tasks-container\"\n\n if self.theme:\n self.theme.theme_it(main_div)\n\n self.parent.appendChild(main_div)\n\n def add(self, *args, **kws):\n if not isinstance(args[0], self.item_class):\n child = self.item_class(*args, **kws)\n else:\n child = args[0]\n child.register_parent(self)\n return self._add(child)\n\n def _add(self, child_elem):\n self.pre_child_append(child_elem)\n child_elem.pre_append()\n self._children.append(child_elem)\n self.md.appendChild(child_elem.create().element)\n child_elem.post_append()\n self.child_appended(child_elem)\n return child_elem\n\n def pre_child_append(self, child):\n pass\n\n def child_appended(self, child):\n \"\"\"Overwrite me to define logic\"\"\"\n pass\n\n\nclass TopLevelAsyncFinder(ast.NodeVisitor):\n def is_source_top_level_await(self, source):\n self.async_found = False\n node = ast.parse(source)\n self.generic_visit(node)\n return self.async_found\n\n def visit_Await(self, node):\n self.async_found = True\n\n def visit_AsyncFor(self, node):\n self.async_found = True\n\n def visit_AsyncWith(self, node):\n self.async_found = True\n\n def visit_AsyncFunctionDef(self, node: ast.AsyncFunctionDef):\n pass # Do not visit children of async function defs\n\n\ndef uses_top_level_await(source: str) -> bool:\n return TopLevelAsyncFinder().is_source_top_level_await(source)\n\n\nclass Plugin:\n def __init__(self, name=None):\n if not name:\n name = self.__class__.__name__\n\n self.name = name\n self._custom_elements = []\n self.app = None\n\n def init(self, app):\n self.app = app\n\n def register_custom_element(self, tag):\n \"\"\"\n Decorator to register a new custom element as part of a Plugin and associate\n tag to it. Internally, it delegates the registration to the PyScript internal\n [JS] plugin manager, who actually creates the JS custom element that can be\n attached to the page and instantiate an instance of the class passing the custom\n element to the plugin constructor.\n\n Exammple:\n >> plugin = Plugin(\"PyTutorial\")\n >> @plugin.register_custom_element(\"py-tutor\")\n >> class PyTutor:\n >> def __init__(self, element):\n >> self.element = element\n \"\"\"\n # TODO: Ideally would be better to use the logger.\n js.console.info(f\"Defining new custom element {tag}\")\n\n def wrapper(class_):\n # TODO: this is very pyodide specific but will have to do\n # until we have JS interface that works across interpreters\n define_custom_element(tag, create_proxy(class_)) # noqa: F821\n\n self._custom_elements.append(tag)\n return create_proxy(wrapper)\n\n\nclass DeprecatedGlobal:\n \"\"\"\n Proxy for globals which are deprecated.\n\n The intendend usage is as follows:\n\n # in the global namespace\n Element = pyscript.DeprecatedGlobal('Element', pyscript.Element, \"...\")\n console = pyscript.DeprecatedGlobal('console', js.console, \"...\")\n ...\n\n The proxy forwards __getattr__ and __call__ to the underlying object, and\n emit a warning on the first usage.\n\n This way users see a warning only if they actually access the top-level\n name.\n \"\"\"\n\n def __init__(self, name, obj, message):\n self.__name = name\n self.__obj = obj\n self.__message = message\n self.__warning_already_shown = False\n\n def __repr__(self):\n return f\"<DeprecatedGlobal({self.__name!r})>\"\n\n def _show_warning(self, message):\n \"\"\"\n NOTE: this is overridden by unit tests\n \"\"\"\n # this showWarning is implemented in js and injected into this\n # namespace by main.ts\n showWarning(message, \"html\") # noqa: F821\n\n def _show_warning_maybe(self):\n if self.__warning_already_shown:\n return\n self._show_warning(self.__message)\n self.__warning_already_shown = True\n\n def __getattr__(self, attr):\n self._show_warning_maybe()\n return getattr(self.__obj, attr)\n\n def __call__(self, *args, **kwargs):\n self._show_warning_maybe()\n return self.__obj(*args, **kwargs)\n\n def __iter__(self):\n self._show_warning_maybe()\n return iter(self.__obj)\n\n def __getitem__(self, key):\n self._show_warning_maybe()\n return self.__obj[key]\n\n def __setitem__(self, key, value):\n self._show_warning_maybe()\n self.__obj[key] = value\n\n\nclass PyScript:\n \"\"\"\n This class is deprecated since 2022.12.1.\n\n All its old functionalities are available as module-level functions. This\n class should be killed eventually.\n \"\"\"\n\n loop = loop\n\n @staticmethod\n def run_until_complete(f):\n run_until_complete(f)\n\n @staticmethod\n def write(element_id, value, append=False, exec_id=0):\n write(element_id, value, append, exec_id)\n\n\ndef _install_deprecated_globals_2022_12_1(ns):\n \"\"\"\n Install into the given namespace all the globals which have been\n deprecated since the 2022.12.1 release. Eventually they should be killed.\n \"\"\"\n\n def deprecate(name, obj, instead):\n message = f\"Direct usage of <code>{name}</code> is deprecated. \" + instead\n ns[name] = DeprecatedGlobal(name, obj, message)\n\n # function/classes defined in pyscript.py ===> pyscript.XXX\n pyscript_names = [\n \"PyItemTemplate\",\n \"PyListTemplate\",\n \"PyWidgetTheme\",\n \"add_classes\",\n \"create\",\n \"loop\",\n ]\n for name in pyscript_names:\n deprecate(\n name, globals()[name], f\"Please use <code>pyscript.{name}</code> instead.\"\n )\n\n # stdlib modules ===> import XXX\n stdlib_names = [\n \"asyncio\",\n \"base64\",\n \"io\",\n \"sys\",\n \"time\",\n \"datetime\",\n \"pyodide\",\n \"micropip\",\n ]\n for name in stdlib_names:\n obj = __import__(name)\n deprecate(name, obj, f\"Please use <code>import {name}</code> instead.\")\n\n # special case\n deprecate(\n \"dedent\", dedent, \"Please use <code>from textwrap import dedent</code> instead.\"\n )\n\n # these are names that used to leak in the globals but they are just\n # implementation details. People should not use them.\n private_names = [\n \"eval_formatter\",\n \"format_mime\",\n \"identity\",\n \"render_image\",\n \"MIME_RENDERERS\",\n \"MIME_METHODS\",\n ]\n for name in private_names:\n obj = globals()[name]\n message = (\n f\"<code>{name}</code> is deprecated. \"\n \"This is a private implementation detail of pyscript. \"\n \"You should not use it.\"\n )\n ns[name] = DeprecatedGlobal(name, obj, message)\n\n # these names are available as js.XXX\n for name in [\"document\", \"console\"]:\n obj = getattr(js, name)\n deprecate(name, obj, f\"Please use <code>js.{name}</code> instead.\")\n\n # PyScript is special, use a different message\n message = (\n \"The <code>PyScript</code> object is deprecated. \"\n \"Please use <code>pyscript</code> instead.\"\n )\n ns[\"PyScript\"] = DeprecatedGlobal(\"PyScript\", PyScript, message)\n"; - const DefaultSplit = /\r\n?|\n/; - /** - Distinguishes different ways in which positions can be mapped. - */ - var MapMode = /*@__PURE__*/(function (MapMode) { - /** - Map a position to a valid new position, even when its context - was deleted. - */ - MapMode[MapMode["Simple"] = 0] = "Simple"; - /** - Return null if deletion happens across the position. - */ - MapMode[MapMode["TrackDel"] = 1] = "TrackDel"; - /** - Return null if the character _before_ the position is deleted. - */ - MapMode[MapMode["TrackBefore"] = 2] = "TrackBefore"; - /** - Return null if the character _after_ the position is deleted. - */ - MapMode[MapMode["TrackAfter"] = 3] = "TrackAfter"; - return MapMode})(MapMode || (MapMode = {})); - /** - A change description is a variant of [change set](https://codemirror.net/6/docs/ref/#state.ChangeSet) - that doesn't store the inserted text. As such, it can't be - applied, but is cheaper to store and manipulate. - */ - class ChangeDesc { - // Sections are encoded as pairs of integers. The first is the - // length in the current document, and the second is -1 for - // unaffected sections, and the length of the replacement content - // otherwise. So an insertion would be (0, n>0), a deletion (n>0, - // 0), and a replacement two positive numbers. - /** - @internal - */ - constructor( - /** - @internal - */ - sections) { - this.sections = sections; - } - /** - The length of the document before the change. - */ - get length() { - let result = 0; - for (let i = 0; i < this.sections.length; i += 2) - result += this.sections[i]; - return result; - } - /** - The length of the document after the change. - */ - get newLength() { - let result = 0; - for (let i = 0; i < this.sections.length; i += 2) { - let ins = this.sections[i + 1]; - result += ins < 0 ? this.sections[i] : ins; - } - return result; - } - /** - False when there are actual changes in this set. - */ - get empty() { return this.sections.length == 0 || this.sections.length == 2 && this.sections[1] < 0; } - /** - Iterate over the unchanged parts left by these changes. - */ - iterGaps(f) { - for (let i = 0, posA = 0, posB = 0; i < this.sections.length;) { - let len = this.sections[i++], ins = this.sections[i++]; - if (ins < 0) { - f(posA, posB, len); - posB += len; - } - else { - posB += ins; - } - posA += len; - } - } - /** - Iterate over the ranges changed by these changes. (See - [`ChangeSet.iterChanges`](https://codemirror.net/6/docs/ref/#state.ChangeSet.iterChanges) for a - variant that also provides you with the inserted text.) - - When `individual` is true, adjacent changes (which are kept - separate for [position mapping](https://codemirror.net/6/docs/ref/#state.ChangeDesc.mapPos)) are - reported separately. - */ - iterChangedRanges(f, individual = false) { - iterChanges(this, f, individual); - } - /** - Get a description of the inverted form of these changes. - */ - get invertedDesc() { - let sections = []; - for (let i = 0; i < this.sections.length;) { - let len = this.sections[i++], ins = this.sections[i++]; - if (ins < 0) - sections.push(len, ins); - else - sections.push(ins, len); - } - return new ChangeDesc(sections); - } - /** - Compute the combined effect of applying another set of changes - after this one. The length of the document after this set should - match the length before `other`. - */ - composeDesc(other) { return this.empty ? other : other.empty ? this : composeSets(this, other); } - /** - Map this description, which should start with the same document - as `other`, over another set of changes, so that it can be - applied after it. When `before` is true, map as if the changes - in `other` happened before the ones in `this`. - */ - mapDesc(other, before = false) { return other.empty ? this : mapSet(this, other, before); } - mapPos(pos, assoc = -1, mode = MapMode.Simple) { - let posA = 0, posB = 0; - for (let i = 0; i < this.sections.length;) { - let len = this.sections[i++], ins = this.sections[i++], endA = posA + len; - if (ins < 0) { - if (endA > pos) - return posB + (pos - posA); - posB += len; - } - else { - if (mode != MapMode.Simple && endA >= pos && - (mode == MapMode.TrackDel && posA < pos && endA > pos || - mode == MapMode.TrackBefore && posA < pos || - mode == MapMode.TrackAfter && endA > pos)) - return null; - if (endA > pos || endA == pos && assoc < 0 && !len) - return pos == posA || assoc < 0 ? posB : posB + ins; - posB += ins; - } - posA = endA; - } - if (pos > posA) - throw new RangeError(`Position ${pos} is out of range for changeset of length ${posA}`); - return posB; - } - /** - Check whether these changes touch a given range. When one of the - changes entirely covers the range, the string `"cover"` is - returned. - */ - touchesRange(from, to = from) { - for (let i = 0, pos = 0; i < this.sections.length && pos <= to;) { - let len = this.sections[i++], ins = this.sections[i++], end = pos + len; - if (ins >= 0 && pos <= to && end >= from) - return pos < from && end > to ? "cover" : true; - pos = end; - } - return false; - } - /** - @internal - */ - toString() { - let result = ""; - for (let i = 0; i < this.sections.length;) { - let len = this.sections[i++], ins = this.sections[i++]; - result += (result ? " " : "") + len + (ins >= 0 ? ":" + ins : ""); - } - return result; - } - /** - Serialize this change desc to a JSON-representable value. - */ - toJSON() { return this.sections; } - /** - Create a change desc from its JSON representation (as produced - by [`toJSON`](https://codemirror.net/6/docs/ref/#state.ChangeDesc.toJSON). - */ - static fromJSON(json) { - if (!Array.isArray(json) || json.length % 2 || json.some(a => typeof a != "number")) - throw new RangeError("Invalid JSON representation of ChangeDesc"); - return new ChangeDesc(json); - } - } - /** - A change set represents a group of modifications to a document. It - stores the document length, and can only be applied to documents - with exactly that length. - */ - class ChangeSet extends ChangeDesc { - /** - @internal - */ - constructor(sections, - /** - @internal - */ - inserted) { - super(sections); - this.inserted = inserted; - } - /** - Apply the changes to a document, returning the modified - document. - */ - apply(doc) { - if (this.length != doc.length) - throw new RangeError("Applying change set to a document with the wrong length"); - iterChanges(this, (fromA, toA, fromB, _toB, text) => doc = doc.replace(fromB, fromB + (toA - fromA), text), false); - return doc; - } - mapDesc(other, before = false) { return mapSet(this, other, before, true); } - /** - Given the document as it existed _before_ the changes, return a - change set that represents the inverse of this set, which could - be used to go from the document created by the changes back to - the document as it existed before the changes. - */ - invert(doc) { - let sections = this.sections.slice(), inserted = []; - for (let i = 0, pos = 0; i < sections.length; i += 2) { - let len = sections[i], ins = sections[i + 1]; - if (ins >= 0) { - sections[i] = ins; - sections[i + 1] = len; - let index = i >> 1; - while (inserted.length < index) - inserted.push(Text.empty); - inserted.push(len ? doc.slice(pos, pos + len) : Text.empty); - } - pos += len; - } - return new ChangeSet(sections, inserted); - } - /** - Combine two subsequent change sets into a single set. `other` - must start in the document produced by `this`. If `this` goes - `docA` → `docB` and `other` represents `docB` → `docC`, the - returned value will represent the change `docA` → `docC`. - */ - compose(other) { return this.empty ? other : other.empty ? this : composeSets(this, other, true); } - /** - Given another change set starting in the same document, maps this - change set over the other, producing a new change set that can be - applied to the document produced by applying `other`. When - `before` is `true`, order changes as if `this` comes before - `other`, otherwise (the default) treat `other` as coming first. - - Given two changes `A` and `B`, `A.compose(B.map(A))` and - `B.compose(A.map(B, true))` will produce the same document. This - provides a basic form of [operational - transformation](https://en.wikipedia.org/wiki/Operational_transformation), - and can be used for collaborative editing. - */ - map(other, before = false) { return other.empty ? this : mapSet(this, other, before, true); } - /** - Iterate over the changed ranges in the document, calling `f` for - each, with the range in the original document (`fromA`-`toA`) - and the range that replaces it in the new document - (`fromB`-`toB`). - - When `individual` is true, adjacent changes are reported - separately. - */ - iterChanges(f, individual = false) { - iterChanges(this, f, individual); - } - /** - Get a [change description](https://codemirror.net/6/docs/ref/#state.ChangeDesc) for this change - set. - */ - get desc() { return new ChangeDesc(this.sections); } - /** - @internal - */ - filter(ranges) { - let resultSections = [], resultInserted = [], filteredSections = []; - let iter = new SectionIter(this); - done: for (let i = 0, pos = 0;;) { - let next = i == ranges.length ? 1e9 : ranges[i++]; - while (pos < next || pos == next && iter.len == 0) { - if (iter.done) - break done; - let len = Math.min(iter.len, next - pos); - addSection(filteredSections, len, -1); - let ins = iter.ins == -1 ? -1 : iter.off == 0 ? iter.ins : 0; - addSection(resultSections, len, ins); - if (ins > 0) - addInsert(resultInserted, resultSections, iter.text); - iter.forward(len); - pos += len; - } - let end = ranges[i++]; - while (pos < end) { - if (iter.done) - break done; - let len = Math.min(iter.len, end - pos); - addSection(resultSections, len, -1); - addSection(filteredSections, len, iter.ins == -1 ? -1 : iter.off == 0 ? iter.ins : 0); - iter.forward(len); - pos += len; - } - } - return { changes: new ChangeSet(resultSections, resultInserted), - filtered: new ChangeDesc(filteredSections) }; - } - /** - Serialize this change set to a JSON-representable value. - */ - toJSON() { - let parts = []; - for (let i = 0; i < this.sections.length; i += 2) { - let len = this.sections[i], ins = this.sections[i + 1]; - if (ins < 0) - parts.push(len); - else if (ins == 0) - parts.push([len]); - else - parts.push([len].concat(this.inserted[i >> 1].toJSON())); - } - return parts; - } - /** - Create a change set for the given changes, for a document of the - given length, using `lineSep` as line separator. - */ - static of(changes, length, lineSep) { - let sections = [], inserted = [], pos = 0; - let total = null; - function flush(force = false) { - if (!force && !sections.length) - return; - if (pos < length) - addSection(sections, length - pos, -1); - let set = new ChangeSet(sections, inserted); - total = total ? total.compose(set.map(total)) : set; - sections = []; - inserted = []; - pos = 0; - } - function process(spec) { - if (Array.isArray(spec)) { - for (let sub of spec) - process(sub); - } - else if (spec instanceof ChangeSet) { - if (spec.length != length) - throw new RangeError(`Mismatched change set length (got ${spec.length}, expected ${length})`); - flush(); - total = total ? total.compose(spec.map(total)) : spec; - } - else { - let { from, to = from, insert } = spec; - if (from > to || from < 0 || to > length) - throw new RangeError(`Invalid change range ${from} to ${to} (in doc of length ${length})`); - let insText = !insert ? Text.empty : typeof insert == "string" ? Text.of(insert.split(lineSep || DefaultSplit)) : insert; - let insLen = insText.length; - if (from == to && insLen == 0) - return; - if (from < pos) - flush(); - if (from > pos) - addSection(sections, from - pos, -1); - addSection(sections, to - from, insLen); - addInsert(inserted, sections, insText); - pos = to; - } - } - process(changes); - flush(!total); - return total; - } - /** - Create an empty changeset of the given length. - */ - static empty(length) { - return new ChangeSet(length ? [length, -1] : [], []); - } - /** - Create a changeset from its JSON representation (as produced by - [`toJSON`](https://codemirror.net/6/docs/ref/#state.ChangeSet.toJSON). - */ - static fromJSON(json) { - if (!Array.isArray(json)) - throw new RangeError("Invalid JSON representation of ChangeSet"); - let sections = [], inserted = []; - for (let i = 0; i < json.length; i++) { - let part = json[i]; - if (typeof part == "number") { - sections.push(part, -1); - } - else if (!Array.isArray(part) || typeof part[0] != "number" || part.some((e, i) => i && typeof e != "string")) { - throw new RangeError("Invalid JSON representation of ChangeSet"); - } - else if (part.length == 1) { - sections.push(part[0], 0); - } - else { - while (inserted.length < i) - inserted.push(Text.empty); - inserted[i] = Text.of(part.slice(1)); - sections.push(part[0], inserted[i].length); - } - } - return new ChangeSet(sections, inserted); - } - } - function addSection(sections, len, ins, forceJoin = false) { - if (len == 0 && ins <= 0) - return; - let last = sections.length - 2; - if (last >= 0 && ins <= 0 && ins == sections[last + 1]) - sections[last] += len; - else if (len == 0 && sections[last] == 0) - sections[last + 1] += ins; - else if (forceJoin) { - sections[last] += len; - sections[last + 1] += ins; - } - else - sections.push(len, ins); - } - function addInsert(values, sections, value) { - if (value.length == 0) - return; - let index = (sections.length - 2) >> 1; - if (index < values.length) { - values[values.length - 1] = values[values.length - 1].append(value); - } - else { - while (values.length < index) - values.push(Text.empty); - values.push(value); - } - } - function iterChanges(desc, f, individual) { - let inserted = desc.inserted; - for (let posA = 0, posB = 0, i = 0; i < desc.sections.length;) { - let len = desc.sections[i++], ins = desc.sections[i++]; - if (ins < 0) { - posA += len; - posB += len; - } - else { - let endA = posA, endB = posB, text = Text.empty; - for (;;) { - endA += len; - endB += ins; - if (ins && inserted) - text = text.append(inserted[(i - 2) >> 1]); - if (individual || i == desc.sections.length || desc.sections[i + 1] < 0) - break; - len = desc.sections[i++]; - ins = desc.sections[i++]; - } - f(posA, endA, posB, endB, text); - posA = endA; - posB = endB; - } - } - } - function mapSet(setA, setB, before, mkSet = false) { - let sections = [], insert = mkSet ? [] : null; - let a = new SectionIter(setA), b = new SectionIter(setB); - for (let posA = 0, posB = 0;;) { - if (a.ins == -1) { - posA += a.len; - a.next(); - } - else if (b.ins == -1 && posB < posA) { - let skip = Math.min(b.len, posA - posB); - b.forward(skip); - addSection(sections, skip, -1); - posB += skip; - } - else if (b.ins >= 0 && (a.done || posB < posA || posB == posA && (b.len < a.len || b.len == a.len && !before))) { - addSection(sections, b.ins, -1); - while (posA > posB && !a.done && posA + a.len < posB + b.len) { - posA += a.len; - a.next(); - } - posB += b.len; - b.next(); - } - else if (a.ins >= 0) { - let len = 0, end = posA + a.len; - for (;;) { - if (b.ins >= 0 && posB > posA && posB + b.len < end) { - len += b.ins; - posB += b.len; - b.next(); - } - else if (b.ins == -1 && posB < end) { - let skip = Math.min(b.len, end - posB); - len += skip; - b.forward(skip); - posB += skip; - } - else { - break; - } - } - addSection(sections, len, a.ins); - if (insert) - addInsert(insert, sections, a.text); - posA = end; - a.next(); - } - else if (a.done && b.done) { - return insert ? new ChangeSet(sections, insert) : new ChangeDesc(sections); - } - else { - throw new Error("Mismatched change set lengths"); - } - } - } - function composeSets(setA, setB, mkSet = false) { - let sections = []; - let insert = mkSet ? [] : null; - let a = new SectionIter(setA), b = new SectionIter(setB); - for (let open = false;;) { - if (a.done && b.done) { - return insert ? new ChangeSet(sections, insert) : new ChangeDesc(sections); - } - else if (a.ins == 0) { // Deletion in A - addSection(sections, a.len, 0, open); - a.next(); - } - else if (b.len == 0 && !b.done) { // Insertion in B - addSection(sections, 0, b.ins, open); - if (insert) - addInsert(insert, sections, b.text); - b.next(); - } - else if (a.done || b.done) { - throw new Error("Mismatched change set lengths"); - } - else { - let len = Math.min(a.len2, b.len), sectionLen = sections.length; - if (a.ins == -1) { - let insB = b.ins == -1 ? -1 : b.off ? 0 : b.ins; - addSection(sections, len, insB, open); - if (insert && insB) - addInsert(insert, sections, b.text); - } - else if (b.ins == -1) { - addSection(sections, a.off ? 0 : a.len, len, open); - if (insert) - addInsert(insert, sections, a.textBit(len)); - } - else { - addSection(sections, a.off ? 0 : a.len, b.off ? 0 : b.ins, open); - if (insert && !b.off) - addInsert(insert, sections, b.text); - } - open = (a.ins > len || b.ins >= 0 && b.len > len) && (open || sections.length > sectionLen); - a.forward2(len); - b.forward(len); - } - } - } - class SectionIter { - constructor(set) { - this.set = set; - this.i = 0; - this.next(); - } - next() { - let { sections } = this.set; - if (this.i < sections.length) { - this.len = sections[this.i++]; - this.ins = sections[this.i++]; - } - else { - this.len = 0; - this.ins = -2; - } - this.off = 0; - } - get done() { return this.ins == -2; } - get len2() { return this.ins < 0 ? this.len : this.ins; } - get text() { - let { inserted } = this.set, index = (this.i - 2) >> 1; - return index >= inserted.length ? Text.empty : inserted[index]; - } - textBit(len) { - let { inserted } = this.set, index = (this.i - 2) >> 1; - return index >= inserted.length && !len ? Text.empty - : inserted[index].slice(this.off, len == null ? undefined : this.off + len); - } - forward(len) { - if (len == this.len) - this.next(); - else { - this.len -= len; - this.off += len; - } - } - forward2(len) { - if (this.ins == -1) - this.forward(len); - else if (len == this.ins) - this.next(); - else { - this.ins -= len; - this.off += len; - } - } - } + const logger = getLogger('pyscript/main'); + /* High-level overview of the lifecycle of a PyScript App: - /** - A single selection range. When - [`allowMultipleSelections`](https://codemirror.net/6/docs/ref/#state.EditorState^allowMultipleSelections) - is enabled, a [selection](https://codemirror.net/6/docs/ref/#state.EditorSelection) may hold - multiple ranges. By default, selections hold exactly one range. - */ - class SelectionRange { - /** - @internal - */ - constructor( - /** - The lower boundary of the range. - */ - from, - /** - The upper boundary of the range. - */ - to, flags) { - this.from = from; - this.to = to; - this.flags = flags; - } - /** - The anchor of the range—the side that doesn't move when you - extend it. - */ - get anchor() { return this.flags & 16 /* Inverted */ ? this.to : this.from; } - /** - The head of the range, which is moved when the range is - [extended](https://codemirror.net/6/docs/ref/#state.SelectionRange.extend). - */ - get head() { return this.flags & 16 /* Inverted */ ? this.from : this.to; } - /** - True when `anchor` and `head` are at the same position. - */ - get empty() { return this.from == this.to; } - /** - If this is a cursor that is explicitly associated with the - character on one of its sides, this returns the side. -1 means - the character before its position, 1 the character after, and 0 - means no association. - */ - get assoc() { return this.flags & 4 /* AssocBefore */ ? -1 : this.flags & 8 /* AssocAfter */ ? 1 : 0; } - /** - The bidirectional text level associated with this cursor, if - any. - */ - get bidiLevel() { - let level = this.flags & 3 /* BidiLevelMask */; - return level == 3 ? null : level; - } - /** - The goal column (stored vertical offset) associated with a - cursor. This is used to preserve the vertical position when - [moving](https://codemirror.net/6/docs/ref/#view.EditorView.moveVertically) across - lines of different length. - */ - get goalColumn() { - let value = this.flags >> 5 /* GoalColumnOffset */; - return value == 33554431 /* NoGoalColumn */ ? undefined : value; - } - /** - Map this range through a change, producing a valid range in the - updated document. - */ - map(change, assoc = -1) { - let from, to; - if (this.empty) { - from = to = change.mapPos(this.from, assoc); - } - else { - from = change.mapPos(this.from, 1); - to = change.mapPos(this.to, -1); - } - return from == this.from && to == this.to ? this : new SelectionRange(from, to, this.flags); - } - /** - Extend this range to cover at least `from` to `to`. - */ - extend(from, to = from) { - if (from <= this.anchor && to >= this.anchor) - return EditorSelection.range(from, to); - let head = Math.abs(from - this.anchor) > Math.abs(to - this.anchor) ? from : to; - return EditorSelection.range(this.anchor, head); - } - /** - Compare this range to another range. - */ - eq(other) { - return this.anchor == other.anchor && this.head == other.head; - } - /** - Return a JSON-serializable object representing the range. - */ - toJSON() { return { anchor: this.anchor, head: this.head }; } - /** - Convert a JSON representation of a range to a `SelectionRange` - instance. - */ - static fromJSON(json) { - if (!json || typeof json.anchor != "number" || typeof json.head != "number") - throw new RangeError("Invalid JSON representation for SelectionRange"); - return EditorSelection.range(json.anchor, json.head); - } - } - /** - An editor selection holds one or more selection ranges. - */ - class EditorSelection { - /** - @internal - */ - constructor( - /** - The ranges in the selection, sorted by position. Ranges cannot - overlap (but they may touch, if they aren't empty). - */ - ranges, - /** - The index of the _main_ range in the selection (which is - usually the range that was added last). - */ - mainIndex = 0) { - this.ranges = ranges; - this.mainIndex = mainIndex; - } - /** - Map a selection through a change. Used to adjust the selection - position for changes. - */ - map(change, assoc = -1) { - if (change.empty) - return this; - return EditorSelection.create(this.ranges.map(r => r.map(change, assoc)), this.mainIndex); - } - /** - Compare this selection to another selection. - */ - eq(other) { - if (this.ranges.length != other.ranges.length || - this.mainIndex != other.mainIndex) - return false; - for (let i = 0; i < this.ranges.length; i++) - if (!this.ranges[i].eq(other.ranges[i])) - return false; - return true; - } - /** - Get the primary selection range. Usually, you should make sure - your code applies to _all_ ranges, by using methods like - [`changeByRange`](https://codemirror.net/6/docs/ref/#state.EditorState.changeByRange). - */ - get main() { return this.ranges[this.mainIndex]; } - /** - Make sure the selection only has one range. Returns a selection - holding only the main range from this selection. - */ - asSingle() { - return this.ranges.length == 1 ? this : new EditorSelection([this.main]); - } - /** - Extend this selection with an extra range. - */ - addRange(range, main = true) { - return EditorSelection.create([range].concat(this.ranges), main ? 0 : this.mainIndex + 1); - } - /** - Replace a given range with another range, and then normalize the - selection to merge and sort ranges if necessary. - */ - replaceRange(range, which = this.mainIndex) { - let ranges = this.ranges.slice(); - ranges[which] = range; - return EditorSelection.create(ranges, this.mainIndex); - } - /** - Convert this selection to an object that can be serialized to - JSON. - */ - toJSON() { - return { ranges: this.ranges.map(r => r.toJSON()), main: this.mainIndex }; - } - /** - Create a selection from a JSON representation. - */ - static fromJSON(json) { - if (!json || !Array.isArray(json.ranges) || typeof json.main != "number" || json.main >= json.ranges.length) - throw new RangeError("Invalid JSON representation for EditorSelection"); - return new EditorSelection(json.ranges.map((r) => SelectionRange.fromJSON(r)), json.main); - } - /** - Create a selection holding a single range. - */ - static single(anchor, head = anchor) { - return new EditorSelection([EditorSelection.range(anchor, head)], 0); - } - /** - Sort and merge the given set of ranges, creating a valid - selection. - */ - static create(ranges, mainIndex = 0) { - if (ranges.length == 0) - throw new RangeError("A selection needs at least one range"); - for (let pos = 0, i = 0; i < ranges.length; i++) { - let range = ranges[i]; - if (range.empty ? range.from <= pos : range.from < pos) - return normalized(ranges.slice(), mainIndex); - pos = range.to; - } - return new EditorSelection(ranges, mainIndex); - } - /** - Create a cursor selection range at the given position. You can - safely ignore the optional arguments in most situations. - */ - static cursor(pos, assoc = 0, bidiLevel, goalColumn) { - return new SelectionRange(pos, pos, (assoc == 0 ? 0 : assoc < 0 ? 4 /* AssocBefore */ : 8 /* AssocAfter */) | - (bidiLevel == null ? 3 : Math.min(2, bidiLevel)) | - ((goalColumn !== null && goalColumn !== void 0 ? goalColumn : 33554431 /* NoGoalColumn */) << 5 /* GoalColumnOffset */)); - } - /** - Create a selection range. - */ - static range(anchor, head, goalColumn) { - let goal = (goalColumn !== null && goalColumn !== void 0 ? goalColumn : 33554431 /* NoGoalColumn */) << 5 /* GoalColumnOffset */; - return head < anchor ? new SelectionRange(head, anchor, 16 /* Inverted */ | goal | 8 /* AssocAfter */) - : new SelectionRange(anchor, head, goal | (head > anchor ? 4 /* AssocBefore */ : 0)); - } - } - function normalized(ranges, mainIndex = 0) { - let main = ranges[mainIndex]; - ranges.sort((a, b) => a.from - b.from); - mainIndex = ranges.indexOf(main); - for (let i = 1; i < ranges.length; i++) { - let range = ranges[i], prev = ranges[i - 1]; - if (range.empty ? range.from <= prev.to : range.from < prev.to) { - let from = prev.from, to = Math.max(range.to, prev.to); - if (i <= mainIndex) - mainIndex--; - ranges.splice(--i, 2, range.anchor > range.head ? EditorSelection.range(to, from) : EditorSelection.range(from, to)); - } - } - return new EditorSelection(ranges, mainIndex); - } - function checkSelection(selection, docLength) { - for (let range of selection.ranges) - if (range.to > docLength) - throw new RangeError("Selection points outside of document"); - } + 1. pyscript.js is loaded by the browser. PyScriptApp().main() is called - let nextID = 0; - /** - A facet is a labeled value that is associated with an editor - state. It takes inputs from any number of extensions, and combines - those into a single output value. + 2. loadConfig(): search for py-config and compute the config for the app - Examples of facets are the [theme](https://codemirror.net/6/docs/ref/#view.EditorView^theme) styles - associated with an editor or the [tab - size](https://codemirror.net/6/docs/ref/#state.EditorState^tabSize) (which is reduced to a single - value, using the input with the hightest precedence). - */ - class Facet { - constructor( - /** - @internal - */ - combine, - /** - @internal - */ - compareInput, - /** - @internal - */ - compare, isStatic, - /** - @internal - */ - extensions) { - this.combine = combine; - this.compareInput = compareInput; - this.compare = compare; - this.isStatic = isStatic; - this.extensions = extensions; - /** - @internal - */ - this.id = nextID++; - this.default = combine([]); - } - /** - Define a new facet. - */ - static define(config = {}) { - return new Facet(config.combine || ((a) => a), config.compareInput || ((a, b) => a === b), config.compare || (!config.combine ? sameArray$1 : (a, b) => a === b), !!config.static, config.enables); - } - /** - Returns an extension that adds the given value for this facet. - */ - of(value) { - return new FacetProvider([], this, 0 /* Static */, value); - } - /** - Create an extension that computes a value for the facet from a - state. You must take care to declare the parts of the state that - this value depends on, since your function is only called again - for a new state when one of those parts changed. - - In most cases, you'll want to use the - [`provide`](https://codemirror.net/6/docs/ref/#state.StateField^define^config.provide) option when - defining a field instead. - */ - compute(deps, get) { - if (this.isStatic) - throw new Error("Can't compute a static facet"); - return new FacetProvider(deps, this, 1 /* Single */, get); - } - /** - Create an extension that computes zero or more values for this - facet from a state. - */ - computeN(deps, get) { - if (this.isStatic) - throw new Error("Can't compute a static facet"); - return new FacetProvider(deps, this, 2 /* Multi */, get); - } - from(field, get) { - if (!get) - get = x => x; - return this.compute([field], state => get(state.field(field))); - } - } - function sameArray$1(a, b) { - return a == b || a.length == b.length && a.every((e, i) => e === b[i]); - } - class FacetProvider { - constructor(dependencies, facet, type, value) { - this.dependencies = dependencies; - this.facet = facet; - this.type = type; - this.value = value; - this.id = nextID++; - } - dynamicSlot(addresses) { - var _a; - let getter = this.value; - let compare = this.facet.compareInput; - let id = this.id, idx = addresses[id] >> 1, multi = this.type == 2 /* Multi */; - let depDoc = false, depSel = false, depAddrs = []; - for (let dep of this.dependencies) { - if (dep == "doc") - depDoc = true; - else if (dep == "selection") - depSel = true; - else if ((((_a = addresses[dep.id]) !== null && _a !== void 0 ? _a : 1) & 1) == 0) - depAddrs.push(addresses[dep.id]); - } - return { - create(state) { - state.values[idx] = getter(state); - return 1 /* Changed */; - }, - update(state, tr) { - if ((depDoc && tr.docChanged) || (depSel && (tr.docChanged || tr.selection)) || - depAddrs.some(addr => (ensureAddr(state, addr) & 1 /* Changed */) > 0)) { - let newVal = getter(state); - if (multi ? !compareArray(newVal, state.values[idx], compare) : !compare(newVal, state.values[idx])) { - state.values[idx] = newVal; - return 1 /* Changed */; - } - } - return 0; - }, - reconfigure(state, oldState) { - let newVal = getter(state); - let oldAddr = oldState.config.address[id]; - if (oldAddr != null) { - let oldVal = getAddr(oldState, oldAddr); - if (multi ? compareArray(newVal, oldVal, compare) : compare(newVal, oldVal)) { - state.values[idx] = oldVal; - return 0; - } - } - state.values[idx] = newVal; - return 1 /* Changed */; - } - }; - } - } - function compareArray(a, b, compare) { - if (a.length != b.length) - return false; - for (let i = 0; i < a.length; i++) - if (!compare(a[i], b[i])) - return false; - return true; - } - function dynamicFacetSlot(addresses, facet, providers) { - let providerAddrs = providers.map(p => addresses[p.id]); - let providerTypes = providers.map(p => p.type); - let dynamic = providerAddrs.filter(p => !(p & 1)); - let idx = addresses[facet.id] >> 1; - function get(state) { - let values = []; - for (let i = 0; i < providerAddrs.length; i++) { - let value = getAddr(state, providerAddrs[i]); - if (providerTypes[i] == 2 /* Multi */) - for (let val of value) - values.push(val); - else - values.push(value); - } - return facet.combine(values); - } - return { - create(state) { - for (let addr of providerAddrs) - ensureAddr(state, addr); - state.values[idx] = get(state); - return 1 /* Changed */; - }, - update(state, tr) { - if (!dynamic.some(dynAddr => ensureAddr(state, dynAddr) & 1 /* Changed */)) - return 0; - let value = get(state); - if (facet.compare(value, state.values[idx])) - return 0; - state.values[idx] = value; - return 1 /* Changed */; - }, - reconfigure(state, oldState) { - let depChanged = providerAddrs.some(addr => ensureAddr(state, addr) & 1 /* Changed */); - let oldProviders = oldState.config.facets[facet.id], oldValue = oldState.facet(facet); - if (oldProviders && !depChanged && sameArray$1(providers, oldProviders)) { - state.values[idx] = oldValue; - return 0; - } - let value = get(state); - if (facet.compare(value, oldValue)) { - state.values[idx] = oldValue; - return 0; - } - state.values[idx] = value; - return 1 /* Changed */; - } - }; - } - const initField = /*@__PURE__*/Facet.define({ static: true }); - /** - Fields can store additional information in an editor state, and - keep it in sync with the rest of the state. - */ - class StateField { - constructor( - /** - @internal - */ - id, createF, updateF, compareF, - /** - @internal - */ - spec) { - this.id = id; - this.createF = createF; - this.updateF = updateF; - this.compareF = compareF; - this.spec = spec; - /** - @internal - */ - this.provides = undefined; - } - /** - Define a state field. - */ - static define(config) { - let field = new StateField(nextID++, config.create, config.update, config.compare || ((a, b) => a === b), config); - if (config.provide) - field.provides = config.provide(field); - return field; - } - create(state) { - let init = state.facet(initField).find(i => i.field == this); - return ((init === null || init === void 0 ? void 0 : init.create) || this.createF)(state); - } - /** - @internal - */ - slot(addresses) { - let idx = addresses[this.id] >> 1; - return { - create: (state) => { - state.values[idx] = this.create(state); - return 1 /* Changed */; - }, - update: (state, tr) => { - let oldVal = state.values[idx]; - let value = this.updateF(oldVal, tr); - if (this.compareF(oldVal, value)) - return 0; - state.values[idx] = value; - return 1 /* Changed */; - }, - reconfigure: (state, oldState) => { - if (oldState.config.address[this.id] != null) { - state.values[idx] = oldState.field(this); - return 0; - } - state.values[idx] = this.create(state); - return 1 /* Changed */; - } - }; - } - /** - Returns an extension that enables this field and overrides the - way it is initialized. Can be useful when you need to provide a - non-default starting value for the field. - */ - init(create) { - return [this, initField.of({ field: this, create })]; - } - /** - State field instances can be used as - [`Extension`](https://codemirror.net/6/docs/ref/#state.Extension) values to enable the field in a - given state. - */ - get extension() { return this; } - } - const Prec_ = { lowest: 4, low: 3, default: 2, high: 1, highest: 0 }; - function prec(value) { - return (ext) => new PrecExtension(ext, value); - } - /** - By default extensions are registered in the order they are found - in the flattened form of nested array that was provided. - Individual extension values can be assigned a precedence to - override this. Extensions that do not have a precedence set get - the precedence of the nearest parent with a precedence, or - [`default`](https://codemirror.net/6/docs/ref/#state.Prec.default) if there is no such parent. The - final ordering of extensions is determined by first sorting by - precedence and then by order within each precedence. - */ - const Prec = { - /** - The lowest precedence level. Meant for things that should end up - near the end of the extension order. - */ - lowest: /*@__PURE__*/prec(Prec_.lowest), - /** - A lower-than-default precedence, for extensions. - */ - low: /*@__PURE__*/prec(Prec_.low), - /** - The default precedence, which is also used for extensions - without an explicit precedence. - */ - default: /*@__PURE__*/prec(Prec_.default), - /** - A higher-than-default precedence, for extensions that should - come before those with default precedence. - */ - high: /*@__PURE__*/prec(Prec_.high), - /** - The highest precedence level, for extensions that should end up - near the start of the precedence ordering. - */ - highest: /*@__PURE__*/prec(Prec_.highest), - // FIXME Drop these in some future breaking version - /** - Backwards-compatible synonym for `Prec.lowest`. - */ - fallback: /*@__PURE__*/prec(Prec_.lowest), - /** - Backwards-compatible synonym for `Prec.high`. - */ - extend: /*@__PURE__*/prec(Prec_.high), - /** - Backwards-compatible synonym for `Prec.highest`. - */ - override: /*@__PURE__*/prec(Prec_.highest) - }; - class PrecExtension { - constructor(inner, prec) { - this.inner = inner; - this.prec = prec; - } - } - /** - Extension compartments can be used to make a configuration - dynamic. By [wrapping](https://codemirror.net/6/docs/ref/#state.Compartment.of) part of your - configuration in a compartment, you can later - [replace](https://codemirror.net/6/docs/ref/#state.Compartment.reconfigure) that part through a - transaction. - */ - class Compartment { - /** - Create an instance of this compartment to add to your [state - configuration](https://codemirror.net/6/docs/ref/#state.EditorStateConfig.extensions). - */ - of(ext) { return new CompartmentInstance(this, ext); } - /** - Create an [effect](https://codemirror.net/6/docs/ref/#state.TransactionSpec.effects) that - reconfigures this compartment. - */ - reconfigure(content) { - return Compartment.reconfigure.of({ compartment: this, extension: content }); - } - /** - Get the current content of the compartment in the state, or - `undefined` if it isn't present. - */ - get(state) { - return state.config.compartments.get(this); - } - } - class CompartmentInstance { - constructor(compartment, inner) { - this.compartment = compartment; - this.inner = inner; - } - } - class Configuration { - constructor(base, compartments, dynamicSlots, address, staticValues, facets) { - this.base = base; - this.compartments = compartments; - this.dynamicSlots = dynamicSlots; - this.address = address; - this.staticValues = staticValues; - this.facets = facets; - this.statusTemplate = []; - while (this.statusTemplate.length < dynamicSlots.length) - this.statusTemplate.push(0 /* Unresolved */); - } - staticFacet(facet) { - let addr = this.address[facet.id]; - return addr == null ? facet.default : this.staticValues[addr >> 1]; - } - static resolve(base, compartments, oldState) { - let fields = []; - let facets = Object.create(null); - let newCompartments = new Map(); - for (let ext of flatten(base, compartments, newCompartments)) { - if (ext instanceof StateField) - fields.push(ext); - else - (facets[ext.facet.id] || (facets[ext.facet.id] = [])).push(ext); - } - let address = Object.create(null); - let staticValues = []; - let dynamicSlots = []; - for (let field of fields) { - address[field.id] = dynamicSlots.length << 1; - dynamicSlots.push(a => field.slot(a)); - } - let oldFacets = oldState === null || oldState === void 0 ? void 0 : oldState.config.facets; - for (let id in facets) { - let providers = facets[id], facet = providers[0].facet; - let oldProviders = oldFacets && oldFacets[id] || []; - if (providers.every(p => p.type == 0 /* Static */)) { - address[facet.id] = (staticValues.length << 1) | 1; - if (sameArray$1(oldProviders, providers)) { - staticValues.push(oldState.facet(facet)); - } - else { - let value = facet.combine(providers.map(p => p.value)); - staticValues.push(oldState && facet.compare(value, oldState.facet(facet)) ? oldState.facet(facet) : value); - } - } - else { - for (let p of providers) { - if (p.type == 0 /* Static */) { - address[p.id] = (staticValues.length << 1) | 1; - staticValues.push(p.value); - } - else { - address[p.id] = dynamicSlots.length << 1; - dynamicSlots.push(a => p.dynamicSlot(a)); - } - } - address[facet.id] = dynamicSlots.length << 1; - dynamicSlots.push(a => dynamicFacetSlot(a, facet, providers)); - } - } - let dynamic = dynamicSlots.map(f => f(address)); - return new Configuration(base, newCompartments, dynamic, address, staticValues, facets); - } - } - function flatten(extension, compartments, newCompartments) { - let result = [[], [], [], [], []]; - let seen = new Map(); - function inner(ext, prec) { - let known = seen.get(ext); - if (known != null) { - if (known >= prec) - return; - let found = result[known].indexOf(ext); - if (found > -1) - result[known].splice(found, 1); - if (ext instanceof CompartmentInstance) - newCompartments.delete(ext.compartment); - } - seen.set(ext, prec); - if (Array.isArray(ext)) { - for (let e of ext) - inner(e, prec); - } - else if (ext instanceof CompartmentInstance) { - if (newCompartments.has(ext.compartment)) - throw new RangeError(`Duplicate use of compartment in extensions`); - let content = compartments.get(ext.compartment) || ext.inner; - newCompartments.set(ext.compartment, content); - inner(content, prec); - } - else if (ext instanceof PrecExtension) { - inner(ext.inner, ext.prec); - } - else if (ext instanceof StateField) { - result[prec].push(ext); - if (ext.provides) - inner(ext.provides, prec); - } - else if (ext instanceof FacetProvider) { - result[prec].push(ext); - if (ext.facet.extensions) - inner(ext.facet.extensions, prec); - } - else { - let content = ext.extension; - if (!content) - throw new Error(`Unrecognized extension value in extension set (${ext}). This sometimes happens because multiple instances of @codemirror/state are loaded, breaking instanceof checks.`); - inner(content, prec); - } - } - inner(extension, Prec_.default); - return result.reduce((a, b) => a.concat(b)); - } - function ensureAddr(state, addr) { - if (addr & 1) - return 2 /* Computed */; - let idx = addr >> 1; - let status = state.status[idx]; - if (status == 4 /* Computing */) - throw new Error("Cyclic dependency between fields and/or facets"); - if (status & 2 /* Computed */) - return status; - state.status[idx] = 4 /* Computing */; - let changed = state.computeSlot(state, state.config.dynamicSlots[idx]); - return state.status[idx] = 2 /* Computed */ | changed; - } - function getAddr(state, addr) { - return addr & 1 ? state.config.staticValues[addr >> 1] : state.values[addr >> 1]; - } + 3. (it used to be "show the splashscreen", but now it's a plugin) - const languageData = /*@__PURE__*/Facet.define(); - const allowMultipleSelections = /*@__PURE__*/Facet.define({ - combine: values => values.some(v => v), - static: true - }); - const lineSeparator = /*@__PURE__*/Facet.define({ - combine: values => values.length ? values[0] : undefined, - static: true - }); - const changeFilter = /*@__PURE__*/Facet.define(); - const transactionFilter = /*@__PURE__*/Facet.define(); - const transactionExtender = /*@__PURE__*/Facet.define(); - const readOnly = /*@__PURE__*/Facet.define({ - combine: values => values.length ? values[0] : false - }); + 4. loadInterpreter(): start downloading the actual interpreter (e.g. pyodide.js) - /** - Annotations are tagged values that are used to add metadata to - transactions in an extensible way. They should be used to model - things that effect the entire transaction (such as its [time - stamp](https://codemirror.net/6/docs/ref/#state.Transaction^time) or information about its - [origin](https://codemirror.net/6/docs/ref/#state.Transaction^userEvent)). For effects that happen - _alongside_ the other changes made by the transaction, [state - effects](https://codemirror.net/6/docs/ref/#state.StateEffect) are more appropriate. - */ - class Annotation { - /** - @internal - */ - constructor( - /** - The annotation type. - */ - type, - /** - The value of this annotation. - */ - value) { - this.type = type; - this.value = value; - } - /** - Define a new type of annotation. - */ - static define() { return new AnnotationType(); } - } - /** - Marker that identifies a type of [annotation](https://codemirror.net/6/docs/ref/#state.Annotation). - */ - class AnnotationType { - /** - Create an instance of this annotation. - */ - of(value) { return new Annotation(this, value); } - } - /** - Representation of a type of state effect. Defined with - [`StateEffect.define`](https://codemirror.net/6/docs/ref/#state.StateEffect^define). - */ - class StateEffectType { - /** - @internal - */ - constructor( - // The `any` types in these function types are there to work - // around TypeScript issue #37631, where the type guard on - // `StateEffect.is` mysteriously stops working when these properly - // have type `Value`. - /** - @internal - */ - map) { - this.map = map; - } - /** - Create a [state effect](https://codemirror.net/6/docs/ref/#state.StateEffect) instance of this - type. - */ - of(value) { return new StateEffect(this, value); } - } - /** - State effects can be used to represent additional effects - associated with a [transaction](https://codemirror.net/6/docs/ref/#state.Transaction.effects). They - are often useful to model changes to custom [state - fields](https://codemirror.net/6/docs/ref/#state.StateField), when those changes aren't implicit in - document or selection changes. - */ - class StateEffect { - /** - @internal - */ - constructor( - /** - @internal - */ - type, - /** - The value of this effect. - */ - value) { - this.type = type; - this.value = value; - } - /** - Map this effect through a position mapping. Will return - `undefined` when that ends up deleting the effect. - */ - map(mapping) { - let mapped = this.type.map(this.value, mapping); - return mapped === undefined ? undefined : mapped == this.value ? this : new StateEffect(this.type, mapped); - } - /** - Tells you whether this effect object is of a given - [type](https://codemirror.net/6/docs/ref/#state.StateEffectType). - */ - is(type) { return this.type == type; } - /** - Define a new effect type. The type parameter indicates the type - of values that his effect holds. - */ - static define(spec = {}) { - return new StateEffectType(spec.map || (v => v)); - } - /** - Map an array of effects through a change set. - */ - static mapEffects(effects, mapping) { - if (!effects.length) - return effects; - let result = []; - for (let effect of effects) { - let mapped = effect.map(mapping); - if (mapped) - result.push(mapped); - } - return result; - } - } - /** - This effect can be used to reconfigure the root extensions of - the editor. Doing this will discard any extensions - [appended](https://codemirror.net/6/docs/ref/#state.StateEffect^appendConfig), but does not reset - the content of [reconfigured](https://codemirror.net/6/docs/ref/#state.Compartment.reconfigure) - compartments. - */ - StateEffect.reconfigure = /*@__PURE__*/StateEffect.define(); - /** - Append extensions to the top-level configuration of the editor. - */ - StateEffect.appendConfig = /*@__PURE__*/StateEffect.define(); - /** - Changes to the editor state are grouped into transactions. - Typically, a user action creates a single transaction, which may - contain any number of document changes, may change the selection, - or have other effects. Create a transaction by calling - [`EditorState.update`](https://codemirror.net/6/docs/ref/#state.EditorState.update). - */ - class Transaction { - /** - @internal - */ - constructor( - /** - The state from which the transaction starts. - */ - startState, - /** - The document changes made by this transaction. - */ - changes, - /** - The selection set by this transaction, or undefined if it - doesn't explicitly set a selection. - */ - selection, - /** - The effects added to the transaction. - */ - effects, - /** - @internal - */ - annotations, - /** - Whether the selection should be scrolled into view after this - transaction is dispatched. - */ - scrollIntoView) { - this.startState = startState; - this.changes = changes; - this.selection = selection; - this.effects = effects; - this.annotations = annotations; - this.scrollIntoView = scrollIntoView; - /** - @internal - */ - this._doc = null; - /** - @internal - */ - this._state = null; - if (selection) - checkSelection(selection, changes.newLength); - if (!annotations.some((a) => a.type == Transaction.time)) - this.annotations = annotations.concat(Transaction.time.of(Date.now())); - } - /** - The new document produced by the transaction. Contrary to - [`.state`](https://codemirror.net/6/docs/ref/#state.Transaction.state)`.doc`, accessing this won't - force the entire new state to be computed right away, so it is - recommended that [transaction - filters](https://codemirror.net/6/docs/ref/#state.EditorState^transactionFilter) use this getter - when they need to look at the new document. - */ - get newDoc() { - return this._doc || (this._doc = this.changes.apply(this.startState.doc)); - } - /** - The new selection produced by the transaction. If - [`this.selection`](https://codemirror.net/6/docs/ref/#state.Transaction.selection) is undefined, - this will [map](https://codemirror.net/6/docs/ref/#state.EditorSelection.map) the start state's - current selection through the changes made by the transaction. - */ - get newSelection() { - return this.selection || this.startState.selection.map(this.changes); - } - /** - The new state created by the transaction. Computed on demand - (but retained for subsequent access), so itis recommended not to - access it in [transaction - filters](https://codemirror.net/6/docs/ref/#state.EditorState^transactionFilter) when possible. - */ - get state() { - if (!this._state) - this.startState.applyTransaction(this); - return this._state; - } - /** - Get the value of the given annotation type, if any. - */ - annotation(type) { - for (let ann of this.annotations) - if (ann.type == type) - return ann.value; - return undefined; - } - /** - Indicates whether the transaction changed the document. - */ - get docChanged() { return !this.changes.empty; } - /** - Indicates whether this transaction reconfigures the state - (through a [configuration compartment](https://codemirror.net/6/docs/ref/#state.Compartment) or - with a top-level configuration - [effect](https://codemirror.net/6/docs/ref/#state.StateEffect^reconfigure). - */ - get reconfigured() { return this.startState.config != this.state.config; } - /** - Returns true if the transaction has a [user - event](https://codemirror.net/6/docs/ref/#state.Transaction^userEvent) annotation that is equal to - or more specific than `event`. For example, if the transaction - has `"select.pointer"` as user event, `"select"` and - `"select.pointer"` will match it. - */ - isUserEvent(event) { - let e = this.annotation(Transaction.userEvent); - return !!(e && (e == event || e.length > event.length && e.slice(0, event.length) == event && e[event.length] == ".")); - } - } - /** - Annotation used to store transaction timestamps. - */ - Transaction.time = /*@__PURE__*/Annotation.define(); - /** - Annotation used to associate a transaction with a user interface - event. Holds a string identifying the event, using a - dot-separated format to support attaching more specific - information. The events used by the core libraries are: + --- wait until (4) has finished --- - - `"input"` when content is entered - - `"input.type"` for typed input - - `"input.type.compose"` for composition - - `"input.paste"` for pasted input - - `"input.drop"` when adding content with drag-and-drop - - `"input.complete"` when autocompleting - - `"delete"` when the user deletes content - - `"delete.selection"` when deleting the selection - - `"delete.forward"` when deleting forward from the selection - - `"delete.backward"` when deleting backward from the selection - - `"delete.cut"` when cutting to the clipboard - - `"move"` when content is moved - - `"move.drop"` when content is moved within the editor through drag-and-drop - - `"select"` when explicitly changing the selection - - `"select.pointer"` when selecting with a mouse or other pointing device - - `"undo"` and `"redo"` for history actions + 5. now the pyodide src is available. Initialize the engine - Use [`isUserEvent`](https://codemirror.net/6/docs/ref/#state.Transaction.isUserEvent) to check - whether the annotation matches a given event. - */ - Transaction.userEvent = /*@__PURE__*/Annotation.define(); - /** - Annotation indicating whether a transaction should be added to - the undo history or not. - */ - Transaction.addToHistory = /*@__PURE__*/Annotation.define(); - /** - Annotation indicating (when present and true) that a transaction - represents a change made by some other actor, not the user. This - is used, for example, to tag other people's changes in - collaborative editing. - */ - Transaction.remote = /*@__PURE__*/Annotation.define(); - function joinRanges(a, b) { - let result = []; - for (let iA = 0, iB = 0;;) { - let from, to; - if (iA < a.length && (iB == b.length || b[iB] >= a[iA])) { - from = a[iA++]; - to = a[iA++]; - } - else if (iB < b.length) { - from = b[iB++]; - to = b[iB++]; - } - else - return result; - if (!result.length || result[result.length - 1] < from) - result.push(from, to); - else if (result[result.length - 1] < to) - result[result.length - 1] = to; - } - } - function mergeTransaction(a, b, sequential) { - var _a; - let mapForA, mapForB, changes; - if (sequential) { - mapForA = b.changes; - mapForB = ChangeSet.empty(b.changes.length); - changes = a.changes.compose(b.changes); - } - else { - mapForA = b.changes.map(a.changes); - mapForB = a.changes.mapDesc(b.changes, true); - changes = a.changes.compose(mapForA); - } - return { - changes, - selection: b.selection ? b.selection.map(mapForB) : (_a = a.selection) === null || _a === void 0 ? void 0 : _a.map(mapForA), - effects: StateEffect.mapEffects(a.effects, mapForA).concat(StateEffect.mapEffects(b.effects, mapForB)), - annotations: a.annotations.length ? a.annotations.concat(b.annotations) : b.annotations, - scrollIntoView: a.scrollIntoView || b.scrollIntoView - }; - } - function resolveTransactionInner(state, spec, docSize) { - let sel = spec.selection, annotations = asArray$1(spec.annotations); - if (spec.userEvent) - annotations = annotations.concat(Transaction.userEvent.of(spec.userEvent)); - return { - changes: spec.changes instanceof ChangeSet ? spec.changes - : ChangeSet.of(spec.changes || [], docSize, state.facet(lineSeparator)), - selection: sel && (sel instanceof EditorSelection ? sel : EditorSelection.single(sel.anchor, sel.head)), - effects: asArray$1(spec.effects), - annotations, - scrollIntoView: !!spec.scrollIntoView - }; - } - function resolveTransaction(state, specs, filter) { - let s = resolveTransactionInner(state, specs.length ? specs[0] : {}, state.doc.length); - if (specs.length && specs[0].filter === false) - filter = false; - for (let i = 1; i < specs.length; i++) { - if (specs[i].filter === false) - filter = false; - let seq = !!specs[i].sequential; - s = mergeTransaction(s, resolveTransactionInner(state, specs[i], seq ? s.changes.newLength : state.doc.length), seq); - } - let tr = new Transaction(state, s.changes, s.selection, s.effects, s.annotations, s.scrollIntoView); - return extendTransaction(filter ? filterTransaction(tr) : tr); - } - // Finish a transaction by applying filters if necessary. - function filterTransaction(tr) { - let state = tr.startState; - // Change filters - let result = true; - for (let filter of state.facet(changeFilter)) { - let value = filter(tr); - if (value === false) { - result = false; - break; - } - if (Array.isArray(value)) - result = result === true ? value : joinRanges(result, value); - } - if (result !== true) { - let changes, back; - if (result === false) { - back = tr.changes.invertedDesc; - changes = ChangeSet.empty(state.doc.length); - } - else { - let filtered = tr.changes.filter(result); - changes = filtered.changes; - back = filtered.filtered.invertedDesc; - } - tr = new Transaction(state, changes, tr.selection && tr.selection.map(back), StateEffect.mapEffects(tr.effects, back), tr.annotations, tr.scrollIntoView); - } - // Transaction filters - let filters = state.facet(transactionFilter); - for (let i = filters.length - 1; i >= 0; i--) { - let filtered = filters[i](tr); - if (filtered instanceof Transaction) - tr = filtered; - else if (Array.isArray(filtered) && filtered.length == 1 && filtered[0] instanceof Transaction) - tr = filtered[0]; - else - tr = resolveTransaction(state, asArray$1(filtered), false); - } - return tr; - } - function extendTransaction(tr) { - let state = tr.startState, extenders = state.facet(transactionExtender), spec = tr; - for (let i = extenders.length - 1; i >= 0; i--) { - let extension = extenders[i](tr); - if (extension && Object.keys(extension).length) - spec = mergeTransaction(tr, resolveTransactionInner(state, extension, tr.changes.newLength), true); - } - return spec == tr ? tr : new Transaction(state, tr.changes, tr.selection, spec.effects, spec.annotations, spec.scrollIntoView); - } - const none$3 = []; - function asArray$1(value) { - return value == null ? none$3 : Array.isArray(value) ? value : [value]; - } + 6. setup the environment, install packages - /** - The categories produced by a [character - categorizer](https://codemirror.net/6/docs/ref/#state.EditorState.charCategorizer). These are used - do things like selecting by word. - */ - var CharCategory = /*@__PURE__*/(function (CharCategory) { - /** - Word characters. - */ - CharCategory[CharCategory["Word"] = 0] = "Word"; - /** - Whitespace. - */ - CharCategory[CharCategory["Space"] = 1] = "Space"; - /** - Anything else. - */ - CharCategory[CharCategory["Other"] = 2] = "Other"; - return CharCategory})(CharCategory || (CharCategory = {})); - const nonASCIISingleCaseWordChar = /[\u00df\u0587\u0590-\u05f4\u0600-\u06ff\u3040-\u309f\u30a0-\u30ff\u3400-\u4db5\u4e00-\u9fcc\uac00-\ud7af]/; - let wordChar; - try { - wordChar = /*@__PURE__*/new RegExp("[\\p{Alphabetic}\\p{Number}_]", "u"); - } - catch (_) { } - function hasWordChar(str) { - if (wordChar) - return wordChar.test(str); - for (let i = 0; i < str.length; i++) { - let ch = str[i]; - if (/\w/.test(ch) || ch > "\x80" && (ch.toUpperCase() != ch.toLowerCase() || nonASCIISingleCaseWordChar.test(ch))) - return true; - } - return false; - } - function makeCategorizer(wordChars) { - return (char) => { - if (!/\S/.test(char)) - return CharCategory.Space; - if (hasWordChar(char)) - return CharCategory.Word; - for (let i = 0; i < wordChars.length; i++) - if (char.indexOf(wordChars[i]) > -1) - return CharCategory.Word; - return CharCategory.Other; - }; - } + 6.5: call the Plugin.afterSetup() hook - /** - The editor state class is a persistent (immutable) data structure. - To update a state, you [create](https://codemirror.net/6/docs/ref/#state.EditorState.update) a - [transaction](https://codemirror.net/6/docs/ref/#state.Transaction), which produces a _new_ state - instance, without modifying the original object. + 7. connect the py-script web component. This causes the execution of all the + user scripts - As such, _never_ mutate properties of a state directly. That'll - just break things. - */ - class EditorState { - /** - @internal - */ - constructor( - /** - @internal - */ - config, - /** - The current document. - */ - doc, - /** - The current selection. - */ - selection, - /** - @internal - */ - values, computeSlot, tr) { - this.config = config; - this.doc = doc; - this.selection = selection; - this.values = values; - this.status = config.statusTemplate.slice(); - this.computeSlot = computeSlot; - // Fill in the computed state immediately, so that further queries - // for it made during the update return this state - if (tr) - tr._state = this; - for (let i = 0; i < this.config.dynamicSlots.length; i++) - ensureAddr(this, i << 1); - this.computeSlot = null; - } - field(field, require = true) { - let addr = this.config.address[field.id]; - if (addr == null) { - if (require) - throw new RangeError("Field is not present in this state"); - return undefined; - } - ensureAddr(this, addr); - return getAddr(this, addr); - } - /** - Create a [transaction](https://codemirror.net/6/docs/ref/#state.Transaction) that updates this - state. Any number of [transaction specs](https://codemirror.net/6/docs/ref/#state.TransactionSpec) - can be passed. Unless - [`sequential`](https://codemirror.net/6/docs/ref/#state.TransactionSpec.sequential) is set, the - [changes](https://codemirror.net/6/docs/ref/#state.TransactionSpec.changes) (if any) of each spec - are assumed to start in the _current_ document (not the document - produced by previous specs), and its - [selection](https://codemirror.net/6/docs/ref/#state.TransactionSpec.selection) and - [effects](https://codemirror.net/6/docs/ref/#state.TransactionSpec.effects) are assumed to refer - to the document created by its _own_ changes. The resulting - transaction contains the combined effect of all the different - specs. For [selection](https://codemirror.net/6/docs/ref/#state.TransactionSpec.selection), later - specs take precedence over earlier ones. - */ - update(...specs) { - return resolveTransaction(this, specs, true); - } - /** - @internal - */ - applyTransaction(tr) { - let conf = this.config, { base, compartments } = conf; - for (let effect of tr.effects) { - if (effect.is(Compartment.reconfigure)) { - if (conf) { - compartments = new Map; - conf.compartments.forEach((val, key) => compartments.set(key, val)); - conf = null; - } - compartments.set(effect.value.compartment, effect.value.extension); - } - else if (effect.is(StateEffect.reconfigure)) { - conf = null; - base = effect.value; - } - else if (effect.is(StateEffect.appendConfig)) { - conf = null; - base = asArray$1(base).concat(effect.value); - } - } - let startValues; - if (!conf) { - conf = Configuration.resolve(base, compartments, this); - let intermediateState = new EditorState(conf, this.doc, this.selection, conf.dynamicSlots.map(() => null), (state, slot) => slot.reconfigure(state, this), null); - startValues = intermediateState.values; - } - else { - startValues = tr.startState.values.slice(); - } - new EditorState(conf, tr.newDoc, tr.newSelection, startValues, (state, slot) => slot.update(state, tr), tr); - } - /** - Create a [transaction spec](https://codemirror.net/6/docs/ref/#state.TransactionSpec) that - replaces every selection range with the given content. - */ - replaceSelection(text) { - if (typeof text == "string") - text = this.toText(text); - return this.changeByRange(range => ({ changes: { from: range.from, to: range.to, insert: text }, - range: EditorSelection.cursor(range.from + text.length) })); - } - /** - Create a set of changes and a new selection by running the given - function for each range in the active selection. The function - can return an optional set of changes (in the coordinate space - of the start document), plus an updated range (in the coordinate - space of the document produced by the call's own changes). This - method will merge all the changes and ranges into a single - changeset and selection, and return it as a [transaction - spec](https://codemirror.net/6/docs/ref/#state.TransactionSpec), which can be passed to - [`update`](https://codemirror.net/6/docs/ref/#state.EditorState.update). - */ - changeByRange(f) { - let sel = this.selection; - let result1 = f(sel.ranges[0]); - let changes = this.changes(result1.changes), ranges = [result1.range]; - let effects = asArray$1(result1.effects); - for (let i = 1; i < sel.ranges.length; i++) { - let result = f(sel.ranges[i]); - let newChanges = this.changes(result.changes), newMapped = newChanges.map(changes); - for (let j = 0; j < i; j++) - ranges[j] = ranges[j].map(newMapped); - let mapBy = changes.mapDesc(newChanges, true); - ranges.push(result.range.map(mapBy)); - changes = changes.compose(newMapped); - effects = StateEffect.mapEffects(effects, newMapped).concat(StateEffect.mapEffects(asArray$1(result.effects), mapBy)); - } - return { - changes, - selection: EditorSelection.create(ranges, sel.mainIndex), - effects - }; - } - /** - Create a [change set](https://codemirror.net/6/docs/ref/#state.ChangeSet) from the given change - description, taking the state's document length and line - separator into account. - */ - changes(spec = []) { - if (spec instanceof ChangeSet) - return spec; - return ChangeSet.of(spec, this.doc.length, this.facet(EditorState.lineSeparator)); - } - /** - Using the state's [line - separator](https://codemirror.net/6/docs/ref/#state.EditorState^lineSeparator), create a - [`Text`](https://codemirror.net/6/docs/ref/#text.Text) instance from the given string. - */ - toText(string) { - return Text.of(string.split(this.facet(EditorState.lineSeparator) || DefaultSplit)); - } - /** - Return the given range of the document as a string. - */ - sliceDoc(from = 0, to = this.doc.length) { - return this.doc.sliceString(from, to, this.lineBreak); - } - /** - Get the value of a state [facet](https://codemirror.net/6/docs/ref/#state.Facet). - */ - facet(facet) { - let addr = this.config.address[facet.id]; - if (addr == null) - return facet.default; - ensureAddr(this, addr); - return getAddr(this, addr); - } - /** - Convert this state to a JSON-serializable object. When custom - fields should be serialized, you can pass them in as an object - mapping property names (in the resulting object, which should - not use `doc` or `selection`) to fields. - */ - toJSON(fields) { - let result = { - doc: this.sliceDoc(), - selection: this.selection.toJSON() - }; - if (fields) - for (let prop in fields) { - let value = fields[prop]; - if (value instanceof StateField) - result[prop] = value.spec.toJSON(this.field(fields[prop]), this); - } - return result; - } - /** - Deserialize a state from its JSON representation. When custom - fields should be deserialized, pass the same object you passed - to [`toJSON`](https://codemirror.net/6/docs/ref/#state.EditorState.toJSON) when serializing as - third argument. - */ - static fromJSON(json, config = {}, fields) { - if (!json || typeof json.doc != "string") - throw new RangeError("Invalid JSON representation for EditorState"); - let fieldInit = []; - if (fields) - for (let prop in fields) { - let field = fields[prop], value = json[prop]; - fieldInit.push(field.init(state => field.spec.fromJSON(value, state))); - } - return EditorState.create({ - doc: json.doc, - selection: EditorSelection.fromJSON(json.selection), - extensions: config.extensions ? fieldInit.concat([config.extensions]) : fieldInit - }); - } - /** - Create a new state. You'll usually only need this when - initializing an editor—updated states are created by applying - transactions. - */ - static create(config = {}) { - let configuration = Configuration.resolve(config.extensions || [], new Map); - let doc = config.doc instanceof Text ? config.doc - : Text.of((config.doc || "").split(configuration.staticFacet(EditorState.lineSeparator) || DefaultSplit)); - let selection = !config.selection ? EditorSelection.single(0) - : config.selection instanceof EditorSelection ? config.selection - : EditorSelection.single(config.selection.anchor, config.selection.head); - checkSelection(selection, doc.length); - if (!configuration.staticFacet(allowMultipleSelections)) - selection = selection.asSingle(); - return new EditorState(configuration, doc, selection, configuration.dynamicSlots.map(() => null), (state, slot) => slot.create(state), null); - } - /** - The size (in columns) of a tab in the document, determined by - the [`tabSize`](https://codemirror.net/6/docs/ref/#state.EditorState^tabSize) facet. - */ - get tabSize() { return this.facet(EditorState.tabSize); } - /** - Get the proper [line-break](https://codemirror.net/6/docs/ref/#state.EditorState^lineSeparator) - string for this state. - */ - get lineBreak() { return this.facet(EditorState.lineSeparator) || "\n"; } - /** - Returns true when the editor is - [configured](https://codemirror.net/6/docs/ref/#state.EditorState^readOnly) to be read-only. - */ - get readOnly() { return this.facet(readOnly); } - /** - Look up a translation for the given phrase (via the - [`phrases`](https://codemirror.net/6/docs/ref/#state.EditorState^phrases) facet), or return the - original string if no translation is found. - */ - phrase(phrase) { - for (let map of this.facet(EditorState.phrases)) - if (Object.prototype.hasOwnProperty.call(map, phrase)) - return map[phrase]; - return phrase; - } - /** - Find the values for a given language data field, provided by the - the [`languageData`](https://codemirror.net/6/docs/ref/#state.EditorState^languageData) facet. - */ - languageDataAt(name, pos, side = -1) { - let values = []; - for (let provider of this.facet(languageData)) { - for (let result of provider(this, pos, side)) { - if (Object.prototype.hasOwnProperty.call(result, name)) - values.push(result[name]); - } - } - return values; - } - /** - Return a function that can categorize strings (expected to - represent a single [grapheme cluster](https://codemirror.net/6/docs/ref/#text.findClusterBreak)) - into one of: - - - Word (contains an alphanumeric character or a character - explicitly listed in the local language's `"wordChars"` - language data, which should be a string) - - Space (contains only whitespace) - - Other (anything else) - */ - charCategorizer(at) { - return makeCategorizer(this.languageDataAt("wordChars", at).join("")); - } - /** - Find the word at the given position, meaning the range - containing all [word](https://codemirror.net/6/docs/ref/#state.CharCategory.Word) characters - around it. If no word characters are adjacent to the position, - this returns null. - */ - wordAt(pos) { - let { text, from, length } = this.doc.lineAt(pos); - let cat = this.charCategorizer(pos); - let start = pos - from, end = pos - from; - while (start > 0) { - let prev = findClusterBreak(text, start, false); - if (cat(text.slice(prev, start)) != CharCategory.Word) - break; - start = prev; - } - while (end < length) { - let next = findClusterBreak(text, end); - if (cat(text.slice(end, next)) != CharCategory.Word) - break; - end = next; - } - return start == end ? null : EditorSelection.range(start + from, end + from); - } - } - /** - A facet that, when enabled, causes the editor to allow multiple - ranges to be selected. Be careful though, because by default the - editor relies on the native DOM selection, which cannot handle - multiple selections. An extension like - [`drawSelection`](https://codemirror.net/6/docs/ref/#view.drawSelection) can be used to make - secondary selections visible to the user. - */ - EditorState.allowMultipleSelections = allowMultipleSelections; - /** - Configures the tab size to use in this state. The first - (highest-precedence) value of the facet is used. If no value is - given, this defaults to 4. - */ - EditorState.tabSize = /*@__PURE__*/Facet.define({ - combine: values => values.length ? values[0] : 4 - }); - /** - The line separator to use. By default, any of `"\n"`, `"\r\n"` - and `"\r"` is treated as a separator when splitting lines, and - lines are joined with `"\n"`. + 8. initialize the rest of web components such as py-button, py-repl, etc. - When you configure a value here, only that precise separator - will be used, allowing you to round-trip documents through the - editor without normalizing line separators. - */ - EditorState.lineSeparator = lineSeparator; - /** - This facet controls the value of the - [`readOnly`](https://codemirror.net/6/docs/ref/#state.EditorState.readOnly) getter, which is - consulted by commands and extensions that implement editing - functionality to determine whether they should apply. It - defaults to false, but when its highest-precedence value is - `true`, such functionality disables itself. + More concretely: - Not to be confused with - [`EditorView.editable`](https://codemirror.net/6/docs/ref/#view.EditorView^editable), which - controls whether the editor's DOM is set to be editable (and - thus focusable). - */ - EditorState.readOnly = readOnly; - /** - Registers translation phrases. The - [`phrase`](https://codemirror.net/6/docs/ref/#state.EditorState.phrase) method will look through - all objects registered with this facet to find translations for - its argument. - */ - EditorState.phrases = /*@__PURE__*/Facet.define(); - /** - A facet used to register [language - data](https://codemirror.net/6/docs/ref/#state.EditorState.languageDataAt) providers. - */ - EditorState.languageData = languageData; - /** - Facet used to register change filters, which are called for each - transaction (unless explicitly - [disabled](https://codemirror.net/6/docs/ref/#state.TransactionSpec.filter)), and can suppress - part of the transaction's changes. + - Points 1-4 are implemented sequentially in PyScriptApp.main(). - Such a function can return `true` to indicate that it doesn't - want to do anything, `false` to completely stop the changes in - the transaction, or a set of ranges in which changes should be - suppressed. Such ranges are represented as an array of numbers, - with each pair of two number indicating the start and end of a - range. So for example `[10, 20, 100, 110]` suppresses changes - between 10 and 20, and between 100 and 110. - */ - EditorState.changeFilter = changeFilter; - /** - Facet used to register a hook that gets a chance to update or - replace transaction specs before they are applied. This will - only be applied for transactions that don't have - [`filter`](https://codemirror.net/6/docs/ref/#state.TransactionSpec.filter) set to `false`. You - can either return a single transaction spec (possibly the input - transaction), or an array of specs (which will be combined in - the same way as the arguments to - [`EditorState.update`](https://codemirror.net/6/docs/ref/#state.EditorState.update)). + - PyScriptApp.loadInterpreter adds a <script> tag to the document to initiate + the download, and then adds an event listener for the 'load' event, which + in turns calls PyScriptApp.afterInterpreterLoad(). - When possible, it is recommended to avoid accessing - [`Transaction.state`](https://codemirror.net/6/docs/ref/#state.Transaction.state) in a filter, - since it will force creation of a state that will then be - discarded again, if the transaction is actually filtered. - - (This functionality should be used with care. Indiscriminately - modifying transaction is likely to break something or degrade - the user experience.) - */ - EditorState.transactionFilter = transactionFilter; - /** - This is a more limited form of - [`transactionFilter`](https://codemirror.net/6/docs/ref/#state.EditorState^transactionFilter), - which can only add - [annotations](https://codemirror.net/6/docs/ref/#state.TransactionSpec.annotations) and - [effects](https://codemirror.net/6/docs/ref/#state.TransactionSpec.effects). _But_, this type - of filter runs even the transaction has disabled regular - [filtering](https://codemirror.net/6/docs/ref/#state.TransactionSpec.filter), making it suitable - for effects that don't need to touch the changes or selection, - but do want to process every transaction. - - Extenders run _after_ filters, when both are applied. - */ - EditorState.transactionExtender = transactionExtender; - Compartment.reconfigure = /*@__PURE__*/StateEffect.define(); - - /** - Utility function for combining behaviors to fill in a config - object from an array of provided configs. Will, by default, error - when a field gets two values that aren't `===`-equal, but you can - provide combine functions per field to do something else. - */ - function combineConfig(configs, defaults, // Should hold only the optional properties of Config, but I haven't managed to express that - combine = {}) { - let result = {}; - for (let config of configs) - for (let key of Object.keys(config)) { - let value = config[key], current = result[key]; - if (current === undefined) - result[key] = value; - else if (current === value || value === undefined) ; // No conflict - else if (Object.hasOwnProperty.call(combine, key)) - result[key] = combine[key](current, value); - else - throw new Error("Config merge conflict for field " + key); - } - for (let key in defaults) - if (result[key] === undefined) - result[key] = defaults[key]; - return result; - } - - const C = "\u037c"; - const COUNT = typeof Symbol == "undefined" ? "__" + C : Symbol.for(C); - const SET = typeof Symbol == "undefined" ? "__styleSet" + Math.floor(Math.random() * 1e8) : Symbol("styleSet"); - const top = typeof globalThis != "undefined" ? globalThis : typeof window != "undefined" ? window : {}; - - // :: - Style modules encapsulate a set of CSS rules defined from - // JavaScript. Their definitions are only available in a given DOM - // root after it has been _mounted_ there with `StyleModule.mount`. - // - // Style modules should be created once and stored somewhere, as - // opposed to re-creating them every time you need them. The amount of - // CSS rules generated for a given DOM root is bounded by the amount - // of style modules that were used. So to avoid leaking rules, don't - // create these dynamically, but treat them as one-time allocations. - class StyleModule { - // :: (Object<Style>, ?{finish: ?(string) → string}) - // Create a style module from the given spec. + - PyScriptApp.afterInterpreterLoad() implements all the points >= 5. + */ + class PyScriptApp { + constructor() { + // initialize the builtin plugins + this.plugins = new PluginManager(); + this.plugins.add(new SplashscreenPlugin(), new PyTerminalPlugin(this), new ImportmapPlugin()); + this._stdioMultiplexer = new StdioMultiplexer(); + this._stdioMultiplexer.addListener(DEFAULT_STDIO); + this.plugins.add(new StdioDirector(this._stdioMultiplexer)); + this.tagExecutionLock = createLock(); + } + // Error handling logic: if during the execution we encounter an error + // which is ultimate responsibility of the user (e.g.: syntax error in the + // config, file not found in fetch, etc.), we can throw UserError(). It is + // responsibility of main() to catch it and show it to the user in a + // proper way (e.g. by using a banner at the top of the page). + main() { + try { + this._realMain(); + } + catch (error) { + this._handleUserErrorMaybe(error); + } + } + _handleUserErrorMaybe(error) { + if (error instanceof UserError) { + _createAlertBanner(error.message, 'error', error.messageType); + this.plugins.onUserError(error); + } + else { + throw error; + } + } + // ============ lifecycle ============ + // lifecycle (1) + _realMain() { + this.loadConfig(); + this.plugins.configure(this.config); + this.plugins.beforeLaunch(this.config); + this.loadInterpreter(); + } + // lifecycle (2) + loadConfig() { + // find the <py-config> tag. If not found, we get null which means + // "use the default config" + // XXX: we should actively complain if there are multiple <py-config> + // and show a big error. PRs welcome :) + logger.info('searching for <py-config>'); + const elements = document.getElementsByTagName('py-config'); + let el = null; + if (elements.length > 0) + el = elements[0]; + if (elements.length >= 2) { + showWarning('Multiple <py-config> tags detected. Only the first is ' + + 'going to be parsed, all the others will be ignored'); + } + this.config = loadConfigFromElement(el); + logger.info('config loaded:\n' + JSON.stringify(this.config, null, 2)); + } + // lifecycle (4) + loadInterpreter() { + logger.info('Initializing interpreter'); + if (this.config.interpreters.length == 0) { + throw new UserError(ErrorCode.BAD_CONFIG, 'Fatal error: config.interpreter is empty'); + } + if (this.config.interpreters.length > 1) { + showWarning('Multiple interpreters are not supported yet.<br />Only the first will be used', 'html'); + } + const interpreter_cfg = this.config.interpreters[0]; + this.interpreter = new InterpreterClient(this.config, this._stdioMultiplexer); + this.logStatus(`Downloading ${interpreter_cfg.name}...`); + // download pyodide by using a <script> tag. Once it's ready, the + // "load" event will be fired and the exeuction logic will continue. + // Note that the load event is fired asynchronously and thus any + // exception which is throw inside the event handler is *NOT* caught + // by the try/catch inside main(): that's why we need to .catch() it + // explicitly and call _handleUserErrorMaybe also there. + const script = document.createElement('script'); // create a script DOM node + script.src = this.interpreter._remote.src; + script.addEventListener('load', () => { + this.afterInterpreterLoad(this.interpreter).catch(error => { + this._handleUserErrorMaybe(error); + }); + }); + document.head.appendChild(script); + } + // lifecycle (5) + // See the overview comment above for an explanation of how we jump from + // point (4) to point (5). // - // When `finish` is given, it is called on regular (non-`@`) - // selectors (after `&` expansion) to compute the final selector. - constructor(spec, options) { - this.rules = []; - let {finish} = options || {}; - - function splitSelector(selector) { - return /^@/.test(selector) ? [selector] : selector.split(/,\s*/) - } - - function render(selectors, spec, target, isKeyframes) { - let local = [], isAt = /^@(\w+)\b/.exec(selectors[0]), keyframes = isAt && isAt[1] == "keyframes"; - if (isAt && spec == null) return target.push(selectors[0] + ";") - for (let prop in spec) { - let value = spec[prop]; - if (/&/.test(prop)) { - render(prop.split(/,\s*/).map(part => selectors.map(sel => part.replace(/&/, sel))).reduce((a, b) => a.concat(b)), - value, target); - } else if (value && typeof value == "object") { - if (!isAt) throw new RangeError("The value of a property (" + prop + ") should be a primitive value.") - render(splitSelector(prop), value, local, keyframes); - } else if (value != null) { - local.push(prop.replace(/_.*/, "").replace(/[A-Z]/g, l => "-" + l.toLowerCase()) + ": " + value + ";"); - } + // Invariant: this.config is set and available. + async afterInterpreterLoad(interpreter) { + console.assert(this.config !== undefined); + this.logStatus('Python startup...'); + await this.interpreter.initializeRemote(); + this.logStatus('Python ready!'); + this.logStatus('Setting up virtual environment...'); + await this.setupVirtualEnv(interpreter); + await mountElements(interpreter); + // lifecycle (6.5) + this.plugins.afterSetup(interpreter); + //Refresh module cache in case plugins have modified the filesystem + interpreter._remote.invalidate_module_path_cache(); + this.logStatus('Executing <py-script> tags...'); + this.executeScripts(interpreter); + this.logStatus('Initializing web components...'); + // lifecycle (8) + createCustomElements(interpreter); + initHandlers(interpreter); + // NOTE: interpreter message is used by integration tests to know that + // pyscript initialization has complete. If you change it, you need to + // change it also in tests/integration/support.py + this.logStatus('Startup complete'); + this.plugins.afterStartup(interpreter); + logger.info('PyScript page fully initialized'); + } + // lifecycle (6) + async setupVirtualEnv(interpreter) { + // XXX: maybe the following calls could be parallelized, instead of + // await()ing immediately. For now I'm using await to be 100% + // compatible with the old behavior. + logger.info('importing pyscript'); + // Save and load pyscript.py from FS + interpreter._remote.interface.FS.mkdirTree('/home/pyodide/pyscript'); + interpreter._remote.interface.FS.writeFile('pyscript/__init__.py', pyscript); + //Refresh the module cache so Python consistently finds pyscript module + interpreter._remote.invalidate_module_path_cache(); + // inject `define_custom_element` and showWarning it into the PyScript + // module scope + const pyscript_module = interpreter._remote.interface.pyimport('pyscript'); + pyscript_module.define_custom_element = define_custom_element; + pyscript_module.showWarning = showWarning; + pyscript_module._set_version_info(version); + pyscript_module.destroy(); + // import some carefully selected names into the global namespace + await interpreter.run(` + import js + import pyscript + from pyscript import Element, display, HTML + pyscript._install_deprecated_globals_2022_12_1(globals()) + `); + if (this.config.packages) { + logger.info('Packages to install: ', this.config.packages); + await interpreter._remote.installPackage(this.config.packages); } - if (local.length || keyframes) { - target.push((finish && !isAt && !isKeyframes ? selectors.map(finish) : selectors).join(", ") + - " {" + local.join(" ") + "}"); + await this.fetchPaths(interpreter); + //This may be unnecessary - only useful if plugins try to import files fetch'd in fetchPaths() + interpreter._remote.invalidate_module_path_cache(); + // Finally load plugins + await this.fetchUserPlugins(interpreter); + } + async fetchPaths(interpreter) { + // XXX this can be VASTLY improved: for each path we need to fetch a + // URL and write to the virtual filesystem: pyodide.loadFromFile does + // it in Python, which means we need to have the interpreter + // initialized. But we could easily do it in JS in parallel with the + // download/startup of pyodide. + const [paths, fetchPaths] = calculatePaths(this.config.fetch); + logger.info('Paths to write: ', paths); + logger.info('Paths to fetch: ', fetchPaths); + for (let i = 0; i < paths.length; i++) { + logger.info(` fetching path: ${fetchPaths[i]}`); + // Exceptions raised from here will create an alert banner + await interpreter._remote.loadFromFile(paths[i], fetchPaths[i]); } - } - - for (let prop in spec) render(splitSelector(prop), spec[prop], this.rules); + logger.info('All paths fetched'); } - - // :: () → string - // Returns a string containing the module's CSS rules. - getRules() { return this.rules.join("\n") } - - // :: () → string - // Generate a new unique CSS class name. - static newName() { - let id = top[COUNT] || 1; - top[COUNT] = id + 1; - return C + id.toString(36) - } - - // :: (union<Document, ShadowRoot>, union<[StyleModule], StyleModule>) - // - // Mount the given set of modules in the given DOM root, which ensures - // that the CSS rules defined by the module are available in that - // context. - // - // Rules are only added to the document once per root. - // - // Rule order will follow the order of the modules, so that rules from - // modules later in the array take precedence of those from earlier - // modules. If you call this function multiple times for the same root - // in a way that changes the order of already mounted modules, the old - // order will be changed. - static mount(root, modules) { - (root[SET] || new StyleSet(root)).mount(Array.isArray(modules) ? modules : [modules]); - } - } - - let adoptedSet = null; - - class StyleSet { - constructor(root) { - if (!root.head && root.adoptedStyleSheets && typeof CSSStyleSheet != "undefined") { - if (adoptedSet) { - root.adoptedStyleSheets = [adoptedSet.sheet].concat(root.adoptedStyleSheets); - return root[SET] = adoptedSet + /** + * Fetch user plugins and adds them to `this.plugins` so they can + * be loaded by the PluginManager. Currently, we are just looking + * for .py and .js files and calling the appropriate methods. + * + * @param interpreter - the interpreter that will be used to execute the plugins that need it. + */ + async fetchUserPlugins(interpreter) { + const plugins = this.config.plugins; + logger.info('Plugins to fetch: ', plugins); + for (const singleFile of plugins) { + logger.info(` fetching plugins: ${singleFile}`); + if (singleFile.endsWith('.py')) { + await this.fetchPythonPlugin(interpreter, singleFile); + } + else if (singleFile.endsWith('.js')) { + await this.fetchJSPlugin(singleFile); + } + else { + throw new UserError(ErrorCode.BAD_PLUGIN_FILE_EXTENSION, `Unable to load plugin from '${singleFile}'. ` + + `Plugins need to contain a file extension and be ` + + `either a python or javascript file.`); + } + logger.info('All plugins fetched'); } - this.sheet = new CSSStyleSheet; - root.adoptedStyleSheets = [this.sheet].concat(root.adoptedStyleSheets); - adoptedSet = this; - } else { - this.styleTag = (root.ownerDocument || root).createElement("style"); - let target = root.head || root; - target.insertBefore(this.styleTag, target.firstChild); - } - this.modules = []; - root[SET] = this; } - - mount(modules) { - let sheet = this.sheet; - let pos = 0 /* Current rule offset */, j = 0; /* Index into this.modules */ - for (let i = 0; i < modules.length; i++) { - let mod = modules[i], index = this.modules.indexOf(mod); - if (index < j && index > -1) { // Ordering conflict - this.modules.splice(index, 1); - j--; - index = -1; + /** + * Fetch a javascript plugin from a filePath, it gets a blob from the + * fetch and creates a file from it, then we create a URL from the file + * so we can import it as a module. + * + * This allow us to instantiate the imported plugin with the default + * export in the module (the plugin class) and add it to the plugins + * list with `new importedPlugin()`. + * + * @param filePath - URL of the javascript file to fetch. + */ + async fetchJSPlugin(filePath) { + const pluginBlob = await (await robustFetch(filePath)).blob(); + const blobFile = new File([pluginBlob], 'plugin.js', { type: 'text/javascript' }); + const fileUrl = URL.createObjectURL(blobFile); + const module = await import(fileUrl); + // Note: We have to put module.default in a variable + // because we have seen weird behaviour when doing + // new module.default() directly. + const importedPlugin = module.default; + // If the imported plugin doesn't have a default export + // it will be undefined, so we throw a user error, so + // an alter banner will be created. + if (importedPlugin === undefined) { + throw new UserError(ErrorCode.NO_DEFAULT_EXPORT, `Unable to load plugin from '${filePath}'. ` + `Plugins need to contain a default export.`); } - if (index == -1) { - this.modules.splice(j++, 0, mod); - if (sheet) for (let k = 0; k < mod.rules.length; k++) - sheet.insertRule(mod.rules[k], pos++); - } else { - while (j < index) pos += this.modules[j++].rules.length; - pos += mod.rules.length; - j++; + else { + this.plugins.add(new importedPlugin()); } - } - - if (!sheet) { - let text = ""; - for (let i = 0; i < this.modules.length; i++) - text += this.modules[i].getRules() + "\n"; - this.styleTag.textContent = text; - } } - } - - // Style::Object<union<Style,string>> - // - // A style is an object that, in the simple case, maps CSS property - // names to strings holding their values, as in `{color: "red", - // fontWeight: "bold"}`. The property names can be given in - // camel-case—the library will insert a dash before capital letters - // when converting them to CSS. - // - // If you include an underscore in a property name, it and everything - // after it will be removed from the output, which can be useful when - // providing a property multiple times, for browser compatibility - // reasons. - // - // A property in a style object can also be a sub-selector, which - // extends the current context to add a pseudo-selector or a child - // selector. Such a property should contain a `&` character, which - // will be replaced by the current selector. For example `{"&:before": - // {content: '"hi"'}}`. Sub-selectors and regular properties can - // freely be mixed in a given object. Any property containing a `&` is - // assumed to be a sub-selector. - // - // Finally, a property can specify an @-block to be wrapped around the - // styles defined inside the object that's the property's value. For - // example to create a media query you can do `{"@media screen and - // (min-width: 400px)": {...}}`. - - /** - Each range is associated with a value, which must inherit from - this class. - */ - class RangeValue { - /** - Compare this value with another value. The default - implementation compares by identity. - */ - eq(other) { return this == other; } - /** - Create a [range](https://codemirror.net/6/docs/ref/#rangeset.Range) with this value. - */ - range(from, to = from) { return new Range$1(from, to, this); } - } - RangeValue.prototype.startSide = RangeValue.prototype.endSide = 0; - RangeValue.prototype.point = false; - RangeValue.prototype.mapMode = MapMode.TrackDel; - /** - A range associates a value with a range of positions. - */ - class Range$1 { - /** - @internal - */ - constructor( - /** - The range's start position. - */ - from, - /** - Its end position. - */ - to, - /** - The value associated with this range. - */ - value) { - this.from = from; - this.to = to; - this.value = value; - } - } - function cmpRange(a, b) { - return a.from - b.from || a.value.startSide - b.value.startSide; - } - class Chunk { - constructor(from, to, value, - // Chunks are marked with the largest point that occurs - // in them (or -1 for no points), so that scans that are - // only interested in points (such as the - // heightmap-related logic) can skip range-only chunks. - maxPoint) { - this.from = from; - this.to = to; - this.value = value; - this.maxPoint = maxPoint; - } - get length() { return this.to[this.to.length - 1]; } - // Find the index of the given position and side. Use the ranges' - // `from` pos when `end == false`, `to` when `end == true`. - findIndex(pos, side, end, startAt = 0) { - let arr = end ? this.to : this.from; - for (let lo = startAt, hi = arr.length;;) { - if (lo == hi) - return lo; - let mid = (lo + hi) >> 1; - let diff = arr[mid] - pos || (end ? this.value[mid].endSide : this.value[mid].startSide) - side; - if (mid == lo) - return diff >= 0 ? lo : hi; - if (diff >= 0) - hi = mid; - else - lo = mid + 1; - } - } - between(offset, from, to, f) { - for (let i = this.findIndex(from, -1000000000 /* Far */, true), e = this.findIndex(to, 1000000000 /* Far */, false, i); i < e; i++) - if (f(this.from[i] + offset, this.to[i] + offset, this.value[i]) === false) - return false; - } - map(offset, changes) { - let value = [], from = [], to = [], newPos = -1, maxPoint = -1; - for (let i = 0; i < this.value.length; i++) { - let val = this.value[i], curFrom = this.from[i] + offset, curTo = this.to[i] + offset, newFrom, newTo; - if (curFrom == curTo) { - let mapped = changes.mapPos(curFrom, val.startSide, val.mapMode); - if (mapped == null) - continue; - newFrom = newTo = mapped; - if (val.startSide != val.endSide) { - newTo = changes.mapPos(curFrom, val.endSide); - if (newTo < newFrom) - continue; - } - } - else { - newFrom = changes.mapPos(curFrom, val.startSide); - newTo = changes.mapPos(curTo, val.endSide); - if (newFrom > newTo || newFrom == newTo && val.startSide > 0 && val.endSide <= 0) - continue; - } - if ((newTo - newFrom || val.endSide - val.startSide) < 0) - continue; - if (newPos < 0) - newPos = newFrom; - if (val.point) - maxPoint = Math.max(maxPoint, newTo - newFrom); - value.push(val); - from.push(newFrom - newPos); - to.push(newTo - newPos); - } - return { mapped: value.length ? new Chunk(from, to, value, maxPoint) : null, pos: newPos }; - } - } - /** - A range set stores a collection of [ranges](https://codemirror.net/6/docs/ref/#rangeset.Range) in a - way that makes them efficient to [map](https://codemirror.net/6/docs/ref/#rangeset.RangeSet.map) and - [update](https://codemirror.net/6/docs/ref/#rangeset.RangeSet.update). This is an immutable data - structure. - */ - class RangeSet { - /** - @internal - */ - constructor( - /** - @internal - */ - chunkPos, - /** - @internal - */ - chunk, - /** - @internal - */ - nextLayer = RangeSet.empty, - /** - @internal - */ - maxPoint) { - this.chunkPos = chunkPos; - this.chunk = chunk; - this.nextLayer = nextLayer; - this.maxPoint = maxPoint; - } - /** - @internal - */ - get length() { - let last = this.chunk.length - 1; - return last < 0 ? 0 : Math.max(this.chunkEnd(last), this.nextLayer.length); - } - /** - The number of ranges in the set. - */ - get size() { - if (this.isEmpty) - return 0; - let size = this.nextLayer.size; - for (let chunk of this.chunk) - size += chunk.value.length; - return size; - } - /** - @internal - */ - chunkEnd(index) { - return this.chunkPos[index] + this.chunk[index].length; - } - /** - Update the range set, optionally adding new ranges or filtering - out existing ones. - - (The extra type parameter is just there as a kludge to work - around TypeScript variance issues that prevented `RangeSet<X>` - from being a subtype of `RangeSet<Y>` when `X` is a subtype of - `Y`.) - */ - update(updateSpec) { - let { add = [], sort = false, filterFrom = 0, filterTo = this.length } = updateSpec; - let filter = updateSpec.filter; - if (add.length == 0 && !filter) - return this; - if (sort) - add = add.slice().sort(cmpRange); - if (this.isEmpty) - return add.length ? RangeSet.of(add) : this; - let cur = new LayerCursor(this, null, -1).goto(0), i = 0, spill = []; - let builder = new RangeSetBuilder(); - while (cur.value || i < add.length) { - if (i < add.length && (cur.from - add[i].from || cur.startSide - add[i].value.startSide) >= 0) { - let range = add[i++]; - if (!builder.addInner(range.from, range.to, range.value)) - spill.push(range); - } - else if (cur.rangeIndex == 1 && cur.chunkIndex < this.chunk.length && - (i == add.length || this.chunkEnd(cur.chunkIndex) < add[i].from) && - (!filter || filterFrom > this.chunkEnd(cur.chunkIndex) || filterTo < this.chunkPos[cur.chunkIndex]) && - builder.addChunk(this.chunkPos[cur.chunkIndex], this.chunk[cur.chunkIndex])) { - cur.nextChunk(); - } - else { - if (!filter || filterFrom > cur.to || filterTo < cur.from || filter(cur.from, cur.to, cur.value)) { - if (!builder.addInner(cur.from, cur.to, cur.value)) - spill.push(new Range$1(cur.from, cur.to, cur.value)); - } - cur.next(); - } - } - return builder.finishInner(this.nextLayer.isEmpty && !spill.length ? RangeSet.empty - : this.nextLayer.update({ add: spill, filter, filterFrom, filterTo })); - } - /** - Map this range set through a set of changes, return the new set. - */ - map(changes) { - if (changes.empty || this.isEmpty) - return this; - let chunks = [], chunkPos = [], maxPoint = -1; - for (let i = 0; i < this.chunk.length; i++) { - let start = this.chunkPos[i], chunk = this.chunk[i]; - let touch = changes.touchesRange(start, start + chunk.length); - if (touch === false) { - maxPoint = Math.max(maxPoint, chunk.maxPoint); - chunks.push(chunk); - chunkPos.push(changes.mapPos(start)); - } - else if (touch === true) { - let { mapped, pos } = chunk.map(start, changes); - if (mapped) { - maxPoint = Math.max(maxPoint, mapped.maxPoint); - chunks.push(mapped); - chunkPos.push(pos); - } - } - } - let next = this.nextLayer.map(changes); - return chunks.length == 0 ? next : new RangeSet(chunkPos, chunks, next, maxPoint); - } - /** - Iterate over the ranges that touch the region `from` to `to`, - calling `f` for each. There is no guarantee that the ranges will - be reported in any specific order. When the callback returns - `false`, iteration stops. - */ - between(from, to, f) { - if (this.isEmpty) - return; - for (let i = 0; i < this.chunk.length; i++) { - let start = this.chunkPos[i], chunk = this.chunk[i]; - if (to >= start && from <= start + chunk.length && - chunk.between(start, from - start, to - start, f) === false) - return; - } - this.nextLayer.between(from, to, f); - } - /** - Iterate over the ranges in this set, in order, including all - ranges that end at or after `from`. - */ - iter(from = 0) { - return HeapCursor.from([this]).goto(from); - } - /** - @internal - */ - get isEmpty() { return this.nextLayer == this; } - /** - Iterate over the ranges in a collection of sets, in order, - starting from `from`. - */ - static iter(sets, from = 0) { - return HeapCursor.from(sets).goto(from); - } - /** - Iterate over two groups of sets, calling methods on `comparator` - to notify it of possible differences. - */ - static compare(oldSets, newSets, - /** - This indicates how the underlying data changed between these - ranges, and is needed to synchronize the iteration. `from` and - `to` are coordinates in the _new_ space, after these changes. - */ - textDiff, comparator, - /** - Can be used to ignore all non-point ranges, and points below - the given size. When -1, all ranges are compared. - */ - minPointSize = -1) { - let a = oldSets.filter(set => set.maxPoint > 0 || !set.isEmpty && set.maxPoint >= minPointSize); - let b = newSets.filter(set => set.maxPoint > 0 || !set.isEmpty && set.maxPoint >= minPointSize); - let sharedChunks = findSharedChunks(a, b, textDiff); - let sideA = new SpanCursor(a, sharedChunks, minPointSize); - let sideB = new SpanCursor(b, sharedChunks, minPointSize); - textDiff.iterGaps((fromA, fromB, length) => compare(sideA, fromA, sideB, fromB, length, comparator)); - if (textDiff.empty && textDiff.length == 0) - compare(sideA, 0, sideB, 0, 0, comparator); - } - /** - Compare the contents of two groups of range sets, returning true - if they are equivalent in the given range. - */ - static eq(oldSets, newSets, from = 0, to) { - if (to == null) - to = 1000000000 /* Far */; - let a = oldSets.filter(set => !set.isEmpty && newSets.indexOf(set) < 0); - let b = newSets.filter(set => !set.isEmpty && oldSets.indexOf(set) < 0); - if (a.length != b.length) - return false; - if (!a.length) - return true; - let sharedChunks = findSharedChunks(a, b); - let sideA = new SpanCursor(a, sharedChunks, 0).goto(from), sideB = new SpanCursor(b, sharedChunks, 0).goto(from); - for (;;) { - if (sideA.to != sideB.to || - !sameValues(sideA.active, sideB.active) || - sideA.point && (!sideB.point || !sideA.point.eq(sideB.point))) - return false; - if (sideA.to > to) - return true; - sideA.next(); - sideB.next(); - } - } - /** - Iterate over a group of range sets at the same time, notifying - the iterator about the ranges covering every given piece of - content. Returns the open count (see - [`SpanIterator.span`](https://codemirror.net/6/docs/ref/#rangeset.SpanIterator.span)) at the end - of the iteration. - */ - static spans(sets, from, to, iterator, - /** - When given and greater than -1, only points of at least this - size are taken into account. - */ - minPointSize = -1) { - var _a; - let cursor = new SpanCursor(sets, null, minPointSize, (_a = iterator.filterPoint) === null || _a === void 0 ? void 0 : _a.bind(iterator)).goto(from), pos = from; - let open = cursor.openStart; - for (;;) { - let curTo = Math.min(cursor.to, to); - if (cursor.point) { - iterator.point(pos, curTo, cursor.point, cursor.activeForPoint(cursor.to), open); - open = cursor.openEnd(curTo) + (cursor.to > curTo ? 1 : 0); - } - else if (curTo > pos) { - iterator.span(pos, curTo, cursor.active, open); - open = cursor.openEnd(curTo); - } - if (cursor.to > to) - break; - pos = cursor.to; - cursor.next(); - } - return open; - } - /** - Create a range set for the given range or array of ranges. By - default, this expects the ranges to be _sorted_ (by start - position and, if two start at the same position, - `value.startSide`). You can pass `true` as second argument to - cause the method to sort them. - */ - static of(ranges, sort = false) { - let build = new RangeSetBuilder(); - for (let range of ranges instanceof Range$1 ? [ranges] : sort ? lazySort(ranges) : ranges) - build.add(range.from, range.to, range.value); - return build.finish(); - } - } - /** - The empty set of ranges. - */ - RangeSet.empty = /*@__PURE__*/new RangeSet([], [], null, -1); - function lazySort(ranges) { - if (ranges.length > 1) - for (let prev = ranges[0], i = 1; i < ranges.length; i++) { - let cur = ranges[i]; - if (cmpRange(prev, cur) > 0) - return ranges.slice().sort(cmpRange); - prev = cur; - } - return ranges; - } - RangeSet.empty.nextLayer = RangeSet.empty; - /** - A range set builder is a data structure that helps build up a - [range set](https://codemirror.net/6/docs/ref/#rangeset.RangeSet) directly, without first allocating - an array of [`Range`](https://codemirror.net/6/docs/ref/#rangeset.Range) objects. - */ - class RangeSetBuilder { - /** - Create an empty builder. - */ - constructor() { - this.chunks = []; - this.chunkPos = []; - this.chunkStart = -1; - this.last = null; - this.lastFrom = -1000000000 /* Far */; - this.lastTo = -1000000000 /* Far */; - this.from = []; - this.to = []; - this.value = []; - this.maxPoint = -1; - this.setMaxPoint = -1; - this.nextLayer = null; - } - finishChunk(newArrays) { - this.chunks.push(new Chunk(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; - if (newArrays) { - this.from = []; - this.to = []; - this.value = []; - } - } - /** - Add a range. Ranges should be added in sorted (by `from` and - `value.startSide`) order. - */ - add(from, to, value) { - if (!this.addInner(from, to, value)) - (this.nextLayer || (this.nextLayer = new RangeSetBuilder)).add(from, to, value); - } - /** - @internal - */ - addInner(from, to, value) { - let diff = from - this.lastTo || value.startSide - this.last.endSide; - if (diff <= 0 && (from - this.lastFrom || value.startSide - this.last.startSide) < 0) - throw new Error("Ranges must be added sorted by `from` position and `startSide`"); - if (diff < 0) - return false; - if (this.from.length == 250 /* ChunkSize */) - this.finishChunk(true); - if (this.chunkStart < 0) - this.chunkStart = from; - this.from.push(from - this.chunkStart); - this.to.push(to - this.chunkStart); - this.last = value; - this.lastFrom = from; - this.lastTo = to; - this.value.push(value); - if (value.point) - this.maxPoint = Math.max(this.maxPoint, to - from); - return true; - } - /** - @internal - */ - addChunk(from, chunk) { - if ((from - this.lastTo || chunk.value[0].startSide - this.last.endSide) < 0) - return false; - if (this.from.length) - this.finishChunk(true); - this.setMaxPoint = Math.max(this.setMaxPoint, chunk.maxPoint); - this.chunks.push(chunk); - this.chunkPos.push(from); - let last = chunk.value.length - 1; - this.last = chunk.value[last]; - this.lastFrom = chunk.from[last] + from; - this.lastTo = chunk.to[last] + from; - return true; - } - /** - Finish the range set. Returns the new set. The builder can't be - used anymore after this has been called. - */ - finish() { return this.finishInner(RangeSet.empty); } - /** - @internal - */ - finishInner(next) { - if (this.from.length) - this.finishChunk(false); - if (this.chunks.length == 0) - return next; - let result = new RangeSet(this.chunkPos, this.chunks, this.nextLayer ? this.nextLayer.finishInner(next) : next, this.setMaxPoint); - this.from = null; // Make sure further `add` calls produce errors - return result; - } - } - function findSharedChunks(a, b, textDiff) { - let inA = new Map(); - for (let set of a) - for (let i = 0; i < set.chunk.length; i++) - if (set.chunk[i].maxPoint <= 0) - inA.set(set.chunk[i], set.chunkPos[i]); - let shared = new Set(); - for (let set of b) - for (let i = 0; i < set.chunk.length; i++) { - let known = inA.get(set.chunk[i]); - if (known != null && (textDiff ? textDiff.mapPos(known) : known) == set.chunkPos[i] && - !(textDiff === null || textDiff === void 0 ? void 0 : textDiff.touchesRange(known, known + set.chunk[i].length))) - shared.add(set.chunk[i]); - } - return shared; - } - class LayerCursor { - constructor(layer, skip, minPoint, rank = 0) { - this.layer = layer; - this.skip = skip; - this.minPoint = minPoint; - this.rank = rank; - } - get startSide() { return this.value ? this.value.startSide : 0; } - get endSide() { return this.value ? this.value.endSide : 0; } - goto(pos, side = -1000000000 /* Far */) { - this.chunkIndex = this.rangeIndex = 0; - this.gotoInner(pos, side, false); - return this; - } - gotoInner(pos, side, forward) { - while (this.chunkIndex < this.layer.chunk.length) { - let next = this.layer.chunk[this.chunkIndex]; - if (!(this.skip && this.skip.has(next) || - this.layer.chunkEnd(this.chunkIndex) < pos || - next.maxPoint < this.minPoint)) - break; - this.chunkIndex++; - forward = false; - } - if (this.chunkIndex < this.layer.chunk.length) { - let rangeIndex = this.layer.chunk[this.chunkIndex].findIndex(pos - this.layer.chunkPos[this.chunkIndex], side, true); - if (!forward || this.rangeIndex < rangeIndex) - this.setRangeIndex(rangeIndex); - } - this.next(); - } - forward(pos, side) { - if ((this.to - pos || this.endSide - side) < 0) - this.gotoInner(pos, side, true); - } - next() { - for (;;) { - if (this.chunkIndex == this.layer.chunk.length) { - this.from = this.to = 1000000000 /* Far */; - this.value = null; - break; - } - else { - let chunkPos = this.layer.chunkPos[this.chunkIndex], chunk = this.layer.chunk[this.chunkIndex]; - let from = chunkPos + chunk.from[this.rangeIndex]; - this.from = from; - this.to = chunkPos + chunk.to[this.rangeIndex]; - this.value = chunk.value[this.rangeIndex]; - this.setRangeIndex(this.rangeIndex + 1); - if (this.minPoint < 0 || this.value.point && this.to - this.from >= this.minPoint) - break; - } - } - } - setRangeIndex(index) { - if (index == this.layer.chunk[this.chunkIndex].value.length) { - this.chunkIndex++; - if (this.skip) { - while (this.chunkIndex < this.layer.chunk.length && this.skip.has(this.layer.chunk[this.chunkIndex])) - this.chunkIndex++; - } - this.rangeIndex = 0; - } - else { - this.rangeIndex = index; - } - } - nextChunk() { - this.chunkIndex++; - this.rangeIndex = 0; - this.next(); - } - compare(other) { - return this.from - other.from || this.startSide - other.startSide || this.rank - other.rank || - this.to - other.to || this.endSide - other.endSide; - } - } - class HeapCursor { - constructor(heap) { - this.heap = heap; - } - static from(sets, skip = null, minPoint = -1) { - let heap = []; - for (let i = 0; i < sets.length; i++) { - for (let cur = sets[i]; !cur.isEmpty; cur = cur.nextLayer) { - if (cur.maxPoint >= minPoint) - heap.push(new LayerCursor(cur, skip, minPoint, i)); - } - } - return heap.length == 1 ? heap[0] : new HeapCursor(heap); - } - get startSide() { return this.value ? this.value.startSide : 0; } - goto(pos, side = -1000000000 /* Far */) { - for (let cur of this.heap) - cur.goto(pos, side); - for (let i = this.heap.length >> 1; i >= 0; i--) - heapBubble(this.heap, i); - this.next(); - return this; - } - forward(pos, side) { - for (let cur of this.heap) - cur.forward(pos, side); - for (let i = this.heap.length >> 1; i >= 0; i--) - heapBubble(this.heap, i); - if ((this.to - pos || this.value.endSide - side) < 0) - this.next(); - } - next() { - if (this.heap.length == 0) { - this.from = this.to = 1000000000 /* Far */; - this.value = null; - this.rank = -1; - } - else { - let top = this.heap[0]; - this.from = top.from; - this.to = top.to; - this.value = top.value; - this.rank = top.rank; - if (top.value) - top.next(); - heapBubble(this.heap, 0); - } - } - } - function heapBubble(heap, index) { - for (let cur = heap[index];;) { - let childIndex = (index << 1) + 1; - if (childIndex >= heap.length) - break; - let child = heap[childIndex]; - if (childIndex + 1 < heap.length && child.compare(heap[childIndex + 1]) >= 0) { - child = heap[childIndex + 1]; - childIndex++; - } - if (cur.compare(child) < 0) - break; - heap[childIndex] = cur; - heap[index] = child; - index = childIndex; - } - } - class SpanCursor { - constructor(sets, skip, minPoint, filterPoint = () => true) { - this.minPoint = minPoint; - this.filterPoint = filterPoint; - this.active = []; - this.activeTo = []; - this.activeRank = []; - this.minActive = -1; - // A currently active point range, if any - this.point = null; - this.pointFrom = 0; - this.pointRank = 0; - this.to = -1000000000 /* Far */; - this.endSide = 0; - this.openStart = -1; - this.cursor = HeapCursor.from(sets, skip, minPoint); - } - goto(pos, side = -1000000000 /* Far */) { - this.cursor.goto(pos, side); - this.active.length = this.activeTo.length = this.activeRank.length = 0; - this.minActive = -1; - this.to = pos; - this.endSide = side; - this.openStart = -1; - this.next(); - return this; - } - forward(pos, side) { - while (this.minActive > -1 && (this.activeTo[this.minActive] - pos || this.active[this.minActive].endSide - side) < 0) - this.removeActive(this.minActive); - this.cursor.forward(pos, side); - } - removeActive(index) { - remove(this.active, index); - remove(this.activeTo, index); - remove(this.activeRank, index); - this.minActive = findMinIndex(this.active, this.activeTo); - } - addActive(trackOpen) { - let i = 0, { value, to, rank } = this.cursor; - while (i < this.activeRank.length && this.activeRank[i] <= rank) - i++; - insert(this.active, i, value); - insert(this.activeTo, i, to); - insert(this.activeRank, i, rank); - if (trackOpen) - insert(trackOpen, i, this.cursor.from); - this.minActive = findMinIndex(this.active, this.activeTo); - } - // After calling this, if `this.point` != null, the next range is a - // point. Otherwise, it's a regular range, covered by `this.active`. - next() { - let from = this.to, wasPoint = this.point; - this.point = null; - let trackOpen = this.openStart < 0 ? [] : null, trackExtra = 0; - for (;;) { - let a = this.minActive; - if (a > -1 && (this.activeTo[a] - this.cursor.from || this.active[a].endSide - this.cursor.startSide) < 0) { - if (this.activeTo[a] > from) { - this.to = this.activeTo[a]; - this.endSide = this.active[a].endSide; - break; - } - this.removeActive(a); - if (trackOpen) - remove(trackOpen, a); - } - else if (!this.cursor.value) { - this.to = this.endSide = 1000000000 /* Far */; - break; - } - else if (this.cursor.from > from) { - this.to = this.cursor.from; - this.endSide = this.cursor.startSide; - break; - } - else { - let nextVal = this.cursor.value; - if (!nextVal.point) { // Opening a range - this.addActive(trackOpen); - this.cursor.next(); - } - else if (wasPoint && this.cursor.to == this.to && this.cursor.from < this.cursor.to) { - // Ignore any non-empty points that end precisely at the end of the prev point - this.cursor.next(); - } - else if (!this.filterPoint(this.cursor.from, this.cursor.to, this.cursor.value, this.cursor.rank)) { - this.cursor.next(); - } - else { // New point - this.point = nextVal; - this.pointFrom = this.cursor.from; - this.pointRank = this.cursor.rank; - this.to = this.cursor.to; - this.endSide = nextVal.endSide; - if (this.cursor.from < from) - trackExtra = 1; - this.cursor.next(); - this.forward(this.to, this.endSide); - break; - } - } - } - if (trackOpen) { - let openStart = 0; - while (openStart < trackOpen.length && trackOpen[openStart] < from) - openStart++; - this.openStart = openStart + trackExtra; - } - } - activeForPoint(to) { - if (!this.active.length) - return this.active; - let active = []; - for (let i = this.active.length - 1; i >= 0; i--) { - if (this.activeRank[i] < this.pointRank) - break; - if (this.activeTo[i] > to || this.activeTo[i] == to && this.active[i].endSide >= this.point.endSide) - active.push(this.active[i]); - } - return active.reverse(); - } - openEnd(to) { - let open = 0; - for (let i = this.activeTo.length - 1; i >= 0 && this.activeTo[i] > to; i--) - open++; - return open; - } - } - function compare(a, startA, b, startB, length, comparator) { - a.goto(startA); - b.goto(startB); - let endB = startB + length; - let pos = startB, dPos = startB - startA; - for (;;) { - let diff = (a.to + dPos) - b.to || a.endSide - b.endSide; - let end = diff < 0 ? a.to + dPos : b.to, clipEnd = Math.min(end, endB); - if (a.point || b.point) { - if (!(a.point && b.point && (a.point == b.point || a.point.eq(b.point)) && - sameValues(a.activeForPoint(a.to + dPos), b.activeForPoint(b.to)))) - comparator.comparePoint(pos, clipEnd, a.point, b.point); - } - else { - if (clipEnd > pos && !sameValues(a.active, b.active)) - comparator.compareRange(pos, clipEnd, a.active, b.active); - } - if (end > endB) - break; - pos = end; - if (diff <= 0) - a.next(); - if (diff >= 0) - b.next(); - } - } - function sameValues(a, b) { - if (a.length != b.length) - return false; - for (let i = 0; i < a.length; i++) - if (a[i] != b[i] && !a[i].eq(b[i])) - return false; - return true; - } - function remove(array, index) { - for (let i = index, e = array.length - 1; i < e; i++) - array[i] = array[i + 1]; - array.pop(); - } - function insert(array, index, value) { - for (let i = array.length - 1; i >= index; i--) - array[i + 1] = array[i]; - array[index] = value; - } - function findMinIndex(value, array) { - let found = -1, foundPos = 1000000000 /* Far */; - for (let i = 0; i < array.length; i++) - if ((array[i] - foundPos || value[i].endSide - value[found].endSide) < 0) { - found = i; - foundPos = array[i]; - } - return found; - } - - var base = { - 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: "'" - }; - - var shift = { - 48: ")", - 49: "!", - 50: "@", - 51: "#", - 52: "$", - 53: "%", - 54: "^", - 55: "&", - 56: "*", - 57: "(", - 59: ":", - 61: "+", - 173: "_", - 186: ":", - 187: "+", - 188: "<", - 189: "_", - 190: ">", - 191: "?", - 192: "~", - 219: "{", - 220: "|", - 221: "}", - 222: "\"" - }; - - var chrome$1 = typeof navigator != "undefined" && /Chrome\/(\d+)/.exec(navigator.userAgent); - typeof navigator != "undefined" && /Gecko\/\d+/.test(navigator.userAgent); - var mac = typeof navigator != "undefined" && /Mac/.test(navigator.platform); - var ie$1 = typeof navigator != "undefined" && /MSIE \d|Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(navigator.userAgent); - var brokenModifierNames = mac || chrome$1 && +chrome$1[1] < 57; - - // Fill in the digit keys - for (var i = 0; i < 10; i++) base[48 + i] = base[96 + i] = String(i); - - // The function keys - for (var i = 1; i <= 24; i++) base[i + 111] = "F" + i; - - // And the alphabetic keys - for (var i = 65; i <= 90; i++) { - base[i] = String.fromCharCode(i + 32); - shift[i] = String.fromCharCode(i); - } - - // For each code that doesn't have a shift-equivalent, copy the base name - for (var code in base) if (!shift.hasOwnProperty(code)) shift[code] = base[code]; - - function keyName(event) { - var ignoreKey = brokenModifierNames && (event.ctrlKey || event.altKey || event.metaKey) || - ie$1 && event.shiftKey && event.key && event.key.length == 1 || - event.key == "Unidentified"; - var name = (!ignoreKey && event.key) || - (event.shiftKey ? shift : base)[event.keyCode] || - event.key || "Unidentified"; - // Edge sometimes produces wrong names (Issue #3) - if (name == "Esc") name = "Escape"; - if (name == "Del") name = "Delete"; - // https://developer.microsoft.com/en-us/microsoft-edge/platform/issues/8860571/ - if (name == "Left") name = "ArrowLeft"; - if (name == "Up") name = "ArrowUp"; - if (name == "Right") name = "ArrowRight"; - if (name == "Down") name = "ArrowDown"; - return name - } - - function getSelection(root) { - let target; - // Browsers differ on whether shadow roots have a getSelection - // method. If it exists, use that, otherwise, call it on the - // document. - if (root.nodeType == 11) { // Shadow root - target = root.getSelection ? root : root.ownerDocument; - } - else { - target = root; - } - return target.getSelection(); - } - function contains(dom, node) { - return node ? dom == node || dom.contains(node.nodeType != 1 ? node.parentNode : node) : false; - } - function deepActiveElement() { - let elt = document.activeElement; - while (elt && elt.shadowRoot) - elt = elt.shadowRoot.activeElement; - return elt; - } - function hasSelection(dom, selection) { - if (!selection.anchorNode) - return false; - try { - // Firefox will raise 'permission denied' errors when accessing - // properties of `sel.anchorNode` when it's in a generated CSS - // element. - return contains(dom, selection.anchorNode); - } - catch (_) { - return false; - } - } - function clientRectsFor(dom) { - if (dom.nodeType == 3) - return textRange(dom, 0, dom.nodeValue.length).getClientRects(); - else if (dom.nodeType == 1) - return dom.getClientRects(); - else - return []; - } - // Scans forward and backward through DOM positions equivalent to the - // given one to see if the two are in the same place (i.e. after a - // text node vs at the end of that text node) - function isEquivalentPosition(node, off, targetNode, targetOff) { - return targetNode ? (scanFor(node, off, targetNode, targetOff, -1) || - scanFor(node, off, targetNode, targetOff, 1)) : false; - } - function domIndex(node) { - for (var index = 0;; index++) { - node = node.previousSibling; - if (!node) - return index; - } - } - function scanFor(node, off, targetNode, targetOff, dir) { - for (;;) { - if (node == targetNode && off == targetOff) - return true; - if (off == (dir < 0 ? 0 : maxOffset(node))) { - if (node.nodeName == "DIV") - return false; - let parent = node.parentNode; - if (!parent || parent.nodeType != 1) - return false; - off = domIndex(node) + (dir < 0 ? 0 : 1); - node = parent; - } - else if (node.nodeType == 1) { - node = node.childNodes[off + (dir < 0 ? -1 : 0)]; - if (node.nodeType == 1 && node.contentEditable == "false") - return false; - off = dir < 0 ? maxOffset(node) : 0; - } - else { - return false; - } - } - } - function maxOffset(node) { - return node.nodeType == 3 ? node.nodeValue.length : node.childNodes.length; - } - const Rect0 = { left: 0, right: 0, top: 0, bottom: 0 }; - function flattenRect(rect, left) { - let x = left ? rect.left : rect.right; - return { left: x, right: x, top: rect.top, bottom: rect.bottom }; - } - function windowRect(win) { - return { left: 0, right: win.innerWidth, - top: 0, bottom: win.innerHeight }; - } - function scrollRectIntoView(dom, rect, side, x, y, xMargin, yMargin, ltr) { - let doc = dom.ownerDocument, win = doc.defaultView; - for (let cur = dom; cur;) { - if (cur.nodeType == 1) { // Element - let bounding, top = cur == doc.body; - if (top) { - bounding = windowRect(win); - } - else { - if (cur.scrollHeight <= cur.clientHeight && cur.scrollWidth <= cur.clientWidth) { - cur = cur.parentNode; - continue; - } - let rect = cur.getBoundingClientRect(); - // Make sure scrollbar width isn't included in the rectangle - bounding = { left: rect.left, right: rect.left + cur.clientWidth, - top: rect.top, bottom: rect.top + cur.clientHeight }; - } - let moveX = 0, moveY = 0; - if (y == "nearest") { - if (rect.top < bounding.top) { - moveY = -(bounding.top - rect.top + yMargin); - if (side > 0 && rect.bottom > bounding.bottom + moveY) - moveY = rect.bottom - bounding.bottom + moveY + yMargin; - } - else if (rect.bottom > bounding.bottom) { - moveY = rect.bottom - bounding.bottom + yMargin; - if (side < 0 && (rect.top - moveY) < bounding.top) - moveY = -(bounding.top + moveY - rect.top + yMargin); - } - } - else { - let rectHeight = rect.bottom - rect.top, boundingHeight = bounding.bottom - bounding.top; - let targetTop = y == "center" && rectHeight <= boundingHeight ? rect.top + rectHeight / 2 - boundingHeight / 2 : - y == "start" || y == "center" && side < 0 ? rect.top - yMargin : - rect.bottom - boundingHeight + yMargin; - moveY = targetTop - bounding.top; - } - if (x == "nearest") { - if (rect.left < bounding.left) { - moveX = -(bounding.left - rect.left + xMargin); - if (side > 0 && rect.right > bounding.right + moveX) - moveX = rect.right - bounding.right + moveX + xMargin; - } - else if (rect.right > bounding.right) { - moveX = rect.right - bounding.right + xMargin; - if (side < 0 && rect.left < bounding.left + moveX) - moveX = -(bounding.left + moveX - rect.left + xMargin); - } - } - else { - let targetLeft = x == "center" ? rect.left + (rect.right - rect.left) / 2 - (bounding.right - bounding.left) / 2 : - (x == "start") == ltr ? rect.left - xMargin : - rect.right - (bounding.right - bounding.left) + xMargin; - moveX = targetLeft - bounding.left; - } - if (moveX || moveY) { - if (top) { - win.scrollBy(moveX, moveY); - } - else { - if (moveY) { - let start = cur.scrollTop; - cur.scrollTop += moveY; - moveY = cur.scrollTop - start; - } - if (moveX) { - let start = cur.scrollLeft; - cur.scrollLeft += moveX; - moveX = cur.scrollLeft - start; - } - rect = { left: rect.left - moveX, top: rect.top - moveY, - right: rect.right - moveX, bottom: rect.bottom - moveY }; - } - } - if (top) - break; - cur = cur.assignedSlot || cur.parentNode; - x = y = "nearest"; - } - else if (cur.nodeType == 11) { // A shadow root - cur = cur.host; - } - else { - break; - } - } - } - class DOMSelectionState { - constructor() { - this.anchorNode = null; - this.anchorOffset = 0; - this.focusNode = null; - this.focusOffset = 0; - } - eq(domSel) { - return this.anchorNode == domSel.anchorNode && this.anchorOffset == domSel.anchorOffset && - this.focusNode == domSel.focusNode && this.focusOffset == domSel.focusOffset; - } - setRange(range) { - this.set(range.anchorNode, range.anchorOffset, range.focusNode, range.focusOffset); - } - set(anchorNode, anchorOffset, focusNode, focusOffset) { - this.anchorNode = anchorNode; - this.anchorOffset = anchorOffset; - this.focusNode = focusNode; - this.focusOffset = focusOffset; - } - } - let preventScrollSupported = null; - // Feature-detects support for .focus({preventScroll: true}), and uses - // a fallback kludge when not supported. - function focusPreventScroll(dom) { - if (dom.setActive) - return dom.setActive(); // in IE - if (preventScrollSupported) - return dom.focus(preventScrollSupported); - let stack = []; - for (let cur = dom; cur; cur = cur.parentNode) { - stack.push(cur, cur.scrollTop, cur.scrollLeft); - if (cur == cur.ownerDocument) - break; - } - dom.focus(preventScrollSupported == null ? { - get preventScroll() { - preventScrollSupported = { preventScroll: true }; - return true; - } - } : undefined); - if (!preventScrollSupported) { - preventScrollSupported = false; - for (let i = 0; i < stack.length;) { - let elt = stack[i++], top = stack[i++], left = stack[i++]; - if (elt.scrollTop != top) - elt.scrollTop = top; - if (elt.scrollLeft != left) - elt.scrollLeft = left; - } - } - } - let scratchRange; - function textRange(node, from, to = from) { - let range = scratchRange || (scratchRange = document.createRange()); - range.setEnd(node, to); - range.setStart(node, from); - return range; - } - function dispatchKey(elt, name, code) { - let options = { key: name, code: name, keyCode: code, which: code, cancelable: true }; - let down = new KeyboardEvent("keydown", options); - down.synthetic = true; - elt.dispatchEvent(down); - let up = new KeyboardEvent("keyup", options); - up.synthetic = true; - elt.dispatchEvent(up); - return down.defaultPrevented || up.defaultPrevented; - } - function getRoot(node) { - while (node) { - if (node && (node.nodeType == 9 || node.nodeType == 11 && node.host)) - return node; - node = node.assignedSlot || node.parentNode; - } - return null; - } - function clearAttributes(node) { - while (node.attributes.length) - node.removeAttributeNode(node.attributes[0]); - } - - class DOMPos { - constructor(node, offset, precise = true) { - this.node = node; - this.offset = offset; - this.precise = precise; - } - static before(dom, precise) { return new DOMPos(dom.parentNode, domIndex(dom), precise); } - static after(dom, precise) { return new DOMPos(dom.parentNode, domIndex(dom) + 1, precise); } - } - const noChildren = []; - class ContentView { - constructor() { - this.parent = null; - this.dom = null; - this.dirty = 2 /* Node */; - } - get editorView() { - if (!this.parent) - throw new Error("Accessing view in orphan content view"); - return this.parent.editorView; - } - get overrideDOMText() { return null; } - get posAtStart() { - return this.parent ? this.parent.posBefore(this) : 0; - } - get posAtEnd() { - return this.posAtStart + this.length; - } - posBefore(view) { - let pos = this.posAtStart; - for (let child of this.children) { - if (child == view) - return pos; - pos += child.length + child.breakAfter; - } - throw new RangeError("Invalid child in posBefore"); - } - posAfter(view) { - return this.posBefore(view) + view.length; - } - // Will return a rectangle directly before (when side < 0), after - // (side > 0) or directly on (when the browser supports it) the - // given position. - coordsAt(_pos, _side) { return null; } - sync(track) { - if (this.dirty & 2 /* Node */) { - let parent = this.dom; - let prev = null, next; - for (let child of this.children) { - if (child.dirty) { - if (!child.dom && (next = prev ? prev.nextSibling : parent.firstChild)) { - let contentView = ContentView.get(next); - if (!contentView || !contentView.parent && contentView.constructor == child.constructor) - child.reuseDOM(next); - } - child.sync(track); - child.dirty = 0 /* Not */; - } - next = prev ? prev.nextSibling : parent.firstChild; - if (track && !track.written && track.node == parent && next != child.dom) - track.written = true; - if (child.dom.parentNode == parent) { - while (next && next != child.dom) - next = rm$1(next); - } - else { - parent.insertBefore(child.dom, next); - } - prev = child.dom; - } - next = prev ? prev.nextSibling : parent.firstChild; - if (next && track && track.node == parent) - track.written = true; - while (next) - next = rm$1(next); - } - else if (this.dirty & 1 /* Child */) { - for (let child of this.children) - if (child.dirty) { - child.sync(track); - child.dirty = 0 /* Not */; - } - } - } - reuseDOM(_dom) { } - localPosFromDOM(node, offset) { - let after; - if (node == this.dom) { - after = this.dom.childNodes[offset]; - } - else { - let bias = maxOffset(node) == 0 ? 0 : offset == 0 ? -1 : 1; - for (;;) { - let parent = node.parentNode; - if (parent == this.dom) - break; - if (bias == 0 && parent.firstChild != parent.lastChild) { - if (node == parent.firstChild) - bias = -1; - else - bias = 1; - } - node = parent; - } - if (bias < 0) - after = node; - else - after = node.nextSibling; - } - if (after == this.dom.firstChild) - return 0; - while (after && !ContentView.get(after)) - after = after.nextSibling; - if (!after) - return this.length; - for (let i = 0, pos = 0;; i++) { - let child = this.children[i]; - if (child.dom == after) - return pos; - pos += child.length + child.breakAfter; - } - } - domBoundsAround(from, to, offset = 0) { - let fromI = -1, fromStart = -1, toI = -1, toEnd = -1; - for (let i = 0, pos = offset, prevEnd = offset; i < this.children.length; i++) { - let child = this.children[i], end = pos + child.length; - if (pos < from && end > to) - return child.domBoundsAround(from, to, pos); - if (end >= from && fromI == -1) { - fromI = i; - fromStart = pos; - } - if (pos > to && child.dom.parentNode == this.dom) { - toI = i; - toEnd = prevEnd; - break; - } - prevEnd = end; - pos = end + child.breakAfter; - } - return { from: fromStart, to: toEnd < 0 ? offset + this.length : toEnd, - startDOM: (fromI ? this.children[fromI - 1].dom.nextSibling : null) || this.dom.firstChild, - endDOM: toI < this.children.length && toI >= 0 ? this.children[toI].dom : null }; - } - markDirty(andParent = false) { - this.dirty |= 2 /* Node */; - this.markParentsDirty(andParent); - } - markParentsDirty(childList) { - for (let parent = this.parent; parent; parent = parent.parent) { - if (childList) - parent.dirty |= 2 /* Node */; - if (parent.dirty & 1 /* Child */) - return; - parent.dirty |= 1 /* Child */; - childList = false; - } - } - setParent(parent) { - if (this.parent != parent) { - this.parent = parent; - if (this.dirty) - this.markParentsDirty(true); - } - } - setDOM(dom) { - if (this.dom) - this.dom.cmView = null; - this.dom = dom; - dom.cmView = this; - } - get rootView() { - for (let v = this;;) { - let parent = v.parent; - if (!parent) - return v; - v = parent; - } - } - replaceChildren(from, to, children = noChildren) { - this.markDirty(); - for (let i = from; i < to; i++) { - let child = this.children[i]; - if (child.parent == this) - child.destroy(); - } - this.children.splice(from, to - from, ...children); - for (let i = 0; i < children.length; i++) - children[i].setParent(this); - } - ignoreMutation(_rec) { return false; } - ignoreEvent(_event) { return false; } - childCursor(pos = this.length) { - return new ChildCursor(this.children, pos, this.children.length); - } - childPos(pos, bias = 1) { - return this.childCursor().findPos(pos, bias); - } - toString() { - let name = this.constructor.name.replace("View", ""); - return name + (this.children.length ? "(" + this.children.join() + ")" : - this.length ? "[" + (name == "Text" ? this.text : this.length) + "]" : "") + - (this.breakAfter ? "#" : ""); - } - static get(node) { return node.cmView; } - get isEditable() { return true; } - merge(from, to, source, hasStart, openStart, openEnd) { - return false; - } - become(other) { return false; } - // When this is a zero-length view with a side, this should return a - // number <= 0 to indicate it is before its position, or a - // number > 0 when after its position. - getSide() { return 0; } - destroy() { - this.parent = null; - } - } - ContentView.prototype.breakAfter = 0; - // Remove a DOM node and return its next sibling. - function rm$1(dom) { - let next = dom.nextSibling; - dom.parentNode.removeChild(dom); - return next; - } - class ChildCursor { - constructor(children, pos, i) { - this.children = children; - this.pos = pos; - this.i = i; - this.off = 0; - } - findPos(pos, bias = 1) { - for (;;) { - if (pos > this.pos || pos == this.pos && - (bias > 0 || this.i == 0 || this.children[this.i - 1].breakAfter)) { - this.off = pos - this.pos; - return this; - } - let next = this.children[--this.i]; - this.pos -= next.length + next.breakAfter; - } - } - } - function replaceRange(parent, fromI, fromOff, toI, toOff, insert, breakAtStart, openStart, openEnd) { - let { children } = parent; - let before = children.length ? children[fromI] : null; - let last = insert.length ? insert[insert.length - 1] : null; - let breakAtEnd = last ? last.breakAfter : breakAtStart; - // Change within a single child - if (fromI == toI && before && !breakAtStart && !breakAtEnd && insert.length < 2 && - before.merge(fromOff, toOff, insert.length ? last : null, fromOff == 0, openStart, openEnd)) - return; - if (toI < children.length) { - let after = children[toI]; - // Make sure the end of the child after the update is preserved in `after` - if (after && toOff < after.length) { - // If we're splitting a child, separate part of it to avoid that - // being mangled when updating the child before the update. - if (fromI == toI) { - after = after.split(toOff); - toOff = 0; - } - // If the element after the replacement should be merged with - // the last replacing element, update `content` - if (!breakAtEnd && last && after.merge(0, toOff, last, true, 0, openEnd)) { - insert[insert.length - 1] = after; - } - else { - // Remove the start of the after element, if necessary, and - // add it to `content`. - if (toOff) - after.merge(0, toOff, null, false, 0, openEnd); - insert.push(after); - } - } - else if (after === null || after === void 0 ? void 0 : after.breakAfter) { - // The element at `toI` is entirely covered by this range. - // Preserve its line break, if any. - if (last) - last.breakAfter = 1; - else - breakAtStart = 1; - } - // Since we've handled the next element from the current elements - // now, make sure `toI` points after that. - toI++; - } - if (before) { - before.breakAfter = breakAtStart; - if (fromOff > 0) { - if (!breakAtStart && insert.length && before.merge(fromOff, before.length, insert[0], false, openStart, 0)) { - before.breakAfter = insert.shift().breakAfter; - } - else if (fromOff < before.length || before.children.length && before.children[before.children.length - 1].length == 0) { - before.merge(fromOff, before.length, null, false, openStart, 0); - } - fromI++; - } - } - // Try to merge widgets on the boundaries of the replacement - while (fromI < toI && insert.length) { - if (children[toI - 1].become(insert[insert.length - 1])) { - toI--; - insert.pop(); - openEnd = insert.length ? 0 : openStart; - } - else if (children[fromI].become(insert[0])) { - fromI++; - insert.shift(); - openStart = insert.length ? 0 : openEnd; - } - else { - break; - } - } - if (!insert.length && fromI && toI < children.length && !children[fromI - 1].breakAfter && - children[toI].merge(0, 0, children[fromI - 1], false, openStart, openEnd)) - fromI--; - if (fromI < toI || insert.length) - parent.replaceChildren(fromI, toI, insert); - } - function mergeChildrenInto(parent, from, to, insert, openStart, openEnd) { - let cur = parent.childCursor(); - let { i: toI, off: toOff } = cur.findPos(to, 1); - let { i: fromI, off: fromOff } = cur.findPos(from, -1); - let dLen = from - to; - for (let view of insert) - dLen += view.length; - parent.length += dLen; - replaceRange(parent, fromI, fromOff, toI, toOff, insert, 0, openStart, openEnd); - } - - let nav = typeof navigator != "undefined" ? navigator : { userAgent: "", vendor: "", platform: "" }; - let doc = typeof document != "undefined" ? document : { documentElement: { style: {} } }; - const ie_edge = /*@__PURE__*//Edge\/(\d+)/.exec(nav.userAgent); - const ie_upto10 = /*@__PURE__*//MSIE \d/.test(nav.userAgent); - const ie_11up = /*@__PURE__*//Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(nav.userAgent); - const ie = !!(ie_upto10 || ie_11up || ie_edge); - const gecko = !ie && /*@__PURE__*//gecko\/(\d+)/i.test(nav.userAgent); - const chrome = !ie && /*@__PURE__*//Chrome\/(\d+)/.exec(nav.userAgent); - const webkit = "webkitFontSmoothing" in doc.documentElement.style; - const safari = !ie && /*@__PURE__*//Apple Computer/.test(nav.vendor); - const ios$1 = safari && (/*@__PURE__*//Mobile\/\w+/.test(nav.userAgent) || nav.maxTouchPoints > 2); - var browser = { - mac: ios$1 || /*@__PURE__*//Mac/.test(nav.platform), - windows: /*@__PURE__*//Win/.test(nav.platform), - linux: /*@__PURE__*//Linux|X11/.test(nav.platform), - ie, - ie_version: ie_upto10 ? doc.documentMode || 6 : ie_11up ? +ie_11up[1] : ie_edge ? +ie_edge[1] : 0, - gecko, - gecko_version: gecko ? +(/*@__PURE__*//Firefox\/(\d+)/.exec(nav.userAgent) || [0, 0])[1] : 0, - chrome: !!chrome, - chrome_version: chrome ? +chrome[1] : 0, - ios: ios$1, - android: /*@__PURE__*//Android\b/.test(nav.userAgent), - webkit, - safari, - webkit_version: webkit ? +(/*@__PURE__*//\bAppleWebKit\/(\d+)/.exec(navigator.userAgent) || [0, 0])[1] : 0, - tabSize: doc.documentElement.style.tabSize != null ? "tab-size" : "-moz-tab-size" - }; - - const MaxJoinLen = 256; - class TextView extends ContentView { - constructor(text) { - super(); - this.text = text; - } - get length() { return this.text.length; } - createDOM(textDOM) { - this.setDOM(textDOM || document.createTextNode(this.text)); - } - sync(track) { - if (!this.dom) - this.createDOM(); - if (this.dom.nodeValue != this.text) { - if (track && track.node == this.dom) - track.written = true; - this.dom.nodeValue = this.text; - } - } - reuseDOM(dom) { - if (dom.nodeType == 3) - this.createDOM(dom); - } - merge(from, to, source) { - if (source && (!(source instanceof TextView) || this.length - (to - from) + source.length > MaxJoinLen)) - return false; - this.text = this.text.slice(0, from) + (source ? source.text : "") + this.text.slice(to); - this.markDirty(); - return true; - } - split(from) { - let result = new TextView(this.text.slice(from)); - this.text = this.text.slice(0, from); - this.markDirty(); - return result; - } - localPosFromDOM(node, offset) { - return node == this.dom ? offset : offset ? this.text.length : 0; - } - domAtPos(pos) { return new DOMPos(this.dom, pos); } - domBoundsAround(_from, _to, offset) { - return { from: offset, to: offset + this.length, startDOM: this.dom, endDOM: this.dom.nextSibling }; - } - coordsAt(pos, side) { - return textCoords(this.dom, pos, side); - } - } - class MarkView extends ContentView { - constructor(mark, children = [], length = 0) { - super(); - this.mark = mark; - this.children = children; - this.length = length; - for (let ch of children) - ch.setParent(this); - } - setAttrs(dom) { - clearAttributes(dom); - if (this.mark.class) - dom.className = this.mark.class; - if (this.mark.attrs) - for (let name in this.mark.attrs) - dom.setAttribute(name, this.mark.attrs[name]); - return dom; - } - reuseDOM(node) { - if (node.nodeName == this.mark.tagName.toUpperCase()) { - this.setDOM(node); - this.dirty |= 4 /* Attrs */ | 2 /* Node */; - } - } - sync(track) { - if (!this.dom) - this.setDOM(this.setAttrs(document.createElement(this.mark.tagName))); - else if (this.dirty & 4 /* Attrs */) - this.setAttrs(this.dom); - super.sync(track); - } - merge(from, to, source, _hasStart, openStart, openEnd) { - if (source && (!(source instanceof MarkView && source.mark.eq(this.mark)) || - (from && openStart <= 0) || (to < this.length && openEnd <= 0))) - return false; - mergeChildrenInto(this, from, to, source ? source.children : [], openStart - 1, openEnd - 1); - this.markDirty(); - return true; - } - split(from) { - let result = [], off = 0, detachFrom = -1, i = 0; - for (let elt of this.children) { - let end = off + elt.length; - if (end > from) - result.push(off < from ? elt.split(from - off) : elt); - if (detachFrom < 0 && off >= from) - detachFrom = i; - off = end; - i++; - } - let length = this.length - from; - this.length = from; - if (detachFrom > -1) { - this.children.length = detachFrom; - this.markDirty(); - } - return new MarkView(this.mark, result, length); - } - domAtPos(pos) { - return inlineDOMAtPos(this.dom, this.children, pos); - } - coordsAt(pos, side) { - return coordsInChildren(this, pos, side); - } - } - function textCoords(text, pos, side) { - let length = text.nodeValue.length; - if (pos > length) - pos = length; - let from = pos, to = pos, flatten = 0; - if (pos == 0 && side < 0 || pos == length && side >= 0) { - if (!(browser.chrome || browser.gecko)) { // These browsers reliably return valid rectangles for empty ranges - if (pos) { - from--; - flatten = 1; - } // FIXME this is wrong in RTL text - else { - to++; - flatten = -1; - } - } - } - else { - if (side < 0) - from--; - else - to++; - } - let rects = textRange(text, from, to).getClientRects(); - if (!rects.length) - return Rect0; - let rect = rects[(flatten ? flatten < 0 : side >= 0) ? 0 : rects.length - 1]; - if (browser.safari && !flatten && rect.width == 0) - rect = Array.prototype.find.call(rects, r => r.width) || rect; - return flatten ? flattenRect(rect, flatten < 0) : rect || null; - } - // Also used for collapsed ranges that don't have a placeholder widget! - class WidgetView extends ContentView { - constructor(widget, length, side) { - super(); - this.widget = widget; - this.length = length; - this.side = side; - this.prevWidget = null; - } - static create(widget, length, side) { - return new (widget.customView || WidgetView)(widget, length, side); - } - split(from) { - let result = WidgetView.create(this.widget, this.length - from, this.side); - this.length -= from; - return result; - } - sync() { - if (!this.dom || !this.widget.updateDOM(this.dom)) { - if (this.dom && this.prevWidget) - this.prevWidget.destroy(this.dom); - this.prevWidget = null; - this.setDOM(this.widget.toDOM(this.editorView)); - this.dom.contentEditable = "false"; - } - } - getSide() { return this.side; } - merge(from, to, source, hasStart, openStart, openEnd) { - if (source && (!(source instanceof WidgetView) || !this.widget.compare(source.widget) || - from > 0 && openStart <= 0 || to < this.length && openEnd <= 0)) - return false; - this.length = from + (source ? source.length : 0) + (this.length - to); - return true; - } - become(other) { - if (other.length == this.length && other instanceof WidgetView && other.side == this.side) { - if (this.widget.constructor == other.widget.constructor) { - if (!this.widget.eq(other.widget)) - this.markDirty(true); - if (this.dom && !this.prevWidget) - this.prevWidget = this.widget; - this.widget = other.widget; - return true; - } - } - return false; - } - ignoreMutation() { return true; } - ignoreEvent(event) { return this.widget.ignoreEvent(event); } - get overrideDOMText() { - if (this.length == 0) - return Text.empty; - let top = this; - while (top.parent) - top = top.parent; - let view = top.editorView, text = view && view.state.doc, start = this.posAtStart; - return text ? text.slice(start, start + this.length) : Text.empty; - } - domAtPos(pos) { - return pos == 0 ? DOMPos.before(this.dom) : DOMPos.after(this.dom, pos == this.length); - } - domBoundsAround() { return null; } - coordsAt(pos, side) { - let rects = this.dom.getClientRects(), rect = null; - if (!rects.length) - return Rect0; - for (let i = pos > 0 ? rects.length - 1 : 0;; i += (pos > 0 ? -1 : 1)) { - rect = rects[i]; - if (pos > 0 ? i == 0 : i == rects.length - 1 || rect.top < rect.bottom) - break; - } - return (pos == 0 && side > 0 || pos == this.length && side <= 0) ? rect : flattenRect(rect, pos == 0); - } - get isEditable() { return false; } - destroy() { - super.destroy(); - if (this.dom) - this.widget.destroy(this.dom); - } - } - class CompositionView extends WidgetView { - domAtPos(pos) { - let { topView, text } = this.widget; - if (!topView) - return new DOMPos(text, Math.min(pos, text.nodeValue.length)); - return scanCompositionTree(pos, 0, topView, text, (v, p) => v.domAtPos(p), p => new DOMPos(text, Math.min(p, text.nodeValue.length))); - } - sync() { this.setDOM(this.widget.toDOM()); } - localPosFromDOM(node, offset) { - let { topView, text } = this.widget; - if (!topView) - return Math.min(offset, this.length); - return posFromDOMInCompositionTree(node, offset, topView, text); - } - ignoreMutation() { return false; } - get overrideDOMText() { return null; } - coordsAt(pos, side) { - let { topView, text } = this.widget; - if (!topView) - return textCoords(text, pos, side); - return scanCompositionTree(pos, side, topView, text, (v, pos, side) => v.coordsAt(pos, side), (pos, side) => textCoords(text, pos, side)); - } - destroy() { - var _a; - super.destroy(); - (_a = this.widget.topView) === null || _a === void 0 ? void 0 : _a.destroy(); - } - get isEditable() { return true; } - } - // Uses the old structure of a chunk of content view frozen for - // composition to try and find a reasonable DOM location for the given - // offset. - function scanCompositionTree(pos, side, view, text, enterView, fromText) { - if (view instanceof MarkView) { - for (let child of view.children) { - let hasComp = contains(child.dom, text); - let len = hasComp ? text.nodeValue.length : child.length; - if (pos < len || pos == len && child.getSide() <= 0) - return hasComp ? scanCompositionTree(pos, side, child, text, enterView, fromText) : enterView(child, pos, side); - pos -= len; - } - return enterView(view, view.length, -1); - } - else if (view.dom == text) { - return fromText(pos, side); - } - else { - return enterView(view, pos, side); - } - } - function posFromDOMInCompositionTree(node, offset, view, text) { - if (view instanceof MarkView) { - for (let child of view.children) { - let pos = 0, hasComp = contains(child.dom, text); - if (contains(child.dom, node)) - return pos + (hasComp ? posFromDOMInCompositionTree(node, offset, child, text) : child.localPosFromDOM(node, offset)); - pos += hasComp ? text.nodeValue.length : child.length; - } - } - else if (view.dom == text) { - return Math.min(offset, text.nodeValue.length); - } - return view.localPosFromDOM(node, offset); - } - // These are drawn around uneditable widgets to avoid a number of - // browser bugs that show up when the cursor is directly next to - // uneditable inline content. - class WidgetBufferView extends ContentView { - constructor(side) { - super(); - this.side = side; - } - get length() { return 0; } - merge() { return false; } - become(other) { - return other instanceof WidgetBufferView && other.side == this.side; - } - split() { return new WidgetBufferView(this.side); } - sync() { - if (!this.dom) { - let dom = document.createElement("img"); - dom.className = "cm-widgetBuffer"; - dom.setAttribute("aria-hidden", "true"); - this.setDOM(dom); - } - } - getSide() { return this.side; } - domAtPos(pos) { return DOMPos.before(this.dom); } - localPosFromDOM() { return 0; } - domBoundsAround() { return null; } - coordsAt(pos) { - let imgRect = this.dom.getBoundingClientRect(); - // Since the <img> height doesn't correspond to text height, try - // to borrow the height from some sibling node. - let siblingRect = inlineSiblingRect(this, this.side > 0 ? -1 : 1); - return siblingRect && siblingRect.top < imgRect.bottom && siblingRect.bottom > imgRect.top - ? { left: imgRect.left, right: imgRect.right, top: siblingRect.top, bottom: siblingRect.bottom } : imgRect; - } - get overrideDOMText() { - return Text.empty; - } - } - TextView.prototype.children = WidgetView.prototype.children = WidgetBufferView.prototype.children = noChildren; - function inlineSiblingRect(view, side) { - let parent = view.parent, index = parent ? parent.children.indexOf(view) : -1; - while (parent && index >= 0) { - if (side < 0 ? index > 0 : index < parent.children.length) { - let next = parent.children[index + side]; - if (next instanceof TextView) { - let nextRect = next.coordsAt(side < 0 ? next.length : 0, side); - if (nextRect) - return nextRect; - } - index += side; - } - else if (parent instanceof MarkView && parent.parent) { - index = parent.parent.children.indexOf(parent) + (side < 0 ? 0 : 1); - parent = parent.parent; - } - else { - let last = parent.dom.lastChild; - if (last && last.nodeName == "BR") - return last.getClientRects()[0]; - break; - } - } - return undefined; - } - function inlineDOMAtPos(dom, children, pos) { - let i = 0; - for (let off = 0; i < children.length; i++) { - let child = children[i], end = off + child.length; - if (end == off && child.getSide() <= 0) - continue; - if (pos > off && pos < end && child.dom.parentNode == dom) - return child.domAtPos(pos - off); - if (pos <= off) - break; - off = end; - } - for (; i > 0; i--) { - let before = children[i - 1].dom; - if (before.parentNode == dom) - return DOMPos.after(before); - } - return new DOMPos(dom, 0); - } - // Assumes `view`, if a mark view, has precisely 1 child. - function joinInlineInto(parent, view, open) { - let last, { children } = parent; - if (open > 0 && view instanceof MarkView && children.length && - (last = children[children.length - 1]) instanceof MarkView && last.mark.eq(view.mark)) { - joinInlineInto(last, view.children[0], open - 1); - } - else { - children.push(view); - view.setParent(parent); - } - parent.length += view.length; - } - function coordsInChildren(view, pos, side) { - for (let off = 0, i = 0; i < view.children.length; i++) { - let child = view.children[i], end = off + child.length, next; - if ((side <= 0 || end == view.length || child.getSide() > 0 ? end >= pos : end > pos) && - (pos < end || i + 1 == view.children.length || (next = view.children[i + 1]).length || next.getSide() > 0)) { - let flatten = 0; - if (end == off) { - if (child.getSide() <= 0) - continue; - flatten = side = -child.getSide(); - } - let rect = child.coordsAt(Math.max(0, pos - off), side); - return flatten && rect ? flattenRect(rect, side < 0) : rect; - } - off = end; - } - let last = view.dom.lastChild; - if (!last) - return view.dom.getBoundingClientRect(); - let rects = clientRectsFor(last); - return rects[rects.length - 1] || null; - } - - function combineAttrs(source, target) { - for (let name in source) { - if (name == "class" && target.class) - target.class += " " + source.class; - else if (name == "style" && target.style) - target.style += ";" + source.style; - else - target[name] = source[name]; - } - return target; - } - function attrsEq(a, b) { - if (a == b) - return true; - if (!a || !b) - return false; - let keysA = Object.keys(a), keysB = Object.keys(b); - if (keysA.length != keysB.length) - return false; - for (let key of keysA) { - if (keysB.indexOf(key) == -1 || a[key] !== b[key]) - return false; - } - return true; - } - function updateAttrs(dom, prev, attrs) { - if (prev) - for (let name in prev) - if (!(attrs && name in attrs)) - dom.removeAttribute(name); - if (attrs) - for (let name in attrs) - if (!(prev && prev[name] == attrs[name])) - dom.setAttribute(name, attrs[name]); - } - - /** - Widgets added to the content are described by subclasses of this - class. Using a description object like that makes it possible to - delay creating of the DOM structure for a widget until it is - needed, and to avoid redrawing widgets even when the decorations - that define them are recreated. - */ - class WidgetType { - /** - Compare this instance to another instance of the same type. - (TypeScript can't express this, but only instances of the same - specific class will be passed to this method.) This is used to - avoid redrawing widgets when they are replaced by a new - decoration of the same type. The default implementation just - returns `false`, which will cause new instances of the widget to - always be redrawn. - */ - eq(_widget) { return false; } - /** - Update a DOM element created by a widget of the same type (but - different, non-`eq` content) to reflect this widget. May return - true to indicate that it could update, false to indicate it - couldn't (in which case the widget will be redrawn). The default - implementation just returns false. - */ - updateDOM(_dom) { return false; } - /** - @internal - */ - compare(other) { - return this == other || this.constructor == other.constructor && this.eq(other); - } - /** - The estimated height this widget will have, to be used when - estimating the height of content that hasn't been drawn. May - return -1 to indicate you don't know. The default implementation - returns -1. - */ - get estimatedHeight() { return -1; } - /** - Can be used to configure which kinds of events inside the widget - should be ignored by the editor. The default is to ignore all - events. - */ - ignoreEvent(_event) { return true; } - /** - @internal - */ - get customView() { return null; } - /** - This is called when the an instance of the widget is removed - from the editor view. - */ - destroy(_dom) { } - } - /** - The different types of blocks that can occur in an editor view. - */ - var BlockType = /*@__PURE__*/(function (BlockType) { - /** - A line of text. - */ - BlockType[BlockType["Text"] = 0] = "Text"; - /** - A block widget associated with the position after it. - */ - BlockType[BlockType["WidgetBefore"] = 1] = "WidgetBefore"; - /** - A block widget associated with the position before it. - */ - BlockType[BlockType["WidgetAfter"] = 2] = "WidgetAfter"; - /** - A block widget [replacing](https://codemirror.net/6/docs/ref/#view.Decoration^replace) a range of content. - */ - BlockType[BlockType["WidgetRange"] = 3] = "WidgetRange"; - return BlockType})(BlockType || (BlockType = {})); - /** - A decoration provides information on how to draw or style a piece - of content. You'll usually use it wrapped in a - [`Range`](https://codemirror.net/6/docs/ref/#rangeset.Range), which adds a start and end position. - */ - class Decoration extends RangeValue { - /** - @internal - */ - constructor( - /** - @internal - */ - startSide, - /** - @internal - */ - endSide, - /** - @internal - */ - widget, - /** - The config object used to create this decoration. You can - include additional properties in there to store metadata about - your decoration. - */ - spec) { - super(); - this.startSide = startSide; - this.endSide = endSide; - this.widget = widget; - this.spec = spec; - } - /** - @internal - */ - get heightRelevant() { return false; } - /** - Create a mark decoration, which influences the styling of the - content in its range. Nested mark decorations will cause nested - DOM elements to be created. Nesting order is determined by - precedence of the [facet](https://codemirror.net/6/docs/ref/#view.EditorView^decorations) or - (below the facet-provided decorations) [view - plugin](https://codemirror.net/6/docs/ref/#view.PluginSpec.decorations). Such elements are split - on line boundaries and on the boundaries of higher-precedence - decorations. - */ - static mark(spec) { - return new MarkDecoration(spec); - } - /** - Create a widget decoration, which adds an element at the given - position. - */ - static widget(spec) { - let side = spec.side || 0, block = !!spec.block; - side += block ? (side > 0 ? 300000000 /* BlockAfter */ : -400000000 /* BlockBefore */) : (side > 0 ? 100000000 /* InlineAfter */ : -100000000 /* InlineBefore */); - return new PointDecoration(spec, side, side, block, spec.widget || null, false); - } - /** - Create a replace decoration which replaces the given range with - a widget, or simply hides it. - */ - static replace(spec) { - let block = !!spec.block, startSide, endSide; - if (spec.isBlockGap) { - startSide = -500000000 /* GapStart */; - endSide = 400000000 /* GapEnd */; - } - else { - let { start, end } = getInclusive(spec, block); - startSide = (start ? (block ? -300000000 /* BlockIncStart */ : -1 /* InlineIncStart */) : 500000000 /* NonIncStart */) - 1; - endSide = (end ? (block ? 200000000 /* BlockIncEnd */ : 1 /* InlineIncEnd */) : -600000000 /* NonIncEnd */) + 1; - } - return new PointDecoration(spec, startSide, endSide, block, spec.widget || null, true); - } - /** - Create a line decoration, which can add DOM attributes to the - line starting at the given position. - */ - static line(spec) { - return new LineDecoration(spec); - } - /** - Build a [`DecorationSet`](https://codemirror.net/6/docs/ref/#view.DecorationSet) from the given - decorated range or ranges. If the ranges aren't already sorted, - pass `true` for `sort` to make the library sort them for you. - */ - static set(of, sort = false) { - return RangeSet.of(of, sort); - } - /** - @internal - */ - hasHeight() { return this.widget ? this.widget.estimatedHeight > -1 : false; } - } - /** - The empty set of decorations. - */ - Decoration.none = RangeSet.empty; - class MarkDecoration extends Decoration { - constructor(spec) { - let { start, end } = getInclusive(spec); - super(start ? -1 /* InlineIncStart */ : 500000000 /* NonIncStart */, end ? 1 /* InlineIncEnd */ : -600000000 /* NonIncEnd */, null, spec); - this.tagName = spec.tagName || "span"; - this.class = spec.class || ""; - this.attrs = spec.attributes || null; - } - eq(other) { - return this == other || - other instanceof MarkDecoration && - this.tagName == other.tagName && - this.class == other.class && - attrsEq(this.attrs, other.attrs); - } - range(from, to = from) { - if (from >= to) - throw new RangeError("Mark decorations may not be empty"); - return super.range(from, to); - } - } - MarkDecoration.prototype.point = false; - class LineDecoration extends Decoration { - constructor(spec) { - super(-200000000 /* Line */, -200000000 /* Line */, null, spec); - } - eq(other) { - return other instanceof LineDecoration && attrsEq(this.spec.attributes, other.spec.attributes); - } - range(from, to = from) { - if (to != from) - throw new RangeError("Line decoration ranges must be zero-length"); - return super.range(from, to); - } - } - LineDecoration.prototype.mapMode = MapMode.TrackBefore; - LineDecoration.prototype.point = true; - class PointDecoration extends Decoration { - constructor(spec, startSide, endSide, block, widget, isReplace) { - super(startSide, endSide, widget, spec); - this.block = block; - this.isReplace = isReplace; - this.mapMode = !block ? MapMode.TrackDel : startSide <= 0 ? MapMode.TrackBefore : MapMode.TrackAfter; - } - // Only relevant when this.block == true - get type() { - return this.startSide < this.endSide ? BlockType.WidgetRange - : this.startSide <= 0 ? BlockType.WidgetBefore : BlockType.WidgetAfter; - } - get heightRelevant() { return this.block || !!this.widget && this.widget.estimatedHeight >= 5; } - eq(other) { - return other instanceof PointDecoration && - widgetsEq(this.widget, other.widget) && - this.block == other.block && - this.startSide == other.startSide && this.endSide == other.endSide; - } - range(from, to = from) { - if (this.isReplace && (from > to || (from == to && this.startSide > 0 && this.endSide <= 0))) - throw new RangeError("Invalid range for replacement decoration"); - if (!this.isReplace && to != from) - throw new RangeError("Widget decorations can only have zero-length ranges"); - return super.range(from, to); - } - } - PointDecoration.prototype.point = true; - function getInclusive(spec, block = false) { - let { inclusiveStart: start, inclusiveEnd: end } = spec; - if (start == null) - start = spec.inclusive; - if (end == null) - end = spec.inclusive; - return { start: start !== null && start !== void 0 ? start : block, end: end !== null && end !== void 0 ? end : block }; - } - function widgetsEq(a, b) { - return a == b || !!(a && b && a.compare(b)); - } - function addRange(from, to, ranges, margin = 0) { - let last = ranges.length - 1; - if (last >= 0 && ranges[last] + margin >= from) - ranges[last] = Math.max(ranges[last], to); - else - ranges.push(from, to); - } - - class LineView extends ContentView { - constructor() { - super(...arguments); - this.children = []; - this.length = 0; - this.prevAttrs = undefined; - this.attrs = null; - this.breakAfter = 0; - } - // Consumes source - merge(from, to, source, hasStart, openStart, openEnd) { - if (source) { - if (!(source instanceof LineView)) - return false; - if (!this.dom) - source.transferDOM(this); // Reuse source.dom when appropriate - } - if (hasStart) - this.setDeco(source ? source.attrs : null); - mergeChildrenInto(this, from, to, source ? source.children : [], openStart, openEnd); - return true; - } - split(at) { - let end = new LineView; - end.breakAfter = this.breakAfter; - if (this.length == 0) - return end; - let { i, off } = this.childPos(at); - if (off) { - end.append(this.children[i].split(off), 0); - this.children[i].merge(off, this.children[i].length, null, false, 0, 0); - i++; - } - for (let j = i; j < this.children.length; j++) - end.append(this.children[j], 0); - while (i > 0 && this.children[i - 1].length == 0) - this.children[--i].destroy(); - this.children.length = i; - this.markDirty(); - this.length = at; - return end; - } - transferDOM(other) { - if (!this.dom) - return; - other.setDOM(this.dom); - other.prevAttrs = this.prevAttrs === undefined ? this.attrs : this.prevAttrs; - this.prevAttrs = undefined; - this.dom = null; - } - setDeco(attrs) { - if (!attrsEq(this.attrs, attrs)) { - if (this.dom) { - this.prevAttrs = this.attrs; - this.markDirty(); - } - this.attrs = attrs; - } - } - append(child, openStart) { - joinInlineInto(this, child, openStart); - } - // Only called when building a line view in ContentBuilder - addLineDeco(deco) { - let attrs = deco.spec.attributes, cls = deco.spec.class; - if (attrs) - this.attrs = combineAttrs(attrs, this.attrs || {}); - if (cls) - this.attrs = combineAttrs({ class: cls }, this.attrs || {}); - } - domAtPos(pos) { - return inlineDOMAtPos(this.dom, this.children, pos); - } - reuseDOM(node) { - if (node.nodeName == "DIV") { - this.setDOM(node); - this.dirty |= 4 /* Attrs */ | 2 /* Node */; - } - } - sync(track) { - var _a; - if (!this.dom) { - this.setDOM(document.createElement("div")); - this.dom.className = "cm-line"; - this.prevAttrs = this.attrs ? null : undefined; - } - else if (this.dirty & 4 /* Attrs */) { - clearAttributes(this.dom); - this.dom.className = "cm-line"; - this.prevAttrs = this.attrs ? null : undefined; - } - if (this.prevAttrs !== undefined) { - updateAttrs(this.dom, this.prevAttrs, this.attrs); - this.dom.classList.add("cm-line"); - this.prevAttrs = undefined; - } - super.sync(track); - let last = this.dom.lastChild; - while (last && ContentView.get(last) instanceof MarkView) - last = last.lastChild; - if (!last || !this.length || - last.nodeName != "BR" && ((_a = ContentView.get(last)) === null || _a === void 0 ? void 0 : _a.isEditable) == false && - (!browser.ios || !this.children.some(ch => ch instanceof TextView))) { - let hack = document.createElement("BR"); - hack.cmIgnore = true; - this.dom.appendChild(hack); - } - } - measureTextSize() { - if (this.children.length == 0 || this.length > 20) - return null; - let totalWidth = 0; - for (let child of this.children) { - if (!(child instanceof TextView)) - return null; - let rects = clientRectsFor(child.dom); - if (rects.length != 1) - return null; - totalWidth += rects[0].width; - } - return { lineHeight: this.dom.getBoundingClientRect().height, - charWidth: totalWidth / this.length }; - } - coordsAt(pos, side) { - return coordsInChildren(this, pos, side); - } - become(_other) { return false; } - get type() { return BlockType.Text; } - static find(docView, pos) { - for (let i = 0, off = 0; i < docView.children.length; i++) { - let block = docView.children[i], end = off + block.length; - if (end >= pos) { - if (block instanceof LineView) - return block; - if (end > pos) - break; - } - off = end + block.breakAfter; - } - return null; - } - } - class BlockWidgetView extends ContentView { - constructor(widget, length, type) { - super(); - this.widget = widget; - this.length = length; - this.type = type; - this.breakAfter = 0; - this.prevWidget = null; - } - merge(from, to, source, _takeDeco, openStart, openEnd) { - if (source && (!(source instanceof BlockWidgetView) || !this.widget.compare(source.widget) || - from > 0 && openStart <= 0 || to < this.length && openEnd <= 0)) - return false; - this.length = from + (source ? source.length : 0) + (this.length - to); - return true; - } - domAtPos(pos) { - return pos == 0 ? DOMPos.before(this.dom) : DOMPos.after(this.dom, pos == this.length); - } - split(at) { - let len = this.length - at; - this.length = at; - let end = new BlockWidgetView(this.widget, len, this.type); - end.breakAfter = this.breakAfter; - return end; - } - get children() { return noChildren; } - sync() { - if (!this.dom || !this.widget.updateDOM(this.dom)) { - if (this.dom && this.prevWidget) - this.prevWidget.destroy(this.dom); - this.prevWidget = null; - this.setDOM(this.widget.toDOM(this.editorView)); - this.dom.contentEditable = "false"; - } - } - get overrideDOMText() { - return this.parent ? this.parent.view.state.doc.slice(this.posAtStart, this.posAtEnd) : Text.empty; - } - domBoundsAround() { return null; } - become(other) { - if (other instanceof BlockWidgetView && other.type == this.type && - other.widget.constructor == this.widget.constructor) { - if (!other.widget.eq(this.widget)) - this.markDirty(true); - if (this.dom && !this.prevWidget) - this.prevWidget = this.widget; - this.widget = other.widget; - this.length = other.length; - this.breakAfter = other.breakAfter; - return true; - } - return false; - } - ignoreMutation() { return true; } - ignoreEvent(event) { return this.widget.ignoreEvent(event); } - destroy() { - super.destroy(); - if (this.dom) - this.widget.destroy(this.dom); - } - } - - class ContentBuilder { - constructor(doc, pos, end, disallowBlockEffectsBelow) { - this.doc = doc; - this.pos = pos; - this.end = end; - this.disallowBlockEffectsBelow = disallowBlockEffectsBelow; - this.content = []; - this.curLine = null; - this.breakAtStart = 0; - this.pendingBuffer = 0 /* No */; - // Set to false directly after a widget that covers the position after it - this.atCursorPos = true; - this.openStart = -1; - this.openEnd = -1; - this.text = ""; - this.textOff = 0; - this.cursor = doc.iter(); - this.skip = pos; - } - posCovered() { - if (this.content.length == 0) - return !this.breakAtStart && this.doc.lineAt(this.pos).from != this.pos; - let last = this.content[this.content.length - 1]; - return !last.breakAfter && !(last instanceof BlockWidgetView && last.type == BlockType.WidgetBefore); - } - getLine() { - if (!this.curLine) { - this.content.push(this.curLine = new LineView); - this.atCursorPos = true; - } - return this.curLine; - } - flushBuffer(active) { - if (this.pendingBuffer) { - this.curLine.append(wrapMarks(new WidgetBufferView(-1), active), active.length); - this.pendingBuffer = 0 /* No */; - } - } - addBlockWidget(view) { - this.flushBuffer([]); - this.curLine = null; - this.content.push(view); - } - finish(openEnd) { - if (!openEnd) - this.flushBuffer([]); - else - this.pendingBuffer = 0 /* No */; - if (!this.posCovered()) - this.getLine(); - } - buildText(length, active, openStart) { - while (length > 0) { - if (this.textOff == this.text.length) { - let { value, lineBreak, done } = this.cursor.next(this.skip); - this.skip = 0; - if (done) - throw new Error("Ran out of text content when drawing inline views"); - if (lineBreak) { - if (!this.posCovered()) - this.getLine(); - if (this.content.length) - this.content[this.content.length - 1].breakAfter = 1; - else - this.breakAtStart = 1; - this.flushBuffer([]); - this.curLine = null; - length--; - continue; - } - else { - this.text = value; - this.textOff = 0; - } - } - let take = Math.min(this.text.length - this.textOff, length, 512 /* Chunk */); - this.flushBuffer(active.slice(0, openStart)); - this.getLine().append(wrapMarks(new TextView(this.text.slice(this.textOff, this.textOff + take)), active), openStart); - this.atCursorPos = true; - this.textOff += take; - length -= take; - openStart = 0; - } - } - span(from, to, active, openStart) { - this.buildText(to - from, active, openStart); - this.pos = to; - if (this.openStart < 0) - this.openStart = openStart; - } - point(from, to, deco, active, openStart) { - let len = to - from; - if (deco instanceof PointDecoration) { - if (deco.block) { - let { type } = deco; - if (type == BlockType.WidgetAfter && !this.posCovered()) - this.getLine(); - this.addBlockWidget(new BlockWidgetView(deco.widget || new NullWidget("div"), len, type)); - } - else { - let view = WidgetView.create(deco.widget || new NullWidget("span"), len, deco.startSide); - let cursorBefore = this.atCursorPos && !view.isEditable && openStart <= active.length && (from < to || deco.startSide > 0); - let cursorAfter = !view.isEditable && (from < to || deco.startSide <= 0); - let line = this.getLine(); - if (this.pendingBuffer == 2 /* IfCursor */ && !cursorBefore) - this.pendingBuffer = 0 /* No */; - this.flushBuffer(active); - if (cursorBefore) { - line.append(wrapMarks(new WidgetBufferView(1), active), openStart); - openStart = active.length + Math.max(0, openStart - active.length); - } - line.append(wrapMarks(view, active), openStart); - this.atCursorPos = cursorAfter; - this.pendingBuffer = !cursorAfter ? 0 /* No */ : from < to ? 1 /* Yes */ : 2 /* IfCursor */; - } - } - else if (this.doc.lineAt(this.pos).from == this.pos) { // Line decoration - this.getLine().addLineDeco(deco); - } - if (len) { - // Advance the iterator past the replaced content - if (this.textOff + len <= this.text.length) { - this.textOff += len; - } - else { - this.skip += len - (this.text.length - this.textOff); - this.text = ""; - this.textOff = 0; - } - this.pos = to; - } - if (this.openStart < 0) - this.openStart = openStart; - } - filterPoint(from, to, value, index) { - if (index < this.disallowBlockEffectsBelow && value instanceof PointDecoration) { - if (value.block) - throw new RangeError("Block decorations may not be specified via plugins"); - if (to > this.doc.lineAt(this.pos).to) - throw new RangeError("Decorations that replace line breaks may not be specified via plugins"); - } - return true; - } - static build(text, from, to, decorations, pluginDecorationLength) { - let builder = new ContentBuilder(text, from, to, pluginDecorationLength); - builder.openEnd = RangeSet.spans(decorations, from, to, builder); - if (builder.openStart < 0) - builder.openStart = builder.openEnd; - builder.finish(builder.openEnd); - return builder; - } - } - function wrapMarks(view, active) { - for (let mark of active) - view = new MarkView(mark, [view], view.length); - return view; - } - class NullWidget extends WidgetType { - constructor(tag) { - super(); - this.tag = tag; - } - eq(other) { return other.tag == this.tag; } - toDOM() { return document.createElement(this.tag); } - updateDOM(elt) { return elt.nodeName.toLowerCase() == this.tag; } - } - - const none$2 = []; - const clickAddsSelectionRange = /*@__PURE__*/Facet.define(); - const dragMovesSelection$1 = /*@__PURE__*/Facet.define(); - const mouseSelectionStyle = /*@__PURE__*/Facet.define(); - const exceptionSink = /*@__PURE__*/Facet.define(); - const updateListener = /*@__PURE__*/Facet.define(); - const inputHandler$1 = /*@__PURE__*/Facet.define(); - // FIXME remove - const scrollTo = /*@__PURE__*/StateEffect.define({ - map: (range, changes) => range.map(changes) - }); - // FIXME remove - const centerOn = /*@__PURE__*/StateEffect.define({ - map: (range, changes) => range.map(changes) - }); - class ScrollTarget { - constructor(range, y = "nearest", x = "nearest", yMargin = 5, xMargin = 5) { - this.range = range; - this.y = y; - this.x = x; - this.yMargin = yMargin; - this.xMargin = xMargin; - } - map(changes) { - return changes.empty ? this : new ScrollTarget(this.range.map(changes), this.y, this.x, this.yMargin, this.xMargin); - } - } - const scrollIntoView$1 = /*@__PURE__*/StateEffect.define({ map: (t, ch) => t.map(ch) }); - /** - Log or report an unhandled exception in client code. Should - probably only be used by extension code that allows client code to - provide functions, and calls those functions in a context where an - exception can't be propagated to calling code in a reasonable way - (for example when in an event handler). - - Either calls a handler registered with - [`EditorView.exceptionSink`](https://codemirror.net/6/docs/ref/#view.EditorView^exceptionSink), - `window.onerror`, if defined, or `console.error` (in which case - it'll pass `context`, when given, as first argument). - */ - function logException(state, exception, context) { - let handler = state.facet(exceptionSink); - if (handler.length) - handler[0](exception); - else if (window.onerror) - window.onerror(String(exception), context, undefined, undefined, exception); - else if (context) - console.error(context + ":", exception); - else - console.error(exception); - } - const editable = /*@__PURE__*/Facet.define({ combine: values => values.length ? values[0] : true }); - /** - Used to [declare](https://codemirror.net/6/docs/ref/#view.PluginSpec.provide) which - [fields](https://codemirror.net/6/docs/ref/#view.PluginValue) a [view plugin](https://codemirror.net/6/docs/ref/#view.ViewPlugin) - provides. - */ - class PluginFieldProvider { - /** - @internal - */ - constructor( - /** - @internal - */ - field, - /** - @internal - */ - get) { - this.field = field; - this.get = get; - } - } - /** - Plugin fields are a mechanism for allowing plugins to provide - values that can be retrieved through the - [`pluginField`](https://codemirror.net/6/docs/ref/#view.EditorView.pluginField) view method. - */ - class PluginField { - /** - Create a [provider](https://codemirror.net/6/docs/ref/#view.PluginFieldProvider) for this field, - to use with a plugin's [provide](https://codemirror.net/6/docs/ref/#view.PluginSpec.provide) - option. - */ - from(get) { - return new PluginFieldProvider(this, get); - } - /** - Define a new plugin field. - */ - static define() { return new PluginField(); } - } - /** - This field can be used by plugins to provide - [decorations](https://codemirror.net/6/docs/ref/#view.Decoration). - - **Note**: For reasons of data flow (plugins are only updated - after the viewport is computed), decorations produced by plugins - are _not_ taken into account when predicting the vertical layout - structure of the editor. They **must not** introduce block - widgets (that will raise an error) or replacing decorations that - cover line breaks (these will be ignored if they occur). Such - decorations, or others that cause a large amount of vertical - size shift compared to the undecorated content, should be - provided through the state-level [`decorations` - facet](https://codemirror.net/6/docs/ref/#view.EditorView^decorations) instead. - */ - PluginField.decorations = /*@__PURE__*/PluginField.define(); - /** - Used to provide ranges that should be treated as atoms as far as - cursor motion is concerned. This causes methods like - [`moveByChar`](https://codemirror.net/6/docs/ref/#view.EditorView.moveByChar) and - [`moveVertically`](https://codemirror.net/6/docs/ref/#view.EditorView.moveVertically) (and the - commands built on top of them) to skip across such regions when - a selection endpoint would enter them. This does _not_ prevent - direct programmatic [selection - updates](https://codemirror.net/6/docs/ref/#state.TransactionSpec.selection) from moving into such - regions. - */ - PluginField.atomicRanges = /*@__PURE__*/PluginField.define(); - /** - Plugins can provide additional scroll margins (space around the - sides of the scrolling element that should be considered - invisible) through this field. This can be useful when the - plugin introduces elements that cover part of that element (for - example a horizontally fixed gutter). - */ - PluginField.scrollMargins = /*@__PURE__*/PluginField.define(); - let nextPluginID = 0; - const viewPlugin = /*@__PURE__*/Facet.define(); - /** - View plugins associate stateful values with a view. They can - influence the way the content is drawn, and are notified of things - that happen in the view. - */ - class ViewPlugin { - constructor( - /** - @internal - */ - id, - /** - @internal - */ - create, - /** - @internal - */ - fields) { - this.id = id; - this.create = create; - this.fields = fields; - this.extension = viewPlugin.of(this); - } - /** - Define a plugin from a constructor function that creates the - plugin's value, given an editor view. - */ - static define(create, spec) { - let { eventHandlers, provide, decorations } = spec || {}; - let fields = []; - if (provide) - for (let provider of Array.isArray(provide) ? provide : [provide]) - fields.push(provider); - if (eventHandlers) - fields.push(domEventHandlers.from((value) => ({ plugin: value, handlers: eventHandlers }))); - if (decorations) - fields.push(PluginField.decorations.from(decorations)); - return new ViewPlugin(nextPluginID++, create, fields); - } - /** - Create a plugin for a class whose constructor takes a single - editor view as argument. - */ - static fromClass(cls, spec) { - return ViewPlugin.define(view => new cls(view), spec); - } - } - const domEventHandlers = /*@__PURE__*/PluginField.define(); - class PluginInstance { - constructor(spec) { - this.spec = spec; - // When starting an update, all plugins have this field set to the - // update object, indicating they need to be updated. When finished - // updating, it is set to `false`. Retrieving a plugin that needs to - // be updated with `view.plugin` forces an eager update. - this.mustUpdate = null; - // This is null when the plugin is initially created, but - // initialized on the first update. - this.value = null; - } - takeField(type, target) { - if (this.spec) - for (let { field, get } of this.spec.fields) - if (field == type) - target.push(get(this.value)); - } - update(view) { - if (!this.value) { - if (this.spec) { - try { - this.value = this.spec.create(view); - } - catch (e) { - logException(view.state, e, "CodeMirror plugin crashed"); - this.deactivate(); - } - } - } - else if (this.mustUpdate) { - let update = this.mustUpdate; - this.mustUpdate = null; - if (this.value.update) { - try { - this.value.update(update); - } - catch (e) { - logException(update.state, e, "CodeMirror plugin crashed"); - if (this.value.destroy) - try { - this.value.destroy(); - } - catch (_) { } - this.deactivate(); - } - } - } - return this; - } - destroy(view) { - var _a; - if ((_a = this.value) === null || _a === void 0 ? void 0 : _a.destroy) { - try { - this.value.destroy(); - } - catch (e) { - logException(view.state, e, "CodeMirror plugin crashed"); - } - } - } - deactivate() { - this.spec = this.value = null; - } - } - const editorAttributes = /*@__PURE__*/Facet.define(); - const contentAttributes = /*@__PURE__*/Facet.define(); - // Provide decorations - const decorations = /*@__PURE__*/Facet.define(); - const styleModule = /*@__PURE__*/Facet.define(); - class ChangedRange { - constructor(fromA, toA, fromB, toB) { - this.fromA = fromA; - this.toA = toA; - this.fromB = fromB; - this.toB = toB; - } - join(other) { - return new ChangedRange(Math.min(this.fromA, other.fromA), Math.max(this.toA, other.toA), Math.min(this.fromB, other.fromB), Math.max(this.toB, other.toB)); - } - addToSet(set) { - let i = set.length, me = this; - for (; i > 0; i--) { - let range = set[i - 1]; - if (range.fromA > me.toA) - continue; - if (range.toA < me.fromA) - break; - me = me.join(range); - set.splice(i - 1, 1); - } - set.splice(i, 0, me); - return set; - } - static extendWithRanges(diff, ranges) { - if (ranges.length == 0) - return diff; - let result = []; - for (let dI = 0, rI = 0, posA = 0, posB = 0;; dI++) { - let next = dI == diff.length ? null : diff[dI], off = posA - posB; - let end = next ? next.fromB : 1e9; - while (rI < ranges.length && ranges[rI] < end) { - let from = ranges[rI], to = ranges[rI + 1]; - let fromB = Math.max(posB, from), toB = Math.min(end, to); - if (fromB <= toB) - new ChangedRange(fromB + off, toB + off, fromB, toB).addToSet(result); - if (to > end) - break; - else - rI += 2; - } - if (!next) - return result; - new ChangedRange(next.fromA, next.toA, next.fromB, next.toB).addToSet(result); - posA = next.toA; - posB = next.toB; - } - } - } - /** - View [plugins](https://codemirror.net/6/docs/ref/#view.ViewPlugin) are given instances of this - class, which describe what happened, whenever the view is updated. - */ - class ViewUpdate { - /** - @internal - */ - constructor( - /** - The editor view that the update is associated with. - */ - view, - /** - The new editor state. - */ - state, - /** - The transactions involved in the update. May be empty. - */ - transactions = none$2) { - this.view = view; - this.state = state; - this.transactions = transactions; - /** - @internal - */ - this.flags = 0; - this.startState = view.state; - this.changes = ChangeSet.empty(this.startState.doc.length); - for (let tr of transactions) - this.changes = this.changes.compose(tr.changes); - let changedRanges = []; - this.changes.iterChangedRanges((fromA, toA, fromB, toB) => changedRanges.push(new ChangedRange(fromA, toA, fromB, toB))); - this.changedRanges = changedRanges; - let focus = view.hasFocus; - if (focus != view.inputState.notifiedFocused) { - view.inputState.notifiedFocused = focus; - this.flags |= 1 /* Focus */; - } - } - /** - Tells you whether the [viewport](https://codemirror.net/6/docs/ref/#view.EditorView.viewport) or - [visible ranges](https://codemirror.net/6/docs/ref/#view.EditorView.visibleRanges) changed in this - update. - */ - get viewportChanged() { - return (this.flags & 4 /* Viewport */) > 0; - } - /** - Indicates whether the height of an element in the editor changed - in this update. - */ - get heightChanged() { - return (this.flags & 2 /* Height */) > 0; - } - /** - Returns true when the document was modified or the size of the - editor, or elements within the editor, changed. - */ - get geometryChanged() { - return this.docChanged || (this.flags & (8 /* Geometry */ | 2 /* Height */)) > 0; - } - /** - True when this update indicates a focus change. - */ - get focusChanged() { - return (this.flags & 1 /* Focus */) > 0; - } - /** - Whether the document changed in this update. - */ - get docChanged() { - return !this.changes.empty; - } - /** - Whether the selection was explicitly set in this update. - */ - get selectionSet() { - return this.transactions.some(tr => tr.selection); - } - /** - @internal - */ - get empty() { return this.flags == 0 && this.transactions.length == 0; } - } - - /** - Used to indicate [text direction](https://codemirror.net/6/docs/ref/#view.EditorView.textDirection). - */ - var Direction = /*@__PURE__*/(function (Direction) { - // (These are chosen to match the base levels, in bidi algorithm - // terms, of spans in that direction.) - /** - Left-to-right. - */ - Direction[Direction["LTR"] = 0] = "LTR"; - /** - Right-to-left. - */ - Direction[Direction["RTL"] = 1] = "RTL"; - return Direction})(Direction || (Direction = {})); - const LTR = Direction.LTR, RTL = Direction.RTL; - // Decode a string with each type encoded as log2(type) - function dec(str) { - let result = []; - for (let i = 0; i < str.length; i++) - result.push(1 << +str[i]); - return result; - } - // Character types for codepoints 0 to 0xf8 - const LowTypes = /*@__PURE__*/dec("88888888888888888888888888888888888666888888787833333333337888888000000000000000000000000008888880000000000000000000000000088888888888888888888888888888888888887866668888088888663380888308888800000000000000000000000800000000000000000000000000000008"); - // Character types for codepoints 0x600 to 0x6f9 - const ArabicTypes = /*@__PURE__*/dec("4444448826627288999999999992222222222222222222222222222222222222222222222229999999999999999999994444444444644222822222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222999999949999999229989999223333333333"); - const Brackets = /*@__PURE__*/Object.create(null), BracketStack = []; - // There's a lot more in - // https://www.unicode.org/Public/UCD/latest/ucd/BidiBrackets.txt, - // which are left out to keep code size down. - for (let p of ["()", "[]", "{}"]) { - let l = /*@__PURE__*/p.charCodeAt(0), r = /*@__PURE__*/p.charCodeAt(1); - Brackets[l] = r; - Brackets[r] = -l; - } - function charType(ch) { - return ch <= 0xf7 ? LowTypes[ch] : - 0x590 <= ch && ch <= 0x5f4 ? 2 /* R */ : - 0x600 <= ch && ch <= 0x6f9 ? ArabicTypes[ch - 0x600] : - 0x6ee <= ch && ch <= 0x8ac ? 4 /* AL */ : - 0x2000 <= ch && ch <= 0x200b ? 256 /* NI */ : - ch == 0x200c ? 256 /* NI */ : 1 /* L */; - } - const BidiRE = /[\u0590-\u05f4\u0600-\u06ff\u0700-\u08ac]/; - /** - Represents a contiguous range of text that has a single direction - (as in left-to-right or right-to-left). - */ - class BidiSpan { - /** - @internal - */ - constructor( - /** - The start of the span (relative to the start of the line). - */ - from, - /** - The end of the span. - */ - to, - /** - The ["bidi - level"](https://unicode.org/reports/tr9/#Basic_Display_Algorithm) - of the span (in this context, 0 means - left-to-right, 1 means right-to-left, 2 means left-to-right - number inside right-to-left text). - */ - level) { - this.from = from; - this.to = to; - this.level = level; - } - /** - The direction of this span. - */ - get dir() { return this.level % 2 ? RTL : LTR; } - /** - @internal - */ - side(end, dir) { return (this.dir == dir) == end ? this.to : this.from; } - /** - @internal - */ - static find(order, index, level, assoc) { - let maybe = -1; - for (let i = 0; i < order.length; i++) { - let span = order[i]; - if (span.from <= index && span.to >= index) { - if (span.level == level) - return i; - // When multiple spans match, if assoc != 0, take the one that - // covers that side, otherwise take the one with the minimum - // level. - if (maybe < 0 || (assoc != 0 ? (assoc < 0 ? span.from < index : span.to > index) : order[maybe].level > span.level)) - maybe = i; - } - } - if (maybe < 0) - throw new RangeError("Index out of range"); - return maybe; - } - } - // Reused array of character types - const types = []; - function computeOrder(line, direction) { - let len = line.length, outerType = direction == LTR ? 1 /* L */ : 2 /* R */, oppositeType = direction == LTR ? 2 /* R */ : 1 /* L */; - if (!line || outerType == 1 /* L */ && !BidiRE.test(line)) - return trivialOrder(len); - // 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. - // 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. - // (Left after this: L, R, EN, AN, ET, CS, NI) - for (let i = 0, prev = outerType, prevStrong = outerType; i < len; i++) { - let type = charType(line.charCodeAt(i)); - if (type == 512 /* NSM */) - type = prev; - else if (type == 8 /* EN */ && prevStrong == 4 /* AL */) - type = 16 /* AN */; - types[i] = type == 4 /* AL */ ? 2 /* R */ : type; - if (type & 7 /* Strong */) - prevStrong = type; - prev = type; - } - // W5. A sequence of European terminators adjacent to European - // numbers changes to all European numbers. - // W6. Otherwise, separators and terminators change to Other - // Neutral. - // 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. - // (Left after this: L, R, EN+AN, NI) - for (let i = 0, prev = outerType, prevStrong = outerType; i < len; i++) { - let type = types[i]; - if (type == 128 /* CS */) { - if (i < len - 1 && prev == types[i + 1] && (prev & 24 /* Num */)) - type = types[i] = prev; - else - types[i] = 256 /* NI */; - } - else if (type == 64 /* ET */) { - let end = i + 1; - while (end < len && types[end] == 64 /* ET */) - end++; - let replace = (i && prev == 8 /* EN */) || (end < len && types[end] == 8 /* EN */) ? (prevStrong == 1 /* L */ ? 1 /* L */ : 8 /* EN */) : 256 /* NI */; - for (let j = i; j < end; j++) - types[j] = replace; - i = end - 1; - } - else if (type == 8 /* EN */ && prevStrong == 1 /* L */) { - types[i] = 1 /* L */; - } - prev = type; - if (type & 7 /* Strong */) - prevStrong = type; - } - // N0. Process bracket pairs in an isolating run sequence - // sequentially in the logical order of the text positions of the - // opening paired brackets using the logic given below. Within this - // scope, bidirectional types EN and AN are treated as R. - for (let i = 0, sI = 0, context = 0, ch, br, type; i < len; i++) { - // Keeps [startIndex, type, strongSeen] triples for each open - // bracket on BracketStack. - if (br = Brackets[ch = line.charCodeAt(i)]) { - if (br < 0) { // Closing bracket - for (let sJ = sI - 3; sJ >= 0; sJ -= 3) { - if (BracketStack[sJ + 1] == -br) { - let flags = BracketStack[sJ + 2]; - let type = (flags & 2 /* EmbedInside */) ? outerType : - !(flags & 4 /* OppositeInside */) ? 0 : - (flags & 1 /* OppositeBefore */) ? oppositeType : outerType; - if (type) - types[i] = types[BracketStack[sJ]] = type; - sI = sJ; - break; - } - } - } - else if (BracketStack.length == 189 /* MaxDepth */) { - break; - } - else { - BracketStack[sI++] = i; - BracketStack[sI++] = ch; - BracketStack[sI++] = context; - } - } - else if ((type = types[i]) == 2 /* R */ || type == 1 /* L */) { - let embed = type == outerType; - context = embed ? 0 : 1 /* OppositeBefore */; - for (let sJ = sI - 3; sJ >= 0; sJ -= 3) { - let cur = BracketStack[sJ + 2]; - if (cur & 2 /* EmbedInside */) - break; - if (embed) { - BracketStack[sJ + 2] |= 2 /* EmbedInside */; - } - else { - if (cur & 4 /* OppositeInside */) - break; - BracketStack[sJ + 2] |= 4 /* OppositeInside */; - } - } - } - } - // 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. - // (Left after this: L, R, EN+AN) - for (let i = 0; i < len; i++) { - if (types[i] == 256 /* NI */) { - let end = i + 1; - while (end < len && types[end] == 256 /* NI */) - end++; - let beforeL = (i ? types[i - 1] : outerType) == 1 /* L */; - let afterL = (end < len ? types[end] : outerType) == 1 /* L */; - let replace = beforeL == afterL ? (beforeL ? 1 /* L */ : 2 /* R */) : outerType; - for (let j = i; j < end; j++) - types[j] = replace; - i = end - 1; - } - } - // Here we depart from the documented algorithm, in order to avoid - // building up an actual levels array. Since there are only three - // levels (0, 1, 2) in an implementation that doesn't take - // explicit embedding into account, we can build up the order on - // the fly, without following the level-based algorithm. - let order = []; - if (outerType == 1 /* L */) { - for (let i = 0; i < len;) { - let start = i, rtl = types[i++] != 1 /* L */; - while (i < len && rtl == (types[i] != 1 /* L */)) - i++; - if (rtl) { - for (let j = i; j > start;) { - let end = j, l = types[--j] != 2 /* R */; - while (j > start && l == (types[j - 1] != 2 /* R */)) - j--; - order.push(new BidiSpan(j, end, l ? 2 : 1)); - } - } - else { - order.push(new BidiSpan(start, i, 0)); - } - } - } - else { - for (let i = 0; i < len;) { - let start = i, rtl = types[i++] == 2 /* R */; - while (i < len && rtl == (types[i] == 2 /* R */)) - i++; - order.push(new BidiSpan(start, i, rtl ? 1 : 2)); - } - } - return order; - } - function trivialOrder(length) { - return [new BidiSpan(0, length, 0)]; - } - let movedOver = ""; - function moveVisually(line, order, dir, start, forward) { - var _a; - let startIndex = start.head - line.from, spanI = -1; - if (startIndex == 0) { - if (!forward || !line.length) - return null; - if (order[0].level != dir) { - startIndex = order[0].side(false, dir); - spanI = 0; - } - } - else if (startIndex == line.length) { - if (forward) - return null; - let last = order[order.length - 1]; - if (last.level != dir) { - startIndex = last.side(true, dir); - spanI = order.length - 1; - } - } - if (spanI < 0) - spanI = BidiSpan.find(order, startIndex, (_a = start.bidiLevel) !== null && _a !== void 0 ? _a : -1, start.assoc); - let span = order[spanI]; - // End of span. (But not end of line--that was checked for above.) - if (startIndex == span.side(forward, dir)) { - span = order[spanI += forward ? 1 : -1]; - startIndex = span.side(!forward, dir); - } - let indexForward = forward == (span.dir == dir); - let nextIndex = findClusterBreak(line.text, startIndex, indexForward); - movedOver = line.text.slice(Math.min(startIndex, nextIndex), Math.max(startIndex, nextIndex)); - if (nextIndex != span.side(forward, dir)) - return EditorSelection.cursor(nextIndex + line.from, indexForward ? -1 : 1, span.level); - let nextSpan = spanI == (forward ? order.length - 1 : 0) ? null : order[spanI + (forward ? 1 : -1)]; - if (!nextSpan && span.level != dir) - return EditorSelection.cursor(forward ? line.to : line.from, forward ? -1 : 1, dir); - if (nextSpan && nextSpan.level < span.level) - return EditorSelection.cursor(nextSpan.side(!forward, dir) + line.from, forward ? 1 : -1, nextSpan.level); - return EditorSelection.cursor(nextIndex + line.from, forward ? -1 : 1, span.level); - } - - const LineBreakPlaceholder = "\uffff"; - class DOMReader { - constructor(points, state) { - this.points = points; - this.text = ""; - this.lineSeparator = state.facet(EditorState.lineSeparator); - } - append(text) { - this.text += text; - } - lineBreak() { - this.text += LineBreakPlaceholder; - } - readRange(start, end) { - if (!start) - return this; - let parent = start.parentNode; - for (let cur = start;;) { - this.findPointBefore(parent, cur); - this.readNode(cur); - let next = cur.nextSibling; - if (next == end) - break; - let view = ContentView.get(cur), nextView = ContentView.get(next); - if (view && nextView ? view.breakAfter : - (view ? view.breakAfter : isBlockElement(cur)) || - (isBlockElement(next) && (cur.nodeName != "BR" || cur.cmIgnore))) - this.lineBreak(); - cur = next; - } - this.findPointBefore(parent, end); - return this; - } - readTextNode(node) { - let text = node.nodeValue; - for (let point of this.points) - if (point.node == node) - point.pos = this.text.length + Math.min(point.offset, text.length); - for (let off = 0, re = this.lineSeparator ? null : /\r\n?|\n/g;;) { - let nextBreak = -1, breakSize = 1, m; - if (this.lineSeparator) { - nextBreak = text.indexOf(this.lineSeparator, off); - breakSize = this.lineSeparator.length; - } - else if (m = re.exec(text)) { - nextBreak = m.index; - breakSize = m[0].length; - } - this.append(text.slice(off, nextBreak < 0 ? text.length : nextBreak)); - if (nextBreak < 0) - break; - this.lineBreak(); - if (breakSize > 1) - for (let point of this.points) - if (point.node == node && point.pos > this.text.length) - point.pos -= breakSize - 1; - off = nextBreak + breakSize; - } - } - readNode(node) { - if (node.cmIgnore) - return; - let view = ContentView.get(node); - let fromView = view && view.overrideDOMText; - if (fromView != null) { - this.findPointInside(node, fromView.length); - for (let i = fromView.iter(); !i.next().done;) { - if (i.lineBreak) - this.lineBreak(); - else - this.append(i.value); - } - } - else if (node.nodeType == 3) { - this.readTextNode(node); - } - else if (node.nodeName == "BR") { - if (node.nextSibling) - this.lineBreak(); - } - else if (node.nodeType == 1) { - this.readRange(node.firstChild, null); - } - } - findPointBefore(node, next) { - for (let point of this.points) - if (point.node == node && node.childNodes[point.offset] == next) - point.pos = this.text.length; - } - findPointInside(node, maxLen) { - for (let point of this.points) - if (node.nodeType == 3 ? point.node == node : node.contains(point.node)) - point.pos = this.text.length + Math.min(maxLen, point.offset); - } - } - function isBlockElement(node) { - return node.nodeType == 1 && /^(DIV|P|LI|UL|OL|BLOCKQUOTE|DD|DT|H\d|SECTION|PRE)$/.test(node.nodeName); - } - class DOMPoint { - constructor(node, offset) { - this.node = node; - this.offset = offset; - this.pos = -1; - } - } - - class DocView extends ContentView { - constructor(view) { - super(); - this.view = view; - this.compositionDeco = Decoration.none; - this.decorations = []; - this.pluginDecorationLength = 0; - // Track a minimum width for the editor. When measuring sizes in - // measureVisibleLineHeights, this is updated to point at the width - // of a given element and its extent in the document. When a change - // happens in that range, these are reset. That way, once we've seen - // a line/element of a given length, we keep the editor wide enough - // to fit at least that element, until it is changed, at which point - // we forget it again. - this.minWidth = 0; - this.minWidthFrom = 0; - this.minWidthTo = 0; - // Track whether the DOM selection was set in a lossy way, so that - // we don't mess it up when reading it back it - this.impreciseAnchor = null; - this.impreciseHead = null; - this.forceSelection = false; - // Used by the resize observer to ignore resizes that we caused - // ourselves - this.lastUpdate = Date.now(); - this.setDOM(view.contentDOM); - this.children = [new LineView]; - this.children[0].setParent(this); - this.updateDeco(); - this.updateInner([new ChangedRange(0, 0, 0, view.state.doc.length)], 0); - } - get root() { return this.view.root; } - get editorView() { return this.view; } - get length() { return this.view.state.doc.length; } - // Update the document view to a given state. scrollIntoView can be - // used as a hint to compute a new viewport that includes that - // position, if we know the editor is going to scroll that position - // into view. - update(update) { - let changedRanges = update.changedRanges; - if (this.minWidth > 0 && changedRanges.length) { - if (!changedRanges.every(({ fromA, toA }) => toA < this.minWidthFrom || fromA > this.minWidthTo)) { - this.minWidth = this.minWidthFrom = this.minWidthTo = 0; - } - else { - this.minWidthFrom = update.changes.mapPos(this.minWidthFrom, 1); - this.minWidthTo = update.changes.mapPos(this.minWidthTo, 1); - } - } - if (this.view.inputState.composing < 0) - this.compositionDeco = Decoration.none; - else if (update.transactions.length || this.dirty) - this.compositionDeco = computeCompositionDeco(this.view, update.changes); - // When the DOM nodes around the selection are moved to another - // parent, Chrome sometimes reports a different selection through - // getSelection than the one that it actually shows to the user. - // This forces a selection update when lines are joined to work - // around that. Issue #54 - if ((browser.ie || browser.chrome) && !this.compositionDeco.size && update && - update.state.doc.lines != update.startState.doc.lines) - this.forceSelection = true; - let prevDeco = this.decorations, deco = this.updateDeco(); - let decoDiff = findChangedDeco(prevDeco, deco, update.changes); - changedRanges = ChangedRange.extendWithRanges(changedRanges, decoDiff); - if (this.dirty == 0 /* Not */ && changedRanges.length == 0) { - return false; - } - else { - this.updateInner(changedRanges, update.startState.doc.length); - if (update.transactions.length) - this.lastUpdate = Date.now(); - return true; - } - } - // Used by update and the constructor do perform the actual DOM - // update - updateInner(changes, oldLength) { - this.view.viewState.mustMeasureContent = true; - this.updateChildren(changes, oldLength); - let { observer } = this.view; - observer.ignore(() => { - // Lock the height during redrawing, since Chrome sometimes - // messes with the scroll position during DOM mutation (though - // no relayout is triggered and I cannot imagine how it can - // recompute the scroll position without a layout) - this.dom.style.height = this.view.viewState.contentHeight + "px"; - this.dom.style.minWidth = this.minWidth ? this.minWidth + "px" : ""; - // Chrome will sometimes, when DOM mutations occur directly - // around the selection, get confused and report a different - // selection from the one it displays (issue #218). This tries - // to detect that situation. - let track = browser.chrome || browser.ios ? { node: observer.selectionRange.focusNode, written: false } : undefined; - this.sync(track); - this.dirty = 0 /* Not */; - if (track && (track.written || observer.selectionRange.focusNode != track.node)) - this.forceSelection = true; - this.dom.style.height = ""; - }); - let gaps = []; - if (this.view.viewport.from || this.view.viewport.to < this.view.state.doc.length) - for (let child of this.children) - if (child instanceof BlockWidgetView && child.widget instanceof BlockGapWidget) - gaps.push(child.dom); - observer.updateGaps(gaps); - } - updateChildren(changes, oldLength) { - let cursor = this.childCursor(oldLength); - for (let i = changes.length - 1;; i--) { - let next = i >= 0 ? changes[i] : null; - if (!next) - break; - let { fromA, toA, fromB, toB } = next; - let { content, breakAtStart, openStart, openEnd } = ContentBuilder.build(this.view.state.doc, fromB, toB, this.decorations, this.pluginDecorationLength); - let { i: toI, off: toOff } = cursor.findPos(toA, 1); - let { i: fromI, off: fromOff } = cursor.findPos(fromA, -1); - replaceRange(this, fromI, fromOff, toI, toOff, content, breakAtStart, openStart, openEnd); - } - } - // Sync the DOM selection to this.state.selection - updateSelection(mustRead = false, fromPointer = false) { - if (mustRead) - this.view.observer.readSelectionRange(); - if (!(fromPointer || this.mayControlSelection()) || - browser.ios && this.view.inputState.rapidCompositionStart) - return; - let force = this.forceSelection; - this.forceSelection = false; - let main = this.view.state.selection.main; - // FIXME need to handle the case where the selection falls inside a block range - let anchor = this.domAtPos(main.anchor); - let head = main.empty ? anchor : this.domAtPos(main.head); - // Always reset on Firefox when next to an uneditable node to - // avoid invisible cursor bugs (#111) - if (browser.gecko && main.empty && betweenUneditable(anchor)) { - let dummy = document.createTextNode(""); - this.view.observer.ignore(() => anchor.node.insertBefore(dummy, anchor.node.childNodes[anchor.offset] || null)); - anchor = head = new DOMPos(dummy, 0); - force = true; - } - let domSel = this.view.observer.selectionRange; - // If the selection is already here, or in an equivalent position, don't touch it - if (force || !domSel.focusNode || - !isEquivalentPosition(anchor.node, anchor.offset, domSel.anchorNode, domSel.anchorOffset) || - !isEquivalentPosition(head.node, head.offset, domSel.focusNode, domSel.focusOffset)) { - this.view.observer.ignore(() => { - // Chrome Android will hide the virtual keyboard when tapping - // inside an uneditable node, and not bring it back when we - // move the cursor to its proper position. This tries to - // restore the keyboard by cycling focus. - if (browser.android && browser.chrome && this.dom.contains(domSel.focusNode) && - inUneditable(domSel.focusNode, this.dom)) { - this.dom.blur(); - this.dom.focus({ preventScroll: true }); - } - let rawSel = getSelection(this.root); - if (main.empty) { - // Work around https://bugzilla.mozilla.org/show_bug.cgi?id=1612076 - if (browser.gecko) { - let nextTo = nextToUneditable(anchor.node, anchor.offset); - if (nextTo && nextTo != (1 /* Before */ | 2 /* After */)) { - let text = nearbyTextNode(anchor.node, anchor.offset, nextTo == 1 /* Before */ ? 1 : -1); - if (text) - anchor = new DOMPos(text, nextTo == 1 /* Before */ ? 0 : text.nodeValue.length); - } - } - rawSel.collapse(anchor.node, anchor.offset); - if (main.bidiLevel != null && domSel.cursorBidiLevel != null) - domSel.cursorBidiLevel = main.bidiLevel; - } - else if (rawSel.extend) { - // Selection.extend can be used to create an 'inverted' selection - // (one where the focus is before the anchor), but not all - // browsers support it yet. - rawSel.collapse(anchor.node, anchor.offset); - rawSel.extend(head.node, head.offset); - } - else { - // Primitive (IE) way - let range = document.createRange(); - if (main.anchor > main.head) - [anchor, head] = [head, anchor]; - range.setEnd(head.node, head.offset); - range.setStart(anchor.node, anchor.offset); - rawSel.removeAllRanges(); - rawSel.addRange(range); - } - }); - this.view.observer.setSelectionRange(anchor, head); - } - this.impreciseAnchor = anchor.precise ? null : new DOMPos(domSel.anchorNode, domSel.anchorOffset); - this.impreciseHead = head.precise ? null : new DOMPos(domSel.focusNode, domSel.focusOffset); - } - enforceCursorAssoc() { - if (this.compositionDeco.size) - return; - let cursor = this.view.state.selection.main; - let sel = getSelection(this.root); - if (!cursor.empty || !cursor.assoc || !sel.modify) - return; - let line = LineView.find(this, cursor.head); - if (!line) - return; - let lineStart = line.posAtStart; - if (cursor.head == lineStart || cursor.head == lineStart + line.length) - return; - let before = this.coordsAt(cursor.head, -1), after = this.coordsAt(cursor.head, 1); - if (!before || !after || before.bottom > after.top) - return; - let dom = this.domAtPos(cursor.head + cursor.assoc); - sel.collapse(dom.node, dom.offset); - sel.modify("move", cursor.assoc < 0 ? "forward" : "backward", "lineboundary"); - } - mayControlSelection() { - return this.view.state.facet(editable) ? this.root.activeElement == this.dom - : hasSelection(this.dom, this.view.observer.selectionRange); - } - nearest(dom) { - for (let cur = dom; cur;) { - let domView = ContentView.get(cur); - if (domView && domView.rootView == this) - return domView; - cur = cur.parentNode; - } - return null; - } - posFromDOM(node, offset) { - let view = this.nearest(node); - if (!view) - throw new RangeError("Trying to find position for a DOM position outside of the document"); - return view.localPosFromDOM(node, offset) + view.posAtStart; - } - domAtPos(pos) { - let { i, off } = this.childCursor().findPos(pos, -1); - for (; i < this.children.length - 1;) { - let child = this.children[i]; - if (off < child.length || child instanceof LineView) - break; - i++; - off = 0; - } - return this.children[i].domAtPos(off); - } - coordsAt(pos, side) { - for (let off = this.length, i = this.children.length - 1;; i--) { - let child = this.children[i], start = off - child.breakAfter - child.length; - if (pos > start || - (pos == start && child.type != BlockType.WidgetBefore && child.type != BlockType.WidgetAfter && - (!i || side == 2 || this.children[i - 1].breakAfter || - (this.children[i - 1].type == BlockType.WidgetBefore && side > -2)))) - return child.coordsAt(pos - start, side); - off = start; - } - } - measureVisibleLineHeights() { - let result = [], { from, to } = this.view.viewState.viewport; - let contentWidth = this.view.contentDOM.clientWidth; - let isWider = contentWidth > Math.max(this.view.scrollDOM.clientWidth, this.minWidth) + 1; - let widest = -1; - for (let pos = 0, i = 0; i < this.children.length; i++) { - let child = this.children[i], end = pos + child.length; - if (end > to) - break; - if (pos >= from) { - let childRect = child.dom.getBoundingClientRect(); - result.push(childRect.height); - if (isWider) { - let last = child.dom.lastChild; - let rects = last ? clientRectsFor(last) : []; - if (rects.length) { - let rect = rects[rects.length - 1]; - let width = this.view.textDirection == Direction.LTR ? rect.right - childRect.left - : childRect.right - rect.left; - if (width > widest) { - widest = width; - this.minWidth = contentWidth; - this.minWidthFrom = pos; - this.minWidthTo = end; - } - } - } - } - pos = end + child.breakAfter; - } - return result; - } - measureTextSize() { - for (let child of this.children) { - if (child instanceof LineView) { - let measure = child.measureTextSize(); - if (measure) - return measure; - } - } - // If no workable line exists, force a layout of a measurable element - let dummy = document.createElement("div"), lineHeight, charWidth; - dummy.className = "cm-line"; - dummy.textContent = "abc def ghi jkl mno pqr stu"; - this.view.observer.ignore(() => { - this.dom.appendChild(dummy); - let rect = clientRectsFor(dummy.firstChild)[0]; - lineHeight = dummy.getBoundingClientRect().height; - charWidth = rect ? rect.width / 27 : 7; - dummy.remove(); - }); - return { lineHeight, charWidth }; - } - childCursor(pos = this.length) { - // Move back to start of last element when possible, so that - // `ChildCursor.findPos` doesn't have to deal with the edge case - // of being after the last element. - let i = this.children.length; - if (i) - pos -= this.children[--i].length; - return new ChildCursor(this.children, pos, i); - } - computeBlockGapDeco() { - let deco = [], vs = this.view.viewState; - for (let pos = 0, i = 0;; i++) { - let next = i == vs.viewports.length ? null : vs.viewports[i]; - let end = next ? next.from - 1 : this.length; - if (end > pos) { - let height = vs.lineBlockAt(end).bottom - vs.lineBlockAt(pos).top; - deco.push(Decoration.replace({ - widget: new BlockGapWidget(height), - block: true, - inclusive: true, - isBlockGap: true, - }).range(pos, end)); - } - if (!next) - break; - pos = next.to + 1; - } - return Decoration.set(deco); - } - updateDeco() { - let pluginDecorations = this.view.pluginField(PluginField.decorations); - this.pluginDecorationLength = pluginDecorations.length; - return this.decorations = [ - ...pluginDecorations, - ...this.view.state.facet(decorations), - this.compositionDeco, - this.computeBlockGapDeco(), - this.view.viewState.lineGapDeco - ]; - } - scrollIntoView(target) { - let { range } = target; - let rect = this.coordsAt(range.head, range.empty ? range.assoc : range.head > range.anchor ? -1 : 1), other; - if (!rect) - return; - if (!range.empty && (other = this.coordsAt(range.anchor, range.anchor > range.head ? -1 : 1))) - rect = { left: Math.min(rect.left, other.left), top: Math.min(rect.top, other.top), - right: Math.max(rect.right, other.right), bottom: Math.max(rect.bottom, other.bottom) }; - let mLeft = 0, mRight = 0, mTop = 0, mBottom = 0; - for (let margins of this.view.pluginField(PluginField.scrollMargins)) - if (margins) { - let { left, right, top, bottom } = margins; - if (left != null) - mLeft = Math.max(mLeft, left); - if (right != null) - mRight = Math.max(mRight, right); - if (top != null) - mTop = Math.max(mTop, top); - if (bottom != null) - mBottom = Math.max(mBottom, bottom); - } - let targetRect = { - left: rect.left - mLeft, top: rect.top - mTop, - right: rect.right + mRight, bottom: rect.bottom + mBottom - }; - scrollRectIntoView(this.view.scrollDOM, targetRect, range.head < range.anchor ? -1 : 1, target.x, target.y, target.xMargin, target.yMargin, this.view.textDirection == Direction.LTR); - } - } - function betweenUneditable(pos) { - return pos.node.nodeType == 1 && pos.node.firstChild && - (pos.offset == 0 || pos.node.childNodes[pos.offset - 1].contentEditable == "false") && - (pos.offset == pos.node.childNodes.length || pos.node.childNodes[pos.offset].contentEditable == "false"); - } - class BlockGapWidget extends WidgetType { - constructor(height) { - super(); - this.height = height; - } - toDOM() { - let elt = document.createElement("div"); - this.updateDOM(elt); - return elt; - } - eq(other) { return other.height == this.height; } - updateDOM(elt) { - elt.style.height = this.height + "px"; - return true; - } - get estimatedHeight() { return this.height; } - } - function compositionSurroundingNode(view) { - let sel = view.observer.selectionRange; - let textNode = sel.focusNode && nearbyTextNode(sel.focusNode, sel.focusOffset, 0); - if (!textNode) - return null; - let cView = view.docView.nearest(textNode); - if (!cView) - return null; - if (cView instanceof LineView) { - let topNode = textNode; - while (topNode.parentNode != cView.dom) - topNode = topNode.parentNode; - let prev = topNode.previousSibling; - while (prev && !ContentView.get(prev)) - prev = prev.previousSibling; - let pos = prev ? ContentView.get(prev).posAtEnd : cView.posAtStart; - return { from: pos, to: pos, node: topNode, text: textNode }; - } - else { - for (;;) { - let { parent } = cView; - if (!parent) - return null; - if (parent instanceof LineView) - break; - cView = parent; - } - let from = cView.posAtStart; - return { from, to: from + cView.length, node: cView.dom, text: textNode }; - } - } - function computeCompositionDeco(view, changes) { - let surrounding = compositionSurroundingNode(view); - if (!surrounding) - return Decoration.none; - let { from, to, node, text: textNode } = surrounding; - let newFrom = changes.mapPos(from, 1), newTo = Math.max(newFrom, changes.mapPos(to, -1)); - let { state } = view, text = node.nodeType == 3 ? node.nodeValue : - new DOMReader([], state).readRange(node.firstChild, null).text; - if (newTo - newFrom < text.length) { - if (state.doc.sliceString(newFrom, Math.min(state.doc.length, newFrom + text.length), LineBreakPlaceholder) == text) - newTo = newFrom + text.length; - else if (state.doc.sliceString(Math.max(0, newTo - text.length), newTo, LineBreakPlaceholder) == text) - newFrom = newTo - text.length; - else - return Decoration.none; - } - else if (state.doc.sliceString(newFrom, newTo, LineBreakPlaceholder) != text) { - return Decoration.none; - } - let topView = ContentView.get(node); - if (topView instanceof CompositionView) - topView = topView.widget.topView; - else if (topView) - topView.parent = null; - return Decoration.set(Decoration.replace({ widget: new CompositionWidget(node, textNode, topView) }).range(newFrom, newTo)); - } - class CompositionWidget extends WidgetType { - constructor(top, text, topView) { - super(); - this.top = top; - this.text = text; - this.topView = topView; - } - eq(other) { return this.top == other.top && this.text == other.text; } - toDOM() { return this.top; } - ignoreEvent() { return false; } - get customView() { return CompositionView; } - } - function nearbyTextNode(node, offset, side) { - for (;;) { - if (node.nodeType == 3) - return node; - if (node.nodeType == 1 && offset > 0 && side <= 0) { - node = node.childNodes[offset - 1]; - offset = maxOffset(node); - } - else if (node.nodeType == 1 && offset < node.childNodes.length && side >= 0) { - node = node.childNodes[offset]; - offset = 0; - } - else { - return null; - } - } - } - function nextToUneditable(node, offset) { - if (node.nodeType != 1) - return 0; - return (offset && node.childNodes[offset - 1].contentEditable == "false" ? 1 /* Before */ : 0) | - (offset < node.childNodes.length && node.childNodes[offset].contentEditable == "false" ? 2 /* After */ : 0); - } - class DecorationComparator$1 { - constructor() { - this.changes = []; - } - compareRange(from, to) { addRange(from, to, this.changes); } - comparePoint(from, to) { addRange(from, to, this.changes); } - } - function findChangedDeco(a, b, diff) { - let comp = new DecorationComparator$1; - RangeSet.compare(a, b, diff, comp); - return comp.changes; - } - function inUneditable(node, inside) { - for (let cur = node; cur && cur != inside; cur = cur.assignedSlot || cur.parentNode) { - if (cur.nodeType == 1 && cur.contentEditable == 'false') { - return true; - } - } - return false; - } - - function groupAt(state, pos, bias = 1) { - let categorize = state.charCategorizer(pos); - let line = state.doc.lineAt(pos), linePos = pos - line.from; - if (line.length == 0) - return EditorSelection.cursor(pos); - if (linePos == 0) - bias = 1; - else if (linePos == line.length) - bias = -1; - let from = linePos, to = linePos; - if (bias < 0) - from = findClusterBreak(line.text, linePos, false); - else - to = findClusterBreak(line.text, linePos); - let cat = categorize(line.text.slice(from, to)); - while (from > 0) { - let prev = findClusterBreak(line.text, from, false); - if (categorize(line.text.slice(prev, from)) != cat) - break; - from = prev; - } - while (to < line.length) { - let next = findClusterBreak(line.text, to); - if (categorize(line.text.slice(to, next)) != cat) - break; - to = next; - } - return EditorSelection.range(from + line.from, to + line.from); - } - // Search the DOM for the {node, offset} position closest to the given - // coordinates. Very inefficient and crude, but can usually be avoided - // by calling caret(Position|Range)FromPoint instead. - function getdx(x, rect) { - return rect.left > x ? rect.left - x : Math.max(0, x - rect.right); - } - function getdy(y, rect) { - return rect.top > y ? rect.top - y : Math.max(0, y - rect.bottom); - } - function yOverlap(a, b) { - return a.top < b.bottom - 1 && a.bottom > b.top + 1; - } - function upTop(rect, top) { - return top < rect.top ? { top, left: rect.left, right: rect.right, bottom: rect.bottom } : rect; - } - function upBot(rect, bottom) { - return bottom > rect.bottom ? { top: rect.top, left: rect.left, right: rect.right, bottom } : rect; - } - function domPosAtCoords(parent, x, y) { - let closest, closestRect, closestX, closestY; - let above, below, aboveRect, belowRect; - for (let child = parent.firstChild; child; child = child.nextSibling) { - let rects = clientRectsFor(child); - for (let i = 0; i < rects.length; i++) { - let rect = rects[i]; - if (closestRect && yOverlap(closestRect, rect)) - rect = upTop(upBot(rect, closestRect.bottom), closestRect.top); - let dx = getdx(x, rect), dy = getdy(y, rect); - if (dx == 0 && dy == 0) - return child.nodeType == 3 ? domPosInText(child, x, y) : domPosAtCoords(child, x, y); - if (!closest || closestY > dy || closestY == dy && closestX > dx) { - closest = child; - closestRect = rect; - closestX = dx; - closestY = dy; - } - if (dx == 0) { - if (y > rect.bottom && (!aboveRect || aboveRect.bottom < rect.bottom)) { - above = child; - aboveRect = rect; - } - else if (y < rect.top && (!belowRect || belowRect.top > rect.top)) { - below = child; - belowRect = rect; - } - } - else if (aboveRect && yOverlap(aboveRect, rect)) { - aboveRect = upBot(aboveRect, rect.bottom); - } - else if (belowRect && yOverlap(belowRect, rect)) { - belowRect = upTop(belowRect, rect.top); - } - } - } - if (aboveRect && aboveRect.bottom >= y) { - closest = above; - closestRect = aboveRect; - } - else if (belowRect && belowRect.top <= y) { - closest = below; - closestRect = belowRect; - } - if (!closest) - return { node: parent, offset: 0 }; - let clipX = Math.max(closestRect.left, Math.min(closestRect.right, x)); - if (closest.nodeType == 3) - return domPosInText(closest, clipX, y); - if (!closestX && closest.contentEditable == "true") - return domPosAtCoords(closest, clipX, y); - let offset = Array.prototype.indexOf.call(parent.childNodes, closest) + - (x >= (closestRect.left + closestRect.right) / 2 ? 1 : 0); - return { node: parent, offset }; - } - function domPosInText(node, x, y) { - let len = node.nodeValue.length; - let closestOffset = -1, closestDY = 1e9, generalSide = 0; - for (let i = 0; i < len; i++) { - let rects = textRange(node, i, i + 1).getClientRects(); - for (let j = 0; j < rects.length; j++) { - let rect = rects[j]; - if (rect.top == rect.bottom) - continue; - if (!generalSide) - generalSide = x - rect.left; - let dy = (rect.top > y ? rect.top - y : y - rect.bottom) - 1; - if (rect.left - 1 <= x && rect.right + 1 >= x && dy < closestDY) { - let right = x >= (rect.left + rect.right) / 2, after = right; - if (browser.chrome || browser.gecko) { - // Check for RTL on browsers that support getting client - // rects for empty ranges. - let rectBefore = textRange(node, i).getBoundingClientRect(); - if (rectBefore.left == rect.right) - after = !right; - } - if (dy <= 0) - return { node, offset: i + (after ? 1 : 0) }; - closestOffset = i + (after ? 1 : 0); - closestDY = dy; - } - } - } - return { node, offset: closestOffset > -1 ? closestOffset : generalSide > 0 ? node.nodeValue.length : 0 }; - } - function posAtCoords(view, { x, y }, precise, bias = -1) { - var _a; - let content = view.contentDOM.getBoundingClientRect(), docTop = content.top + view.viewState.paddingTop; - let block, { docHeight } = view.viewState; - let yOffset = y - docTop; - if (yOffset < 0) - return 0; - if (yOffset > docHeight) - return view.state.doc.length; - // Scan for a text block near the queried y position - for (let halfLine = view.defaultLineHeight / 2, bounced = false;;) { - block = view.elementAtHeight(yOffset); - if (block.type == BlockType.Text) - break; - for (;;) { - // Move the y position out of this block - yOffset = bias > 0 ? block.bottom + halfLine : block.top - halfLine; - if (yOffset >= 0 && yOffset <= docHeight) - break; - // If the document consists entirely of replaced widgets, we - // won't find a text block, so return 0 - if (bounced) - return precise ? null : 0; - bounced = true; - bias = -bias; - } - } - y = docTop + yOffset; - let lineStart = block.from; - // If this is outside of the rendered viewport, we can't determine a position - if (lineStart < view.viewport.from) - return view.viewport.from == 0 ? 0 : precise ? null : posAtCoordsImprecise(view, content, block, x, y); - if (lineStart > view.viewport.to) - return view.viewport.to == view.state.doc.length ? view.state.doc.length : - precise ? null : posAtCoordsImprecise(view, content, block, x, y); - // Prefer ShadowRootOrDocument.elementFromPoint if present, fall back to document if not - let doc = view.dom.ownerDocument; - let root = view.root.elementFromPoint ? view.root : doc; - let element = root.elementFromPoint(x, y); - if (element && !view.contentDOM.contains(element)) - element = null; - // If the element is unexpected, clip x at the sides of the content area and try again - if (!element) { - x = Math.max(content.left + 1, Math.min(content.right - 1, x)); - element = root.elementFromPoint(x, y); - if (element && !view.contentDOM.contains(element)) - element = null; - } - // There's visible editor content under the point, so we can try - // using caret(Position|Range)FromPoint as a shortcut - let node, offset = -1; - if (element && ((_a = view.docView.nearest(element)) === null || _a === void 0 ? void 0 : _a.isEditable) != false) { - if (doc.caretPositionFromPoint) { - let pos = doc.caretPositionFromPoint(x, y); - if (pos) - ({ offsetNode: node, offset } = pos); - } - else if (doc.caretRangeFromPoint) { - let range = doc.caretRangeFromPoint(x, y); - if (range) { - ({ startContainer: node, startOffset: offset } = range); - if (browser.safari && isSuspiciousCaretResult(node, offset, x)) - node = undefined; - } - } - } - // No luck, do our own (potentially expensive) search - if (!node || !view.docView.dom.contains(node)) { - let line = LineView.find(view.docView, lineStart); - if (!line) - return yOffset > block.top + block.height / 2 ? block.to : block.from; - ({ node, offset } = domPosAtCoords(line.dom, x, y)); - } - return view.docView.posFromDOM(node, offset); - } - function posAtCoordsImprecise(view, contentRect, block, x, y) { - let into = Math.round((x - contentRect.left) * view.defaultCharacterWidth); - if (view.lineWrapping && block.height > view.defaultLineHeight * 1.5) { - let line = Math.floor((y - block.top) / view.defaultLineHeight); - into += line * view.viewState.heightOracle.lineLength; - } - let content = view.state.sliceDoc(block.from, block.to); - return block.from + findColumn(content, into, view.state.tabSize); - } - // In case of a high line height, Safari's caretRangeFromPoint treats - // the space between lines as belonging to the last character of the - // line before. This is used to detect such a result so that it can be - // ignored (issue #401). - function isSuspiciousCaretResult(node, offset, x) { - let len; - if (node.nodeType != 3 || offset != (len = node.nodeValue.length)) - return false; - for (let next = node.nextSibling; next; next = next.nextSibling) - if (next.nodeType != 1 || next.nodeName != "BR") - return false; - return textRange(node, len - 1, len).getBoundingClientRect().left > x; - } - function moveToLineBoundary(view, start, forward, includeWrap) { - let line = view.state.doc.lineAt(start.head); - let coords = !includeWrap || !view.lineWrapping ? null - : view.coordsAtPos(start.assoc < 0 && start.head > line.from ? start.head - 1 : start.head); - if (coords) { - let editorRect = view.dom.getBoundingClientRect(); - let pos = view.posAtCoords({ x: forward == (view.textDirection == Direction.LTR) ? editorRect.right - 1 : editorRect.left + 1, - y: (coords.top + coords.bottom) / 2 }); - if (pos != null) - return EditorSelection.cursor(pos, forward ? -1 : 1); - } - let lineView = LineView.find(view.docView, start.head); - let end = lineView ? (forward ? lineView.posAtEnd : lineView.posAtStart) : (forward ? line.to : line.from); - return EditorSelection.cursor(end, forward ? -1 : 1); - } - function moveByChar(view, start, forward, by) { - let line = view.state.doc.lineAt(start.head), spans = view.bidiSpans(line); - for (let cur = start, check = null;;) { - let next = moveVisually(line, spans, view.textDirection, cur, forward), char = movedOver; - if (!next) { - if (line.number == (forward ? view.state.doc.lines : 1)) - return cur; - char = "\n"; - line = view.state.doc.line(line.number + (forward ? 1 : -1)); - spans = view.bidiSpans(line); - next = EditorSelection.cursor(forward ? line.from : line.to); - } - if (!check) { - if (!by) - return next; - check = by(char); - } - else if (!check(char)) { - return cur; - } - cur = next; - } - } - function byGroup(view, pos, start) { - let categorize = view.state.charCategorizer(pos); - let cat = categorize(start); - return (next) => { - let nextCat = categorize(next); - if (cat == CharCategory.Space) - cat = nextCat; - return cat == nextCat; - }; - } - function moveVertically(view, start, forward, distance) { - let startPos = start.head, dir = forward ? 1 : -1; - if (startPos == (forward ? view.state.doc.length : 0)) - return EditorSelection.cursor(startPos, start.assoc); - let goal = start.goalColumn, startY; - let rect = view.contentDOM.getBoundingClientRect(); - let startCoords = view.coordsAtPos(startPos), docTop = view.documentTop; - if (startCoords) { - if (goal == null) - goal = startCoords.left - rect.left; - startY = dir < 0 ? startCoords.top : startCoords.bottom; - } - else { - let line = view.viewState.lineBlockAt(startPos - docTop); - if (goal == null) - goal = Math.min(rect.right - rect.left, view.defaultCharacterWidth * (startPos - line.from)); - startY = (dir < 0 ? line.top : line.bottom) + docTop; - } - let resolvedGoal = rect.left + goal; - let dist = distance !== null && distance !== void 0 ? distance : (view.defaultLineHeight >> 1); - for (let extra = 0;; extra += 10) { - let curY = startY + (dist + extra) * dir; - let pos = posAtCoords(view, { x: resolvedGoal, y: curY }, false, dir); - if (curY < rect.top || curY > rect.bottom || (dir < 0 ? pos < startPos : pos > startPos)) - return EditorSelection.cursor(pos, start.assoc, undefined, goal); - } - } - function skipAtoms(view, oldPos, pos) { - let atoms = view.pluginField(PluginField.atomicRanges); - for (;;) { - let moved = false; - for (let set of atoms) { - set.between(pos.from - 1, pos.from + 1, (from, to, value) => { - if (pos.from > from && pos.from < to) { - pos = oldPos.from > pos.from ? EditorSelection.cursor(from, 1) : EditorSelection.cursor(to, -1); - moved = true; - } - }); - } - if (!moved) - return pos; - } - } - - // This will also be where dragging info and such goes - class InputState { - constructor(view) { - this.lastKeyCode = 0; - this.lastKeyTime = 0; - // On iOS, some keys need to have their default behavior happen - // (after which we retroactively handle them and reset the DOM) to - // avoid messing up the virtual keyboard state. - this.pendingIOSKey = undefined; - this.lastSelectionOrigin = null; - this.lastSelectionTime = 0; - this.lastEscPress = 0; - this.lastContextMenu = 0; - this.scrollHandlers = []; - this.registeredEvents = []; - this.customHandlers = []; - // -1 means not in a composition. Otherwise, this counts the number - // of changes made during the composition. The count is used to - // avoid treating the start state of the composition, before any - // changes have been made, as part of the composition. - this.composing = -1; - // Tracks whether the next change should be marked as starting the - // composition (null means no composition, true means next is the - // first, false means first has already been marked for this - // composition) - this.compositionFirstChange = null; - this.compositionEndedAt = 0; - this.rapidCompositionStart = false; - this.mouseSelection = null; - for (let type in handlers) { - let handler = handlers[type]; - view.contentDOM.addEventListener(type, (event) => { - if (!eventBelongsToEditor(view, event) || this.ignoreDuringComposition(event)) - return; - if (type == "keydown" && this.keydown(view, event)) - return; - if (this.mustFlushObserver(event)) - view.observer.forceFlush(); - if (this.runCustomHandlers(type, view, event)) - event.preventDefault(); - else - handler(view, event); - }); - this.registeredEvents.push(type); - } - this.notifiedFocused = view.hasFocus; - this.ensureHandlers(view); - // On Safari adding an input event handler somehow prevents an - // issue where the composition vanishes when you press enter. - if (browser.safari) - view.contentDOM.addEventListener("input", () => null); - } - setSelectionOrigin(origin) { - this.lastSelectionOrigin = origin; - this.lastSelectionTime = Date.now(); - } - ensureHandlers(view) { - let handlers = this.customHandlers = view.pluginField(domEventHandlers); - for (let set of handlers) { - for (let type in set.handlers) - if (this.registeredEvents.indexOf(type) < 0 && type != "scroll") { - this.registeredEvents.push(type); - view.contentDOM.addEventListener(type, (event) => { - if (!eventBelongsToEditor(view, event)) - return; - if (this.runCustomHandlers(type, view, event)) - event.preventDefault(); - }); - } - } - } - runCustomHandlers(type, view, event) { - for (let set of this.customHandlers) { - let handler = set.handlers[type]; - if (handler) { - try { - if (handler.call(set.plugin, event, view) || event.defaultPrevented) - return true; - } - catch (e) { - logException(view.state, e); - } - } - } - return false; - } - runScrollHandlers(view, event) { - for (let set of this.customHandlers) { - let handler = set.handlers.scroll; - if (handler) { - try { - handler.call(set.plugin, event, view); - } - catch (e) { - logException(view.state, e); - } - } - } - } - keydown(view, event) { - // Must always run, even if a custom handler handled the event - this.lastKeyCode = event.keyCode; - this.lastKeyTime = Date.now(); - if (event.keyCode == 9 && Date.now() < this.lastEscPress + 2000) - return true; - // Chrome for Android usually doesn't fire proper key events, but - // occasionally does, usually surrounded by a bunch of complicated - // composition changes. When an enter or backspace key event is - // seen, hold off on handling DOM events for a bit, and then - // dispatch it. - if (browser.android && browser.chrome && !event.synthetic && - (event.keyCode == 13 || event.keyCode == 8)) { - view.observer.delayAndroidKey(event.key, event.keyCode); - return true; - } - // Prevent the default behavior of Enter on iOS makes the - // virtual keyboard get stuck in the wrong (lowercase) - // state. So we let it go through, and then, in - // applyDOMChange, notify key handlers of it and reset to - // the state they produce. - let pending; - if (browser.ios && (pending = PendingKeys.find(key => key.keyCode == event.keyCode)) && - !(event.ctrlKey || event.altKey || event.metaKey) && !event.synthetic) { - this.pendingIOSKey = pending; - setTimeout(() => this.flushIOSKey(view), 250); - return true; - } - return false; - } - flushIOSKey(view) { - let key = this.pendingIOSKey; - if (!key) - return false; - this.pendingIOSKey = undefined; - return dispatchKey(view.contentDOM, key.key, key.keyCode); - } - ignoreDuringComposition(event) { - if (!/^key/.test(event.type)) - return false; - if (this.composing > 0) - return true; - // See https://www.stum.de/2016/06/24/handling-ime-events-in-javascript/. - // On some input method editors (IMEs), the Enter key is used to - // confirm character selection. On Safari, when Enter is pressed, - // compositionend and keydown events are sometimes emitted in the - // wrong order. The key event should still be ignored, even when - // it happens after the compositionend event. - if (browser.safari && Date.now() - this.compositionEndedAt < 500) { - this.compositionEndedAt = 0; - return true; - } - return false; - } - mustFlushObserver(event) { - return (event.type == "keydown" && event.keyCode != 229) || - event.type == "compositionend" && !browser.ios; - } - startMouseSelection(mouseSelection) { - if (this.mouseSelection) - this.mouseSelection.destroy(); - this.mouseSelection = mouseSelection; - } - update(update) { - if (this.mouseSelection) - this.mouseSelection.update(update); - if (update.transactions.length) - this.lastKeyCode = this.lastSelectionTime = 0; - } - destroy() { - if (this.mouseSelection) - this.mouseSelection.destroy(); - } - } - const PendingKeys = [ - { key: "Backspace", keyCode: 8, inputType: "deleteContentBackward" }, - { key: "Enter", keyCode: 13, inputType: "insertParagraph" }, - { key: "Delete", keyCode: 46, inputType: "deleteContentForward" } - ]; - // Key codes for modifier keys - const modifierCodes = [16, 17, 18, 20, 91, 92, 224, 225]; - class MouseSelection { - constructor(view, startEvent, style, mustSelect) { - this.view = view; - this.style = style; - this.mustSelect = mustSelect; - this.lastEvent = startEvent; - let doc = view.contentDOM.ownerDocument; - doc.addEventListener("mousemove", this.move = this.move.bind(this)); - doc.addEventListener("mouseup", this.up = this.up.bind(this)); - this.extend = startEvent.shiftKey; - this.multiple = view.state.facet(EditorState.allowMultipleSelections) && addsSelectionRange(view, startEvent); - this.dragMove = dragMovesSelection(view, startEvent); - this.dragging = isInPrimarySelection(view, startEvent) && getClickType(startEvent) == 1 ? null : false; - // When clicking outside of the selection, immediately apply the - // effect of starting the selection - if (this.dragging === false) { - startEvent.preventDefault(); - this.select(startEvent); - } - } - move(event) { - if (event.buttons == 0) - return this.destroy(); - if (this.dragging !== false) - return; - this.select(this.lastEvent = event); - } - up(event) { - if (this.dragging == null) - this.select(this.lastEvent); - if (!this.dragging) - event.preventDefault(); - this.destroy(); - } - destroy() { - let doc = this.view.contentDOM.ownerDocument; - doc.removeEventListener("mousemove", this.move); - doc.removeEventListener("mouseup", this.up); - this.view.inputState.mouseSelection = null; - } - select(event) { - let selection = this.style.get(event, this.extend, this.multiple); - if (this.mustSelect || !selection.eq(this.view.state.selection) || - selection.main.assoc != this.view.state.selection.main.assoc) - this.view.dispatch({ - selection, - userEvent: "select.pointer", - scrollIntoView: true - }); - this.mustSelect = false; - } - update(update) { - if (update.docChanged && this.dragging) - this.dragging = this.dragging.map(update.changes); - if (this.style.update(update)) - setTimeout(() => this.select(this.lastEvent), 20); - } - } - function addsSelectionRange(view, event) { - let facet = view.state.facet(clickAddsSelectionRange); - return facet.length ? facet[0](event) : browser.mac ? event.metaKey : event.ctrlKey; - } - function dragMovesSelection(view, event) { - let facet = view.state.facet(dragMovesSelection$1); - return facet.length ? facet[0](event) : browser.mac ? !event.altKey : !event.ctrlKey; - } - function isInPrimarySelection(view, event) { - let { main } = view.state.selection; - if (main.empty) - return false; - // On boundary clicks, check whether the coordinates are inside the - // selection's client rectangles - let sel = getSelection(view.root); - if (sel.rangeCount == 0) - return true; - let rects = sel.getRangeAt(0).getClientRects(); - for (let i = 0; i < rects.length; i++) { - let rect = rects[i]; - if (rect.left <= event.clientX && rect.right >= event.clientX && - rect.top <= event.clientY && rect.bottom >= event.clientY) - return true; - } - return false; - } - function eventBelongsToEditor(view, event) { - if (!event.bubbles) - return true; - if (event.defaultPrevented) - return false; - for (let node = event.target, cView; node != view.contentDOM; node = node.parentNode) - if (!node || node.nodeType == 11 || ((cView = ContentView.get(node)) && cView.ignoreEvent(event))) - return false; - return true; - } - const handlers = /*@__PURE__*/Object.create(null); - // This is very crude, but unfortunately both these browsers _pretend_ - // that they have a clipboard API—all the objects and methods are - // there, they just don't work, and they are hard to test. - const brokenClipboardAPI = (browser.ie && browser.ie_version < 15) || - (browser.ios && browser.webkit_version < 604); - function capturePaste(view) { - let parent = view.dom.parentNode; - if (!parent) - return; - let target = parent.appendChild(document.createElement("textarea")); - target.style.cssText = "position: fixed; left: -10000px; top: 10px"; - target.focus(); - setTimeout(() => { - view.focus(); - target.remove(); - doPaste(view, target.value); - }, 50); - } - function doPaste(view, input) { - let { state } = view, changes, i = 1, text = state.toText(input); - let byLine = text.lines == state.selection.ranges.length; - let linewise = lastLinewiseCopy != null && state.selection.ranges.every(r => r.empty) && lastLinewiseCopy == text.toString(); - if (linewise) { - let lastLine = -1; - changes = state.changeByRange(range => { - let line = state.doc.lineAt(range.from); - if (line.from == lastLine) - return { range }; - lastLine = line.from; - let insert = state.toText((byLine ? text.line(i++).text : input) + state.lineBreak); - return { changes: { from: line.from, insert }, - range: EditorSelection.cursor(range.from + insert.length) }; - }); - } - else if (byLine) { - changes = state.changeByRange(range => { - let line = text.line(i++); - return { changes: { from: range.from, to: range.to, insert: line.text }, - range: EditorSelection.cursor(range.from + line.length) }; - }); - } - else { - changes = state.replaceSelection(text); - } - view.dispatch(changes, { - userEvent: "input.paste", - scrollIntoView: true - }); - } - handlers.keydown = (view, event) => { - view.inputState.setSelectionOrigin("select"); - if (event.keyCode == 27) - view.inputState.lastEscPress = Date.now(); - else if (modifierCodes.indexOf(event.keyCode) < 0) - view.inputState.lastEscPress = 0; - }; - let lastTouch = 0; - handlers.touchstart = (view, e) => { - lastTouch = Date.now(); - view.inputState.setSelectionOrigin("select.pointer"); - }; - handlers.touchmove = view => { - view.inputState.setSelectionOrigin("select.pointer"); - }; - handlers.mousedown = (view, event) => { - view.observer.flush(); - if (lastTouch > Date.now() - 2000 && getClickType(event) == 1) - return; // Ignore touch interaction - let style = null; - for (let makeStyle of view.state.facet(mouseSelectionStyle)) { - style = makeStyle(view, event); - if (style) - break; - } - if (!style && event.button == 0) - style = basicMouseSelection(view, event); - if (style) { - let mustFocus = view.root.activeElement != view.contentDOM; - if (mustFocus) - view.observer.ignore(() => focusPreventScroll(view.contentDOM)); - view.inputState.startMouseSelection(new MouseSelection(view, event, style, mustFocus)); - } - }; - function rangeForClick(view, pos, bias, type) { - if (type == 1) { // Single click - return EditorSelection.cursor(pos, bias); - } - else if (type == 2) { // Double click - return groupAt(view.state, pos, bias); - } - else { // Triple click - let visual = LineView.find(view.docView, pos), line = view.state.doc.lineAt(visual ? visual.posAtEnd : pos); - let from = visual ? visual.posAtStart : line.from, to = visual ? visual.posAtEnd : line.to; - if (to < view.state.doc.length && to == line.to) - to++; - return EditorSelection.range(from, to); - } - } - let insideY = (y, rect) => y >= rect.top && y <= rect.bottom; - let inside = (x, y, rect) => insideY(y, rect) && x >= rect.left && x <= rect.right; - // Try to determine, for the given coordinates, associated with the - // given position, whether they are related to the element before or - // the element after the position. - function findPositionSide(view, pos, x, y) { - let line = LineView.find(view.docView, pos); - if (!line) - return 1; - let off = pos - line.posAtStart; - // Line boundaries point into the line - if (off == 0) - return 1; - if (off == line.length) - return -1; - // Positions on top of an element point at that element - let before = line.coordsAt(off, -1); - if (before && inside(x, y, before)) - return -1; - let after = line.coordsAt(off, 1); - if (after && inside(x, y, after)) - return 1; - // This is probably a line wrap point. Pick before if the point is - // beside it. - return before && insideY(y, before) ? -1 : 1; - } - function queryPos(view, event) { - let pos = view.posAtCoords({ x: event.clientX, y: event.clientY }, false); - return { pos, bias: findPositionSide(view, pos, event.clientX, event.clientY) }; - } - const BadMouseDetail = browser.ie && browser.ie_version <= 11; - let lastMouseDown = null, lastMouseDownCount = 0, lastMouseDownTime = 0; - function getClickType(event) { - if (!BadMouseDetail) - return event.detail; - let last = lastMouseDown, lastTime = lastMouseDownTime; - lastMouseDown = event; - lastMouseDownTime = Date.now(); - return lastMouseDownCount = !last || (lastTime > Date.now() - 400 && Math.abs(last.clientX - event.clientX) < 2 && - Math.abs(last.clientY - event.clientY) < 2) ? (lastMouseDownCount + 1) % 3 : 1; - } - function basicMouseSelection(view, event) { - let start = queryPos(view, event), type = getClickType(event); - let startSel = view.state.selection; - let last = start, lastEvent = event; - return { - update(update) { - if (update.docChanged) { - if (start) - start.pos = update.changes.mapPos(start.pos); - startSel = startSel.map(update.changes); - lastEvent = null; - } - }, - get(event, extend, multiple) { - let cur; - if (lastEvent && event.clientX == lastEvent.clientX && event.clientY == lastEvent.clientY) - cur = last; - else { - cur = last = queryPos(view, event); - lastEvent = event; - } - if (!cur || !start) - return startSel; - let range = rangeForClick(view, cur.pos, cur.bias, type); - if (start.pos != cur.pos && !extend) { - let startRange = rangeForClick(view, start.pos, start.bias, type); - let from = Math.min(startRange.from, range.from), to = Math.max(startRange.to, range.to); - range = from < range.from ? EditorSelection.range(from, to) : EditorSelection.range(to, from); - } - if (extend) - return startSel.replaceRange(startSel.main.extend(range.from, range.to)); - else if (multiple) - return startSel.addRange(range); - else - return EditorSelection.create([range]); - } - }; - } - handlers.dragstart = (view, event) => { - let { selection: { main } } = view.state; - let { mouseSelection } = view.inputState; - if (mouseSelection) - mouseSelection.dragging = main; - if (event.dataTransfer) { - event.dataTransfer.setData("Text", view.state.sliceDoc(main.from, main.to)); - event.dataTransfer.effectAllowed = "copyMove"; - } - }; - function dropText(view, event, text, direct) { - if (!text) - return; - let dropPos = view.posAtCoords({ x: event.clientX, y: event.clientY }, false); - event.preventDefault(); - let { mouseSelection } = view.inputState; - let del = direct && mouseSelection && mouseSelection.dragging && mouseSelection.dragMove ? - { from: mouseSelection.dragging.from, to: mouseSelection.dragging.to } : null; - let ins = { from: dropPos, insert: text }; - let changes = view.state.changes(del ? [del, ins] : ins); - view.focus(); - view.dispatch({ - changes, - selection: { anchor: changes.mapPos(dropPos, -1), head: changes.mapPos(dropPos, 1) }, - userEvent: del ? "move.drop" : "input.drop" - }); - } - handlers.drop = (view, event) => { - if (!event.dataTransfer) - return; - if (view.state.readOnly) - return event.preventDefault(); - let files = event.dataTransfer.files; - if (files && files.length) { // For a file drop, read the file's text. - event.preventDefault(); - let text = Array(files.length), read = 0; - let finishFile = () => { - if (++read == files.length) - dropText(view, event, text.filter(s => s != null).join(view.state.lineBreak), false); - }; - for (let i = 0; i < files.length; i++) { - let reader = new FileReader; - reader.onerror = finishFile; - reader.onload = () => { - if (!/[\x00-\x08\x0e-\x1f]{2}/.test(reader.result)) - text[i] = reader.result; - finishFile(); - }; - reader.readAsText(files[i]); - } - } - else { - dropText(view, event, event.dataTransfer.getData("Text"), true); - } - }; - handlers.paste = (view, event) => { - if (view.state.readOnly) - return event.preventDefault(); - view.observer.flush(); - let data = brokenClipboardAPI ? null : event.clipboardData; - if (data) { - doPaste(view, data.getData("text/plain")); - event.preventDefault(); - } - else { - capturePaste(view); - } - }; - function captureCopy(view, text) { - // The extra wrapper is somehow necessary on IE/Edge to prevent the - // content from being mangled when it is put onto the clipboard - let parent = view.dom.parentNode; - if (!parent) - return; - let target = parent.appendChild(document.createElement("textarea")); - target.style.cssText = "position: fixed; left: -10000px; top: 10px"; - target.value = text; - target.focus(); - target.selectionEnd = text.length; - target.selectionStart = 0; - setTimeout(() => { - target.remove(); - view.focus(); - }, 50); - } - function copiedRange(state) { - let content = [], ranges = [], linewise = false; - for (let range of state.selection.ranges) - if (!range.empty) { - content.push(state.sliceDoc(range.from, range.to)); - ranges.push(range); - } - if (!content.length) { - // Nothing selected, do a line-wise copy - let upto = -1; - for (let { from } of state.selection.ranges) { - let line = state.doc.lineAt(from); - if (line.number > upto) { - content.push(line.text); - ranges.push({ from: line.from, to: Math.min(state.doc.length, line.to + 1) }); - } - upto = line.number; - } - linewise = true; - } - return { text: content.join(state.lineBreak), ranges, linewise }; - } - let lastLinewiseCopy = null; - handlers.copy = handlers.cut = (view, event) => { - let { text, ranges, linewise } = copiedRange(view.state); - if (!text && !linewise) - return; - lastLinewiseCopy = linewise ? text : null; - let data = brokenClipboardAPI ? null : event.clipboardData; - if (data) { - event.preventDefault(); - data.clearData(); - data.setData("text/plain", text); - } - else { - captureCopy(view, text); - } - if (event.type == "cut" && !view.state.readOnly) - view.dispatch({ - changes: ranges, - scrollIntoView: true, - userEvent: "delete.cut" - }); - }; - handlers.focus = handlers.blur = view => { - setTimeout(() => { - if (view.hasFocus != view.inputState.notifiedFocused) - view.update([]); - }, 10); - }; - function forceClearComposition(view, rapid) { - if (view.docView.compositionDeco.size) { - view.inputState.rapidCompositionStart = rapid; - try { - view.update([]); - } - finally { - view.inputState.rapidCompositionStart = false; - } - } - } - handlers.compositionstart = handlers.compositionupdate = view => { - if (view.inputState.compositionFirstChange == null) - view.inputState.compositionFirstChange = true; - if (view.inputState.composing < 0) { - // FIXME possibly set a timeout to clear it again on Android - view.inputState.composing = 0; - if (view.docView.compositionDeco.size) { - view.observer.flush(); - forceClearComposition(view, true); - } - } - }; - handlers.compositionend = view => { - view.inputState.composing = -1; - view.inputState.compositionEndedAt = Date.now(); - view.inputState.compositionFirstChange = null; - setTimeout(() => { - if (view.inputState.composing < 0) - forceClearComposition(view, false); - }, 50); - }; - handlers.contextmenu = view => { - view.inputState.lastContextMenu = Date.now(); - }; - handlers.beforeinput = (view, event) => { - var _a; - // Because Chrome Android doesn't fire useful key events, use - // beforeinput to detect backspace (and possibly enter and delete, - // but those usually don't even seem to fire beforeinput events at - // the moment) and fake a key event for it. - // - // (preventDefault on beforeinput, though supported in the spec, - // seems to do nothing at all on Chrome). - let pending; - if (browser.chrome && browser.android && (pending = PendingKeys.find(key => key.inputType == event.inputType))) { - view.observer.delayAndroidKey(pending.key, pending.keyCode); - if (pending.key == "Backspace" || pending.key == "Delete") { - let startViewHeight = ((_a = window.visualViewport) === null || _a === void 0 ? void 0 : _a.height) || 0; - setTimeout(() => { - var _a; - // Backspacing near uneditable nodes on Chrome Android sometimes - // closes the virtual keyboard. This tries to crudely detect - // that and refocus to get it back. - if ((((_a = window.visualViewport) === null || _a === void 0 ? void 0 : _a.height) || 0) > startViewHeight + 10 && view.hasFocus) { - view.contentDOM.blur(); - view.focus(); - } - }, 100); - } - } - }; - - const wrappingWhiteSpace = ["pre-wrap", "normal", "pre-line", "break-spaces"]; - class HeightOracle { - constructor() { - this.doc = Text.empty; - this.lineWrapping = false; - this.direction = Direction.LTR; - this.heightSamples = {}; - this.lineHeight = 14; - this.charWidth = 7; - this.lineLength = 30; - // Used to track, during updateHeight, if any actual heights changed - this.heightChanged = false; - } - heightForGap(from, to) { - let lines = this.doc.lineAt(to).number - this.doc.lineAt(from).number + 1; - if (this.lineWrapping) - lines += Math.ceil(((to - from) - (lines * this.lineLength * 0.5)) / this.lineLength); - return this.lineHeight * lines; - } - heightForLine(length) { - if (!this.lineWrapping) - return this.lineHeight; - let lines = 1 + Math.max(0, Math.ceil((length - this.lineLength) / (this.lineLength - 5))); - return lines * this.lineHeight; - } - setDoc(doc) { this.doc = doc; return this; } - mustRefreshForStyle(whiteSpace, direction) { - return (wrappingWhiteSpace.indexOf(whiteSpace) > -1) != this.lineWrapping || this.direction != direction; - } - mustRefreshForHeights(lineHeights) { - let newHeight = false; - for (let i = 0; i < lineHeights.length; i++) { - let h = lineHeights[i]; - if (h < 0) { - i++; - } - else if (!this.heightSamples[Math.floor(h * 10)]) { // Round to .1 pixels - newHeight = true; - this.heightSamples[Math.floor(h * 10)] = true; - } - } - return newHeight; - } - refresh(whiteSpace, direction, lineHeight, charWidth, lineLength, knownHeights) { - let lineWrapping = wrappingWhiteSpace.indexOf(whiteSpace) > -1; - let changed = Math.round(lineHeight) != Math.round(this.lineHeight) || - this.lineWrapping != lineWrapping || - this.direction != direction; - this.lineWrapping = lineWrapping; - this.direction = direction; - this.lineHeight = lineHeight; - this.charWidth = charWidth; - this.lineLength = lineLength; - if (changed) { - this.heightSamples = {}; - for (let i = 0; i < knownHeights.length; i++) { - let h = knownHeights[i]; - if (h < 0) - i++; - else - this.heightSamples[Math.floor(h * 10)] = true; - } - } - return changed; - } - } - // This object is used by `updateHeight` to make DOM measurements - // arrive at the right nides. The `heights` array is a sequence of - // block heights, starting from position `from`. - class MeasuredHeights { - constructor(from, heights) { - this.from = from; - this.heights = heights; - this.index = 0; - } - get more() { return this.index < this.heights.length; } - } - /** - Record used to represent information about a block-level element - in the editor view. - */ - class BlockInfo { - /** - @internal - */ - constructor( - /** - The start of the element in the document. - */ - from, - /** - The length of the element. - */ - length, - /** - The top position of the element (relative to the top of the - document). - */ - top, - /** - Its height. - */ - height, - /** - The type of element this is. When querying lines, this may be - an array of all the blocks that make up the line. - */ - type) { - this.from = from; - this.length = length; - this.top = top; - this.height = height; - this.type = type; - } - /** - The end of the element as a document position. - */ - get to() { return this.from + this.length; } - /** - The bottom position of the element. - */ - get bottom() { return this.top + this.height; } - /** - @internal - */ - join(other) { - let detail = (Array.isArray(this.type) ? this.type : [this]) - .concat(Array.isArray(other.type) ? other.type : [other]); - return new BlockInfo(this.from, this.length + other.length, this.top, this.height + other.height, detail); - } - /** - FIXME remove on next breaking release @internal - */ - moveY(offset) { - return !offset ? this : new BlockInfo(this.from, this.length, this.top + offset, this.height, Array.isArray(this.type) ? this.type.map(b => b.moveY(offset)) : this.type); - } - } - var QueryType$1 = /*@__PURE__*/(function (QueryType) { - QueryType[QueryType["ByPos"] = 0] = "ByPos"; - QueryType[QueryType["ByHeight"] = 1] = "ByHeight"; - QueryType[QueryType["ByPosNoHeight"] = 2] = "ByPosNoHeight"; - return QueryType})(QueryType$1 || (QueryType$1 = {})); - const Epsilon = 1e-3; - class HeightMap { - constructor(length, // The number of characters covered - height, // Height of this part of the document - flags = 2 /* Outdated */) { - this.length = length; - this.height = height; - this.flags = flags; - } - get outdated() { return (this.flags & 2 /* Outdated */) > 0; } - set outdated(value) { this.flags = (value ? 2 /* Outdated */ : 0) | (this.flags & ~2 /* Outdated */); } - setHeight(oracle, height) { - if (this.height != height) { - if (Math.abs(this.height - height) > Epsilon) - oracle.heightChanged = true; - this.height = height; - } - } - // Base case is to replace a leaf node, which simply builds a tree - // from the new nodes and returns that (HeightMapBranch and - // HeightMapGap override this to actually use from/to) - replace(_from, _to, nodes) { - return HeightMap.of(nodes); - } - // Again, these are base cases, and are overridden for branch and gap nodes. - decomposeLeft(_to, result) { result.push(this); } - decomposeRight(_from, result) { result.push(this); } - applyChanges(decorations, oldDoc, oracle, changes) { - let me = this; - for (let i = changes.length - 1; i >= 0; i--) { - let { fromA, toA, fromB, toB } = changes[i]; - let start = me.lineAt(fromA, QueryType$1.ByPosNoHeight, oldDoc, 0, 0); - let end = start.to >= toA ? start : me.lineAt(toA, QueryType$1.ByPosNoHeight, oldDoc, 0, 0); - toB += end.to - toA; - toA = end.to; - while (i > 0 && start.from <= changes[i - 1].toA) { - fromA = changes[i - 1].fromA; - fromB = changes[i - 1].fromB; - i--; - if (fromA < start.from) - start = me.lineAt(fromA, QueryType$1.ByPosNoHeight, oldDoc, 0, 0); - } - fromB += start.from - fromA; - fromA = start.from; - let nodes = NodeBuilder.build(oracle, decorations, fromB, toB); - me = me.replace(fromA, toA, nodes); - } - return me.updateHeight(oracle, 0); - } - static empty() { return new HeightMapText(0, 0); } - // nodes uses null values to indicate the position of line breaks. - // There are never line breaks at the start or end of the array, or - // two line breaks next to each other, and the array isn't allowed - // to be empty (same restrictions as return value from the builder). - static of(nodes) { - if (nodes.length == 1) - return nodes[0]; - let i = 0, j = nodes.length, before = 0, after = 0; - for (;;) { - if (i == j) { - if (before > after * 2) { - let split = nodes[i - 1]; - if (split.break) - nodes.splice(--i, 1, split.left, null, split.right); - else - nodes.splice(--i, 1, split.left, split.right); - j += 1 + split.break; - before -= split.size; - } - else if (after > before * 2) { - let split = nodes[j]; - if (split.break) - nodes.splice(j, 1, split.left, null, split.right); - else - nodes.splice(j, 1, split.left, split.right); - j += 2 + split.break; - after -= split.size; - } - else { - break; - } - } - else if (before < after) { - let next = nodes[i++]; - if (next) - before += next.size; - } - else { - let next = nodes[--j]; - if (next) - after += next.size; - } - } - let brk = 0; - if (nodes[i - 1] == null) { - brk = 1; - i--; - } - else if (nodes[i] == null) { - brk = 1; - j++; - } - return new HeightMapBranch(HeightMap.of(nodes.slice(0, i)), brk, HeightMap.of(nodes.slice(j))); - } - } - HeightMap.prototype.size = 1; - class HeightMapBlock extends HeightMap { - constructor(length, height, type) { - super(length, height); - this.type = type; - } - blockAt(_height, _doc, top, offset) { - return new BlockInfo(offset, this.length, top, this.height, this.type); - } - lineAt(_value, _type, doc, top, offset) { - return this.blockAt(0, doc, top, offset); - } - forEachLine(_from, _to, doc, top, offset, f) { - f(this.blockAt(0, doc, top, offset)); - } - updateHeight(oracle, offset = 0, _force = false, measured) { - if (measured && measured.from <= offset && measured.more) - this.setHeight(oracle, measured.heights[measured.index++]); - this.outdated = false; - return this; - } - toString() { return `block(${this.length})`; } - } - class HeightMapText extends HeightMapBlock { - constructor(length, height) { - super(length, height, BlockType.Text); - this.collapsed = 0; // Amount of collapsed content in the line - this.widgetHeight = 0; // Maximum inline widget height - } - replace(_from, _to, nodes) { - let node = nodes[0]; - if (nodes.length == 1 && (node instanceof HeightMapText || node instanceof HeightMapGap && (node.flags & 4 /* SingleLine */)) && - Math.abs(this.length - node.length) < 10) { - if (node instanceof HeightMapGap) - node = new HeightMapText(node.length, this.height); - else - node.height = this.height; - if (!this.outdated) - node.outdated = false; - return node; - } - else { - return HeightMap.of(nodes); - } - } - updateHeight(oracle, offset = 0, force = false, measured) { - if (measured && measured.from <= offset && measured.more) - this.setHeight(oracle, measured.heights[measured.index++]); - else if (force || this.outdated) - this.setHeight(oracle, Math.max(this.widgetHeight, oracle.heightForLine(this.length - this.collapsed))); - this.outdated = false; - return this; - } - toString() { - return `line(${this.length}${this.collapsed ? -this.collapsed : ""}${this.widgetHeight ? ":" + this.widgetHeight : ""})`; - } - } - class HeightMapGap extends HeightMap { - constructor(length) { super(length, 0); } - lines(doc, offset) { - let firstLine = doc.lineAt(offset).number, lastLine = doc.lineAt(offset + this.length).number; - return { firstLine, lastLine, lineHeight: this.height / (lastLine - firstLine + 1) }; - } - blockAt(height, doc, top, offset) { - let { firstLine, lastLine, lineHeight } = this.lines(doc, offset); - let line = Math.max(0, Math.min(lastLine - firstLine, Math.floor((height - top) / lineHeight))); - let { from, length } = doc.line(firstLine + line); - return new BlockInfo(from, length, top + lineHeight * line, lineHeight, BlockType.Text); - } - lineAt(value, type, doc, top, offset) { - if (type == QueryType$1.ByHeight) - return this.blockAt(value, doc, top, offset); - if (type == QueryType$1.ByPosNoHeight) { - let { from, to } = doc.lineAt(value); - return new BlockInfo(from, to - from, 0, 0, BlockType.Text); - } - let { firstLine, lineHeight } = this.lines(doc, offset); - let { from, length, number } = doc.lineAt(value); - return new BlockInfo(from, length, top + lineHeight * (number - firstLine), lineHeight, BlockType.Text); - } - forEachLine(from, to, doc, top, offset, f) { - let { firstLine, lineHeight } = this.lines(doc, offset); - for (let pos = Math.max(from, offset), end = Math.min(offset + this.length, to); pos <= end;) { - let line = doc.lineAt(pos); - if (pos == from) - top += lineHeight * (line.number - firstLine); - f(new BlockInfo(line.from, line.length, top, lineHeight, BlockType.Text)); - top += lineHeight; - pos = line.to + 1; - } - } - replace(from, to, nodes) { - let after = this.length - to; - if (after > 0) { - let last = nodes[nodes.length - 1]; - if (last instanceof HeightMapGap) - nodes[nodes.length - 1] = new HeightMapGap(last.length + after); - else - nodes.push(null, new HeightMapGap(after - 1)); - } - if (from > 0) { - let first = nodes[0]; - if (first instanceof HeightMapGap) - nodes[0] = new HeightMapGap(from + first.length); - else - nodes.unshift(new HeightMapGap(from - 1), null); - } - return HeightMap.of(nodes); - } - decomposeLeft(to, result) { - result.push(new HeightMapGap(to - 1), null); - } - decomposeRight(from, result) { - result.push(null, new HeightMapGap(this.length - from - 1)); - } - updateHeight(oracle, offset = 0, force = false, measured) { - let end = offset + this.length; - if (measured && measured.from <= offset + this.length && measured.more) { - // Fill in part of this gap with measured lines. We know there - // can't be widgets or collapsed ranges in those lines, because - // they would already have been added to the heightmap (gaps - // only contain plain text). - let nodes = [], pos = Math.max(offset, measured.from), singleHeight = -1; - let wasChanged = oracle.heightChanged; - if (measured.from > offset) - nodes.push(new HeightMapGap(measured.from - offset - 1).updateHeight(oracle, offset)); - while (pos <= end && measured.more) { - let len = oracle.doc.lineAt(pos).length; - if (nodes.length) - nodes.push(null); - let height = measured.heights[measured.index++]; - if (singleHeight == -1) - singleHeight = height; - else if (Math.abs(height - singleHeight) >= Epsilon) - singleHeight = -2; - let line = new HeightMapText(len, height); - line.outdated = false; - nodes.push(line); - pos += len + 1; - } - if (pos <= end) - nodes.push(null, new HeightMapGap(end - pos).updateHeight(oracle, pos)); - let result = HeightMap.of(nodes); - oracle.heightChanged = wasChanged || singleHeight < 0 || Math.abs(result.height - this.height) >= Epsilon || - Math.abs(singleHeight - this.lines(oracle.doc, offset).lineHeight) >= Epsilon; - return result; - } - else if (force || this.outdated) { - this.setHeight(oracle, oracle.heightForGap(offset, offset + this.length)); - this.outdated = false; - } - return this; - } - toString() { return `gap(${this.length})`; } - } - class HeightMapBranch extends HeightMap { - constructor(left, brk, right) { - super(left.length + brk + right.length, left.height + right.height, brk | (left.outdated || right.outdated ? 2 /* Outdated */ : 0)); - this.left = left; - this.right = right; - this.size = left.size + right.size; - } - get break() { return this.flags & 1 /* Break */; } - blockAt(height, doc, top, offset) { - let mid = top + this.left.height; - return height < mid ? this.left.blockAt(height, doc, top, offset) - : this.right.blockAt(height, doc, mid, offset + this.left.length + this.break); - } - lineAt(value, type, doc, top, offset) { - let rightTop = top + this.left.height, rightOffset = offset + this.left.length + this.break; - let left = type == QueryType$1.ByHeight ? value < rightTop : value < rightOffset; - let base = left ? this.left.lineAt(value, type, doc, top, offset) - : this.right.lineAt(value, type, doc, rightTop, rightOffset); - if (this.break || (left ? base.to < rightOffset : base.from > rightOffset)) - return base; - let subQuery = type == QueryType$1.ByPosNoHeight ? QueryType$1.ByPosNoHeight : QueryType$1.ByPos; - if (left) - return base.join(this.right.lineAt(rightOffset, subQuery, doc, rightTop, rightOffset)); - else - return this.left.lineAt(rightOffset, subQuery, doc, top, offset).join(base); - } - forEachLine(from, to, doc, top, offset, f) { - let rightTop = top + this.left.height, rightOffset = offset + this.left.length + this.break; - if (this.break) { - if (from < rightOffset) - this.left.forEachLine(from, to, doc, top, offset, f); - if (to >= rightOffset) - this.right.forEachLine(from, to, doc, rightTop, rightOffset, f); - } - else { - let mid = this.lineAt(rightOffset, QueryType$1.ByPos, doc, top, offset); - if (from < mid.from) - this.left.forEachLine(from, mid.from - 1, doc, top, offset, f); - if (mid.to >= from && mid.from <= to) - f(mid); - if (to > mid.to) - this.right.forEachLine(mid.to + 1, to, doc, rightTop, rightOffset, f); - } - } - replace(from, to, nodes) { - let rightStart = this.left.length + this.break; - if (to < rightStart) - return this.balanced(this.left.replace(from, to, nodes), this.right); - if (from > this.left.length) - return this.balanced(this.left, this.right.replace(from - rightStart, to - rightStart, nodes)); - let result = []; - if (from > 0) - this.decomposeLeft(from, result); - let left = result.length; - for (let node of nodes) - result.push(node); - if (from > 0) - mergeGaps(result, left - 1); - if (to < this.length) { - let right = result.length; - this.decomposeRight(to, result); - mergeGaps(result, right); - } - return HeightMap.of(result); - } - decomposeLeft(to, result) { - let left = this.left.length; - if (to <= left) - return this.left.decomposeLeft(to, result); - result.push(this.left); - if (this.break) { - left++; - if (to >= left) - result.push(null); - } - if (to > left) - this.right.decomposeLeft(to - left, result); - } - decomposeRight(from, result) { - let left = this.left.length, right = left + this.break; - if (from >= right) - return this.right.decomposeRight(from - right, result); - if (from < left) - this.left.decomposeRight(from, result); - if (this.break && from < right) - result.push(null); - result.push(this.right); - } - balanced(left, right) { - if (left.size > 2 * right.size || right.size > 2 * left.size) - return HeightMap.of(this.break ? [left, null, right] : [left, right]); - this.left = left; - this.right = right; - this.height = left.height + right.height; - this.outdated = left.outdated || right.outdated; - this.size = left.size + right.size; - this.length = left.length + this.break + right.length; - return this; - } - updateHeight(oracle, offset = 0, force = false, measured) { - let { left, right } = this, rightStart = offset + left.length + this.break, rebalance = null; - if (measured && measured.from <= offset + left.length && measured.more) - rebalance = left = left.updateHeight(oracle, offset, force, measured); - else - left.updateHeight(oracle, offset, force); - if (measured && measured.from <= rightStart + right.length && measured.more) - rebalance = right = right.updateHeight(oracle, rightStart, force, measured); - else - right.updateHeight(oracle, rightStart, force); - if (rebalance) - return this.balanced(left, right); - this.height = this.left.height + this.right.height; - this.outdated = false; - return this; - } - toString() { return this.left + (this.break ? " " : "-") + this.right; } - } - function mergeGaps(nodes, around) { - let before, after; - if (nodes[around] == null && - (before = nodes[around - 1]) instanceof HeightMapGap && - (after = nodes[around + 1]) instanceof HeightMapGap) - nodes.splice(around - 1, 3, new HeightMapGap(before.length + 1 + after.length)); - } - const relevantWidgetHeight = 5; - class NodeBuilder { - constructor(pos, oracle) { - this.pos = pos; - this.oracle = oracle; - this.nodes = []; - this.lineStart = -1; - this.lineEnd = -1; - this.covering = null; - this.writtenTo = pos; - } - get isCovered() { - return this.covering && this.nodes[this.nodes.length - 1] == this.covering; - } - span(_from, to) { - if (this.lineStart > -1) { - let end = Math.min(to, this.lineEnd), last = this.nodes[this.nodes.length - 1]; - if (last instanceof HeightMapText) - last.length += end - this.pos; - else if (end > this.pos || !this.isCovered) - this.nodes.push(new HeightMapText(end - this.pos, -1)); - this.writtenTo = end; - if (to > end) { - this.nodes.push(null); - this.writtenTo++; - this.lineStart = -1; - } - } - this.pos = to; - } - point(from, to, deco) { - if (from < to || deco.heightRelevant) { - let height = deco.widget ? deco.widget.estimatedHeight : 0; - if (height < 0) - height = this.oracle.lineHeight; - let len = to - from; - if (deco.block) { - this.addBlock(new HeightMapBlock(len, height, deco.type)); - } - else if (len || height >= relevantWidgetHeight) { - this.addLineDeco(height, len); - } - } - else if (to > from) { - this.span(from, to); - } - if (this.lineEnd > -1 && this.lineEnd < this.pos) - this.lineEnd = this.oracle.doc.lineAt(this.pos).to; - } - enterLine() { - if (this.lineStart > -1) - return; - let { from, to } = this.oracle.doc.lineAt(this.pos); - this.lineStart = from; - this.lineEnd = to; - if (this.writtenTo < from) { - if (this.writtenTo < from - 1 || this.nodes[this.nodes.length - 1] == null) - this.nodes.push(this.blankContent(this.writtenTo, from - 1)); - this.nodes.push(null); - } - if (this.pos > from) - this.nodes.push(new HeightMapText(this.pos - from, -1)); - this.writtenTo = this.pos; - } - blankContent(from, to) { - let gap = new HeightMapGap(to - from); - if (this.oracle.doc.lineAt(from).to == to) - gap.flags |= 4 /* SingleLine */; - return gap; - } - ensureLine() { - this.enterLine(); - let last = this.nodes.length ? this.nodes[this.nodes.length - 1] : null; - if (last instanceof HeightMapText) - return last; - let line = new HeightMapText(0, -1); - this.nodes.push(line); - return line; - } - addBlock(block) { - this.enterLine(); - if (block.type == BlockType.WidgetAfter && !this.isCovered) - this.ensureLine(); - this.nodes.push(block); - this.writtenTo = this.pos = this.pos + block.length; - if (block.type != BlockType.WidgetBefore) - this.covering = block; - } - addLineDeco(height, length) { - let line = this.ensureLine(); - line.length += length; - line.collapsed += length; - line.widgetHeight = Math.max(line.widgetHeight, height); - this.writtenTo = this.pos = this.pos + length; - } - finish(from) { - let last = this.nodes.length == 0 ? null : this.nodes[this.nodes.length - 1]; - if (this.lineStart > -1 && !(last instanceof HeightMapText) && !this.isCovered) - this.nodes.push(new HeightMapText(0, -1)); - else if (this.writtenTo < this.pos || last == null) - this.nodes.push(this.blankContent(this.writtenTo, this.pos)); - let pos = from; - for (let node of this.nodes) { - if (node instanceof HeightMapText) - node.updateHeight(this.oracle, pos); - pos += node ? node.length : 1; - } - return this.nodes; - } - // Always called with a region that on both sides either stretches - // to a line break or the end of the document. - // The returned array uses null to indicate line breaks, but never - // starts or ends in a line break, or has multiple line breaks next - // to each other. - static build(oracle, decorations, from, to) { - let builder = new NodeBuilder(from, oracle); - RangeSet.spans(decorations, from, to, builder, 0); - return builder.finish(from); - } - } - function heightRelevantDecoChanges(a, b, diff) { - let comp = new DecorationComparator; - RangeSet.compare(a, b, diff, comp, 0); - return comp.changes; - } - class DecorationComparator { - constructor() { - this.changes = []; - } - compareRange() { } - comparePoint(from, to, a, b) { - if (from < to || a && a.heightRelevant || b && b.heightRelevant) - addRange(from, to, this.changes, 5); - } - } - - function visiblePixelRange(dom, paddingTop) { - let rect = dom.getBoundingClientRect(); - let left = Math.max(0, rect.left), right = Math.min(innerWidth, rect.right); - let top = Math.max(0, rect.top), bottom = Math.min(innerHeight, rect.bottom); - let body = dom.ownerDocument.body; - for (let parent = dom.parentNode; parent && parent != body;) { - if (parent.nodeType == 1) { - let elt = parent; - let style = window.getComputedStyle(elt); - if ((elt.scrollHeight > elt.clientHeight || elt.scrollWidth > elt.clientWidth) && - style.overflow != "visible") { - let parentRect = elt.getBoundingClientRect(); - left = Math.max(left, parentRect.left); - right = Math.min(right, parentRect.right); - top = Math.max(top, parentRect.top); - bottom = Math.min(bottom, parentRect.bottom); - } - parent = style.position == "absolute" || style.position == "fixed" ? elt.offsetParent : elt.parentNode; - } - else if (parent.nodeType == 11) { // Shadow root - parent = parent.host; - } - else { - break; - } - } - return { left: left - rect.left, right: Math.max(left, right) - rect.left, - top: top - (rect.top + paddingTop), bottom: Math.max(top, bottom) - (rect.top + paddingTop) }; - } - function fullPixelRange(dom, paddingTop) { - let rect = dom.getBoundingClientRect(); - return { left: 0, right: rect.right - rect.left, - top: paddingTop, bottom: rect.bottom - (rect.top + paddingTop) }; - } - // Line gaps are placeholder widgets used to hide pieces of overlong - // lines within the viewport, as a kludge to keep the editor - // responsive when a ridiculously long line is loaded into it. - class LineGap { - constructor(from, to, size) { - this.from = from; - this.to = to; - this.size = size; - } - static same(a, b) { - if (a.length != b.length) - return false; - for (let i = 0; i < a.length; i++) { - let gA = a[i], gB = b[i]; - if (gA.from != gB.from || gA.to != gB.to || gA.size != gB.size) - return false; - } - return true; - } - draw(wrapping) { - return Decoration.replace({ widget: new LineGapWidget(this.size, wrapping) }).range(this.from, this.to); - } - } - class LineGapWidget extends WidgetType { - constructor(size, vertical) { - super(); - this.size = size; - this.vertical = vertical; - } - eq(other) { return other.size == this.size && other.vertical == this.vertical; } - toDOM() { - let elt = document.createElement("div"); - if (this.vertical) { - elt.style.height = this.size + "px"; - } - else { - elt.style.width = this.size + "px"; - elt.style.height = "2px"; - elt.style.display = "inline-block"; - } - return elt; - } - get estimatedHeight() { return this.vertical ? this.size : -1; } - } - class ViewState { - constructor(state) { - this.state = state; - // These are contentDOM-local coordinates - this.pixelViewport = { left: 0, right: window.innerWidth, top: 0, bottom: 0 }; - this.inView = true; - this.paddingTop = 0; - this.paddingBottom = 0; - this.contentDOMWidth = 0; - this.contentDOMHeight = 0; - this.editorHeight = 0; - this.editorWidth = 0; - this.heightOracle = new HeightOracle; - // See VP.MaxDOMHeight - this.scaler = IdScaler; - this.scrollTarget = null; - // Briefly set to true when printing, to disable viewport limiting - this.printing = false; - // Flag set when editor content was redrawn, so that the next - // measure stage knows it must read DOM layout - this.mustMeasureContent = true; - this.visibleRanges = []; - // Cursor 'assoc' is only significant when the cursor is on a line - // wrap point, where it must stick to the character that it is - // associated with. Since browsers don't provide a reasonable - // interface to set or query this, when a selection is set that - // might cause this to be significant, this flag is set. The next - // measure phase will check whether the cursor is on a line-wrapping - // boundary and, if so, reset it to make sure it is positioned in - // the right place. - this.mustEnforceCursorAssoc = false; - this.heightMap = HeightMap.empty().applyChanges(state.facet(decorations), Text.empty, this.heightOracle.setDoc(state.doc), [new ChangedRange(0, 0, 0, state.doc.length)]); - this.viewport = this.getViewport(0, null); - this.updateViewportLines(); - this.updateForViewport(); - this.lineGaps = this.ensureLineGaps([]); - this.lineGapDeco = Decoration.set(this.lineGaps.map(gap => gap.draw(false))); - this.computeVisibleRanges(); - } - updateForViewport() { - let viewports = [this.viewport], { main } = this.state.selection; - for (let i = 0; i <= 1; i++) { - let pos = i ? main.head : main.anchor; - if (!viewports.some(({ from, to }) => pos >= from && pos <= to)) { - let { from, to } = this.lineBlockAt(pos); - viewports.push(new Viewport(from, to)); - } - } - this.viewports = viewports.sort((a, b) => a.from - b.from); - this.scaler = this.heightMap.height <= 7000000 /* MaxDOMHeight */ ? IdScaler : - new BigScaler(this.heightOracle.doc, this.heightMap, this.viewports); - } - updateViewportLines() { - this.viewportLines = []; - this.heightMap.forEachLine(this.viewport.from, this.viewport.to, this.state.doc, 0, 0, block => { - this.viewportLines.push(this.scaler.scale == 1 ? block : scaleBlock(block, this.scaler)); - }); - } - update(update, scrollTarget = null) { - let prev = this.state; - this.state = update.state; - let newDeco = this.state.facet(decorations); - let contentChanges = update.changedRanges; - let heightChanges = ChangedRange.extendWithRanges(contentChanges, heightRelevantDecoChanges(update.startState.facet(decorations), newDeco, update ? update.changes : ChangeSet.empty(this.state.doc.length))); - let prevHeight = this.heightMap.height; - this.heightMap = this.heightMap.applyChanges(newDeco, prev.doc, this.heightOracle.setDoc(this.state.doc), heightChanges); - if (this.heightMap.height != prevHeight) - update.flags |= 2 /* Height */; - let viewport = heightChanges.length ? this.mapViewport(this.viewport, update.changes) : this.viewport; - if (scrollTarget && (scrollTarget.range.head < viewport.from || scrollTarget.range.head > viewport.to) || - !this.viewportIsAppropriate(viewport)) - viewport = this.getViewport(0, scrollTarget); - let updateLines = !update.changes.empty || (update.flags & 2 /* Height */) || - viewport.from != this.viewport.from || viewport.to != this.viewport.to; - this.viewport = viewport; - this.updateForViewport(); - if (updateLines) - this.updateViewportLines(); - if (this.lineGaps.length || this.viewport.to - this.viewport.from > 4000 /* DoubleMargin */) - this.updateLineGaps(this.ensureLineGaps(this.mapLineGaps(this.lineGaps, update.changes))); - update.flags |= this.computeVisibleRanges(); - if (scrollTarget) - this.scrollTarget = scrollTarget; - if (!this.mustEnforceCursorAssoc && update.selectionSet && update.view.lineWrapping && - update.state.selection.main.empty && update.state.selection.main.assoc) - this.mustEnforceCursorAssoc = true; - } - measure(view) { - let dom = view.contentDOM, style = window.getComputedStyle(dom); - let oracle = this.heightOracle; - let whiteSpace = style.whiteSpace, direction = style.direction == "rtl" ? Direction.RTL : Direction.LTR; - let refresh = this.heightOracle.mustRefreshForStyle(whiteSpace, direction); - let measureContent = refresh || this.mustMeasureContent || this.contentDOMHeight != dom.clientHeight; - let result = 0, bias = 0; - if (this.editorWidth != view.scrollDOM.clientWidth) { - if (oracle.lineWrapping) - measureContent = true; - this.editorWidth = view.scrollDOM.clientWidth; - result |= 8 /* Geometry */; - } - if (measureContent) { - this.mustMeasureContent = false; - this.contentDOMHeight = dom.clientHeight; - // Vertical padding - let paddingTop = parseInt(style.paddingTop) || 0, paddingBottom = parseInt(style.paddingBottom) || 0; - if (this.paddingTop != paddingTop || this.paddingBottom != paddingBottom) { - result |= 8 /* Geometry */; - this.paddingTop = paddingTop; - this.paddingBottom = paddingBottom; - } - } - // Pixel viewport - let pixelViewport = (this.printing ? fullPixelRange : visiblePixelRange)(dom, this.paddingTop); - let dTop = pixelViewport.top - this.pixelViewport.top, dBottom = pixelViewport.bottom - this.pixelViewport.bottom; - this.pixelViewport = pixelViewport; - let inView = this.pixelViewport.bottom > this.pixelViewport.top && this.pixelViewport.right > this.pixelViewport.left; - if (inView != this.inView) { - this.inView = inView; - if (inView) - measureContent = true; - } - if (!this.inView) - return 0; - let contentWidth = dom.clientWidth; - if (this.contentDOMWidth != contentWidth || this.editorHeight != view.scrollDOM.clientHeight) { - this.contentDOMWidth = contentWidth; - this.editorHeight = view.scrollDOM.clientHeight; - result |= 8 /* Geometry */; - } - if (measureContent) { - let lineHeights = view.docView.measureVisibleLineHeights(); - if (oracle.mustRefreshForHeights(lineHeights)) - refresh = true; - if (refresh || oracle.lineWrapping && Math.abs(contentWidth - this.contentDOMWidth) > oracle.charWidth) { - let { lineHeight, charWidth } = view.docView.measureTextSize(); - refresh = oracle.refresh(whiteSpace, direction, lineHeight, charWidth, contentWidth / charWidth, lineHeights); - if (refresh) { - view.docView.minWidth = 0; - result |= 8 /* Geometry */; - } - } - if (dTop > 0 && dBottom > 0) - bias = Math.max(dTop, dBottom); - else if (dTop < 0 && dBottom < 0) - bias = Math.min(dTop, dBottom); - oracle.heightChanged = false; - this.heightMap = this.heightMap.updateHeight(oracle, 0, refresh, new MeasuredHeights(this.viewport.from, lineHeights)); - if (oracle.heightChanged) - result |= 2 /* Height */; - } - let viewportChange = !this.viewportIsAppropriate(this.viewport, bias) || - this.scrollTarget && (this.scrollTarget.range.head < this.viewport.from || this.scrollTarget.range.head > this.viewport.to); - if (viewportChange) - this.viewport = this.getViewport(bias, this.scrollTarget); - this.updateForViewport(); - if ((result & 2 /* Height */) || viewportChange) - this.updateViewportLines(); - if (this.lineGaps.length || this.viewport.to - this.viewport.from > 4000 /* DoubleMargin */) - this.updateLineGaps(this.ensureLineGaps(refresh ? [] : this.lineGaps)); - result |= this.computeVisibleRanges(); - if (this.mustEnforceCursorAssoc) { - this.mustEnforceCursorAssoc = false; - // This is done in the read stage, because moving the selection - // to a line end is going to trigger a layout anyway, so it - // can't be a pure write. It should be rare that it does any - // writing. - view.docView.enforceCursorAssoc(); - } - return result; - } - get visibleTop() { return this.scaler.fromDOM(this.pixelViewport.top); } - get visibleBottom() { return this.scaler.fromDOM(this.pixelViewport.bottom); } - getViewport(bias, scrollTarget) { - // This will divide VP.Margin between the top and the - // bottom, depending on the bias (the change in viewport position - // since the last update). It'll hold a number between 0 and 1 - let marginTop = 0.5 - Math.max(-0.5, Math.min(0.5, bias / 1000 /* Margin */ / 2)); - let map = this.heightMap, doc = this.state.doc, { visibleTop, visibleBottom } = this; - let viewport = new Viewport(map.lineAt(visibleTop - marginTop * 1000 /* Margin */, QueryType$1.ByHeight, doc, 0, 0).from, map.lineAt(visibleBottom + (1 - marginTop) * 1000 /* Margin */, QueryType$1.ByHeight, doc, 0, 0).to); - // If scrollTarget is given, make sure the viewport includes that position - if (scrollTarget) { - let { head } = scrollTarget.range; - if (head < viewport.from || head > viewport.to) { - let viewHeight = Math.min(this.editorHeight, this.pixelViewport.bottom - this.pixelViewport.top); - let block = map.lineAt(head, QueryType$1.ByPos, doc, 0, 0), topPos; - if (scrollTarget.y == "center") - topPos = (block.top + block.bottom) / 2 - viewHeight / 2; - else if (scrollTarget.y == "start" || scrollTarget.y == "nearest" && head < viewport.from) - topPos = block.top; - else - topPos = block.bottom - viewHeight; - viewport = new Viewport(map.lineAt(topPos - 1000 /* Margin */ / 2, QueryType$1.ByHeight, doc, 0, 0).from, map.lineAt(topPos + viewHeight + 1000 /* Margin */ / 2, QueryType$1.ByHeight, doc, 0, 0).to); - } - } - return viewport; - } - mapViewport(viewport, changes) { - let from = changes.mapPos(viewport.from, -1), to = changes.mapPos(viewport.to, 1); - return new Viewport(this.heightMap.lineAt(from, QueryType$1.ByPos, this.state.doc, 0, 0).from, this.heightMap.lineAt(to, QueryType$1.ByPos, this.state.doc, 0, 0).to); - } - // Checks if a given viewport covers the visible part of the - // document and not too much beyond that. - viewportIsAppropriate({ from, to }, bias = 0) { - if (!this.inView) - return true; - let { top } = this.heightMap.lineAt(from, QueryType$1.ByPos, this.state.doc, 0, 0); - let { bottom } = this.heightMap.lineAt(to, QueryType$1.ByPos, this.state.doc, 0, 0); - let { visibleTop, visibleBottom } = this; - return (from == 0 || top <= visibleTop - Math.max(10 /* MinCoverMargin */, Math.min(-bias, 250 /* MaxCoverMargin */))) && - (to == this.state.doc.length || - bottom >= visibleBottom + Math.max(10 /* MinCoverMargin */, Math.min(bias, 250 /* MaxCoverMargin */))) && - (top > visibleTop - 2 * 1000 /* Margin */ && bottom < visibleBottom + 2 * 1000 /* Margin */); - } - mapLineGaps(gaps, changes) { - if (!gaps.length || changes.empty) - return gaps; - let mapped = []; - for (let gap of gaps) - if (!changes.touchesRange(gap.from, gap.to)) - mapped.push(new LineGap(changes.mapPos(gap.from), changes.mapPos(gap.to), gap.size)); - return mapped; - } - // Computes positions in the viewport where the start or end of a - // line should be hidden, trying to reuse existing line gaps when - // appropriate to avoid unneccesary redraws. - // Uses crude character-counting for the positioning and sizing, - // since actual DOM coordinates aren't always available and - // predictable. Relies on generous margins (see LG.Margin) to hide - // the artifacts this might produce from the user. - ensureLineGaps(current) { - let gaps = []; - // This won't work at all in predominantly right-to-left text. - if (this.heightOracle.direction != Direction.LTR) - return gaps; - for (let line of this.viewportLines) { - if (line.length < 4000 /* DoubleMargin */) - continue; - let structure = lineStructure(line.from, line.to, this.state); - if (structure.total < 4000 /* DoubleMargin */) - continue; - let viewFrom, viewTo; - if (this.heightOracle.lineWrapping) { - let marginHeight = (2000 /* Margin */ / this.heightOracle.lineLength) * this.heightOracle.lineHeight; - viewFrom = findPosition(structure, (this.visibleTop - line.top - marginHeight) / line.height); - viewTo = findPosition(structure, (this.visibleBottom - line.top + marginHeight) / line.height); - } - else { - let totalWidth = structure.total * this.heightOracle.charWidth; - let marginWidth = 2000 /* Margin */ * this.heightOracle.charWidth; - viewFrom = findPosition(structure, (this.pixelViewport.left - marginWidth) / totalWidth); - viewTo = findPosition(structure, (this.pixelViewport.right + marginWidth) / totalWidth); - } - let outside = []; - if (viewFrom > line.from) - outside.push({ from: line.from, to: viewFrom }); - if (viewTo < line.to) - outside.push({ from: viewTo, to: line.to }); - let sel = this.state.selection.main; - // Make sure the gaps don't cover a selection end - if (sel.from >= line.from && sel.from <= line.to) - cutRange(outside, sel.from - 10 /* SelectionMargin */, sel.from + 10 /* SelectionMargin */); - if (!sel.empty && sel.to >= line.from && sel.to <= line.to) - cutRange(outside, sel.to - 10 /* SelectionMargin */, sel.to + 10 /* SelectionMargin */); - for (let { from, to } of outside) - if (to - from > 1000 /* HalfMargin */) { - gaps.push(find(current, gap => gap.from >= line.from && gap.to <= line.to && - Math.abs(gap.from - from) < 1000 /* HalfMargin */ && Math.abs(gap.to - to) < 1000 /* HalfMargin */) || - new LineGap(from, to, this.gapSize(line, from, to, structure))); - } - } - return gaps; - } - gapSize(line, from, to, structure) { - let fraction = findFraction(structure, to) - findFraction(structure, from); - if (this.heightOracle.lineWrapping) { - return line.height * fraction; - } - else { - return structure.total * this.heightOracle.charWidth * fraction; - } - } - updateLineGaps(gaps) { - if (!LineGap.same(gaps, this.lineGaps)) { - this.lineGaps = gaps; - this.lineGapDeco = Decoration.set(gaps.map(gap => gap.draw(this.heightOracle.lineWrapping))); - } - } - computeVisibleRanges() { - let deco = this.state.facet(decorations); - if (this.lineGaps.length) - deco = deco.concat(this.lineGapDeco); - let ranges = []; - RangeSet.spans(deco, this.viewport.from, this.viewport.to, { - span(from, to) { ranges.push({ from, to }); }, - point() { } - }, 20); - let changed = ranges.length != this.visibleRanges.length || - this.visibleRanges.some((r, i) => r.from != ranges[i].from || r.to != ranges[i].to); - this.visibleRanges = ranges; - return changed ? 4 /* Viewport */ : 0; - } - lineBlockAt(pos) { - return (pos >= this.viewport.from && pos <= this.viewport.to && this.viewportLines.find(b => b.from <= pos && b.to >= pos)) || - scaleBlock(this.heightMap.lineAt(pos, QueryType$1.ByPos, this.state.doc, 0, 0), this.scaler); - } - lineBlockAtHeight(height) { - return scaleBlock(this.heightMap.lineAt(this.scaler.fromDOM(height), QueryType$1.ByHeight, this.state.doc, 0, 0), this.scaler); - } - elementAtHeight(height) { - return scaleBlock(this.heightMap.blockAt(this.scaler.fromDOM(height), this.state.doc, 0, 0), this.scaler); - } - get docHeight() { - return this.scaler.toDOM(this.heightMap.height); - } - get contentHeight() { - return this.docHeight + this.paddingTop + this.paddingBottom; - } - } - class Viewport { - constructor(from, to) { - this.from = from; - this.to = to; - } - } - function lineStructure(from, to, state) { - let ranges = [], pos = from, total = 0; - RangeSet.spans(state.facet(decorations), from, to, { - span() { }, - point(from, to) { - if (from > pos) { - ranges.push({ from: pos, to: from }); - total += from - pos; - } - pos = to; - } - }, 20); // We're only interested in collapsed ranges of a significant size - if (pos < to) { - ranges.push({ from: pos, to }); - total += to - pos; - } - return { total, ranges }; - } - function findPosition({ total, ranges }, ratio) { - if (ratio <= 0) - return ranges[0].from; - if (ratio >= 1) - return ranges[ranges.length - 1].to; - let dist = Math.floor(total * ratio); - for (let i = 0;; i++) { - let { from, to } = ranges[i], size = to - from; - if (dist <= size) - return from + dist; - dist -= size; - } - } - function findFraction(structure, pos) { - let counted = 0; - for (let { from, to } of structure.ranges) { - if (pos <= to) { - counted += pos - from; - break; - } - counted += to - from; - } - return counted / structure.total; - } - function cutRange(ranges, from, to) { - for (let i = 0; i < ranges.length; i++) { - let r = ranges[i]; - if (r.from < to && r.to > from) { - let pieces = []; - if (r.from < from) - pieces.push({ from: r.from, to: from }); - if (r.to > to) - pieces.push({ from: to, to: r.to }); - ranges.splice(i, 1, ...pieces); - i += pieces.length - 1; - } - } - } - function find(array, f) { - for (let val of array) - if (f(val)) - return val; - return undefined; - } - // Don't scale when the document height is within the range of what - // the DOM can handle. - const IdScaler = { - toDOM(n) { return n; }, - fromDOM(n) { return n; }, - scale: 1 - }; - // When the height is too big (> VP.MaxDOMHeight), scale down the - // regions outside the viewports so that the total height is - // VP.MaxDOMHeight. - class BigScaler { - constructor(doc, heightMap, viewports) { - let vpHeight = 0, base = 0, domBase = 0; - this.viewports = viewports.map(({ from, to }) => { - let top = heightMap.lineAt(from, QueryType$1.ByPos, doc, 0, 0).top; - let bottom = heightMap.lineAt(to, QueryType$1.ByPos, doc, 0, 0).bottom; - vpHeight += bottom - top; - return { from, to, top, bottom, domTop: 0, domBottom: 0 }; - }); - this.scale = (7000000 /* MaxDOMHeight */ - vpHeight) / (heightMap.height - vpHeight); - for (let obj of this.viewports) { - obj.domTop = domBase + (obj.top - base) * this.scale; - domBase = obj.domBottom = obj.domTop + (obj.bottom - obj.top); - base = obj.bottom; - } - } - toDOM(n) { - for (let i = 0, base = 0, domBase = 0;; i++) { - let vp = i < this.viewports.length ? this.viewports[i] : null; - if (!vp || n < vp.top) - return domBase + (n - base) * this.scale; - if (n <= vp.bottom) - return vp.domTop + (n - vp.top); - base = vp.bottom; - domBase = vp.domBottom; - } - } - fromDOM(n) { - for (let i = 0, base = 0, domBase = 0;; i++) { - let vp = i < this.viewports.length ? this.viewports[i] : null; - if (!vp || n < vp.domTop) - return base + (n - domBase) / this.scale; - if (n <= vp.domBottom) - return vp.top + (n - vp.domTop); - base = vp.bottom; - domBase = vp.domBottom; - } - } - } - function scaleBlock(block, scaler) { - if (scaler.scale == 1) - return block; - let bTop = scaler.toDOM(block.top), bBottom = scaler.toDOM(block.bottom); - return new BlockInfo(block.from, block.length, bTop, bBottom - bTop, Array.isArray(block.type) ? block.type.map(b => scaleBlock(b, scaler)) : block.type); - } - - const theme = /*@__PURE__*/Facet.define({ combine: strs => strs.join(" ") }); - const darkTheme = /*@__PURE__*/Facet.define({ combine: values => values.indexOf(true) > -1 }); - const baseThemeID = /*@__PURE__*/StyleModule.newName(), baseLightID = /*@__PURE__*/StyleModule.newName(), baseDarkID = /*@__PURE__*/StyleModule.newName(); - const lightDarkIDs = { "&light": "." + baseLightID, "&dark": "." + baseDarkID }; - function buildTheme(main, spec, scopes) { - return new StyleModule(spec, { - finish(sel) { - return /&/.test(sel) ? sel.replace(/&\w*/, m => { - if (m == "&") - return main; - if (!scopes || !scopes[m]) - throw new RangeError(`Unsupported selector: ${m}`); - return scopes[m]; - }) : main + " " + sel; - } - }); - } - const baseTheme$8 = /*@__PURE__*/buildTheme("." + baseThemeID, { - "&.cm-editor": { - position: "relative !important", - boxSizing: "border-box", - "&.cm-focused": { - // Provide a simple default outline to make sure a focused - // editor is visually distinct. Can't leave the default behavior - // because that will apply to the content element, which is - // inside the scrollable container and doesn't include the - // gutters. We also can't use an 'auto' outline, since those - // are, for some reason, drawn behind the element content, which - // will cause things like the active line background to cover - // the outline (#297). - 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, - minHeight: "100%", - display: "block", - whiteSpace: "pre", - wordWrap: "normal", - boxSizing: "border-box", - 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" - }, - "&light .cm-content": { caretColor: "black" }, - "&dark .cm-content": { caretColor: "white" }, - ".cm-line": { - display: "block", - padding: "0 2px 0 4px" - }, - ".cm-selectionLayer": { - zIndex: -1, - contain: "size style" - }, - ".cm-selectionBackground": { - position: "absolute", - }, - "&light .cm-selectionBackground": { - background: "#d9d9d9" - }, - "&dark .cm-selectionBackground": { - background: "#222" - }, - "&light.cm-focused .cm-selectionBackground": { - background: "#d7d4f0" - }, - "&dark.cm-focused .cm-selectionBackground": { - background: "#233" - }, - ".cm-cursorLayer": { - zIndex: 100, - contain: "size style", - pointerEvents: "none" - }, - "&.cm-focused .cm-cursorLayer": { - animation: "steps(1) cm-blink 1.2s infinite" - }, - // Two animations defined so that we can switch between them to - // restart the animation without forcing another style - // recomputation. - "@keyframes cm-blink": { "0%": {}, "50%": { visibility: "hidden" }, "100%": {} }, - "@keyframes cm-blink2": { "0%": {}, "50%": { visibility: "hidden" }, "100%": {} }, - ".cm-cursor, .cm-dropCursor": { - position: "absolute", - borderLeft: "1.2px solid black", - marginLeft: "-0.6px", - pointerEvents: "none", - }, - ".cm-cursor": { - display: "none" - }, - "&dark .cm-cursor": { - borderLeftColor: "#444" - }, - "&.cm-focused .cm-cursor": { - display: "block" - }, - "&light .cm-activeLine": { backgroundColor: "#f3f9ff" }, - "&dark .cm-activeLine": { backgroundColor: "#223039" }, - "&light .cm-specialChar": { color: "red" }, - "&dark .cm-specialChar": { color: "#f78" }, - ".cm-tab": { - display: "inline-block", - overflow: "hidden", - verticalAlign: "bottom" - }, - ".cm-widgetBuffer": { - verticalAlign: "text-top", - height: "1em", - display: "inline" - }, - ".cm-placeholder": { - color: "#888", - display: "inline-block", - verticalAlign: "top", - }, - ".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" - } - }, lightDarkIDs); - - const observeOptions = { - childList: true, - characterData: true, - subtree: true, - attributes: true, - characterDataOldValue: true - }; - // IE11 has very broken mutation observers, so we also listen to - // DOMCharacterDataModified there - const useCharData = browser.ie && browser.ie_version <= 11; - class DOMObserver { - constructor(view, onChange, onScrollChanged) { - this.view = view; - this.onChange = onChange; - this.onScrollChanged = onScrollChanged; - this.active = false; - // The known selection. Kept in our own object, as opposed to just - // directly accessing the selection because: - // - Safari doesn't report the right selection in shadow DOM - // - Reading from the selection forces a DOM layout - // - This way, we can ignore selectionchange events if we have - // already seen the 'new' selection - this.selectionRange = new DOMSelectionState; - // Set when a selection change is detected, cleared on flush - this.selectionChanged = false; - this.delayedFlush = -1; - this.resizeTimeout = -1; - this.queue = []; - this.delayedAndroidKey = null; - this.scrollTargets = []; - this.intersection = null; - this.resize = null; - this.intersecting = false; - this.gapIntersection = null; - this.gaps = []; - // Timeout for scheduling check of the parents that need scroll handlers - this.parentCheck = -1; - this.dom = view.contentDOM; - this.observer = new MutationObserver(mutations => { - for (let mut of mutations) - this.queue.push(mut); - // IE11 will sometimes (on typing over a selection or - // backspacing out a single character text node) call the - // observer callback before actually updating the DOM. - // - // Unrelatedly, iOS Safari will, when ending a composition, - // sometimes first clear it, deliver the mutations, and then - // reinsert the finished text. CodeMirror's handling of the - // deletion will prevent the reinsertion from happening, - // breaking composition. - if ((browser.ie && browser.ie_version <= 11 || browser.ios && view.composing) && - mutations.some(m => m.type == "childList" && m.removedNodes.length || - m.type == "characterData" && m.oldValue.length > m.target.nodeValue.length)) - this.flushSoon(); - else - this.flush(); - }); - if (useCharData) - this.onCharData = (event) => { - this.queue.push({ target: event.target, - type: "characterData", - oldValue: event.prevValue }); - this.flushSoon(); - }; - this.onSelectionChange = this.onSelectionChange.bind(this); - window.addEventListener("resize", this.onResize = this.onResize.bind(this)); - if (typeof ResizeObserver == "function") { - this.resize = new ResizeObserver(() => { - if (this.view.docView.lastUpdate < Date.now() - 75) - this.onResize(); - }); - this.resize.observe(view.scrollDOM); - } - window.addEventListener("beforeprint", this.onPrint = this.onPrint.bind(this)); - this.start(); - window.addEventListener("scroll", this.onScroll = this.onScroll.bind(this)); - if (typeof IntersectionObserver == "function") { - this.intersection = new IntersectionObserver(entries => { - if (this.parentCheck < 0) - this.parentCheck = setTimeout(this.listenForScroll.bind(this), 1000); - if (entries.length > 0 && (entries[entries.length - 1].intersectionRatio > 0) != this.intersecting) { - this.intersecting = !this.intersecting; - if (this.intersecting != this.view.inView) - this.onScrollChanged(document.createEvent("Event")); - } - }, {}); - this.intersection.observe(this.dom); - this.gapIntersection = new IntersectionObserver(entries => { - if (entries.length > 0 && entries[entries.length - 1].intersectionRatio > 0) - this.onScrollChanged(document.createEvent("Event")); - }, {}); - } - this.listenForScroll(); - this.readSelectionRange(); - this.dom.ownerDocument.addEventListener("selectionchange", this.onSelectionChange); - } - onScroll(e) { - if (this.intersecting) - this.flush(false); - this.onScrollChanged(e); - } - onResize() { - if (this.resizeTimeout < 0) - this.resizeTimeout = setTimeout(() => { - this.resizeTimeout = -1; - this.view.requestMeasure(); - }, 50); - } - onPrint() { - this.view.viewState.printing = true; - this.view.measure(); - setTimeout(() => { - this.view.viewState.printing = false; - this.view.requestMeasure(); - }, 500); - } - updateGaps(gaps) { - if (this.gapIntersection && (gaps.length != this.gaps.length || this.gaps.some((g, i) => g != gaps[i]))) { - this.gapIntersection.disconnect(); - for (let gap of gaps) - this.gapIntersection.observe(gap); - this.gaps = gaps; - } - } - onSelectionChange(event) { - if (!this.readSelectionRange() || this.delayedAndroidKey) - return; - let { view } = this, sel = this.selectionRange; - if (view.state.facet(editable) ? view.root.activeElement != this.dom : !hasSelection(view.dom, sel)) - return; - let context = sel.anchorNode && view.docView.nearest(sel.anchorNode); - if (context && context.ignoreEvent(event)) - return; - // Deletions on IE11 fire their events in the wrong order, giving - // us a selection change event before the DOM changes are - // reported. - // Chrome Android has a similar issue when backspacing out a - // selection (#645). - if ((browser.ie && browser.ie_version <= 11 || browser.android && browser.chrome) && !view.state.selection.main.empty && - // (Selection.isCollapsed isn't reliable on IE) - sel.focusNode && isEquivalentPosition(sel.focusNode, sel.focusOffset, sel.anchorNode, sel.anchorOffset)) - this.flushSoon(); - else - this.flush(false); - } - readSelectionRange() { - let { root } = this.view, domSel = getSelection(root); - // The Selection object is broken in shadow roots in Safari. See - // https://github.com/codemirror/codemirror.next/issues/414 - let range = browser.safari && root.nodeType == 11 && deepActiveElement() == this.view.contentDOM && - safariSelectionRangeHack(this.view) || domSel; - if (this.selectionRange.eq(range)) - return false; - this.selectionRange.setRange(range); - return this.selectionChanged = true; - } - setSelectionRange(anchor, head) { - this.selectionRange.set(anchor.node, anchor.offset, head.node, head.offset); - this.selectionChanged = false; - } - listenForScroll() { - this.parentCheck = -1; - let i = 0, changed = null; - for (let dom = this.dom; dom;) { - if (dom.nodeType == 1) { - if (!changed && i < this.scrollTargets.length && this.scrollTargets[i] == dom) - i++; - else if (!changed) - changed = this.scrollTargets.slice(0, i); - if (changed) - changed.push(dom); - dom = dom.assignedSlot || dom.parentNode; - } - else if (dom.nodeType == 11) { // Shadow root - dom = dom.host; - } - else { - break; - } - } - if (i < this.scrollTargets.length && !changed) - changed = this.scrollTargets.slice(0, i); - if (changed) { - for (let dom of this.scrollTargets) - dom.removeEventListener("scroll", this.onScroll); - for (let dom of this.scrollTargets = changed) - dom.addEventListener("scroll", this.onScroll); - } - } - ignore(f) { - if (!this.active) - return f(); - try { - this.stop(); - return f(); - } - finally { - this.start(); - this.clear(); - } - } - start() { - if (this.active) - return; - this.observer.observe(this.dom, observeOptions); - if (useCharData) - this.dom.addEventListener("DOMCharacterDataModified", this.onCharData); - this.active = true; - } - stop() { - if (!this.active) - return; - this.active = false; - this.observer.disconnect(); - if (useCharData) - this.dom.removeEventListener("DOMCharacterDataModified", this.onCharData); - } - // Throw away any pending changes - clear() { - this.processRecords(); - this.queue.length = 0; - this.selectionChanged = false; - } - // Chrome Android, especially in combination with GBoard, not only - // doesn't reliably fire regular key events, but also often - // surrounds the effect of enter or backspace with a bunch of - // composition events that, when interrupted, cause text duplication - // or other kinds of corruption. This hack makes the editor back off - // from handling DOM changes for a moment when such a key is - // detected (via beforeinput or keydown), and then dispatches the - // key event, throwing away the DOM changes if it gets handled. - delayAndroidKey(key, keyCode) { - if (!this.delayedAndroidKey) - requestAnimationFrame(() => { - let key = this.delayedAndroidKey; - this.delayedAndroidKey = null; - let startState = this.view.state; - if (dispatchKey(this.view.contentDOM, key.key, key.keyCode)) - this.processRecords(); - else - this.flush(); - if (this.view.state == startState) - this.view.update([]); - }); - // Since backspace beforeinput is sometimes signalled spuriously, - // Enter always takes precedence. - if (!this.delayedAndroidKey || key == "Enter") - this.delayedAndroidKey = { key, keyCode }; - } - flushSoon() { - if (this.delayedFlush < 0) - this.delayedFlush = window.setTimeout(() => { this.delayedFlush = -1; this.flush(); }, 20); - } - forceFlush() { - if (this.delayedFlush >= 0) { - window.clearTimeout(this.delayedFlush); - this.delayedFlush = -1; - this.flush(); - } - } - processRecords() { - let records = this.queue; - for (let mut of this.observer.takeRecords()) - records.push(mut); - if (records.length) - this.queue = []; - let from = -1, to = -1, typeOver = false; - for (let record of records) { - let range = this.readMutation(record); - if (!range) - continue; - if (range.typeOver) - typeOver = true; - if (from == -1) { - ({ from, to } = range); - } - else { - from = Math.min(range.from, from); - to = Math.max(range.to, to); - } - } - return { from, to, typeOver }; - } - // Apply pending changes, if any - flush(readSelection = true) { - // Completely hold off flushing when pending keys are set—the code - // managing those will make sure processRecords is called and the - // view is resynchronized after - if (this.delayedFlush >= 0 || this.delayedAndroidKey) - return; - if (readSelection) - this.readSelectionRange(); - let { from, to, typeOver } = this.processRecords(); - let newSel = this.selectionChanged && hasSelection(this.dom, this.selectionRange); - if (from < 0 && !newSel) - return; - this.selectionChanged = false; - let startState = this.view.state; - this.onChange(from, to, typeOver); - // The view wasn't updated - if (this.view.state == startState) - this.view.update([]); - } - readMutation(rec) { - let cView = this.view.docView.nearest(rec.target); - if (!cView || cView.ignoreMutation(rec)) - return null; - cView.markDirty(rec.type == "attributes"); - if (rec.type == "attributes") - cView.dirty |= 4 /* Attrs */; - if (rec.type == "childList") { - let childBefore = findChild(cView, rec.previousSibling || rec.target.previousSibling, -1); - let childAfter = findChild(cView, rec.nextSibling || rec.target.nextSibling, 1); - return { from: childBefore ? cView.posAfter(childBefore) : cView.posAtStart, - to: childAfter ? cView.posBefore(childAfter) : cView.posAtEnd, typeOver: false }; - } - else if (rec.type == "characterData") { - return { from: cView.posAtStart, to: cView.posAtEnd, typeOver: rec.target.nodeValue == rec.oldValue }; - } - else { - return null; - } - } - destroy() { - var _a, _b, _c; - this.stop(); - (_a = this.intersection) === null || _a === void 0 ? void 0 : _a.disconnect(); - (_b = this.gapIntersection) === null || _b === void 0 ? void 0 : _b.disconnect(); - (_c = this.resize) === null || _c === void 0 ? void 0 : _c.disconnect(); - for (let dom of this.scrollTargets) - dom.removeEventListener("scroll", this.onScroll); - window.removeEventListener("scroll", this.onScroll); - window.removeEventListener("resize", this.onResize); - window.removeEventListener("beforeprint", this.onPrint); - this.dom.ownerDocument.removeEventListener("selectionchange", this.onSelectionChange); - clearTimeout(this.parentCheck); - clearTimeout(this.resizeTimeout); - } - } - function findChild(cView, dom, dir) { - while (dom) { - let curView = ContentView.get(dom); - if (curView && curView.parent == cView) - return curView; - let parent = dom.parentNode; - dom = parent != cView.dom ? parent : dir > 0 ? dom.nextSibling : dom.previousSibling; - } - return null; - } - // Used to work around a Safari Selection/shadow DOM bug (#414) - function safariSelectionRangeHack(view) { - let found = null; - // Because Safari (at least in 2018-2021) doesn't provide regular - // access to the selection inside a shadowroot, we have to perform a - // ridiculous hack to get at it—using `execCommand` to trigger a - // `beforeInput` event so that we can read the target range from the - // event. - function read(event) { - event.preventDefault(); - event.stopImmediatePropagation(); - found = event.getTargetRanges()[0]; - } - view.contentDOM.addEventListener("beforeinput", read, true); - document.execCommand("indent"); - view.contentDOM.removeEventListener("beforeinput", read, true); - if (!found) - return null; - let anchorNode = found.startContainer, anchorOffset = found.startOffset; - let focusNode = found.endContainer, focusOffset = found.endOffset; - let curAnchor = view.docView.domAtPos(view.state.selection.main.anchor); - // Since such a range doesn't distinguish between anchor and head, - // use a heuristic that flips it around if its end matches the - // current anchor. - if (isEquivalentPosition(curAnchor.node, curAnchor.offset, focusNode, focusOffset)) - [anchorNode, anchorOffset, focusNode, focusOffset] = [focusNode, focusOffset, anchorNode, anchorOffset]; - return { anchorNode, anchorOffset, focusNode, focusOffset }; - } - - function applyDOMChange(view, start, end, typeOver) { - let change, newSel; - let sel = view.state.selection.main; - if (start > -1) { - let bounds = view.docView.domBoundsAround(start, end, 0); - if (!bounds || view.state.readOnly) - return; - let { from, to } = bounds; - let selPoints = view.docView.impreciseHead || view.docView.impreciseAnchor ? [] : selectionPoints(view); - let reader = new DOMReader(selPoints, view.state); - reader.readRange(bounds.startDOM, bounds.endDOM); - let preferredPos = sel.from, preferredSide = null; - // Prefer anchoring to end when Backspace is pressed (or, on - // Android, when something was deleted) - if (view.inputState.lastKeyCode === 8 && view.inputState.lastKeyTime > Date.now() - 100 || - browser.android && reader.text.length < to - from) { - preferredPos = sel.to; - preferredSide = "end"; - } - let diff = findDiff(view.state.doc.sliceString(from, to, LineBreakPlaceholder), reader.text, preferredPos - from, preferredSide); - if (diff) { - // Chrome inserts two newlines when pressing shift-enter at the - // end of a line. This drops one of those. - if (browser.chrome && view.inputState.lastKeyCode == 13 && - diff.toB == diff.from + 2 && reader.text.slice(diff.from, diff.toB) == LineBreakPlaceholder + LineBreakPlaceholder) - diff.toB--; - change = { from: from + diff.from, to: from + diff.toA, - insert: Text.of(reader.text.slice(diff.from, diff.toB).split(LineBreakPlaceholder)) }; - } - newSel = selectionFromPoints(selPoints, from); - } - else if (view.hasFocus || !view.state.facet(editable)) { - let domSel = view.observer.selectionRange; - let { impreciseHead: iHead, impreciseAnchor: iAnchor } = view.docView; - let head = iHead && iHead.node == domSel.focusNode && iHead.offset == domSel.focusOffset || - !contains(view.contentDOM, domSel.focusNode) - ? view.state.selection.main.head - : view.docView.posFromDOM(domSel.focusNode, domSel.focusOffset); - let anchor = iAnchor && iAnchor.node == domSel.anchorNode && iAnchor.offset == domSel.anchorOffset || - !contains(view.contentDOM, domSel.anchorNode) - ? view.state.selection.main.anchor - : view.docView.posFromDOM(domSel.anchorNode, domSel.anchorOffset); - if (head != sel.head || anchor != sel.anchor) - newSel = EditorSelection.single(anchor, head); - } - if (!change && !newSel) - return; - // Heuristic to notice typing over a selected character - if (!change && typeOver && !sel.empty && newSel && newSel.main.empty) - change = { from: sel.from, to: sel.to, insert: view.state.doc.slice(sel.from, sel.to) }; - // If the change is inside the selection and covers most of it, - // assume it is a selection replace (with identical characters at - // the start/end not included in the diff) - else if (change && change.from >= sel.from && change.to <= sel.to && - (change.from != sel.from || change.to != sel.to) && - (sel.to - sel.from) - (change.to - change.from) <= 4) - change = { - from: sel.from, to: sel.to, - insert: view.state.doc.slice(sel.from, change.from).append(change.insert).append(view.state.doc.slice(change.to, sel.to)) - }; - if (change) { - let startState = view.state; - if (browser.ios && view.inputState.flushIOSKey(view)) - return; - // Android browsers don't fire reasonable key events for enter, - // backspace, or delete. So this detects changes that look like - // they're caused by those keys, and reinterprets them as key - // events. (Some of these keys are also handled by beforeinput - // events and the pendingAndroidKey mechanism, but that's not - // reliable in all situations.) - if (browser.android && - ((change.from == sel.from && change.to == sel.to && - change.insert.length == 1 && change.insert.lines == 2 && - dispatchKey(view.contentDOM, "Enter", 13)) || - (change.from == sel.from - 1 && change.to == sel.to && change.insert.length == 0 && - dispatchKey(view.contentDOM, "Backspace", 8)) || - (change.from == sel.from && change.to == sel.to + 1 && change.insert.length == 0 && - dispatchKey(view.contentDOM, "Delete", 46)))) - return; - let text = change.insert.toString(); - if (view.state.facet(inputHandler$1).some(h => h(view, change.from, change.to, text))) - return; - if (view.inputState.composing >= 0) - view.inputState.composing++; - let tr; - if (change.from >= sel.from && change.to <= sel.to && change.to - change.from >= (sel.to - sel.from) / 3 && - (!newSel || newSel.main.empty && newSel.main.from == change.from + change.insert.length) && - view.inputState.composing < 0) { - let before = sel.from < change.from ? startState.sliceDoc(sel.from, change.from) : ""; - let after = sel.to > change.to ? startState.sliceDoc(change.to, sel.to) : ""; - tr = startState.replaceSelection(view.state.toText(before + change.insert.sliceString(0, undefined, view.state.lineBreak) + after)); - } - else { - let changes = startState.changes(change); - let mainSel = newSel && !startState.selection.main.eq(newSel.main) && newSel.main.to <= changes.newLength - ? newSel.main : undefined; - // Try to apply a composition change to all cursors - if (startState.selection.ranges.length > 1 && view.inputState.composing >= 0 && - change.to <= sel.to && change.to >= sel.to - 10) { - let replaced = view.state.sliceDoc(change.from, change.to); - let compositionRange = compositionSurroundingNode(view) || view.state.doc.lineAt(sel.head); - let offset = sel.to - change.to, size = sel.to - sel.from; - tr = startState.changeByRange(range => { - if (range.from == sel.from && range.to == sel.to) - return { changes, range: mainSel || range.map(changes) }; - let to = range.to - offset, from = to - replaced.length; - if (range.to - range.from != size || view.state.sliceDoc(from, to) != replaced || - // Unfortunately, there's no way to make multiple - // changes in the same node work without aborting - // composition, so cursors in the composition range are - // ignored. - compositionRange && range.to >= compositionRange.from && range.from <= compositionRange.to) - return { range }; - let rangeChanges = startState.changes({ from, to, insert: change.insert }), selOff = range.to - sel.to; - return { - changes: rangeChanges, - range: !mainSel ? range.map(rangeChanges) : - EditorSelection.range(Math.max(0, mainSel.anchor + selOff), Math.max(0, mainSel.head + selOff)) - }; - }); - } - else { - tr = { - changes, - selection: mainSel && startState.selection.replaceRange(mainSel) - }; - } - } - let userEvent = "input.type"; - if (view.composing) { - userEvent += ".compose"; - if (view.inputState.compositionFirstChange) { - userEvent += ".start"; - view.inputState.compositionFirstChange = false; - } - } - view.dispatch(tr, { scrollIntoView: true, userEvent }); - } - else if (newSel && !newSel.main.eq(sel)) { - let scrollIntoView = false, userEvent = "select"; - if (view.inputState.lastSelectionTime > Date.now() - 50) { - if (view.inputState.lastSelectionOrigin == "select") - scrollIntoView = true; - userEvent = view.inputState.lastSelectionOrigin; - } - view.dispatch({ selection: newSel, scrollIntoView, userEvent }); - } - } - function findDiff(a, b, preferredPos, preferredSide) { - let minLen = Math.min(a.length, b.length); - let from = 0; - while (from < minLen && a.charCodeAt(from) == b.charCodeAt(from)) - from++; - if (from == minLen && a.length == b.length) - return null; - let toA = a.length, toB = b.length; - while (toA > 0 && toB > 0 && a.charCodeAt(toA - 1) == b.charCodeAt(toB - 1)) { - toA--; - toB--; - } - if (preferredSide == "end") { - let adjust = Math.max(0, from - Math.min(toA, toB)); - preferredPos -= toA + adjust - from; - } - if (toA < from && a.length < b.length) { - let move = preferredPos <= from && preferredPos >= toA ? from - preferredPos : 0; - from -= move; - toB = from + (toB - toA); - toA = from; - } - else if (toB < from) { - let move = preferredPos <= from && preferredPos >= toB ? from - preferredPos : 0; - from -= move; - toA = from + (toA - toB); - toB = from; - } - return { from, toA, toB }; - } - function selectionPoints(view) { - let result = []; - if (view.root.activeElement != view.contentDOM) - return result; - let { anchorNode, anchorOffset, focusNode, focusOffset } = view.observer.selectionRange; - if (anchorNode) { - result.push(new DOMPoint(anchorNode, anchorOffset)); - if (focusNode != anchorNode || focusOffset != anchorOffset) - result.push(new DOMPoint(focusNode, focusOffset)); - } - return result; - } - function selectionFromPoints(points, base) { - if (points.length == 0) - return null; - let anchor = points[0].pos, head = points.length == 2 ? points[1].pos : anchor; - return anchor > -1 && head > -1 ? EditorSelection.single(anchor + base, head + base) : null; - } - - // The editor's update state machine looks something like this: - // - // Idle → Updating ⇆ Idle (unchecked) → Measuring → Idle - // ↑ ↓ - // Updating (measure) - // - // The difference between 'Idle' and 'Idle (unchecked)' lies in - // whether a layout check has been scheduled. A regular update through - // the `update` method updates the DOM in a write-only fashion, and - // relies on a check (scheduled with `requestAnimationFrame`) to make - // sure everything is where it should be and the viewport covers the - // visible code. That check continues to measure and then optionally - // update until it reaches a coherent state. - /** - An editor view represents the editor's user interface. It holds - the editable DOM surface, and possibly other elements such as the - line number gutter. It handles events and dispatches state - transactions for editing actions. - */ - class EditorView { - /** - Construct a new view. You'll usually want to put `view.dom` into - your document after creating a view, so that the user can see - it. - */ - constructor( - /** - Initialization options. - */ - config = {}) { - this.plugins = []; - this.pluginMap = new Map; - this.editorAttrs = {}; - this.contentAttrs = {}; - this.bidiCache = []; - this.destroyed = false; - /** - @internal - */ - this.updateState = 2 /* Updating */; - /** - @internal - */ - this.measureScheduled = -1; - /** - @internal - */ - 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.style.cssText = "position: absolute; top: -10000px"; - this.announceDOM.setAttribute("aria-live", "polite"); - this.dom = document.createElement("div"); - this.dom.appendChild(this.announceDOM); - this.dom.appendChild(this.scrollDOM); - this._dispatch = config.dispatch || ((tr) => this.update([tr])); - this.dispatch = this.dispatch.bind(this); - this.root = (config.root || getRoot(config.parent) || document); - this.viewState = new ViewState(config.state || EditorState.create()); - this.plugins = this.state.facet(viewPlugin).map(spec => new PluginInstance(spec)); - for (let plugin of this.plugins) - plugin.update(this); - this.observer = new DOMObserver(this, (from, to, typeOver) => { - applyDOMChange(this, from, to, typeOver); - }, event => { - this.inputState.runScrollHandlers(this, event); - if (this.observer.intersecting) - this.measure(); - }); - this.inputState = new InputState(this); - this.docView = new DocView(this); - this.mountStyles(); - this.updateAttrs(); - this.updateState = 0 /* Idle */; - this.requestMeasure(); - if (config.parent) - config.parent.appendChild(this.dom); - } - /** - The current editor state. - */ - get state() { return this.viewState.state; } - /** - To be able to display large documents without consuming too much - memory or overloading the browser, CodeMirror only draws the - code that is visible (plus a margin around it) to the DOM. This - property tells you the extent of the current drawn viewport, in - document positions. - */ - get viewport() { return this.viewState.viewport; } - /** - When there are, for example, large collapsed ranges in the - viewport, its size can be a lot bigger than the actual visible - content. Thus, if you are doing something like styling the - content in the viewport, it is preferable to only do so for - these ranges, which are the subset of the viewport that is - actually drawn. - */ - get visibleRanges() { return this.viewState.visibleRanges; } - /** - Returns false when the editor is entirely scrolled out of view - or otherwise hidden. - */ - get inView() { return this.viewState.inView; } - /** - Indicates whether the user is currently composing text via - [IME](https://en.wikipedia.org/wiki/Input_method), and at least - one change has been made in the current composition. - */ - get composing() { return this.inputState.composing > 0; } - /** - Indicates whether the user is currently in composing state. Note - that on some platforms, like Android, this will be the case a - lot, since just putting the cursor on a word starts a - composition there. - */ - get compositionStarted() { return this.inputState.composing >= 0; } - dispatch(...input) { - this._dispatch(input.length == 1 && input[0] instanceof Transaction ? input[0] - : this.state.update(...input)); - } - /** - Update the view for the given array of transactions. This will - update the visible document and selection to match the state - produced by the transactions, and notify view plugins of the - change. You should usually call - [`dispatch`](https://codemirror.net/6/docs/ref/#view.EditorView.dispatch) instead, which uses this - as a primitive. - */ - update(transactions) { - if (this.updateState != 0 /* Idle */) - throw new Error("Calls to EditorView.update are not allowed while an update is in progress"); - let redrawn = false, update; - let state = this.state; - for (let tr of transactions) { - if (tr.startState != state) - throw new RangeError("Trying to update state with a transaction that doesn't start from the previous state."); - state = tr.state; - } - if (this.destroyed) { - this.viewState.state = state; - return; - } - // When the phrases change, redraw the editor - if (state.facet(EditorState.phrases) != this.state.facet(EditorState.phrases)) - return this.setState(state); - update = new ViewUpdate(this, state, transactions); - let scrollTarget = this.viewState.scrollTarget; - try { - this.updateState = 2 /* Updating */; - for (let tr of transactions) { - if (scrollTarget) - scrollTarget = scrollTarget.map(tr.changes); - if (tr.scrollIntoView) { - let { main } = tr.state.selection; - scrollTarget = new ScrollTarget(main.empty ? main : EditorSelection.cursor(main.head, main.head > main.anchor ? -1 : 1)); - } - for (let e of tr.effects) { - if (e.is(scrollTo)) - scrollTarget = new ScrollTarget(e.value); - else if (e.is(centerOn)) - scrollTarget = new ScrollTarget(e.value, "center"); - else if (e.is(scrollIntoView$1)) - scrollTarget = e.value; - } - } - this.viewState.update(update, scrollTarget); - this.bidiCache = CachedOrder.update(this.bidiCache, update.changes); - if (!update.empty) { - this.updatePlugins(update); - this.inputState.update(update); - } - redrawn = this.docView.update(update); - if (this.state.facet(styleModule) != this.styleModules) - this.mountStyles(); - this.updateAttrs(); - this.showAnnouncements(transactions); - this.docView.updateSelection(redrawn, transactions.some(tr => tr.isUserEvent("select.pointer"))); - } - finally { - this.updateState = 0 /* Idle */; - } - if (update.startState.facet(theme) != update.state.facet(theme)) - this.viewState.mustMeasureContent = true; - if (redrawn || scrollTarget || this.viewState.mustEnforceCursorAssoc || this.viewState.mustMeasureContent) - this.requestMeasure(); - if (!update.empty) - for (let listener of this.state.facet(updateListener)) - listener(update); - } - /** - Reset the view to the given state. (This will cause the entire - document to be redrawn and all view plugins to be reinitialized, - so you should probably only use it when the new state isn't - derived from the old state. Otherwise, use - [`dispatch`](https://codemirror.net/6/docs/ref/#view.EditorView.dispatch) instead.) - */ - setState(newState) { - if (this.updateState != 0 /* Idle */) - throw new Error("Calls to EditorView.setState are not allowed while an update is in progress"); - if (this.destroyed) { - this.viewState.state = newState; - return; - } - this.updateState = 2 /* Updating */; - let hadFocus = this.hasFocus; - try { - for (let plugin of this.plugins) - plugin.destroy(this); - this.viewState = new ViewState(newState); - this.plugins = newState.facet(viewPlugin).map(spec => new PluginInstance(spec)); - this.pluginMap.clear(); - for (let plugin of this.plugins) - plugin.update(this); - this.docView = new DocView(this); - this.inputState.ensureHandlers(this); - this.mountStyles(); - this.updateAttrs(); - this.bidiCache = []; - } - finally { - this.updateState = 0 /* Idle */; - } - if (hadFocus) - this.focus(); - this.requestMeasure(); - } - updatePlugins(update) { - let prevSpecs = update.startState.facet(viewPlugin), specs = update.state.facet(viewPlugin); - if (prevSpecs != specs) { - let newPlugins = []; - for (let spec of specs) { - let found = prevSpecs.indexOf(spec); - if (found < 0) { - newPlugins.push(new PluginInstance(spec)); - } - else { - let plugin = this.plugins[found]; - plugin.mustUpdate = update; - newPlugins.push(plugin); - } - } - for (let plugin of this.plugins) - if (plugin.mustUpdate != update) - plugin.destroy(this); - this.plugins = newPlugins; - this.pluginMap.clear(); - this.inputState.ensureHandlers(this); - } - else { - for (let p of this.plugins) - p.mustUpdate = update; - } - for (let i = 0; i < this.plugins.length; i++) - this.plugins[i].update(this); - } - /** - @internal - */ - measure(flush = true) { - if (this.destroyed) - return; - if (this.measureScheduled > -1) - cancelAnimationFrame(this.measureScheduled); - this.measureScheduled = 0; // Prevent requestMeasure calls from scheduling another animation frame - if (flush) - this.observer.flush(); - let updated = null; - try { - for (let i = 0;; i++) { - this.updateState = 1 /* Measuring */; - let oldViewport = this.viewport; - let changed = this.viewState.measure(this); - if (!changed && !this.measureRequests.length && this.viewState.scrollTarget == null) - break; - if (i > 5) { - console.warn(this.measureRequests.length - ? "Measure loop restarted more than 5 times" - : "Viewport failed to stabilize"); - break; - } - let measuring = []; - // Only run measure requests in this cycle when the viewport didn't change - if (!(changed & 4 /* Viewport */)) - [this.measureRequests, measuring] = [measuring, this.measureRequests]; - let measured = measuring.map(m => { - try { - return m.read(this); - } - catch (e) { - logException(this.state, e); - return BadMeasure; - } - }); - let update = new ViewUpdate(this, this.state), redrawn = false, scrolled = false; - update.flags |= changed; - if (!updated) - updated = update; - else - updated.flags |= changed; - this.updateState = 2 /* Updating */; - if (!update.empty) { - this.updatePlugins(update); - this.inputState.update(update); - this.updateAttrs(); - redrawn = this.docView.update(update); - } - for (let i = 0; i < measuring.length; i++) - if (measured[i] != BadMeasure) { - try { - let m = measuring[i]; - if (m.write) - m.write(measured[i], this); - } - catch (e) { - logException(this.state, e); - } - } - if (this.viewState.scrollTarget) { - this.docView.scrollIntoView(this.viewState.scrollTarget); - this.viewState.scrollTarget = null; - scrolled = true; - } - if (redrawn) - this.docView.updateSelection(true); - if (this.viewport.from == oldViewport.from && this.viewport.to == oldViewport.to && - !scrolled && this.measureRequests.length == 0) - break; - } - } - finally { - this.updateState = 0 /* Idle */; - this.measureScheduled = -1; - } - if (updated && !updated.empty) - for (let listener of this.state.facet(updateListener)) - listener(updated); - } - /** - Get the CSS classes for the currently active editor themes. - */ - get themeClasses() { - return baseThemeID + " " + - (this.state.facet(darkTheme) ? baseDarkID : baseLightID) + " " + - this.state.facet(theme); - } - updateAttrs() { - let editorAttrs = attrsFromFacet(this, editorAttributes, { - class: "cm-editor" + (this.hasFocus ? " cm-focused " : " ") + this.themeClasses - }); - let contentAttrs = { - spellcheck: "false", - autocorrect: "off", - autocapitalize: "off", - translate: "no", - contenteditable: !this.state.facet(editable) ? "false" : "true", - class: "cm-content", - style: `${browser.tabSize}: ${this.state.tabSize}`, - role: "textbox", - "aria-multiline": "true" - }; - if (this.state.readOnly) - contentAttrs["aria-readonly"] = "true"; - attrsFromFacet(this, contentAttributes, contentAttrs); - this.observer.ignore(() => { - updateAttrs(this.contentDOM, this.contentAttrs, contentAttrs); - updateAttrs(this.dom, this.editorAttrs, editorAttrs); - }); - this.editorAttrs = editorAttrs; - this.contentAttrs = contentAttrs; - } - showAnnouncements(trs) { - let first = true; - for (let tr of trs) - for (let effect of tr.effects) - if (effect.is(EditorView.announce)) { - if (first) - this.announceDOM.textContent = ""; - first = false; - let div = this.announceDOM.appendChild(document.createElement("div")); - div.textContent = effect.value; - } - } - mountStyles() { - this.styleModules = this.state.facet(styleModule); - StyleModule.mount(this.root, this.styleModules.concat(baseTheme$8).reverse()); - } - readMeasured() { - if (this.updateState == 2 /* Updating */) - throw new Error("Reading the editor layout isn't allowed during an update"); - if (this.updateState == 0 /* Idle */ && this.measureScheduled > -1) - this.measure(false); - } - /** - Schedule a layout measurement, optionally providing callbacks to - do custom DOM measuring followed by a DOM write phase. Using - this is preferable reading DOM layout directly from, for - example, an event handler, because it'll make sure measuring and - drawing done by other components is synchronized, avoiding - unnecessary DOM layout computations. - */ - requestMeasure(request) { - if (this.measureScheduled < 0) - this.measureScheduled = requestAnimationFrame(() => this.measure()); - if (request) { - if (request.key != null) - for (let i = 0; i < this.measureRequests.length; i++) { - if (this.measureRequests[i].key === request.key) { - this.measureRequests[i] = request; - return; - } - } - this.measureRequests.push(request); - } - } - /** - Collect all values provided by the active plugins for a given - field. - */ - pluginField(field) { - let result = []; - for (let plugin of this.plugins) - plugin.update(this).takeField(field, result); - return result; - } - /** - Get the value of a specific plugin, if present. Note that - plugins that crash can be dropped from a view, so even when you - know you registered a given plugin, it is recommended to check - the return value of this method. - */ - plugin(plugin) { - let known = this.pluginMap.get(plugin); - if (known === undefined || known && known.spec != plugin) - this.pluginMap.set(plugin, known = this.plugins.find(p => p.spec == plugin) || null); - return known && known.update(this).value; - } - /** - The top position of the document, in screen coordinates. This - may be negative when the editor is scrolled down. Points - directly to the top of the first line, not above the padding. - */ - get documentTop() { - return this.contentDOM.getBoundingClientRect().top + this.viewState.paddingTop; - } - /** - Reports the padding above and below the document. - */ - get documentPadding() { - return { top: this.viewState.paddingTop, bottom: this.viewState.paddingBottom }; - } - /** - Find the line or block widget at the given vertical position. - - By default, this position is interpreted as a screen position, - meaning `docTop` is set to the DOM top position of the editor - content (forcing a layout). You can pass a different `docTop` - value—for example 0 to interpret `height` as a document-relative - position, or a precomputed document top - (`view.contentDOM.getBoundingClientRect().top`) to limit layout - queries. - - *Deprecated: use `elementAtHeight` instead.* - */ - blockAtHeight(height, docTop) { - let top = ensureTop(docTop, this); - return this.elementAtHeight(height - top).moveY(top); - } - /** - Find the text line or block widget at the given vertical - position (which is interpreted as relative to the [top of the - document](https://codemirror.net/6/docs/ref/#view.EditorView.documentTop) - */ - elementAtHeight(height) { - this.readMeasured(); - return this.viewState.elementAtHeight(height); - } - /** - Find information for the visual line (see - [`visualLineAt`](https://codemirror.net/6/docs/ref/#view.EditorView.visualLineAt)) at the given - vertical position. The resulting block info might hold another - array of block info structs in its `type` field if this line - consists of more than one block. - - Defaults to treating `height` as a screen position. See - [`blockAtHeight`](https://codemirror.net/6/docs/ref/#view.EditorView.blockAtHeight) for the - interpretation of the `docTop` parameter. - - *Deprecated: use `lineBlockAtHeight` instead.* - */ - visualLineAtHeight(height, docTop) { - let top = ensureTop(docTop, this); - return this.lineBlockAtHeight(height - top).moveY(top); - } - /** - Find the line block (see - [`lineBlockAt`](https://codemirror.net/6/docs/ref/#view.EditorView.lineBlockAt) at the given - height. - */ - lineBlockAtHeight(height) { - this.readMeasured(); - return this.viewState.lineBlockAtHeight(height); - } - /** - Iterate over the height information of the visual lines in the - viewport. The heights of lines are reported relative to the - given document top, which defaults to the screen position of the - document (forcing a layout). - - *Deprecated: use `viewportLineBlocks` instead.* - */ - viewportLines(f, docTop) { - let top = ensureTop(docTop, this); - for (let line of this.viewportLineBlocks) - f(line.moveY(top)); - } - /** - Get the extent and vertical position of all [line - blocks](https://codemirror.net/6/docs/ref/#view.EditorView.lineBlockAt) in the viewport. Positions - are relative to the [top of the - document](https://codemirror.net/6/docs/ref/#view.EditorView.documentTop); - */ - get viewportLineBlocks() { - return this.viewState.viewportLines; - } - /** - Find the extent and height of the visual line (a range delimited - on both sides by either non-[hidden](https://codemirror.net/6/docs/ref/#view.Decoration^range) - line breaks, or the start/end of the document) at the given position. - - Vertical positions are computed relative to the `docTop` - argument, which defaults to 0 for this method. You can pass - `view.contentDOM.getBoundingClientRect().top` here to get screen - coordinates. - - *Deprecated: use `lineBlockAt` instead.* - */ - visualLineAt(pos, docTop = 0) { - return this.lineBlockAt(pos).moveY(docTop + this.viewState.paddingTop); - } - /** - Find the line block around the given document position. A line - block is a range delimited on both sides by either a - non-[hidden](https://codemirror.net/6/docs/ref/#view.Decoration^range) line breaks, or the - start/end of the document. It will usually just hold a line of - text, but may be broken into multiple textblocks by block - widgets. - */ - lineBlockAt(pos) { - return this.viewState.lineBlockAt(pos); - } - /** - The editor's total content height. - */ - get contentHeight() { - return this.viewState.contentHeight; - } - /** - Move a cursor position by [grapheme - cluster](https://codemirror.net/6/docs/ref/#text.findClusterBreak). `forward` determines whether - the motion is away from the line start, or towards it. Motion in - bidirectional text is in visual order, in the editor's [text - direction](https://codemirror.net/6/docs/ref/#view.EditorView.textDirection). When the start - position was the last one on the line, the returned position - will be across the line break. If there is no further line, the - original position is returned. - - By default, this method moves over a single cluster. The - optional `by` argument can be used to move across more. It will - be called with the first cluster as argument, and should return - a predicate that determines, for each subsequent cluster, - whether it should also be moved over. - */ - moveByChar(start, forward, by) { - return skipAtoms(this, start, moveByChar(this, start, forward, by)); - } - /** - Move a cursor position across the next group of either - [letters](https://codemirror.net/6/docs/ref/#state.EditorState.charCategorizer) or non-letter - non-whitespace characters. - */ - moveByGroup(start, forward) { - return skipAtoms(this, start, moveByChar(this, start, forward, initial => byGroup(this, start.head, initial))); - } - /** - Move to the next line boundary in the given direction. If - `includeWrap` is true, line wrapping is on, and there is a - further wrap point on the current line, the wrap point will be - returned. Otherwise this function will return the start or end - of the line. - */ - moveToLineBoundary(start, forward, includeWrap = true) { - return moveToLineBoundary(this, start, forward, includeWrap); - } - /** - Move a cursor position vertically. When `distance` isn't given, - it defaults to moving to the next line (including wrapped - lines). Otherwise, `distance` should provide a positive distance - in pixels. - - When `start` has a - [`goalColumn`](https://codemirror.net/6/docs/ref/#state.SelectionRange.goalColumn), the vertical - motion will use that as a target horizontal position. Otherwise, - the cursor's own horizontal position is used. The returned - cursor will have its goal column set to whichever column was - used. - */ - moveVertically(start, forward, distance) { - return skipAtoms(this, start, moveVertically(this, start, forward, distance)); - } - // FIXME remove on next major version - scrollPosIntoView(pos) { - this.dispatch({ effects: scrollTo.of(EditorSelection.cursor(pos)) }); - } - /** - Find the DOM parent node and offset (child offset if `node` is - an element, character offset when it is a text node) at the - given document position. - - Note that for positions that aren't currently in - `visibleRanges`, the resulting DOM position isn't necessarily - meaningful (it may just point before or after a placeholder - element). - */ - domAtPos(pos) { - return this.docView.domAtPos(pos); - } - /** - Find the document position at the given DOM node. Can be useful - for associating positions with DOM events. Will raise an error - when `node` isn't part of the editor content. - */ - posAtDOM(node, offset = 0) { - return this.docView.posFromDOM(node, offset); - } - posAtCoords(coords, precise = true) { - this.readMeasured(); - return posAtCoords(this, coords, precise); - } - /** - Get the screen coordinates at the given document position. - `side` determines whether the coordinates are based on the - element before (-1) or after (1) the position (if no element is - available on the given side, the method will transparently use - another strategy to get reasonable coordinates). - */ - coordsAtPos(pos, side = 1) { - this.readMeasured(); - let rect = this.docView.coordsAt(pos, side); - if (!rect || rect.left == rect.right) - return rect; - let line = this.state.doc.lineAt(pos), order = this.bidiSpans(line); - let span = order[BidiSpan.find(order, pos - line.from, -1, side)]; - return flattenRect(rect, (span.dir == Direction.LTR) == (side > 0)); - } - /** - The default width of a character in the editor. May not - accurately reflect the width of all characters (given variable - width fonts or styling of invididual ranges). - */ - get defaultCharacterWidth() { return this.viewState.heightOracle.charWidth; } - /** - The default height of a line in the editor. May not be accurate - for all lines. - */ - get defaultLineHeight() { return this.viewState.heightOracle.lineHeight; } - /** - The text direction - ([`direction`](https://developer.mozilla.org/en-US/docs/Web/CSS/direction) - CSS property) of the editor. - */ - get textDirection() { return this.viewState.heightOracle.direction; } - /** - Whether this editor [wraps lines](https://codemirror.net/6/docs/ref/#view.EditorView.lineWrapping) - (as determined by the - [`white-space`](https://developer.mozilla.org/en-US/docs/Web/CSS/white-space) - CSS property of its content element). - */ - get lineWrapping() { return this.viewState.heightOracle.lineWrapping; } - /** - Returns the bidirectional text structure of the given line - (which should be in the current document) as an array of span - objects. The order of these spans matches the [text - direction](https://codemirror.net/6/docs/ref/#view.EditorView.textDirection)—if that is - left-to-right, the leftmost spans come first, otherwise the - rightmost spans come first. - */ - bidiSpans(line) { - if (line.length > MaxBidiLine) - return trivialOrder(line.length); - let dir = this.textDirection; - for (let entry of this.bidiCache) - if (entry.from == line.from && entry.dir == dir) - return entry.order; - let order = computeOrder(line.text, this.textDirection); - this.bidiCache.push(new CachedOrder(line.from, line.to, dir, order)); - return order; - } - /** - Check whether the editor has focus. - */ - get hasFocus() { - var _a; - // Safari return false for hasFocus when the context menu is open - // or closing, which leads us to ignore selection changes from the - // context menu because it looks like the editor isn't focused. - // This kludges around that. - return (document.hasFocus() || browser.safari && ((_a = this.inputState) === null || _a === void 0 ? void 0 : _a.lastContextMenu) > Date.now() - 3e4) && - this.root.activeElement == this.contentDOM; - } - /** - Put focus on the editor. - */ - focus() { - this.observer.ignore(() => { - focusPreventScroll(this.contentDOM); - this.docView.updateSelection(); - }); - } - /** - Clean up this editor view, removing its element from the - document, unregistering event handlers, and notifying - plugins. The view instance can no longer be used after - calling this. - */ - destroy() { - for (let plugin of this.plugins) - plugin.destroy(this); - this.plugins = []; - this.inputState.destroy(); - this.dom.remove(); - this.observer.destroy(); - if (this.measureScheduled > -1) - cancelAnimationFrame(this.measureScheduled); - this.destroyed = true; - } - /** - Returns an effect that can be - [added](https://codemirror.net/6/docs/ref/#state.TransactionSpec.effects) to a transaction to - cause it to scroll the given position or range into view. - */ - static scrollIntoView(pos, options = {}) { - return scrollIntoView$1.of(new ScrollTarget(typeof pos == "number" ? EditorSelection.cursor(pos) : pos, options.y, options.x, options.yMargin, options.xMargin)); - } - /** - Facet that can be used to add DOM event handlers. The value - should be an object mapping event names to handler functions. The - first such function to return true will be assumed to have handled - that event, and no other handlers or built-in behavior will be - activated for it. - These are registered on the [content - element](https://codemirror.net/6/docs/ref/#view.EditorView.contentDOM), except for `scroll` - handlers, which will be called any time the editor's [scroll - element](https://codemirror.net/6/docs/ref/#view.EditorView.scrollDOM) or one of its parent nodes - is scrolled. - */ - static domEventHandlers(handlers) { - return ViewPlugin.define(() => ({}), { eventHandlers: handlers }); - } - /** - Create a theme extension. The first argument can be a - [`style-mod`](https://github.com/marijnh/style-mod#documentation) - style spec providing the styles for the theme. These will be - prefixed with a generated class for the style. - - Because the selectors will be prefixed with a scope class, rule - that directly match the editor's [wrapper - element](https://codemirror.net/6/docs/ref/#view.EditorView.dom)—to which the scope class will be - added—need to be explicitly differentiated by adding an `&` to - the selector for that element—for example - `&.cm-focused`. - - When `dark` is set to true, the theme will be marked as dark, - which will cause the `&dark` rules from [base - themes](https://codemirror.net/6/docs/ref/#view.EditorView^baseTheme) to be used (as opposed to - `&light` when a light theme is active). - */ - static theme(spec, options) { - let prefix = StyleModule.newName(); - let result = [theme.of(prefix), styleModule.of(buildTheme(`.${prefix}`, spec))]; - if (options && options.dark) - result.push(darkTheme.of(true)); - return result; - } - /** - Create an extension that adds styles to the base theme. Like - with [`theme`](https://codemirror.net/6/docs/ref/#view.EditorView^theme), use `&` to indicate the - place of the editor wrapper element when directly targeting - that. You can also use `&dark` or `&light` instead to only - target editors with a dark or light theme. - */ - static baseTheme(spec) { - return Prec.lowest(styleModule.of(buildTheme("." + baseThemeID, spec, lightDarkIDs))); - } - } - /** - Effect that can be [added](https://codemirror.net/6/docs/ref/#state.TransactionSpec.effects) to a - transaction to make it scroll the given range into view. - - *Deprecated*. Use [`scrollIntoView`](https://codemirror.net/6/docs/ref/#view.EditorView^scrollIntoView) instead. - */ - EditorView.scrollTo = scrollTo; - /** - Effect that makes the editor scroll the given range to the - center of the visible view. - - *Deprecated*. Use [`scrollIntoView`](https://codemirror.net/6/docs/ref/#view.EditorView^scrollIntoView) instead. - */ - EditorView.centerOn = centerOn; - /** - Facet to add a [style - module](https://github.com/marijnh/style-mod#documentation) to - an editor view. The view will ensure that the module is - mounted in its [document - root](https://codemirror.net/6/docs/ref/#view.EditorView.constructor^config.root). - */ - EditorView.styleModule = styleModule; - /** - An input handler can override the way changes to the editable - DOM content are handled. Handlers are passed the document - positions between which the change was found, and the new - content. When one returns true, no further input handlers are - called and the default behavior is prevented. - */ - EditorView.inputHandler = inputHandler$1; - /** - Allows you to provide a function that should be called when the - library catches an exception from an extension (mostly from view - plugins, but may be used by other extensions to route exceptions - from user-code-provided callbacks). This is mostly useful for - debugging and logging. See [`logException`](https://codemirror.net/6/docs/ref/#view.logException). - */ - EditorView.exceptionSink = exceptionSink; - /** - A facet that can be used to register a function to be called - every time the view updates. - */ - EditorView.updateListener = updateListener; - /** - Facet that controls whether the editor content DOM is editable. - When its highest-precedence value is `false`, the element will - not longer have its `contenteditable` attribute set. (Note that - this doesn't affect API calls that change the editor content, - even when those are bound to keys or buttons. See the - [`readOnly`](https://codemirror.net/6/docs/ref/#state.EditorState.readOnly) facet for that.) - */ - EditorView.editable = editable; - /** - Allows you to influence the way mouse selection happens. The - functions in this facet will be called for a `mousedown` event - on the editor, and can return an object that overrides the way a - selection is computed from that mouse click or drag. - */ - EditorView.mouseSelectionStyle = mouseSelectionStyle; - /** - Facet used to configure whether a given selection drag event - should move or copy the selection. The given predicate will be - called with the `mousedown` event, and can return `true` when - the drag should move the content. - */ - EditorView.dragMovesSelection = dragMovesSelection$1; - /** - Facet used to configure whether a given selecting click adds - a new range to the existing selection or replaces it entirely. - */ - EditorView.clickAddsSelectionRange = clickAddsSelectionRange; - /** - A facet that determines which [decorations](https://codemirror.net/6/docs/ref/#view.Decoration) - are shown in the view. See also [view - plugins](https://codemirror.net/6/docs/ref/#view.EditorView^decorations), which have a separate - mechanism for providing decorations. - */ - EditorView.decorations = decorations; - /** - This facet records whether a dark theme is active. The extension - returned by [`theme`](https://codemirror.net/6/docs/ref/#view.EditorView^theme) automatically - includes an instance of this when the `dark` option is set to - true. - */ - EditorView.darkTheme = darkTheme; - /** - Facet that provides additional DOM attributes for the editor's - editable DOM element. - */ - EditorView.contentAttributes = contentAttributes; - /** - Facet that provides DOM attributes for the editor's outer - element. - */ - EditorView.editorAttributes = editorAttributes; - /** - An extension that enables line wrapping in the editor (by - setting CSS `white-space` to `pre-wrap` in the content). - */ - EditorView.lineWrapping = /*@__PURE__*/EditorView.contentAttributes.of({ "class": "cm-lineWrapping" }); - /** - State effect used to include screen reader announcements in a - transaction. These will be added to the DOM in a visually hidden - element with `aria-live="polite"` set, and should be used to - describe effects that are visually obvious but may not be - noticed by screen reader users (such as moving to the next - search match). - */ - EditorView.announce = /*@__PURE__*/StateEffect.define(); - // Maximum line length for which we compute accurate bidi info - const MaxBidiLine = 4096; - // FIXME remove this and its callers on next breaking release - function ensureTop(given, view) { - return (given == null ? view.contentDOM.getBoundingClientRect().top : given) + view.viewState.paddingTop; - } - const BadMeasure = {}; - class CachedOrder { - constructor(from, to, dir, order) { - this.from = from; - this.to = to; - this.dir = dir; - this.order = order; - } - static update(cache, changes) { - if (changes.empty) - return cache; - let result = [], lastDir = cache.length ? cache[cache.length - 1].dir : Direction.LTR; - for (let i = Math.max(0, cache.length - 10); i < cache.length; i++) { - let entry = cache[i]; - if (entry.dir == lastDir && !changes.touchesRange(entry.from, entry.to)) - result.push(new CachedOrder(changes.mapPos(entry.from, 1), changes.mapPos(entry.to, -1), entry.dir, entry.order)); - } - return result; - } - } - function attrsFromFacet(view, facet, base) { - for (let sources = view.state.facet(facet), i = sources.length - 1; i >= 0; i--) { - let source = sources[i], value = typeof source == "function" ? source(view) : source; - if (value) - combineAttrs(value, base); - } - return base; - } - - const currentPlatform = browser.mac ? "mac" : browser.windows ? "win" : browser.linux ? "linux" : "key"; - function normalizeKeyName(name, platform) { - const parts = name.split(/-(?!$)/); - let result = parts[parts.length - 1]; - if (result == "Space") - result = " "; - let alt, ctrl, shift, meta; - for (let i = 0; i < parts.length - 1; ++i) { - const mod = parts[i]; - if (/^(cmd|meta|m)$/i.test(mod)) - meta = 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 if (/^mod$/i.test(mod)) { - if (platform == "mac") - meta = true; - else - ctrl = true; - } - else - throw new Error("Unrecognized modifier name: " + mod); - } - if (alt) - result = "Alt-" + result; - if (ctrl) - result = "Ctrl-" + result; - if (meta) - result = "Meta-" + result; - if (shift) - result = "Shift-" + result; - return result; - } - function modifiers(name, event, shift) { - if (event.altKey) - name = "Alt-" + name; - if (event.ctrlKey) - name = "Ctrl-" + name; - if (event.metaKey) - name = "Meta-" + name; - if (shift !== false && event.shiftKey) - name = "Shift-" + name; - return name; - } - const handleKeyEvents = /*@__PURE__*/EditorView.domEventHandlers({ - keydown(event, view) { - return runHandlers(getKeymap(view.state), event, view, "editor"); - } - }); - /** - Facet used for registering keymaps. - - You can add multiple keymaps to an editor. Their priorities - determine their precedence (the ones specified early or with high - priority get checked first). When a handler has returned `true` - for a given key, no further handlers are called. - */ - const keymap = /*@__PURE__*/Facet.define({ enables: handleKeyEvents }); - const Keymaps = /*@__PURE__*/new WeakMap(); - // This is hidden behind an indirection, rather than directly computed - // by the facet, to keep internal types out of the facet's type. - function getKeymap(state) { - let bindings = state.facet(keymap); - let map = Keymaps.get(bindings); - if (!map) - Keymaps.set(bindings, map = buildKeymap(bindings.reduce((a, b) => a.concat(b), []))); - return map; - } - /** - Run the key handlers registered for a given scope. The event - object should be `"keydown"` event. Returns true if any of the - handlers handled it. - */ - function runScopeHandlers(view, event, scope) { - return runHandlers(getKeymap(view.state), event, view, scope); - } - let storedPrefix = null; - const PrefixTimeout = 4000; - function buildKeymap(bindings, platform = currentPlatform) { - let bound = Object.create(null); - let isPrefix = Object.create(null); - let checkPrefix = (name, is) => { - let current = isPrefix[name]; - if (current == null) - isPrefix[name] = is; - else if (current != is) - throw new Error("Key binding " + name + " is used both as a regular binding and as a multi-stroke prefix"); - }; - let add = (scope, key, command, preventDefault) => { - let scopeObj = bound[scope] || (bound[scope] = Object.create(null)); - let parts = key.split(/ (?!$)/).map(k => normalizeKeyName(k, platform)); - for (let i = 1; i < parts.length; i++) { - let prefix = parts.slice(0, i).join(" "); - checkPrefix(prefix, true); - if (!scopeObj[prefix]) - scopeObj[prefix] = { - preventDefault: true, - commands: [(view) => { - let ourObj = storedPrefix = { view, prefix, scope }; - setTimeout(() => { if (storedPrefix == ourObj) - storedPrefix = null; }, PrefixTimeout); - return true; - }] - }; - } - let full = parts.join(" "); - checkPrefix(full, false); - let binding = scopeObj[full] || (scopeObj[full] = { preventDefault: false, commands: [] }); - binding.commands.push(command); - if (preventDefault) - binding.preventDefault = true; - }; - for (let b of bindings) { - let name = b[platform] || b.key; - if (!name) - continue; - for (let scope of b.scope ? b.scope.split(" ") : ["editor"]) { - add(scope, name, b.run, b.preventDefault); - if (b.shift) - add(scope, "Shift-" + name, b.shift, b.preventDefault); - } - } - return bound; - } - function runHandlers(map, event, view, scope) { - let name = keyName(event), isChar = name.length == 1 && name != " "; - let prefix = "", fallthrough = false; - if (storedPrefix && storedPrefix.view == view && storedPrefix.scope == scope) { - prefix = storedPrefix.prefix + " "; - if (fallthrough = modifierCodes.indexOf(event.keyCode) < 0) - storedPrefix = null; - } - let runFor = (binding) => { - if (binding) { - for (let cmd of binding.commands) - if (cmd(view)) - return true; - if (binding.preventDefault) - fallthrough = true; - } - return false; - }; - let scopeObj = map[scope], baseName; - if (scopeObj) { - if (runFor(scopeObj[prefix + modifiers(name, event, !isChar)])) - return true; - if (isChar && (event.shiftKey || event.altKey || event.metaKey) && - (baseName = base[event.keyCode]) && baseName != name) { - if (runFor(scopeObj[prefix + modifiers(baseName, event, true)])) - return true; - } - else if (isChar && event.shiftKey) { - if (runFor(scopeObj[prefix + modifiers(name, event, true)])) - return true; - } - } - return fallthrough; - } - - const CanHidePrimary = !browser.ios; // FIXME test IE - const selectionConfig = /*@__PURE__*/Facet.define({ - combine(configs) { - return combineConfig(configs, { - cursorBlinkRate: 1200, - drawRangeCursor: true - }, { - cursorBlinkRate: (a, b) => Math.min(a, b), - drawRangeCursor: (a, b) => a || b - }); - } - }); - /** - Returns an extension that hides the browser's native selection and - cursor, replacing the selection with a background behind the text - (with the `cm-selectionBackground` class), and the - cursors with elements overlaid over the code (using - `cm-cursor-primary` and `cm-cursor-secondary`). - - This allows the editor to display secondary selection ranges, and - tends to produce a type of selection more in line with that users - expect in a text editor (the native selection styling will often - leave gaps between lines and won't fill the horizontal space after - a line when the selection continues past it). - - It does have a performance cost, in that it requires an extra DOM - layout cycle for many updates (the selection is drawn based on DOM - layout information that's only available after laying out the - content). - */ - function drawSelection(config = {}) { - return [ - selectionConfig.of(config), - drawSelectionPlugin, - hideNativeSelection - ]; - } - class Piece { - constructor(left, top, width, height, className) { - this.left = left; - this.top = top; - this.width = width; - this.height = height; - this.className = className; - } - draw() { - let elt = document.createElement("div"); - elt.className = this.className; - this.adjust(elt); - return elt; - } - adjust(elt) { - elt.style.left = this.left + "px"; - elt.style.top = this.top + "px"; - if (this.width >= 0) - elt.style.width = this.width + "px"; - elt.style.height = this.height + "px"; - } - eq(p) { - return this.left == p.left && this.top == p.top && this.width == p.width && this.height == p.height && - this.className == p.className; - } - } - const drawSelectionPlugin = /*@__PURE__*/ViewPlugin.fromClass(class { - constructor(view) { - this.view = view; - this.rangePieces = []; - this.cursors = []; - this.measureReq = { read: this.readPos.bind(this), write: this.drawSel.bind(this) }; - this.selectionLayer = view.scrollDOM.appendChild(document.createElement("div")); - this.selectionLayer.className = "cm-selectionLayer"; - this.selectionLayer.setAttribute("aria-hidden", "true"); - this.cursorLayer = view.scrollDOM.appendChild(document.createElement("div")); - this.cursorLayer.className = "cm-cursorLayer"; - this.cursorLayer.setAttribute("aria-hidden", "true"); - view.requestMeasure(this.measureReq); - this.setBlinkRate(); - } - setBlinkRate() { - this.cursorLayer.style.animationDuration = this.view.state.facet(selectionConfig).cursorBlinkRate + "ms"; - } - update(update) { - let confChanged = update.startState.facet(selectionConfig) != update.state.facet(selectionConfig); - if (confChanged || update.selectionSet || update.geometryChanged || update.viewportChanged) - this.view.requestMeasure(this.measureReq); - if (update.transactions.some(tr => tr.scrollIntoView)) - this.cursorLayer.style.animationName = this.cursorLayer.style.animationName == "cm-blink" ? "cm-blink2" : "cm-blink"; - if (confChanged) - this.setBlinkRate(); - } - readPos() { - let { state } = this.view, conf = state.facet(selectionConfig); - let rangePieces = state.selection.ranges.map(r => r.empty ? [] : measureRange(this.view, r)).reduce((a, b) => a.concat(b)); - let cursors = []; - for (let r of state.selection.ranges) { - let prim = r == state.selection.main; - if (r.empty ? !prim || CanHidePrimary : conf.drawRangeCursor) { - let piece = measureCursor(this.view, r, prim); - if (piece) - cursors.push(piece); - } - } - return { rangePieces, cursors }; - } - drawSel({ rangePieces, cursors }) { - if (rangePieces.length != this.rangePieces.length || rangePieces.some((p, i) => !p.eq(this.rangePieces[i]))) { - this.selectionLayer.textContent = ""; - for (let p of rangePieces) - this.selectionLayer.appendChild(p.draw()); - this.rangePieces = rangePieces; - } - if (cursors.length != this.cursors.length || cursors.some((c, i) => !c.eq(this.cursors[i]))) { - let oldCursors = this.cursorLayer.children; - if (oldCursors.length !== cursors.length) { - this.cursorLayer.textContent = ""; - for (const c of cursors) - this.cursorLayer.appendChild(c.draw()); - } - else { - cursors.forEach((c, idx) => c.adjust(oldCursors[idx])); - } - this.cursors = cursors; - } - } - destroy() { - this.selectionLayer.remove(); - this.cursorLayer.remove(); - } - }); - const themeSpec = { - ".cm-line": { - "& ::selection": { backgroundColor: "transparent !important" }, - "&::selection": { backgroundColor: "transparent !important" } - } - }; - if (CanHidePrimary) - themeSpec[".cm-line"].caretColor = "transparent !important"; - const hideNativeSelection = /*@__PURE__*/Prec.highest(/*@__PURE__*/EditorView.theme(themeSpec)); - function getBase(view) { - let rect = view.scrollDOM.getBoundingClientRect(); - let left = view.textDirection == Direction.LTR ? rect.left : rect.right - view.scrollDOM.clientWidth; - return { left: left - view.scrollDOM.scrollLeft, top: rect.top - view.scrollDOM.scrollTop }; - } - function wrappedLine(view, pos, inside) { - let range = EditorSelection.cursor(pos); - return { from: Math.max(inside.from, view.moveToLineBoundary(range, false, true).from), - to: Math.min(inside.to, view.moveToLineBoundary(range, true, true).from), - type: BlockType.Text }; - } - function blockAt(view, pos) { - let line = view.lineBlockAt(pos); - if (Array.isArray(line.type)) - for (let l of line.type) { - if (l.to > pos || l.to == pos && (l.to == line.to || l.type == BlockType.Text)) - return l; - } - return line; - } - function measureRange(view, range) { - if (range.to <= view.viewport.from || range.from >= view.viewport.to) - return []; - let from = Math.max(range.from, view.viewport.from), to = Math.min(range.to, view.viewport.to); - let ltr = view.textDirection == Direction.LTR; - let content = view.contentDOM, contentRect = content.getBoundingClientRect(), base = getBase(view); - let lineStyle = window.getComputedStyle(content.firstChild); - let leftSide = contentRect.left + parseInt(lineStyle.paddingLeft) + Math.min(0, parseInt(lineStyle.textIndent)); - let rightSide = contentRect.right - parseInt(lineStyle.paddingRight); - let startBlock = blockAt(view, from), endBlock = blockAt(view, to); - let visualStart = startBlock.type == BlockType.Text ? startBlock : null; - let visualEnd = endBlock.type == BlockType.Text ? endBlock : null; - if (view.lineWrapping) { - if (visualStart) - visualStart = wrappedLine(view, from, visualStart); - if (visualEnd) - visualEnd = wrappedLine(view, to, visualEnd); - } - if (visualStart && visualEnd && visualStart.from == visualEnd.from) { - return pieces(drawForLine(range.from, range.to, visualStart)); - } - else { - let top = visualStart ? drawForLine(range.from, null, visualStart) : drawForWidget(startBlock, false); - let bottom = visualEnd ? drawForLine(null, range.to, visualEnd) : drawForWidget(endBlock, true); - let between = []; - if ((visualStart || startBlock).to < (visualEnd || endBlock).from - 1) - between.push(piece(leftSide, top.bottom, rightSide, bottom.top)); - else if (top.bottom < bottom.top && view.elementAtHeight((top.bottom + bottom.top) / 2).type == BlockType.Text) - top.bottom = bottom.top = (top.bottom + bottom.top) / 2; - return pieces(top).concat(between).concat(pieces(bottom)); - } - function piece(left, top, right, bottom) { - return new Piece(left - base.left, top - base.top - 0.01 /* Epsilon */, right - left, bottom - top + 0.01 /* Epsilon */, "cm-selectionBackground"); - } - function pieces({ top, bottom, horizontal }) { - let pieces = []; - for (let i = 0; i < horizontal.length; i += 2) - pieces.push(piece(horizontal[i], top, horizontal[i + 1], bottom)); - return pieces; - } - // Gets passed from/to in line-local positions - function drawForLine(from, to, line) { - let top = 1e9, bottom = -1e9, horizontal = []; - function addSpan(from, fromOpen, to, toOpen, dir) { - // Passing 2/-2 is a kludge to force the view to return - // coordinates on the proper side of block widgets, since - // normalizing the side there, though appropriate for most - // coordsAtPos queries, would break selection drawing. - let fromCoords = view.coordsAtPos(from, (from == line.to ? -2 : 2)); - let toCoords = view.coordsAtPos(to, (to == line.from ? 2 : -2)); - top = Math.min(fromCoords.top, toCoords.top, top); - bottom = Math.max(fromCoords.bottom, toCoords.bottom, bottom); - if (dir == Direction.LTR) - horizontal.push(ltr && fromOpen ? leftSide : fromCoords.left, ltr && toOpen ? rightSide : toCoords.right); - else - horizontal.push(!ltr && toOpen ? leftSide : toCoords.left, !ltr && fromOpen ? rightSide : fromCoords.right); - } - let start = from !== null && from !== void 0 ? from : line.from, end = to !== null && to !== void 0 ? to : line.to; - // Split the range by visible range and document line - for (let r of view.visibleRanges) - if (r.to > start && r.from < end) { - for (let pos = Math.max(r.from, start), endPos = Math.min(r.to, end);;) { - let docLine = view.state.doc.lineAt(pos); - for (let span of view.bidiSpans(docLine)) { - let spanFrom = span.from + docLine.from, spanTo = span.to + docLine.from; - if (spanFrom >= endPos) - break; - if (spanTo > pos) - addSpan(Math.max(spanFrom, pos), from == null && spanFrom <= start, Math.min(spanTo, endPos), to == null && spanTo >= end, span.dir); - } - pos = docLine.to + 1; - if (pos >= endPos) - break; - } - } - if (horizontal.length == 0) - addSpan(start, from == null, end, to == null, view.textDirection); - return { top, bottom, horizontal }; - } - function drawForWidget(block, top) { - let y = contentRect.top + (top ? block.top : block.bottom); - return { top: y, bottom: y, horizontal: [] }; - } - } - function measureCursor(view, cursor, primary) { - let pos = view.coordsAtPos(cursor.head, cursor.assoc || 1); - if (!pos) - return null; - let base = getBase(view); - return new Piece(pos.left - base.left, pos.top - base.top, -1, pos.bottom - pos.top, primary ? "cm-cursor cm-cursor-primary" : "cm-cursor cm-cursor-secondary"); - } - - const setDropCursorPos = /*@__PURE__*/StateEffect.define({ - map(pos, mapping) { return pos == null ? null : mapping.mapPos(pos); } - }); - const dropCursorPos = /*@__PURE__*/StateField.define({ - create() { return null; }, - update(pos, tr) { - if (pos != null) - pos = tr.changes.mapPos(pos); - return tr.effects.reduce((pos, e) => e.is(setDropCursorPos) ? e.value : pos, pos); - } - }); - const drawDropCursor = /*@__PURE__*/ViewPlugin.fromClass(class { - constructor(view) { - this.view = view; - this.cursor = null; - this.measureReq = { read: this.readPos.bind(this), write: this.drawCursor.bind(this) }; - } - update(update) { - var _a; - let cursorPos = update.state.field(dropCursorPos); - if (cursorPos == null) { - if (this.cursor != null) { - (_a = this.cursor) === null || _a === void 0 ? void 0 : _a.remove(); - this.cursor = null; - } - } - else { - if (!this.cursor) { - this.cursor = this.view.scrollDOM.appendChild(document.createElement("div")); - this.cursor.className = "cm-dropCursor"; - } - if (update.startState.field(dropCursorPos) != cursorPos || update.docChanged || update.geometryChanged) - this.view.requestMeasure(this.measureReq); - } - } - readPos() { - let pos = this.view.state.field(dropCursorPos); - let rect = pos != null && this.view.coordsAtPos(pos); - if (!rect) - return null; - let outer = this.view.scrollDOM.getBoundingClientRect(); - return { - left: rect.left - outer.left + this.view.scrollDOM.scrollLeft, - top: rect.top - outer.top + this.view.scrollDOM.scrollTop, - height: rect.bottom - rect.top - }; - } - drawCursor(pos) { - if (this.cursor) { - if (pos) { - this.cursor.style.left = pos.left + "px"; - this.cursor.style.top = pos.top + "px"; - this.cursor.style.height = pos.height + "px"; - } - else { - this.cursor.style.left = "-100000px"; - } - } - } - destroy() { - if (this.cursor) - this.cursor.remove(); - } - setDropPos(pos) { - if (this.view.state.field(dropCursorPos) != pos) - this.view.dispatch({ effects: setDropCursorPos.of(pos) }); - } - }, { - eventHandlers: { - dragover(event) { - this.setDropPos(this.view.posAtCoords({ x: event.clientX, y: event.clientY })); - }, - dragleave(event) { - if (event.target == this.view.contentDOM || !this.view.contentDOM.contains(event.relatedTarget)) - this.setDropPos(null); - }, - dragend() { - this.setDropPos(null); - }, - drop() { - this.setDropPos(null); - } - } - }); - /** - Draws a cursor at the current drop position when something is - dragged over the editor. - */ - function dropCursor() { - return [dropCursorPos, drawDropCursor]; - } - - function iterMatches(doc, re, from, to, f) { - re.lastIndex = 0; - for (let cursor = doc.iterRange(from, to), pos = from, m; !cursor.next().done; pos += cursor.value.length) { - if (!cursor.lineBreak) - while (m = re.exec(cursor.value)) - f(pos + m.index, pos + m.index + m[0].length, m); - } - } - function matchRanges(view, maxLength) { - let visible = view.visibleRanges; - if (visible.length == 1 && visible[0].from == view.viewport.from && - visible[0].to == view.viewport.to) - return visible; - let result = []; - for (let { from, to } of visible) { - from = Math.max(view.state.doc.lineAt(from).from, from - maxLength); - to = Math.min(view.state.doc.lineAt(to).to, to + maxLength); - if (result.length && result[result.length - 1].to >= from) - result[result.length - 1].to = to; - else - result.push({ from, to }); - } - return result; - } - /** - Helper class used to make it easier to maintain decorations on - visible code that matches a given regular expression. To be used - in a [view plugin](https://codemirror.net/6/docs/ref/#view.ViewPlugin). Instances of this object - represent a matching configuration. - */ - class MatchDecorator { - /** - Create a decorator. - */ - constructor(config) { - let { regexp, decoration, boundary, maxLength = 1000 } = config; - if (!regexp.global) - throw new RangeError("The regular expression given to MatchDecorator should have its 'g' flag set"); - this.regexp = regexp; - this.getDeco = typeof decoration == "function" ? decoration : () => decoration; - this.boundary = boundary; - this.maxLength = maxLength; - } - /** - Compute the full set of decorations for matches in the given - view's viewport. You'll want to call this when initializing your - plugin. - */ - createDeco(view) { - let build = new RangeSetBuilder(); - for (let { from, to } of matchRanges(view, this.maxLength)) - iterMatches(view.state.doc, this.regexp, from, to, (a, b, m) => build.add(a, b, this.getDeco(m, view, a))); - return build.finish(); - } - /** - Update a set of decorations for a view update. `deco` _must_ be - the set of decorations produced by _this_ `MatchDecorator` for - the view state before the update. - */ - updateDeco(update, deco) { - let changeFrom = 1e9, changeTo = -1; - if (update.docChanged) - update.changes.iterChanges((_f, _t, from, to) => { - if (to > update.view.viewport.from && from < update.view.viewport.to) { - changeFrom = Math.min(from, changeFrom); - changeTo = Math.max(to, changeTo); - } - }); - if (update.viewportChanged || changeTo - changeFrom > 1000) - return this.createDeco(update.view); - if (changeTo > -1) - return this.updateRange(update.view, deco.map(update.changes), changeFrom, changeTo); - return deco; - } - updateRange(view, deco, updateFrom, updateTo) { - for (let r of view.visibleRanges) { - let from = Math.max(r.from, updateFrom), to = Math.min(r.to, updateTo); - if (to > from) { - let fromLine = view.state.doc.lineAt(from), toLine = fromLine.to < to ? view.state.doc.lineAt(to) : fromLine; - let start = Math.max(r.from, fromLine.from), end = Math.min(r.to, toLine.to); - if (this.boundary) { - for (; from > fromLine.from; from--) - if (this.boundary.test(fromLine.text[from - 1 - fromLine.from])) { - start = from; - break; - } - for (; to < toLine.to; to++) - if (this.boundary.test(toLine.text[to - toLine.from])) { - end = to; - break; - } - } - let ranges = [], m; - if (fromLine == toLine) { - this.regexp.lastIndex = start - fromLine.from; - while ((m = this.regexp.exec(fromLine.text)) && m.index < end - fromLine.from) { - let pos = m.index + fromLine.from; - ranges.push(this.getDeco(m, view, pos).range(pos, pos + m[0].length)); - } - } - else { - iterMatches(view.state.doc, this.regexp, start, end, (from, to, m) => ranges.push(this.getDeco(m, view, from).range(from, to))); - } - deco = deco.update({ filterFrom: start, filterTo: end, filter: (from, to) => from < start || to > end, add: ranges }); - } - } - return deco; - } - } - - const UnicodeRegexpSupport = /x/.unicode != null ? "gu" : "g"; - const Specials = /*@__PURE__*/new RegExp("[\u0000-\u0008\u000a-\u001f\u007f-\u009f\u00ad\u061c\u200b\u200e\u200f\u2028\u2029\u202d\u202e\ufeff\ufff9-\ufffc]", UnicodeRegexpSupport); - const Names = { - 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", - 8233: "paragraph separator", - 65279: "zero width no-break space", - 65532: "object replacement" - }; - let _supportsTabSize = null; - function supportsTabSize() { - var _a; - if (_supportsTabSize == null && typeof document != "undefined" && document.body) { - let styles = document.body.style; - _supportsTabSize = ((_a = styles.tabSize) !== null && _a !== void 0 ? _a : styles.MozTabSize) != null; - } - return _supportsTabSize || false; - } - const specialCharConfig = /*@__PURE__*/Facet.define({ - combine(configs) { - let config = combineConfig(configs, { - render: null, - specialChars: Specials, - addSpecialChars: null - }); - if (config.replaceTabs = !supportsTabSize()) - config.specialChars = new RegExp("\t|" + config.specialChars.source, UnicodeRegexpSupport); - if (config.addSpecialChars) - config.specialChars = new RegExp(config.specialChars.source + "|" + config.addSpecialChars.source, UnicodeRegexpSupport); - return config; - } - }); - /** - Returns an extension that installs highlighting of special - characters. - */ - function highlightSpecialChars( - /** - Configuration options. - */ - config = {}) { - return [specialCharConfig.of(config), specialCharPlugin()]; - } - let _plugin = null; - function specialCharPlugin() { - return _plugin || (_plugin = ViewPlugin.fromClass(class { - constructor(view) { - this.view = view; - this.decorations = Decoration.none; - this.decorationCache = Object.create(null); - this.decorator = this.makeDecorator(view.state.facet(specialCharConfig)); - this.decorations = this.decorator.createDeco(view); - } - makeDecorator(conf) { - return new MatchDecorator({ - regexp: conf.specialChars, - decoration: (m, view, pos) => { - let { doc } = view.state; - let code = codePointAt(m[0], 0); - if (code == 9) { - let line = doc.lineAt(pos); - let size = view.state.tabSize, col = countColumn(line.text, size, pos - line.from); - return Decoration.replace({ widget: new TabWidget((size - (col % size)) * this.view.defaultCharacterWidth) }); - } - return this.decorationCache[code] || - (this.decorationCache[code] = Decoration.replace({ widget: new SpecialCharWidget(conf, code) })); - }, - boundary: conf.replaceTabs ? undefined : /[^]/ - }); - } - update(update) { - let conf = update.state.facet(specialCharConfig); - if (update.startState.facet(specialCharConfig) != conf) { - this.decorator = this.makeDecorator(conf); - this.decorations = this.decorator.createDeco(update.view); - } - else { - this.decorations = this.decorator.updateDeco(update, this.decorations); - } - } - }, { - decorations: v => v.decorations - })); - } - const DefaultPlaceholder = "\u2022"; - // Assigns placeholder characters from the Control Pictures block to - // ASCII control characters - function placeholder$1(code) { - if (code >= 32) - return DefaultPlaceholder; - if (code == 10) - return "\u2424"; - return String.fromCharCode(9216 + code); - } - class SpecialCharWidget extends WidgetType { - constructor(options, code) { - super(); - this.options = options; - this.code = code; - } - eq(other) { return other.code == this.code; } - toDOM(view) { - let ph = placeholder$1(this.code); - let desc = view.state.phrase("Control character") + " " + (Names[this.code] || "0x" + this.code.toString(16)); - let custom = this.options.render && this.options.render(this.code, desc, ph); - if (custom) - return custom; - let span = document.createElement("span"); - span.textContent = ph; - span.title = desc; - span.setAttribute("aria-label", desc); - span.className = "cm-specialChar"; - return span; - } - ignoreEvent() { return false; } - } - class TabWidget extends WidgetType { - constructor(width) { - super(); - this.width = width; - } - eq(other) { return other.width == this.width; } - toDOM() { - let span = document.createElement("span"); - span.textContent = "\t"; - span.className = "cm-tab"; - span.style.width = this.width + "px"; - return span; - } - ignoreEvent() { return false; } - } - - /** - Mark lines that have a cursor on them with the `"cm-activeLine"` - DOM class. - */ - function highlightActiveLine() { - return activeLineHighlighter; - } - const lineDeco = /*@__PURE__*/Decoration.line({ class: "cm-activeLine" }); - const activeLineHighlighter = /*@__PURE__*/ViewPlugin.fromClass(class { - constructor(view) { - this.decorations = this.getDeco(view); - } - update(update) { - if (update.docChanged || update.selectionSet) - this.decorations = this.getDeco(update.view); - } - getDeco(view) { - let lastLineStart = -1, deco = []; - for (let r of view.state.selection.ranges) { - if (!r.empty) - return Decoration.none; - let line = view.lineBlockAt(r.head); - if (line.from > lastLineStart) { - deco.push(lineDeco.range(line.from)); - lastLineStart = line.from; - } - } - return Decoration.set(deco); - } - }, { - decorations: v => v.decorations - }); - - const fromHistory = /*@__PURE__*/Annotation.define(); - /** - Transaction annotation that will prevent that transaction from - being combined with other transactions in the undo history. Given - `"before"`, it'll prevent merging with previous transactions. With - `"after"`, subsequent transactions won't be combined with this - one. With `"full"`, the transaction is isolated on both sides. - */ - const isolateHistory = /*@__PURE__*/Annotation.define(); - /** - This facet provides a way to register functions that, given a - transaction, provide a set of effects that the history should - store when inverting the transaction. This can be used to - integrate some kinds of effects in the history, so that they can - be undone (and redone again). - */ - const invertedEffects = /*@__PURE__*/Facet.define(); - const historyConfig = /*@__PURE__*/Facet.define({ - combine(configs) { - return combineConfig(configs, { - minDepth: 100, - newGroupDelay: 500 - }, { minDepth: Math.max, newGroupDelay: Math.min }); - } - }); - function changeEnd(changes) { - let end = 0; - changes.iterChangedRanges((_, to) => end = to); - return end; - } - const historyField_ = /*@__PURE__*/StateField.define({ - create() { - return HistoryState.empty; - }, - update(state, tr) { - let config = tr.state.facet(historyConfig); - let fromHist = tr.annotation(fromHistory); - if (fromHist) { - let selection = tr.docChanged ? EditorSelection.single(changeEnd(tr.changes)) : undefined; - let item = HistEvent.fromTransaction(tr, selection), from = fromHist.side; - let other = from == 0 /* Done */ ? state.undone : state.done; - if (item) - other = updateBranch(other, other.length, config.minDepth, item); - else - other = addSelection(other, tr.startState.selection); - return new HistoryState(from == 0 /* Done */ ? fromHist.rest : other, from == 0 /* Done */ ? other : fromHist.rest); - } - let isolate = tr.annotation(isolateHistory); - if (isolate == "full" || isolate == "before") - state = state.isolate(); - if (tr.annotation(Transaction.addToHistory) === false) - return !tr.changes.empty ? state.addMapping(tr.changes.desc) : state; - let event = HistEvent.fromTransaction(tr); - let time = tr.annotation(Transaction.time), userEvent = tr.annotation(Transaction.userEvent); - if (event) - state = state.addChanges(event, time, userEvent, config.newGroupDelay, config.minDepth); - else if (tr.selection) - state = state.addSelection(tr.startState.selection, time, userEvent, config.newGroupDelay); - if (isolate == "full" || isolate == "after") - state = state.isolate(); - return state; - }, - toJSON(value) { - return { done: value.done.map(e => e.toJSON()), undone: value.undone.map(e => e.toJSON()) }; - }, - fromJSON(json) { - return new HistoryState(json.done.map(HistEvent.fromJSON), json.undone.map(HistEvent.fromJSON)); - } - }); - /** - Create a history extension with the given configuration. - */ - function history(config = {}) { - return [ - historyField_, - historyConfig.of(config), - EditorView.domEventHandlers({ - beforeinput(e, view) { - let command = e.inputType == "historyUndo" ? undo : e.inputType == "historyRedo" ? redo : null; - if (!command) - return false; - e.preventDefault(); - return command(view); - } - }) - ]; - } - function cmd(side, selection) { - return function ({ state, dispatch }) { - if (!selection && state.readOnly) - return false; - let historyState = state.field(historyField_, false); - if (!historyState) - return false; - let tr = historyState.pop(side, state, selection); - if (!tr) - return false; - dispatch(tr); - return true; - }; - } - /** - Undo a single group of history events. Returns false if no group - was available. - */ - const undo = /*@__PURE__*/cmd(0 /* Done */, false); - /** - Redo a group of history events. Returns false if no group was - available. - */ - const redo = /*@__PURE__*/cmd(1 /* Undone */, false); - /** - Undo a selection change. - */ - const undoSelection = /*@__PURE__*/cmd(0 /* Done */, true); - /** - Redo a selection change. - */ - const redoSelection = /*@__PURE__*/cmd(1 /* Undone */, true); - // History events store groups of changes or effects that need to be - // undone/redone together. - class HistEvent { - constructor( - // The changes in this event. Normal events hold at least one - // change or effect. But it may be necessary to store selection - // events before the first change, in which case a special type of - // instance is created which doesn't hold any changes, with - // changes == startSelection == undefined - changes, - // The effects associated with this event - effects, mapped, - // The selection before this event - startSelection, - // Stores selection changes after this event, to be used for - // selection undo/redo. - selectionsAfter) { - this.changes = changes; - this.effects = effects; - this.mapped = mapped; - this.startSelection = startSelection; - this.selectionsAfter = selectionsAfter; - } - setSelAfter(after) { - return new HistEvent(this.changes, this.effects, this.mapped, this.startSelection, after); - } - toJSON() { - var _a, _b, _c; - return { - changes: (_a = this.changes) === null || _a === void 0 ? void 0 : _a.toJSON(), - mapped: (_b = this.mapped) === null || _b === void 0 ? void 0 : _b.toJSON(), - startSelection: (_c = this.startSelection) === null || _c === void 0 ? void 0 : _c.toJSON(), - selectionsAfter: this.selectionsAfter.map(s => s.toJSON()) - }; - } - static fromJSON(json) { - return new HistEvent(json.changes && ChangeSet.fromJSON(json.changes), [], json.mapped && ChangeDesc.fromJSON(json.mapped), json.startSelection && EditorSelection.fromJSON(json.startSelection), json.selectionsAfter.map(EditorSelection.fromJSON)); - } - // This does not check `addToHistory` and such, it assumes the - // transaction needs to be converted to an item. Returns null when - // there are no changes or effects in the transaction. - static fromTransaction(tr, selection) { - let effects = none$1; - for (let invert of tr.startState.facet(invertedEffects)) { - let result = invert(tr); - if (result.length) - effects = effects.concat(result); - } - if (!effects.length && tr.changes.empty) - return null; - return new HistEvent(tr.changes.invert(tr.startState.doc), effects, undefined, selection || tr.startState.selection, none$1); - } - static selection(selections) { - return new HistEvent(undefined, none$1, undefined, undefined, selections); - } - } - function updateBranch(branch, to, maxLen, newEvent) { - let start = to + 1 > maxLen + 20 ? to - maxLen - 1 : 0; - let newBranch = branch.slice(start, to); - newBranch.push(newEvent); - return newBranch; - } - function isAdjacent(a, b) { - let ranges = [], isAdjacent = false; - a.iterChangedRanges((f, t) => ranges.push(f, t)); - b.iterChangedRanges((_f, _t, f, t) => { - for (let i = 0; i < ranges.length;) { - let from = ranges[i++], to = ranges[i++]; - if (t >= from && f <= to) - isAdjacent = true; - } - }); - return isAdjacent; - } - function eqSelectionShape(a, b) { - return a.ranges.length == b.ranges.length && - a.ranges.filter((r, i) => r.empty != b.ranges[i].empty).length === 0; - } - function conc(a, b) { - return !a.length ? b : !b.length ? a : a.concat(b); - } - const none$1 = []; - const MaxSelectionsPerEvent = 200; - function addSelection(branch, selection) { - if (!branch.length) { - return [HistEvent.selection([selection])]; - } - else { - let lastEvent = branch[branch.length - 1]; - let sels = lastEvent.selectionsAfter.slice(Math.max(0, lastEvent.selectionsAfter.length - MaxSelectionsPerEvent)); - if (sels.length && sels[sels.length - 1].eq(selection)) - return branch; - sels.push(selection); - return updateBranch(branch, branch.length - 1, 1e9, lastEvent.setSelAfter(sels)); - } - } - // Assumes the top item has one or more selectionAfter values - function popSelection(branch) { - let last = branch[branch.length - 1]; - let newBranch = branch.slice(); - newBranch[branch.length - 1] = last.setSelAfter(last.selectionsAfter.slice(0, last.selectionsAfter.length - 1)); - return newBranch; - } - // Add a mapping to the top event in the given branch. If this maps - // away all the changes and effects in that item, drop it and - // propagate the mapping to the next item. - function addMappingToBranch(branch, mapping) { - if (!branch.length) - return branch; - let length = branch.length, selections = none$1; - while (length) { - let event = mapEvent(branch[length - 1], mapping, selections); - if (event.changes && !event.changes.empty || event.effects.length) { // Event survived mapping - let result = branch.slice(0, length); - result[length - 1] = event; - return result; - } - else { // Drop this event, since there's no changes or effects left - mapping = event.mapped; - length--; - selections = event.selectionsAfter; - } - } - return selections.length ? [HistEvent.selection(selections)] : none$1; - } - function mapEvent(event, mapping, extraSelections) { - let selections = conc(event.selectionsAfter.length ? event.selectionsAfter.map(s => s.map(mapping)) : none$1, extraSelections); - // Change-less events don't store mappings (they are always the last event in a branch) - if (!event.changes) - return HistEvent.selection(selections); - let mappedChanges = event.changes.map(mapping), before = mapping.mapDesc(event.changes, true); - let fullMapping = event.mapped ? event.mapped.composeDesc(before) : before; - return new HistEvent(mappedChanges, StateEffect.mapEffects(event.effects, mapping), fullMapping, event.startSelection.map(before), selections); - } - const joinableUserEvent = /^(input\.type|delete)($|\.)/; - class HistoryState { - constructor(done, undone, prevTime = 0, prevUserEvent = undefined) { - this.done = done; - this.undone = undone; - this.prevTime = prevTime; - this.prevUserEvent = prevUserEvent; - } - isolate() { - return this.prevTime ? new HistoryState(this.done, this.undone) : this; - } - addChanges(event, time, userEvent, newGroupDelay, maxLen) { - let done = this.done, lastEvent = done[done.length - 1]; - if (lastEvent && lastEvent.changes && !lastEvent.changes.empty && event.changes && - (!userEvent || joinableUserEvent.test(userEvent)) && - ((!lastEvent.selectionsAfter.length && - time - this.prevTime < newGroupDelay && - isAdjacent(lastEvent.changes, event.changes)) || - // For compose (but not compose.start) events, always join with previous event - userEvent == "input.type.compose")) { - done = updateBranch(done, done.length - 1, maxLen, new HistEvent(event.changes.compose(lastEvent.changes), conc(event.effects, lastEvent.effects), lastEvent.mapped, lastEvent.startSelection, none$1)); - } - else { - done = updateBranch(done, done.length, maxLen, event); - } - return new HistoryState(done, none$1, time, userEvent); - } - addSelection(selection, time, userEvent, newGroupDelay) { - let last = this.done.length ? this.done[this.done.length - 1].selectionsAfter : none$1; - if (last.length > 0 && - time - this.prevTime < newGroupDelay && - userEvent == this.prevUserEvent && userEvent && /^select($|\.)/.test(userEvent) && - eqSelectionShape(last[last.length - 1], selection)) - return this; - return new HistoryState(addSelection(this.done, selection), this.undone, time, userEvent); - } - addMapping(mapping) { - return new HistoryState(addMappingToBranch(this.done, mapping), addMappingToBranch(this.undone, mapping), this.prevTime, this.prevUserEvent); - } - pop(side, state, selection) { - let branch = side == 0 /* Done */ ? this.done : this.undone; - if (branch.length == 0) - return null; - let event = branch[branch.length - 1]; - if (selection && event.selectionsAfter.length) { - return state.update({ - selection: event.selectionsAfter[event.selectionsAfter.length - 1], - annotations: fromHistory.of({ side, rest: popSelection(branch) }), - userEvent: side == 0 /* Done */ ? "select.undo" : "select.redo", - scrollIntoView: true - }); - } - else if (!event.changes) { - return null; - } - else { - let rest = branch.length == 1 ? none$1 : branch.slice(0, branch.length - 1); - if (event.mapped) - rest = addMappingToBranch(rest, event.mapped); - return state.update({ - changes: event.changes, - selection: event.startSelection, - effects: event.effects, - annotations: fromHistory.of({ side, rest }), - filter: false, - userEvent: side == 0 /* Done */ ? "undo" : "redo", - scrollIntoView: true - }); - } - } - } - HistoryState.empty = /*@__PURE__*/new HistoryState(none$1, none$1); - /** - Default key bindings for the undo history. - - - Mod-z: [`undo`](https://codemirror.net/6/docs/ref/#history.undo). - - Mod-y (Mod-Shift-z on macOS): [`redo`](https://codemirror.net/6/docs/ref/#history.redo). - - Mod-u: [`undoSelection`](https://codemirror.net/6/docs/ref/#history.undoSelection). - - Alt-u (Mod-Shift-u on macOS): [`redoSelection`](https://codemirror.net/6/docs/ref/#history.redoSelection). - */ - const historyKeymap = [ - { key: "Mod-z", run: undo, preventDefault: true }, - { key: "Mod-y", mac: "Mod-Shift-z", run: redo, preventDefault: true }, - { key: "Mod-u", run: undoSelection, preventDefault: true }, - { key: "Alt-u", mac: "Mod-Shift-u", run: redoSelection, preventDefault: true } - ]; - - // FIXME profile adding a per-Tree TreeNode cache, validating it by - // parent pointer - /// The default maximum length of a `TreeBuffer` node (1024). - const DefaultBufferLength = 1024; - let nextPropID = 0; - class Range { - constructor(from, to) { - this.from = from; - this.to = to; - } - } - /// Each [node type](#common.NodeType) or [individual tree](#common.Tree) - /// can have metadata associated with it in props. Instances of this - /// class represent prop names. - class NodeProp { - /// Create a new node prop type. - constructor(config = {}) { - this.id = nextPropID++; - this.perNode = !!config.perNode; - this.deserialize = config.deserialize || (() => { - throw new Error("This node type doesn't define a deserialize function"); - }); - } - /// This is meant to be used with - /// [`NodeSet.extend`](#common.NodeSet.extend) or - /// [`LRParser.configure`](#lr.ParserConfig.props) to compute - /// prop values for each node type in the set. Takes a [match - /// object](#common.NodeType^match) or function that returns undefined - /// if the node type doesn't get this prop, and the prop's value if - /// it does. - add(match) { - if (this.perNode) - throw new RangeError("Can't add per-node props to node types"); - if (typeof match != "function") - match = NodeType.match(match); - return (type) => { - let result = match(type); - return result === undefined ? null : [this, result]; - }; - } - } - /// Prop that is used to describe matching delimiters. For opening - /// delimiters, this holds an array of node names (written as a - /// space-separated string when declaring this prop in a grammar) - /// for the node types of closing delimiters that match it. - NodeProp.closedBy = new NodeProp({ deserialize: str => str.split(" ") }); - /// The inverse of [`closedBy`](#common.NodeProp^closedBy). This is - /// attached to closing delimiters, holding an array of node names - /// of types of matching opening delimiters. - NodeProp.openedBy = new NodeProp({ deserialize: str => str.split(" ") }); - /// Used to assign node types to groups (for example, all node - /// types that represent an expression could be tagged with an - /// `"Expression"` group). - NodeProp.group = new NodeProp({ deserialize: str => str.split(" ") }); - /// The hash of the [context](#lr.ContextTracker.constructor) - /// that the node was parsed in, if any. Used to limit reuse of - /// contextual nodes. - NodeProp.contextHash = new NodeProp({ perNode: true }); - /// The distance beyond the end of the node that the tokenizer - /// looked ahead for any of the tokens inside the node. (The LR - /// parser only stores this when it is larger than 25, for - /// efficiency reasons.) - NodeProp.lookAhead = new NodeProp({ perNode: true }); - /// This per-node prop is used to replace a given node, or part of a - /// node, with another tree. This is useful to include trees from - /// different languages. - NodeProp.mounted = new NodeProp({ perNode: true }); - const noProps = Object.create(null); - /// Each node in a syntax tree has a node type associated with it. - class NodeType { - /// @internal - constructor( - /// The name of the node type. Not necessarily unique, but if the - /// grammar was written properly, different node types with the - /// same name within a node set should play the same semantic - /// role. - name, - /// @internal - props, - /// The id of this node in its set. Corresponds to the term ids - /// used in the parser. - id, - /// @internal - flags = 0) { - this.name = name; - this.props = props; - this.id = id; - this.flags = flags; - } - static define(spec) { - let props = spec.props && spec.props.length ? Object.create(null) : noProps; - let flags = (spec.top ? 1 /* Top */ : 0) | (spec.skipped ? 2 /* Skipped */ : 0) | - (spec.error ? 4 /* Error */ : 0) | (spec.name == null ? 8 /* Anonymous */ : 0); - let type = new NodeType(spec.name || "", props, spec.id, flags); - if (spec.props) - for (let src of spec.props) { - if (!Array.isArray(src)) - src = src(type); - if (src) { - if (src[0].perNode) - throw new RangeError("Can't store a per-node prop on a node type"); - props[src[0].id] = src[1]; - } - } - return type; - } - /// Retrieves a node prop for this type. Will return `undefined` if - /// the prop isn't present on this node. - prop(prop) { return this.props[prop.id]; } - /// True when this is the top node of a grammar. - get isTop() { return (this.flags & 1 /* Top */) > 0; } - /// True when this node is produced by a skip rule. - get isSkipped() { return (this.flags & 2 /* Skipped */) > 0; } - /// Indicates whether this is an error node. - get isError() { return (this.flags & 4 /* Error */) > 0; } - /// When true, this node type doesn't correspond to a user-declared - /// named node, for example because it is used to cache repetition. - get isAnonymous() { return (this.flags & 8 /* Anonymous */) > 0; } - /// Returns true when this node's name or one of its - /// [groups](#common.NodeProp^group) matches the given string. - is(name) { - if (typeof name == 'string') { - if (this.name == name) - return true; - let group = this.prop(NodeProp.group); - return group ? group.indexOf(name) > -1 : false; - } - return this.id == name; - } - /// Create a function from node types to arbitrary values by - /// specifying an object whose property names are node or - /// [group](#common.NodeProp^group) names. Often useful with - /// [`NodeProp.add`](#common.NodeProp.add). You can put multiple - /// names, separated by spaces, in a single property name to map - /// multiple node names to a single value. - static match(map) { - let direct = Object.create(null); - for (let prop in map) - for (let name of prop.split(" ")) - direct[name] = map[prop]; - return (node) => { - for (let groups = node.prop(NodeProp.group), i = -1; i < (groups ? groups.length : 0); i++) { - let found = direct[i < 0 ? node.name : groups[i]]; - if (found) - return found; - } - }; - } - } - /// An empty dummy node type to use when no actual type is available. - NodeType.none = new NodeType("", Object.create(null), 0, 8 /* Anonymous */); - /// A node set holds a collection of node types. It is used to - /// compactly represent trees by storing their type ids, rather than a - /// full pointer to the type object, in a numeric array. Each parser - /// [has](#lr.LRParser.nodeSet) a node set, and [tree - /// buffers](#common.TreeBuffer) can only store collections of nodes - /// from the same set. A set can have a maximum of 2**16 (65536) node - /// types in it, so that the ids fit into 16-bit typed array slots. - class NodeSet { - /// Create a set with the given types. The `id` property of each - /// type should correspond to its position within the array. - constructor( - /// The node types in this set, by id. - types) { - this.types = types; - for (let i = 0; i < types.length; i++) - if (types[i].id != i) - throw new RangeError("Node type ids should correspond to array positions when creating a node set"); - } - /// Create a copy of this set with some node properties added. The - /// arguments to this method should be created with - /// [`NodeProp.add`](#common.NodeProp.add). - extend(...props) { - let newTypes = []; - for (let type of this.types) { - let newProps = null; - for (let source of props) { - let add = source(type); - if (add) { - if (!newProps) - newProps = Object.assign({}, type.props); - newProps[add[0].id] = add[1]; - } - } - newTypes.push(newProps ? new NodeType(type.name, newProps, type.id, type.flags) : type); - } - return new NodeSet(newTypes); - } - } - const CachedNode = new WeakMap(), CachedInnerNode = new WeakMap(); - /// A piece of syntax tree. There are two ways to approach these - /// trees: the way they are actually stored in memory, and the - /// convenient way. - /// - /// Syntax trees are stored as a tree of `Tree` and `TreeBuffer` - /// objects. By packing detail information into `TreeBuffer` leaf - /// nodes, the representation is made a lot more memory-efficient. - /// - /// However, when you want to actually work with tree nodes, this - /// representation is very awkward, so most client code will want to - /// use the [`TreeCursor`](#common.TreeCursor) or - /// [`SyntaxNode`](#common.SyntaxNode) interface instead, which provides - /// a view on some part of this data structure, and can be used to - /// move around to adjacent nodes. - class Tree { - /// Construct a new tree. See also [`Tree.build`](#common.Tree^build). - constructor( - /// The type of the top node. - type, - /// This node's child nodes. - children, - /// The positions (offsets relative to the start of this tree) of - /// the children. - positions, - /// The total length of this tree - length, - /// Per-node [node props](#common.NodeProp) to associate with this node. - props) { - this.type = type; - this.children = children; - this.positions = positions; - this.length = length; - /// @internal - this.props = null; - if (props && props.length) { - this.props = Object.create(null); - for (let [prop, value] of props) - this.props[typeof prop == "number" ? prop : prop.id] = value; - } - } - /// @internal - toString() { - let mounted = this.prop(NodeProp.mounted); - if (mounted && !mounted.overlay) - return mounted.tree.toString(); - let children = ""; - for (let ch of this.children) { - let str = ch.toString(); - if (str) { - if (children) - children += ","; - children += str; - } - } - return !this.type.name ? children : - (/\W/.test(this.type.name) && !this.type.isError ? JSON.stringify(this.type.name) : this.type.name) + - (children.length ? "(" + children + ")" : ""); - } - /// Get a [tree cursor](#common.TreeCursor) rooted at this tree. When - /// `pos` is given, the cursor is [moved](#common.TreeCursor.moveTo) - /// to the given position and side. - cursor(pos, side = 0) { - let scope = (pos != null && CachedNode.get(this)) || this.topNode; - let cursor = new TreeCursor(scope); - if (pos != null) { - cursor.moveTo(pos, side); - CachedNode.set(this, cursor._tree); - } - return cursor; - } - /// Get a [tree cursor](#common.TreeCursor) that, unlike regular - /// cursors, doesn't skip through - /// [anonymous](#common.NodeType.isAnonymous) nodes and doesn't - /// automatically enter mounted nodes. - fullCursor() { - return new TreeCursor(this.topNode, 1 /* Full */); - } - /// Get a [syntax node](#common.SyntaxNode) object for the top of the - /// tree. - get topNode() { - return new TreeNode(this, 0, 0, null); - } - /// Get the [syntax node](#common.SyntaxNode) at the given position. - /// If `side` is -1, this will move into nodes that end at the - /// position. If 1, it'll move into nodes that start at the - /// position. With 0, it'll only enter nodes that cover the position - /// from both sides. - resolve(pos, side = 0) { - let node = resolveNode(CachedNode.get(this) || this.topNode, pos, side, false); - CachedNode.set(this, node); - return node; - } - /// Like [`resolve`](#common.Tree.resolve), but will enter - /// [overlaid](#common.MountedTree.overlay) nodes, producing a syntax node - /// pointing into the innermost overlaid tree at the given position - /// (with parent links going through all parent structure, including - /// the host trees). - resolveInner(pos, side = 0) { - let node = resolveNode(CachedInnerNode.get(this) || this.topNode, pos, side, true); - CachedInnerNode.set(this, node); - return node; - } - /// Iterate over the tree and its children, calling `enter` for any - /// node that touches the `from`/`to` region (if given) before - /// running over such a node's children, and `leave` (if given) when - /// leaving the node. When `enter` returns `false`, that node will - /// not have its children iterated over (or `leave` called). - iterate(spec) { - let { enter, leave, from = 0, to = this.length } = spec; - for (let c = this.cursor(), get = () => c.node;;) { - let mustLeave = false; - if (c.from <= to && c.to >= from && (c.type.isAnonymous || enter(c.type, c.from, c.to, get) !== false)) { - if (c.firstChild()) - continue; - if (!c.type.isAnonymous) - mustLeave = true; - } - for (;;) { - if (mustLeave && leave) - leave(c.type, c.from, c.to, get); - mustLeave = c.type.isAnonymous; - if (c.nextSibling()) - break; - if (!c.parent()) - return; - mustLeave = true; - } - } - } - /// Get the value of the given [node prop](#common.NodeProp) for this - /// node. Works with both per-node and per-type props. - prop(prop) { - return !prop.perNode ? this.type.prop(prop) : this.props ? this.props[prop.id] : undefined; - } - /// Returns the node's [per-node props](#common.NodeProp.perNode) in a - /// format that can be passed to the [`Tree`](#common.Tree) - /// constructor. - get propValues() { - let result = []; - if (this.props) - for (let id in this.props) - result.push([+id, this.props[id]]); - return result; - } - /// Balance the direct children of this tree, producing a copy of - /// which may have children grouped into subtrees with type - /// [`NodeType.none`](#common.NodeType^none). - balance(config = {}) { - return this.children.length <= 8 /* BranchFactor */ ? this : - balanceRange(NodeType.none, this.children, this.positions, 0, this.children.length, 0, this.length, (children, positions, length) => new Tree(this.type, children, positions, length, this.propValues), config.makeTree || ((children, positions, length) => new Tree(NodeType.none, children, positions, length))); - } - /// Build a tree from a postfix-ordered buffer of node information, - /// or a cursor over such a buffer. - static build(data) { return buildTree(data); } - } - /// The empty tree - Tree.empty = new Tree(NodeType.none, [], [], 0); - class FlatBufferCursor { - constructor(buffer, index) { - this.buffer = buffer; - this.index = index; - } - 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 FlatBufferCursor(this.buffer, this.index); } - } - /// Tree buffers contain (type, start, end, endIndex) quads for each - /// node. In such a buffer, nodes are stored in prefix order (parents - /// before children, with the endIndex of the parent indicating which - /// children belong to it) - class TreeBuffer { - /// Create a tree buffer. - constructor( - /// The buffer's content. - buffer, - /// The total length of the group of nodes in the buffer. - length, - /// The node set used in this buffer. - set) { - this.buffer = buffer; - this.length = length; - this.set = set; - } - /// @internal - get type() { return NodeType.none; } - /// @internal - toString() { - let result = []; - for (let index = 0; index < this.buffer.length;) { - result.push(this.childString(index)); - index = this.buffer[index + 3]; - } - return result.join(","); - } - /// @internal - childString(index) { - let id = this.buffer[index], endIndex = this.buffer[index + 3]; - let type = this.set.types[id], result = type.name; - if (/\W/.test(result) && !type.isError) - result = JSON.stringify(result); - index += 4; - if (endIndex == index) - return result; - let children = []; - while (index < endIndex) { - children.push(this.childString(index)); - index = this.buffer[index + 3]; - } - return result + "(" + children.join(",") + ")"; - } - /// @internal - findChild(startIndex, endIndex, dir, pos, side) { - let { buffer } = this, pick = -1; - for (let i = startIndex; i != endIndex; i = buffer[i + 3]) { - if (checkSide(side, pos, buffer[i + 1], buffer[i + 2])) { - pick = i; - if (dir > 0) - break; - } - } - return pick; - } - /// @internal - slice(startI, endI, from, to) { - let b = this.buffer; - let copy = new Uint16Array(endI - startI); - for (let i = startI, j = 0; i < endI;) { - copy[j++] = b[i++]; - copy[j++] = b[i++] - from; - copy[j++] = b[i++] - from; - copy[j++] = b[i++] - startI; - } - return new TreeBuffer(copy, to - from, this.set); - } - } - function checkSide(side, pos, from, to) { - switch (side) { - case -2 /* Before */: return from < pos; - case -1 /* AtOrBefore */: return to >= pos && from < pos; - case 0 /* Around */: return from < pos && to > pos; - case 1 /* AtOrAfter */: return from <= pos && to > pos; - case 2 /* After */: return to > pos; - case 4 /* DontCare */: return true; - } - } - function enterUnfinishedNodesBefore(node, pos) { - let scan = node.childBefore(pos); - while (scan) { - let last = scan.lastChild; - if (!last || last.to != scan.to) - break; - if (last.type.isError && last.from == last.to) { - node = scan; - scan = last.prevSibling; - } - else { - scan = last; - } - } - return node; - } - function resolveNode(node, pos, side, overlays) { - var _a; - // Move up to a node that actually holds the position, if possible - while (node.from == node.to || - (side < 1 ? node.from >= pos : node.from > pos) || - (side > -1 ? node.to <= pos : node.to < pos)) { - let parent = !overlays && node instanceof TreeNode && node.index < 0 ? null : node.parent; - if (!parent) - return node; - node = parent; - } - // Must go up out of overlays when those do not overlap with pos - if (overlays) - for (let scan = node, parent = scan.parent; parent; scan = parent, parent = scan.parent) { - if (scan instanceof TreeNode && scan.index < 0 && ((_a = parent.enter(pos, side, true)) === null || _a === void 0 ? void 0 : _a.from) != scan.from) - node = parent; - } - for (;;) { - let inner = node.enter(pos, side, overlays); - if (!inner) - return node; - node = inner; - } - } - class TreeNode { - constructor(node, _from, - // Index in parent node, set to -1 if the node is not a direct child of _parent.node (overlay) - index, _parent) { - this.node = node; - this._from = _from; - this.index = index; - this._parent = _parent; - } - get type() { return this.node.type; } - get name() { return this.node.type.name; } - get from() { return this._from; } - get to() { return this._from + this.node.length; } - nextChild(i, dir, pos, side, mode = 0) { - for (let parent = this;;) { - for (let { children, positions } = parent.node, e = dir > 0 ? children.length : -1; i != e; i += dir) { - let next = children[i], start = positions[i] + parent._from; - if (!checkSide(side, pos, start, start + next.length)) - continue; - if (next instanceof TreeBuffer) { - if (mode & 2 /* NoEnterBuffer */) - continue; - let index = next.findChild(0, next.buffer.length, dir, pos - start, side); - if (index > -1) - return new BufferNode(new BufferContext(parent, next, i, start), null, index); - } - else if ((mode & 1 /* Full */) || (!next.type.isAnonymous || hasChild(next))) { - let mounted; - if (!(mode & 1 /* Full */) && next.props && (mounted = next.prop(NodeProp.mounted)) && !mounted.overlay) - return new TreeNode(mounted.tree, start, i, parent); - let inner = new TreeNode(next, start, i, parent); - return (mode & 1 /* Full */) || !inner.type.isAnonymous ? inner - : inner.nextChild(dir < 0 ? next.children.length - 1 : 0, dir, pos, side); - } - } - if ((mode & 1 /* Full */) || !parent.type.isAnonymous) - return null; - if (parent.index >= 0) - i = parent.index + dir; - else - i = dir < 0 ? -1 : parent._parent.node.children.length; - parent = parent._parent; - if (!parent) - return null; - } - } - get firstChild() { return this.nextChild(0, 1, 0, 4 /* DontCare */); } - get lastChild() { return this.nextChild(this.node.children.length - 1, -1, 0, 4 /* DontCare */); } - childAfter(pos) { return this.nextChild(0, 1, pos, 2 /* After */); } - childBefore(pos) { return this.nextChild(this.node.children.length - 1, -1, pos, -2 /* Before */); } - enter(pos, side, overlays = true, buffers = true) { - let mounted; - if (overlays && (mounted = this.node.prop(NodeProp.mounted)) && mounted.overlay) { - let rPos = pos - this.from; - for (let { from, to } of mounted.overlay) { - if ((side > 0 ? from <= rPos : from < rPos) && - (side < 0 ? to >= rPos : to > rPos)) - return new TreeNode(mounted.tree, mounted.overlay[0].from + this.from, -1, this); - } - } - return this.nextChild(0, 1, pos, side, buffers ? 0 : 2 /* NoEnterBuffer */); - } - nextSignificantParent() { - let val = this; - while (val.type.isAnonymous && val._parent) - val = val._parent; - return val; - } - 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 /* DontCare */) : null; - } - get prevSibling() { - return this._parent && this.index >= 0 ? this._parent.nextChild(this.index - 1, -1, 0, 4 /* DontCare */) : null; - } - get cursor() { return new TreeCursor(this); } - get tree() { return this.node; } - toTree() { return this.node; } - resolve(pos, side = 0) { - return resolveNode(this, pos, side, false); - } - resolveInner(pos, side = 0) { - return resolveNode(this, pos, side, true); - } - enterUnfinishedNodesBefore(pos) { return enterUnfinishedNodesBefore(this, pos); } - getChild(type, before = null, after = null) { - let r = getChildren(this, type, before, after); - return r.length ? r[0] : null; - } - getChildren(type, before = null, after = null) { - return getChildren(this, type, before, after); - } - /// @internal - toString() { return this.node.toString(); } - } - function getChildren(node, type, before, after) { - let cur = node.cursor, result = []; - if (!cur.firstChild()) - return result; - if (before != null) - while (!cur.type.is(before)) - if (!cur.nextSibling()) - return result; - for (;;) { - if (after != null && cur.type.is(after)) - return result; - if (cur.type.is(type)) - result.push(cur.node); - if (!cur.nextSibling()) - return after == null ? result : []; - } - } - class BufferContext { - constructor(parent, buffer, index, start) { - this.parent = parent; - this.buffer = buffer; - this.index = index; - this.start = start; - } - } - class BufferNode { - constructor(context, _parent, index) { - this.context = context; - this._parent = _parent; - this.index = index; - this.type = context.buffer.set.types[context.buffer.buffer[index]]; - } - 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]; } - child(dir, pos, side) { - let { buffer } = this.context; - let index = buffer.findChild(this.index + 4, buffer.buffer[this.index + 3], dir, pos - this.context.start, side); - return index < 0 ? null : new BufferNode(this.context, this, index); - } - get firstChild() { return this.child(1, 0, 4 /* DontCare */); } - get lastChild() { return this.child(-1, 0, 4 /* DontCare */); } - childAfter(pos) { return this.child(1, pos, 2 /* After */); } - childBefore(pos) { return this.child(-1, pos, -2 /* Before */); } - enter(pos, side, overlays, buffers = true) { - if (!buffers) - return null; - let { buffer } = this.context; - let index = buffer.findChild(this.index + 4, buffer.buffer[this.index + 3], side > 0 ? 1 : -1, pos - this.context.start, side); - return index < 0 ? null : new BufferNode(this.context, this, index); - } - get parent() { - return this._parent || this.context.parent.nextSignificantParent(); - } - externalSibling(dir) { - return this._parent ? null : this.context.parent.nextChild(this.context.index + dir, dir, 0, 4 /* DontCare */); - } - get nextSibling() { - let { buffer } = this.context; - let after = buffer.buffer[this.index + 3]; - if (after < (this._parent ? buffer.buffer[this._parent.index + 3] : buffer.buffer.length)) - return new BufferNode(this.context, this._parent, after); - return this.externalSibling(1); - } - get prevSibling() { - let { buffer } = this.context; - let parentStart = this._parent ? this._parent.index + 4 : 0; - if (this.index == parentStart) - return this.externalSibling(-1); - return new BufferNode(this.context, this._parent, buffer.findChild(parentStart, this.index, -1, 0, 4 /* DontCare */)); - } - get cursor() { return new TreeCursor(this); } - get tree() { return null; } - toTree() { - let children = [], positions = []; - let { buffer } = this.context; - let startI = this.index + 4, endI = buffer.buffer[this.index + 3]; - if (endI > startI) { - let from = buffer.buffer[this.index + 1], to = buffer.buffer[this.index + 2]; - children.push(buffer.slice(startI, endI, from, to)); - positions.push(0); - } - return new Tree(this.type, children, positions, this.to - this.from); - } - resolve(pos, side = 0) { - return resolveNode(this, pos, side, false); - } - resolveInner(pos, side = 0) { - return resolveNode(this, pos, side, true); - } - enterUnfinishedNodesBefore(pos) { return enterUnfinishedNodesBefore(this, pos); } - /// @internal - toString() { return this.context.buffer.childString(this.index); } - getChild(type, before = null, after = null) { - let r = getChildren(this, type, before, after); - return r.length ? r[0] : null; - } - getChildren(type, before = null, after = null) { - return getChildren(this, type, before, after); - } - } - /// A tree cursor object focuses on a given node in a syntax tree, and - /// allows you to move to adjacent nodes. - class TreeCursor { - /// @internal - constructor(node, - /// @internal - mode = 0) { - this.mode = mode; - this.buffer = null; - this.stack = []; - this.index = 0; - this.bufferNode = null; - if (node instanceof TreeNode) { - this.yieldNode(node); - } - else { - this._tree = node.context.parent; - this.buffer = node.context; - for (let n = node._parent; n; n = n._parent) - this.stack.unshift(n.index); - this.bufferNode = node; - this.yieldBuf(node.index); - } - } - /// Shorthand for `.type.name`. - get name() { return this.type.name; } - yieldNode(node) { - if (!node) - return false; - this._tree = node; - this.type = node.type; - this.from = node.from; - this.to = node.to; - return true; - } - yieldBuf(index, type) { - this.index = index; - let { start, buffer } = this.buffer; - this.type = type || buffer.set.types[buffer.buffer[index]]; - this.from = start + buffer.buffer[index + 1]; - this.to = start + buffer.buffer[index + 2]; - return true; - } - yield(node) { - if (!node) - return false; - if (node instanceof TreeNode) { - this.buffer = null; - return this.yieldNode(node); - } - this.buffer = node.context; - return this.yieldBuf(node.index, node.type); - } - /// @internal - toString() { - return this.buffer ? this.buffer.buffer.childString(this.index) : this._tree.toString(); - } - /// @internal - enterChild(dir, pos, side) { - if (!this.buffer) - return this.yield(this._tree.nextChild(dir < 0 ? this._tree.node.children.length - 1 : 0, dir, pos, side, this.mode)); - let { buffer } = this.buffer; - let index = buffer.findChild(this.index + 4, buffer.buffer[this.index + 3], dir, pos - this.buffer.start, side); - if (index < 0) - return false; - this.stack.push(this.index); - return this.yieldBuf(index); - } - /// Move the cursor to this node's first child. When this returns - /// false, the node has no child, and the cursor has not been moved. - firstChild() { return this.enterChild(1, 0, 4 /* DontCare */); } - /// Move the cursor to this node's last child. - lastChild() { return this.enterChild(-1, 0, 4 /* DontCare */); } - /// Move the cursor to the first child that ends after `pos`. - childAfter(pos) { return this.enterChild(1, pos, 2 /* After */); } - /// Move to the last child that starts before `pos`. - childBefore(pos) { return this.enterChild(-1, pos, -2 /* Before */); } - /// Move the cursor to the child around `pos`. If side is -1 the - /// child may end at that position, when 1 it may start there. This - /// will also enter [overlaid](#common.MountedTree.overlay) - /// [mounted](#common.NodeProp^mounted) trees unless `overlays` is - /// set to false. - enter(pos, side, overlays = true, buffers = true) { - if (!this.buffer) - return this.yield(this._tree.enter(pos, side, overlays && !(this.mode & 1 /* Full */), buffers)); - return buffers ? this.enterChild(1, pos, side) : false; - } - /// Move to the node's parent node, if this isn't the top node. - parent() { - if (!this.buffer) - return this.yieldNode((this.mode & 1 /* Full */) ? this._tree._parent : this._tree.parent); - if (this.stack.length) - return this.yieldBuf(this.stack.pop()); - let parent = (this.mode & 1 /* Full */) ? this.buffer.parent : this.buffer.parent.nextSignificantParent(); - this.buffer = null; - return this.yieldNode(parent); - } - /// @internal - sibling(dir) { - if (!this.buffer) - return !this._tree._parent ? false - : this.yield(this._tree.index < 0 ? null - : this._tree._parent.nextChild(this._tree.index + dir, dir, 0, 4 /* DontCare */, this.mode)); - let { buffer } = this.buffer, d = this.stack.length - 1; - if (dir < 0) { - let parentStart = d < 0 ? 0 : this.stack[d] + 4; - if (this.index != parentStart) - return this.yieldBuf(buffer.findChild(parentStart, this.index, -1, 0, 4 /* DontCare */)); - } - else { - let after = buffer.buffer[this.index + 3]; - if (after < (d < 0 ? buffer.buffer.length : buffer.buffer[this.stack[d] + 3])) - return this.yieldBuf(after); - } - return d < 0 ? this.yield(this.buffer.parent.nextChild(this.buffer.index + dir, dir, 0, 4 /* DontCare */, this.mode)) : false; - } - /// Move to this node's next sibling, if any. - nextSibling() { return this.sibling(1); } - /// Move to this node's previous sibling, if any. - prevSibling() { return this.sibling(-1); } - atLastNode(dir) { - let index, parent, { buffer } = this; - if (buffer) { - if (dir > 0) { - if (this.index < buffer.buffer.buffer.length) - return false; - } - else { - for (let i = 0; i < this.index; i++) - if (buffer.buffer.buffer[i + 3] < this.index) - return false; - } - ({ index, parent } = buffer); - } - else { - ({ index, _parent: parent } = this._tree); - } - for (; parent; { index, _parent: parent } = parent) { - if (index > -1) - for (let i = index + dir, e = dir < 0 ? -1 : parent.node.children.length; i != e; i += dir) { - let child = parent.node.children[i]; - if ((this.mode & 1 /* Full */) || child instanceof TreeBuffer || !child.type.isAnonymous || hasChild(child)) - return false; - } - } - return true; - } - move(dir, enter) { - if (enter && this.enterChild(dir, 0, 4 /* DontCare */)) - return true; - for (;;) { - if (this.sibling(dir)) - return true; - if (this.atLastNode(dir) || !this.parent()) - return false; - } - } - /// Move to the next node in a - /// [pre-order](https://en.wikipedia.org/wiki/Tree_traversal#Pre-order_(NLR)) - /// traversal, going from a node to its first child or, if the - /// current node is empty or `enter` is false, its next sibling or - /// the next sibling of the first parent node that has one. - next(enter = true) { return this.move(1, enter); } - /// Move to the next node in a last-to-first pre-order traveral. A - /// node is followed by its last child or, if it has none, its - /// previous sibling or the previous sibling of the first parent - /// node that has one. - prev(enter = true) { return this.move(-1, enter); } - /// Move the cursor to the innermost node that covers `pos`. If - /// `side` is -1, it will enter nodes that end at `pos`. If it is 1, - /// it will enter nodes that start at `pos`. - moveTo(pos, side = 0) { - // Move up to a node that actually holds the position, if possible - while (this.from == this.to || - (side < 1 ? this.from >= pos : this.from > pos) || - (side > -1 ? this.to <= pos : this.to < pos)) - if (!this.parent()) - break; - // Then scan down into child nodes as far as possible - while (this.enterChild(1, pos, side)) { } - return this; - } - /// Get a [syntax node](#common.SyntaxNode) at the cursor's current - /// position. - get node() { - if (!this.buffer) - return this._tree; - let cache = this.bufferNode, result = null, depth = 0; - if (cache && cache.context == this.buffer) { - scan: for (let index = this.index, d = this.stack.length; d >= 0;) { - for (let c = cache; c; c = c._parent) - if (c.index == index) { - if (index == this.index) - return c; - result = c; - depth = d + 1; - break scan; - } - index = this.stack[--d]; - } - } - for (let i = depth; i < this.stack.length; i++) - result = new BufferNode(this.buffer, result, this.stack[i]); - return this.bufferNode = new BufferNode(this.buffer, result, this.index); - } - /// Get the [tree](#common.Tree) that represents the current node, if - /// any. Will return null when the node is in a [tree - /// buffer](#common.TreeBuffer). - get tree() { - return this.buffer ? null : this._tree.node; - } - } - function hasChild(tree) { - return tree.children.some(ch => ch instanceof TreeBuffer || !ch.type.isAnonymous || hasChild(ch)); - } - function buildTree(data) { - var _a; - let { buffer, nodeSet, maxBufferLength = DefaultBufferLength, reused = [], minRepeatType = nodeSet.types.length } = data; - let cursor = Array.isArray(buffer) ? new FlatBufferCursor(buffer, buffer.length) : buffer; - let types = nodeSet.types; - let contextHash = 0, lookAhead = 0; - function takeNode(parentStart, minPos, children, positions, inRepeat) { - let { id, start, end, size } = cursor; - let lookAheadAtStart = lookAhead; - while (size < 0) { - cursor.next(); - if (size == -1 /* Reuse */) { - let node = reused[id]; - children.push(node); - positions.push(start - parentStart); - return; - } - else if (size == -3 /* ContextChange */) { // Context change - contextHash = id; - return; - } - else if (size == -4 /* LookAhead */) { - lookAhead = id; - return; - } - else { - throw new RangeError(`Unrecognized record size: ${size}`); - } - } - let type = types[id], node, buffer; - let startPos = start - parentStart; - if (end - start <= maxBufferLength && (buffer = findBufferSize(cursor.pos - minPos, inRepeat))) { - // Small enough for a buffer, and no reused nodes inside - let data = new Uint16Array(buffer.size - buffer.skip); - let endPos = cursor.pos - buffer.size, index = data.length; - while (cursor.pos > endPos) - index = copyToBuffer(buffer.start, data, index); - node = new TreeBuffer(data, end - buffer.start, nodeSet); - startPos = buffer.start - parentStart; - } - else { // Make it a node - let endPos = cursor.pos - size; - cursor.next(); - let localChildren = [], localPositions = []; - let localInRepeat = id >= minRepeatType ? id : -1; - let lastGroup = 0, lastEnd = end; - while (cursor.pos > endPos) { - if (localInRepeat >= 0 && cursor.id == localInRepeat && cursor.size >= 0) { - if (cursor.end <= lastEnd - maxBufferLength) { - makeRepeatLeaf(localChildren, localPositions, start, lastGroup, cursor.end, lastEnd, localInRepeat, lookAheadAtStart); - lastGroup = localChildren.length; - lastEnd = cursor.end; - } - cursor.next(); - } - else { - takeNode(start, endPos, localChildren, localPositions, localInRepeat); - } - } - if (localInRepeat >= 0 && lastGroup > 0 && lastGroup < localChildren.length) - makeRepeatLeaf(localChildren, localPositions, start, lastGroup, start, lastEnd, localInRepeat, lookAheadAtStart); - localChildren.reverse(); - localPositions.reverse(); - if (localInRepeat > -1 && lastGroup > 0) { - let make = makeBalanced(type); - node = balanceRange(type, localChildren, localPositions, 0, localChildren.length, 0, end - start, make, make); - } - else { - node = makeTree(type, localChildren, localPositions, end - start, lookAheadAtStart - end); - } - } - children.push(node); - positions.push(startPos); - } - function makeBalanced(type) { - return (children, positions, length) => { - let lookAhead = 0, lastI = children.length - 1, last, lookAheadProp; - if (lastI >= 0 && (last = children[lastI]) instanceof Tree) { - if (!lastI && last.type == type && last.length == length) - return last; - if (lookAheadProp = last.prop(NodeProp.lookAhead)) - lookAhead = positions[lastI] + last.length + lookAheadProp; - } - return makeTree(type, children, positions, length, lookAhead); - }; - } - function makeRepeatLeaf(children, positions, base, i, from, to, type, lookAhead) { - let localChildren = [], localPositions = []; - while (children.length > i) { - localChildren.push(children.pop()); - localPositions.push(positions.pop() + base - from); - } - children.push(makeTree(nodeSet.types[type], localChildren, localPositions, to - from, lookAhead - to)); - positions.push(from - base); - } - function makeTree(type, children, positions, length, lookAhead = 0, props) { - if (contextHash) { - let pair = [NodeProp.contextHash, contextHash]; - props = props ? [pair].concat(props) : [pair]; - } - if (lookAhead > 25) { - let pair = [NodeProp.lookAhead, lookAhead]; - props = props ? [pair].concat(props) : [pair]; - } - return new Tree(type, children, positions, length, props); - } - function findBufferSize(maxSize, inRepeat) { - // Scan through the buffer to find previous siblings that fit - // together in a TreeBuffer, and don't contain any reused nodes - // (which can't be stored in a buffer). - // If `inRepeat` is > -1, ignore node boundaries of that type for - // nesting, but make sure the end falls either at the start - // (`maxSize`) or before such a node. - let fork = cursor.fork(); - let size = 0, start = 0, skip = 0, minStart = fork.end - maxBufferLength; - let result = { size: 0, start: 0, skip: 0 }; - scan: for (let minPos = fork.pos - maxSize; fork.pos > minPos;) { - let nodeSize = fork.size; - // Pretend nested repeat nodes of the same type don't exist - if (fork.id == inRepeat && nodeSize >= 0) { - // Except that we store the current state as a valid return - // value. - result.size = size; - result.start = start; - result.skip = skip; - skip += 4; - size += 4; - fork.next(); - continue; - } - let startPos = fork.pos - nodeSize; - if (nodeSize < 0 || startPos < minPos || fork.start < minStart) - break; - let localSkipped = fork.id >= minRepeatType ? 4 : 0; - let nodeStart = fork.start; - fork.next(); - while (fork.pos > startPos) { - if (fork.size < 0) { - if (fork.size == -3 /* ContextChange */) - localSkipped += 4; - else - break scan; - } - else if (fork.id >= minRepeatType) { - localSkipped += 4; - } - fork.next(); - } - start = nodeStart; - size += nodeSize; - skip += localSkipped; - } - if (inRepeat < 0 || size == maxSize) { - result.size = size; - result.start = start; - result.skip = skip; - } - return result.size > 4 ? result : undefined; - } - function copyToBuffer(bufferStart, buffer, index) { - let { id, start, end, size } = cursor; - cursor.next(); - if (size >= 0 && id < minRepeatType) { - let startIndex = index; - if (size > 4) { - let endPos = cursor.pos - (size - 4); - while (cursor.pos > endPos) - index = copyToBuffer(bufferStart, buffer, index); - } - buffer[--index] = startIndex; - buffer[--index] = end - bufferStart; - buffer[--index] = start - bufferStart; - buffer[--index] = id; - } - else if (size == -3 /* ContextChange */) { - contextHash = id; - } - else if (size == -4 /* LookAhead */) { - lookAhead = id; - } - return index; - } - let children = [], positions = []; - while (cursor.pos > 0) - takeNode(data.start || 0, data.bufferStart || 0, children, positions, -1); - let length = (_a = data.length) !== null && _a !== void 0 ? _a : (children.length ? positions[0] + children[0].length : 0); - return new Tree(types[data.topID], children.reverse(), positions.reverse(), length); - } - const nodeSizeCache = new WeakMap; - function nodeSize(balanceType, node) { - if (!balanceType.isAnonymous || node instanceof TreeBuffer || node.type != balanceType) - return 1; - let size = nodeSizeCache.get(node); - if (size == null) { - size = 1; - for (let child of node.children) { - if (child.type != balanceType || !(child instanceof Tree)) { - size = 1; - break; - } - size += nodeSize(balanceType, child); - } - nodeSizeCache.set(node, size); - } - return size; - } - function balanceRange( - // The type the balanced tree's inner nodes. - balanceType, - // The direct children and their positions - children, positions, - // The index range in children/positions to use - from, to, - // The start position of the nodes, relative to their parent. - start, - // Length of the outer node - length, - // Function to build the top node of the balanced tree - mkTop, - // Function to build internal nodes for the balanced tree - mkTree) { - let total = 0; - for (let i = from; i < to; i++) - total += nodeSize(balanceType, children[i]); - let maxChild = Math.ceil((total * 1.5) / 8 /* BranchFactor */); - let localChildren = [], localPositions = []; - function divide(children, positions, from, to, offset) { - for (let i = from; i < to;) { - let groupFrom = i, groupStart = positions[i], groupSize = nodeSize(balanceType, children[i]); - i++; - for (; i < to; i++) { - let nextSize = nodeSize(balanceType, children[i]); - if (groupSize + nextSize >= maxChild) - break; - groupSize += nextSize; - } - if (i == groupFrom + 1) { - if (groupSize > maxChild) { - let only = children[groupFrom]; // Only trees can have a size > 1 - divide(only.children, only.positions, 0, only.children.length, positions[groupFrom] + offset); - continue; - } - localChildren.push(children[groupFrom]); - } - else { - let length = positions[i - 1] + children[i - 1].length - groupStart; - localChildren.push(balanceRange(balanceType, children, positions, groupFrom, i, groupStart, length, null, mkTree)); - } - localPositions.push(groupStart + offset - start); - } - } - divide(children, positions, from, to, 0); - return (mkTop || mkTree)(localChildren, localPositions, length); - } - - /// Tree fragments are used during [incremental - /// parsing](#common.Parser.startParse) to track parts of old trees - /// that can be reused in a new parse. An array of fragments is used - /// to track regions of an old tree whose nodes might be reused in new - /// parses. Use the static - /// [`applyChanges`](#common.TreeFragment^applyChanges) method to - /// update fragments for document changes. - class TreeFragment { - /// Construct a tree fragment. - constructor( - /// The start of the unchanged range pointed to by this fragment. - /// This refers to an offset in the _updated_ document (as opposed - /// to the original tree). - from, - /// The end of the unchanged range. - to, - /// The tree that this fragment is based on. - tree, - /// The offset between the fragment's tree and the document that - /// this fragment can be used against. Add this when going from - /// document to tree positions, subtract it to go from tree to - /// document positions. - offset, openStart = false, openEnd = false) { - this.from = from; - this.to = to; - this.tree = tree; - this.offset = offset; - this.open = (openStart ? 1 /* Start */ : 0) | (openEnd ? 2 /* End */ : 0); - } - /// Whether the start of the fragment represents the start of a - /// parse, or the end of a change. (In the second case, it may not - /// be safe to reuse some nodes at the start, depending on the - /// parsing algorithm.) - get openStart() { return (this.open & 1 /* Start */) > 0; } - /// Whether the end of the fragment represents the end of a - /// full-document parse, or the start of a change. - get openEnd() { return (this.open & 2 /* End */) > 0; } - /// Create a set of fragments from a freshly parsed tree, or update - /// an existing set of fragments by replacing the ones that overlap - /// with a tree with content from the new tree. When `partial` is - /// true, the parse is treated as incomplete, and the resulting - /// fragment has [`openEnd`](#common.TreeFragment.openEnd) set to - /// true. - static addTree(tree, fragments = [], partial = false) { - let result = [new TreeFragment(0, tree.length, tree, 0, false, partial)]; - for (let f of fragments) - if (f.to > tree.length) - result.push(f); - return result; - } - /// Apply a set of edits to an array of fragments, removing or - /// splitting fragments as necessary to remove edited ranges, and - /// adjusting offsets for fragments that moved. - static applyChanges(fragments, changes, minGap = 128) { - if (!changes.length) - return fragments; - let result = []; - let fI = 1, nextF = fragments.length ? fragments[0] : null; - for (let cI = 0, pos = 0, off = 0;; cI++) { - let nextC = cI < changes.length ? changes[cI] : null; - let nextPos = nextC ? nextC.fromA : 1e9; - if (nextPos - pos >= minGap) - while (nextF && nextF.from < nextPos) { - let cut = nextF; - if (pos >= cut.from || nextPos <= cut.to || off) { - let fFrom = Math.max(cut.from, pos) - off, fTo = Math.min(cut.to, nextPos) - off; - cut = fFrom >= fTo ? null : new TreeFragment(fFrom, fTo, cut.tree, cut.offset + off, cI > 0, !!nextC); - } - if (cut) - result.push(cut); - if (nextF.to > nextPos) - break; - nextF = fI < fragments.length ? fragments[fI++] : null; - } - if (!nextC) - break; - pos = nextC.toA; - off = nextC.toA - nextC.toB; - } - return result; - } - } - /// A superclass that parsers should extend. - class Parser { - /// Start a parse, returning a [partial parse](#common.PartialParse) - /// object. [`fragments`](#common.TreeFragment) can be passed in to - /// make the parse incremental. - /// - /// By default, the entire input is parsed. You can pass `ranges`, - /// which should be a sorted array of non-empty, non-overlapping - /// ranges, to parse only those ranges. The tree returned in that - /// case will start at `ranges[0].from`. - startParse(input, fragments, ranges) { - if (typeof input == "string") - input = new StringInput(input); - ranges = !ranges ? [new Range(0, input.length)] : ranges.length ? ranges.map(r => new Range(r.from, r.to)) : [new Range(0, 0)]; - return this.createParse(input, fragments || [], ranges); - } - /// Run a full parse, returning the resulting tree. - parse(input, fragments, ranges) { - let parse = this.startParse(input, fragments, ranges); - for (;;) { - let done = parse.advance(); - if (done) - return done; - } - } - } - class StringInput { - constructor(string) { - this.string = string; - } - get length() { return this.string.length; } - chunk(from) { return this.string.slice(from); } - get lineChunks() { return false; } - read(from, to) { return this.string.slice(from, to); } - } - new NodeProp({ perNode: true }); - - var _a; - /** - Node prop stored in a grammar's top syntax node to provide the - facet that stores language data for that language. - */ - const languageDataProp = /*@__PURE__*/new NodeProp(); - /** - Helper function to define a facet (to be added to the top syntax - node(s) for a language via - [`languageDataProp`](https://codemirror.net/6/docs/ref/#language.languageDataProp)), that will be - used to associate language data with the language. You - probably only need this when subclassing - [`Language`](https://codemirror.net/6/docs/ref/#language.Language). - */ - function defineLanguageFacet(baseData) { - return Facet.define({ - combine: baseData ? values => values.concat(baseData) : undefined - }); - } - /** - A language object manages parsing and per-language - [metadata](https://codemirror.net/6/docs/ref/#state.EditorState.languageDataAt). Parse data is - managed as a [Lezer](https://lezer.codemirror.net) tree. You'll - want to subclass this class for custom parsers, or use the - [`LRLanguage`](https://codemirror.net/6/docs/ref/#language.LRLanguage) or - [`StreamLanguage`](https://codemirror.net/6/docs/ref/#stream-parser.StreamLanguage) abstractions for - [Lezer](https://lezer.codemirror.net/) or stream parsers. - */ - class Language { - /** - Construct a language object. You usually don't need to invoke - this directly. But when you do, make sure you use - [`defineLanguageFacet`](https://codemirror.net/6/docs/ref/#language.defineLanguageFacet) to create - the first argument. - */ - constructor( - /** - The [language data](https://codemirror.net/6/docs/ref/#state.EditorState.languageDataAt) data - facet used for this language. - */ - data, parser, - /** - The node type of the top node of trees produced by this parser. - */ - topNode, extraExtensions = []) { - this.data = data; - this.topNode = topNode; - // Kludge to define EditorState.tree as a debugging helper, - // without the EditorState package actually knowing about - // languages and lezer trees. - if (!EditorState.prototype.hasOwnProperty("tree")) - Object.defineProperty(EditorState.prototype, "tree", { get() { return syntaxTree(this); } }); - this.parser = parser; - this.extension = [ - language.of(this), - EditorState.languageData.of((state, pos, side) => state.facet(languageDataFacetAt(state, pos, side))) - ].concat(extraExtensions); - } - /** - Query whether this language is active at the given position. - */ - isActiveAt(state, pos, side = -1) { - return languageDataFacetAt(state, pos, side) == this.data; - } - /** - Find the document regions that were parsed using this language. - The returned regions will _include_ any nested languages rooted - in this language, when those exist. - */ - findRegions(state) { - let lang = state.facet(language); - if ((lang === null || lang === void 0 ? void 0 : lang.data) == this.data) - return [{ from: 0, to: state.doc.length }]; - if (!lang || !lang.allowsNesting) - return []; - let result = []; - let explore = (tree, from) => { - if (tree.prop(languageDataProp) == this.data) { - result.push({ from, to: from + tree.length }); - return; - } - let mount = tree.prop(NodeProp.mounted); - if (mount) { - if (mount.tree.prop(languageDataProp) == this.data) { - if (mount.overlay) - for (let r of mount.overlay) - result.push({ from: r.from + from, to: r.to + from }); - else - result.push({ from: from, to: from + tree.length }); - return; - } - else if (mount.overlay) { - let size = result.length; - explore(mount.tree, mount.overlay[0].from + from); - if (result.length > size) - return; - } - } - for (let i = 0; i < tree.children.length; i++) { - let ch = tree.children[i]; - if (ch instanceof Tree) - explore(ch, tree.positions[i] + from); - } - }; - explore(syntaxTree(state), 0); - return result; - } - /** - Indicates whether this language allows nested languages. The - default implementation returns true. - */ - get allowsNesting() { return true; } - } - /** - @internal - */ - Language.setState = /*@__PURE__*/StateEffect.define(); - function languageDataFacetAt(state, pos, side) { - let topLang = state.facet(language); - if (!topLang) - return null; - let facet = topLang.data; - if (topLang.allowsNesting) { - for (let node = syntaxTree(state).topNode; node; node = node.enter(pos, side, true, false)) - facet = node.type.prop(languageDataProp) || facet; - } - return facet; - } - /** - A subclass of [`Language`](https://codemirror.net/6/docs/ref/#language.Language) for use with Lezer - [LR parsers](https://lezer.codemirror.net/docs/ref#lr.LRParser) - parsers. - */ - class LRLanguage extends Language { - constructor(data, parser) { - super(data, parser, parser.topNode); - this.parser = parser; - } - /** - Define a language from a parser. - */ - static define(spec) { - let data = defineLanguageFacet(spec.languageData); - return new LRLanguage(data, spec.parser.configure({ - props: [languageDataProp.add(type => type.isTop ? data : undefined)] - })); - } - /** - Create a new instance of this language with a reconfigured - version of its parser. - */ - configure(options) { - return new LRLanguage(this.data, this.parser.configure(options)); - } - get allowsNesting() { return this.parser.wrappers.length > 0; } // FIXME - } - /** - Get the syntax tree for a state, which is the current (possibly - incomplete) parse tree of active [language](https://codemirror.net/6/docs/ref/#language.Language), - or the empty tree if there is no language available. - */ - function syntaxTree(state) { - let field = state.field(Language.state, false); - return field ? field.tree : Tree.empty; - } - // Lezer-style Input object for a Text document. - class DocInput { - constructor(doc, length = doc.length) { - this.doc = doc; - this.length = length; - this.cursorPos = 0; - this.string = ""; - this.cursor = doc.iter(); - } - syncTo(pos) { - this.string = this.cursor.next(pos - this.cursorPos).value; - this.cursorPos = pos + this.string.length; - return this.cursorPos - this.string.length; - } - chunk(pos) { - this.syncTo(pos); - return this.string; - } - get lineChunks() { return true; } - read(from, to) { - let stringStart = this.cursorPos - this.string.length; - if (from < stringStart || to >= this.cursorPos) - return this.doc.sliceString(from, to); - else - return this.string.slice(from - stringStart, to - stringStart); - } - } - let currentContext = null; - /** - A parse context provided to parsers working on the editor content. - */ - class ParseContext { - /** - @internal - */ - constructor(parser, - /** - The current editor state. - */ - state, - /** - Tree fragments that can be reused by incremental re-parses. - */ - fragments = [], - /** - @internal - */ - tree, treeLen, - /** - The current editor viewport (or some overapproximation - thereof). Intended to be used for opportunistically avoiding - work (in which case - [`skipUntilInView`](https://codemirror.net/6/docs/ref/#language.ParseContext.skipUntilInView) - should be called to make sure the parser is restarted when the - skipped region becomes visible). - */ - viewport, - /** - @internal - */ - skipped, - /** - This is where skipping parsers can register a promise that, - when resolved, will schedule a new parse. It is cleared when - the parse worker picks up the promise. @internal - */ - scheduleOn) { - this.parser = parser; - this.state = state; - this.fragments = fragments; - this.tree = tree; - this.treeLen = treeLen; - this.viewport = viewport; - this.skipped = skipped; - this.scheduleOn = scheduleOn; - this.parse = null; - /** - @internal - */ - this.tempSkipped = []; - } - startParse() { - return this.parser.startParse(new DocInput(this.state.doc), this.fragments); - } - /** - @internal - */ - work(until, upto) { - if (upto != null && upto >= this.state.doc.length) - upto = undefined; - if (this.tree != Tree.empty && this.isDone(upto !== null && upto !== void 0 ? upto : this.state.doc.length)) { - this.takeTree(); - return true; - } - return this.withContext(() => { - var _a; - if (typeof until == "number") { - let endTime = Date.now() + until; - until = () => Date.now() > endTime; - } - if (!this.parse) - this.parse = this.startParse(); - if (upto != null && (this.parse.stoppedAt == null || this.parse.stoppedAt > upto) && - upto < this.state.doc.length) - this.parse.stopAt(upto); - for (;;) { - let done = this.parse.advance(); - if (done) { - this.fragments = this.withoutTempSkipped(TreeFragment.addTree(done, this.fragments, this.parse.stoppedAt != null)); - this.treeLen = (_a = this.parse.stoppedAt) !== null && _a !== void 0 ? _a : this.state.doc.length; - this.tree = done; - this.parse = null; - if (this.treeLen < (upto !== null && upto !== void 0 ? upto : this.state.doc.length)) - this.parse = this.startParse(); - else - return true; - } - if (until()) - return false; - } - }); - } - /** - @internal - */ - takeTree() { - let pos, tree; - if (this.parse && (pos = this.parse.parsedPos) >= this.treeLen) { - if (this.parse.stoppedAt == null || this.parse.stoppedAt > pos) - this.parse.stopAt(pos); - this.withContext(() => { while (!(tree = this.parse.advance())) { } }); - this.treeLen = pos; - this.tree = tree; - this.fragments = this.withoutTempSkipped(TreeFragment.addTree(this.tree, this.fragments, true)); - this.parse = null; - } - } - withContext(f) { - let prev = currentContext; - currentContext = this; - try { - return f(); - } - finally { - currentContext = prev; - } - } - withoutTempSkipped(fragments) { - for (let r; r = this.tempSkipped.pop();) - fragments = cutFragments(fragments, r.from, r.to); - return fragments; - } - /** - @internal - */ - changes(changes, newState) { - let { fragments, tree, treeLen, viewport, skipped } = this; - this.takeTree(); - if (!changes.empty) { - let ranges = []; - changes.iterChangedRanges((fromA, toA, fromB, toB) => ranges.push({ fromA, toA, fromB, toB })); - fragments = TreeFragment.applyChanges(fragments, ranges); - tree = Tree.empty; - treeLen = 0; - viewport = { from: changes.mapPos(viewport.from, -1), to: changes.mapPos(viewport.to, 1) }; - if (this.skipped.length) { - skipped = []; - for (let r of this.skipped) { - let from = changes.mapPos(r.from, 1), to = changes.mapPos(r.to, -1); - if (from < to) - skipped.push({ from, to }); - } - } - } - return new ParseContext(this.parser, newState, fragments, tree, treeLen, viewport, skipped, this.scheduleOn); - } - /** - @internal - */ - updateViewport(viewport) { - if (this.viewport.from == viewport.from && this.viewport.to == viewport.to) - return false; - this.viewport = viewport; - let startLen = this.skipped.length; - for (let i = 0; i < this.skipped.length; i++) { - let { from, to } = this.skipped[i]; - if (from < viewport.to && to > viewport.from) { - this.fragments = cutFragments(this.fragments, from, to); - this.skipped.splice(i--, 1); - } - } - if (this.skipped.length >= startLen) - return false; - this.reset(); - return true; - } - /** - @internal - */ - reset() { - if (this.parse) { - this.takeTree(); - this.parse = null; - } - } - /** - Notify the parse scheduler that the given region was skipped - because it wasn't in view, and the parse should be restarted - when it comes into view. - */ - skipUntilInView(from, to) { - this.skipped.push({ from, to }); - } - /** - Returns a parser intended to be used as placeholder when - asynchronously loading a nested parser. It'll skip its input and - mark it as not-really-parsed, so that the next update will parse - it again. - - When `until` is given, a reparse will be scheduled when that - promise resolves. - */ - static getSkippingParser(until) { - return new class extends Parser { - createParse(input, fragments, ranges) { - let from = ranges[0].from, to = ranges[ranges.length - 1].to; - let parser = { - parsedPos: from, - advance() { - let cx = currentContext; - if (cx) { - for (let r of ranges) - cx.tempSkipped.push(r); - if (until) - cx.scheduleOn = cx.scheduleOn ? Promise.all([cx.scheduleOn, until]) : until; - } - this.parsedPos = to; - return new Tree(NodeType.none, [], [], to - from); - }, - stoppedAt: null, - stopAt() { } - }; - return parser; - } - }; - } - /** - @internal - */ - isDone(upto) { - upto = Math.min(upto, this.state.doc.length); - let frags = this.fragments; - return this.treeLen >= upto && frags.length && frags[0].from == 0 && frags[0].to >= upto; - } - /** - Get the context for the current parse, or `null` if no editor - parse is in progress. - */ - static get() { return currentContext; } - } - function cutFragments(fragments, from, to) { - return TreeFragment.applyChanges(fragments, [{ fromA: from, toA: to, fromB: from, toB: to }]); - } - class LanguageState { - constructor( - // A mutable parse state that is used to preserve work done during - // the lifetime of a state when moving to the next state. - context) { - this.context = context; - this.tree = context.tree; - } - apply(tr) { - if (!tr.docChanged && this.tree == this.context.tree) - return this; - let newCx = this.context.changes(tr.changes, tr.state); - // If the previous parse wasn't done, go forward only up to its - // end position or the end of the viewport, to avoid slowing down - // state updates with parse work beyond the viewport. - let upto = this.context.treeLen == tr.startState.doc.length ? undefined - : Math.max(tr.changes.mapPos(this.context.treeLen), newCx.viewport.to); - if (!newCx.work(20 /* Apply */, upto)) - newCx.takeTree(); - return new LanguageState(newCx); - } - static init(state) { - let vpTo = Math.min(3000 /* InitViewport */, state.doc.length); - let parseState = new ParseContext(state.facet(language).parser, state, [], Tree.empty, 0, { from: 0, to: vpTo }, [], null); - if (!parseState.work(20 /* Apply */, vpTo)) - parseState.takeTree(); - return new LanguageState(parseState); - } - } - Language.state = /*@__PURE__*/StateField.define({ - create: LanguageState.init, - update(value, tr) { - for (let e of tr.effects) - if (e.is(Language.setState)) - return e.value; - if (tr.startState.facet(language) != tr.state.facet(language)) - return LanguageState.init(tr.state); - return value.apply(tr); - } - }); - let requestIdle = (callback) => { - let timeout = setTimeout(() => callback(), 500 /* MaxPause */); - return () => clearTimeout(timeout); - }; - if (typeof requestIdleCallback != "undefined") - requestIdle = (callback) => { - let idle = -1, timeout = setTimeout(() => { - idle = requestIdleCallback(callback, { timeout: 500 /* MaxPause */ - 100 /* MinPause */ }); - }, 100 /* MinPause */); - return () => idle < 0 ? clearTimeout(timeout) : cancelIdleCallback(idle); - }; - const isInputPending = typeof navigator != "undefined" && ((_a = navigator.scheduling) === null || _a === void 0 ? void 0 : _a.isInputPending) - ? () => navigator.scheduling.isInputPending() : null; - const parseWorker = /*@__PURE__*/ViewPlugin.fromClass(class ParseWorker { - constructor(view) { - this.view = view; - this.working = null; - this.workScheduled = 0; - // End of the current time chunk - this.chunkEnd = -1; - // Milliseconds of budget left for this chunk - this.chunkBudget = -1; - this.work = this.work.bind(this); - this.scheduleWork(); - } - update(update) { - let cx = this.view.state.field(Language.state).context; - if (cx.updateViewport(update.view.viewport) || this.view.viewport.to > cx.treeLen) - this.scheduleWork(); - if (update.docChanged) { - if (this.view.hasFocus) - this.chunkBudget += 50 /* ChangeBonus */; - this.scheduleWork(); - } - this.checkAsyncSchedule(cx); - } - scheduleWork() { - if (this.working) - return; - let { state } = this.view, field = state.field(Language.state); - if (field.tree != field.context.tree || !field.context.isDone(state.doc.length)) - this.working = requestIdle(this.work); - } - work(deadline) { - this.working = null; - let now = Date.now(); - if (this.chunkEnd < now && (this.chunkEnd < 0 || this.view.hasFocus)) { // Start a new chunk - this.chunkEnd = now + 30000 /* ChunkTime */; - this.chunkBudget = 3000 /* ChunkBudget */; - } - if (this.chunkBudget <= 0) - return; // No more budget - let { state, viewport: { to: vpTo } } = this.view, field = state.field(Language.state); - if (field.tree == field.context.tree && field.context.isDone(vpTo + 100000 /* MaxParseAhead */)) - return; - let endTime = Date.now() + Math.min(this.chunkBudget, 100 /* Slice */, deadline && !isInputPending ? Math.max(25 /* MinSlice */, deadline.timeRemaining() - 5) : 1e9); - let viewportFirst = field.context.treeLen < vpTo && state.doc.length > vpTo + 1000; - let done = field.context.work(() => { - return isInputPending && isInputPending() || Date.now() > endTime; - }, vpTo + (viewportFirst ? 0 : 100000 /* MaxParseAhead */)); - this.chunkBudget -= Date.now() - now; - if (done || this.chunkBudget <= 0) { - field.context.takeTree(); - this.view.dispatch({ effects: Language.setState.of(new LanguageState(field.context)) }); - } - if (this.chunkBudget > 0 && !(done && !viewportFirst)) - this.scheduleWork(); - this.checkAsyncSchedule(field.context); - } - checkAsyncSchedule(cx) { - if (cx.scheduleOn) { - this.workScheduled++; - cx.scheduleOn - .then(() => this.scheduleWork()) - .catch(err => logException(this.view.state, err)) - .then(() => this.workScheduled--); - cx.scheduleOn = null; - } - } - destroy() { - if (this.working) - this.working(); - } - isWorking() { - return !!(this.working || this.workScheduled > 0); - } - }, { - eventHandlers: { focus() { this.scheduleWork(); } } - }); - /** - The facet used to associate a language with an editor state. - */ - const language = /*@__PURE__*/Facet.define({ - combine(languages) { return languages.length ? languages[0] : null; }, - enables: [Language.state, parseWorker] - }); - /** - This class bundles a [language object](https://codemirror.net/6/docs/ref/#language.Language) with an - optional set of supporting extensions. Language packages are - encouraged to export a function that optionally takes a - configuration object and returns a `LanguageSupport` instance, as - the main way for client code to use the package. - */ - class LanguageSupport { - /** - Create a support object. - */ - constructor( - /** - The language object. - */ - language, - /** - An optional set of supporting extensions. When nesting a - language in another language, the outer language is encouraged - to include the supporting extensions for its inner languages - in its own set of support extensions. - */ - support = []) { - this.language = language; - this.support = support; - this.extension = [language, support]; - } - } - - /** - Facet that defines a way to provide a function that computes the - appropriate indentation depth at the start of a given line, or - `null` to indicate no appropriate indentation could be determined. - */ - const indentService = /*@__PURE__*/Facet.define(); - /** - Facet for overriding the unit by which indentation happens. - Should be a string consisting either entirely of spaces or - entirely of tabs. When not set, this defaults to 2 spaces. - */ - const indentUnit = /*@__PURE__*/Facet.define({ - combine: values => { - if (!values.length) - return " "; - if (!/^(?: +|\t+)$/.test(values[0])) - throw new Error("Invalid indent unit: " + JSON.stringify(values[0])); - return values[0]; - } - }); - /** - Return the _column width_ of an indent unit in the state. - Determined by the [`indentUnit`](https://codemirror.net/6/docs/ref/#language.indentUnit) - facet, and [`tabSize`](https://codemirror.net/6/docs/ref/#state.EditorState^tabSize) when that - contains tabs. - */ - function getIndentUnit(state) { - let unit = state.facet(indentUnit); - return unit.charCodeAt(0) == 9 ? state.tabSize * unit.length : unit.length; - } - /** - Create an indentation string that covers columns 0 to `cols`. - Will use tabs for as much of the columns as possible when the - [`indentUnit`](https://codemirror.net/6/docs/ref/#language.indentUnit) facet contains - tabs. - */ - function indentString(state, cols) { - let result = "", ts = state.tabSize; - if (state.facet(indentUnit).charCodeAt(0) == 9) - while (cols >= ts) { - result += "\t"; - cols -= ts; - } - for (let i = 0; i < cols; i++) - result += " "; - return result; - } - /** - Get the indentation at the given position. Will first consult any - [indent services](https://codemirror.net/6/docs/ref/#language.indentService) that are registered, - and if none of those return an indentation, this will check the - syntax tree for the [indent node prop](https://codemirror.net/6/docs/ref/#language.indentNodeProp) - and use that if found. Returns a number when an indentation could - be determined, and null otherwise. - */ - function getIndentation(context, pos) { - if (context instanceof EditorState) - context = new IndentContext(context); - for (let service of context.state.facet(indentService)) { - let result = service(context, pos); - if (result != null) - return result; - } - let tree = syntaxTree(context.state); - return tree ? syntaxIndentation(context, tree, pos) : null; - } - /** - Indentation contexts are used when calling [indentation - services](https://codemirror.net/6/docs/ref/#language.indentService). They provide helper utilities - useful in indentation logic, and can selectively override the - indentation reported for some lines. - */ - class IndentContext { - /** - Create an indent context. - */ - constructor( - /** - The editor state. - */ - state, - /** - @internal - */ - options = {}) { - this.state = state; - this.options = options; - this.unit = getIndentUnit(state); - } - /** - Get a description of the line at the given position, taking - [simulated line - breaks](https://codemirror.net/6/docs/ref/#language.IndentContext.constructor^options.simulateBreak) - into account. If there is such a break at `pos`, the `bias` - argument determines whether the part of the line line before or - after the break is used. - */ - lineAt(pos, bias = 1) { - let line = this.state.doc.lineAt(pos); - let { simulateBreak, simulateDoubleBreak } = this.options; - if (simulateBreak != null && simulateBreak >= line.from && simulateBreak <= line.to) { - if (simulateDoubleBreak && simulateBreak == pos) - return { text: "", from: pos }; - else if (bias < 0 ? simulateBreak < pos : simulateBreak <= pos) - return { text: line.text.slice(simulateBreak - line.from), from: simulateBreak }; - else - return { text: line.text.slice(0, simulateBreak - line.from), from: line.from }; - } - return line; - } - /** - Get the text directly after `pos`, either the entire line - or the next 100 characters, whichever is shorter. - */ - textAfterPos(pos, bias = 1) { - if (this.options.simulateDoubleBreak && pos == this.options.simulateBreak) - return ""; - let { text, from } = this.lineAt(pos, bias); - return text.slice(pos - from, Math.min(text.length, pos + 100 - from)); - } - /** - Find the column for the given position. - */ - column(pos, bias = 1) { - let { text, from } = this.lineAt(pos, bias); - let result = this.countColumn(text, pos - from); - let override = this.options.overrideIndentation ? this.options.overrideIndentation(from) : -1; - if (override > -1) - result += override - this.countColumn(text, text.search(/\S|$/)); - return result; - } - /** - Find the column position (taking tabs into account) of the given - position in the given string. - */ - countColumn(line, pos = line.length) { - return countColumn(line, this.state.tabSize, pos); - } - /** - Find the indentation column of the line at the given point. - */ - lineIndent(pos, bias = 1) { - let { text, from } = this.lineAt(pos, bias); - let override = this.options.overrideIndentation; - if (override) { - let overriden = override(from); - if (overriden > -1) - return overriden; - } - return this.countColumn(text, text.search(/\S|$/)); - } - /** - Returns the [simulated line - break](https://codemirror.net/6/docs/ref/#language.IndentContext.constructor^options.simulateBreak) - for this context, if any. - */ - get simulatedBreak() { - return this.options.simulateBreak || null; - } - } - /** - A syntax tree node prop used to associate indentation strategies - with node types. Such a strategy is a function from an indentation - context to a column number or null, where null indicates that no - definitive indentation can be determined. - */ - const indentNodeProp = /*@__PURE__*/new NodeProp(); - // Compute the indentation for a given position from the syntax tree. - function syntaxIndentation(cx, ast, pos) { - return indentFrom(ast.resolveInner(pos).enterUnfinishedNodesBefore(pos), pos, cx); - } - function ignoreClosed(cx) { - return cx.pos == cx.options.simulateBreak && cx.options.simulateDoubleBreak; - } - function indentStrategy(tree) { - let strategy = tree.type.prop(indentNodeProp); - if (strategy) - return strategy; - let first = tree.firstChild, close; - if (first && (close = first.type.prop(NodeProp.closedBy))) { - let last = tree.lastChild, closed = last && close.indexOf(last.name) > -1; - return cx => delimitedStrategy(cx, true, 1, undefined, closed && !ignoreClosed(cx) ? last.from : undefined); - } - return tree.parent == null ? topIndent$1 : null; - } - function indentFrom(node, pos, base) { - for (; node; node = node.parent) { - let strategy = indentStrategy(node); - if (strategy) - return strategy(new TreeIndentContext(base, pos, node)); - } - return null; - } - function topIndent$1() { return 0; } - /** - Objects of this type provide context information and helper - methods to indentation functions. - */ - class TreeIndentContext extends IndentContext { - /** - @internal - */ - constructor(base, - /** - The position at which indentation is being computed. - */ - pos, - /** - The syntax tree node to which the indentation strategy - applies. - */ - node) { - super(base.state, base.options); - this.base = base; - this.pos = pos; - this.node = node; - } - /** - Get the text directly after `this.pos`, either the entire line - or the next 100 characters, whichever is shorter. - */ - get textAfter() { - return this.textAfterPos(this.pos); - } - /** - Get the indentation at the reference line for `this.node`, which - is the line on which it starts, unless there is a node that is - _not_ a parent of this node covering the start of that line. If - so, the line at the start of that node is tried, again skipping - on if it is covered by another such node. - */ - get baseIndent() { - let line = this.state.doc.lineAt(this.node.from); - // Skip line starts that are covered by a sibling (or cousin, etc) - for (;;) { - let atBreak = this.node.resolve(line.from); - while (atBreak.parent && atBreak.parent.from == atBreak.from) - atBreak = atBreak.parent; - if (isParent(atBreak, this.node)) - break; - line = this.state.doc.lineAt(atBreak.from); - } - return this.lineIndent(line.from); - } - /** - Continue looking for indentations in the node's parent nodes, - and return the result of that. - */ - continue() { - let parent = this.node.parent; - return parent ? indentFrom(parent, this.pos, this.base) : 0; - } - } - function isParent(parent, of) { - for (let cur = of; cur; cur = cur.parent) - if (parent == cur) - return true; - return false; - } - // Check whether a delimited node is aligned (meaning there are - // non-skipped nodes on the same line as the opening delimiter). And - // if so, return the opening token. - function bracketedAligned(context) { - let tree = context.node; - let openToken = tree.childAfter(tree.from), last = tree.lastChild; - if (!openToken) - return null; - let sim = context.options.simulateBreak; - let openLine = context.state.doc.lineAt(openToken.from); - let lineEnd = sim == null || sim <= openLine.from ? openLine.to : Math.min(openLine.to, sim); - for (let pos = openToken.to;;) { - let next = tree.childAfter(pos); - if (!next || next == last) - return null; - if (!next.type.isSkipped) - return next.from < lineEnd ? openToken : null; - pos = next.to; - } - } - /** - An indentation strategy for delimited (usually bracketed) nodes. - Will, by default, indent one unit more than the parent's base - indent unless the line starts with a closing token. When `align` - is true and there are non-skipped nodes on the node's opening - line, the content of the node will be aligned with the end of the - opening node, like this: - - foo(bar, - baz) - */ - function delimitedIndent({ closing, align = true, units = 1 }) { - return (context) => delimitedStrategy(context, align, units, closing); - } - function delimitedStrategy(context, align, units, closing, closedAt) { - let after = context.textAfter, space = after.match(/^\s*/)[0].length; - let closed = closing && after.slice(space, space + closing.length) == closing || closedAt == context.pos + space; - let aligned = align ? bracketedAligned(context) : null; - if (aligned) - return closed ? context.column(aligned.from) : context.column(aligned.to); - return context.baseIndent + (closed ? 0 : context.unit * units); - } - const DontIndentBeyond = 200; - /** - Enables reindentation on input. When a language defines an - `indentOnInput` field in its [language - data](https://codemirror.net/6/docs/ref/#state.EditorState.languageDataAt), which must hold a regular - expression, the line at the cursor will be reindented whenever new - text is typed and the input from the start of the line up to the - cursor matches that regexp. - - To avoid unneccesary reindents, it is recommended to start the - regexp with `^` (usually followed by `\s*`), and end it with `$`. - For example, `/^\s*\}$/` will reindent when a closing brace is - added at the start of a line. - */ - function indentOnInput() { - return EditorState.transactionFilter.of(tr => { - if (!tr.docChanged || !tr.isUserEvent("input.type") && !tr.isUserEvent("input.complete")) - return tr; - let rules = tr.startState.languageDataAt("indentOnInput", tr.startState.selection.main.head); - if (!rules.length) - return tr; - let doc = tr.newDoc, { head } = tr.newSelection.main, line = doc.lineAt(head); - if (head > line.from + DontIndentBeyond) - return tr; - let lineStart = doc.sliceString(line.from, head); - if (!rules.some(r => r.test(lineStart))) - return tr; - let { state } = tr, last = -1, changes = []; - for (let { head } of state.selection.ranges) { - let line = state.doc.lineAt(head); - if (line.from == last) - continue; - last = line.from; - let indent = getIndentation(state, line.from); - if (indent == null) - continue; - let cur = /^\s*/.exec(line.text)[0]; - let norm = indentString(state, indent); - if (cur != norm) - changes.push({ from: line.from, to: line.from + cur.length, insert: norm }); - } - return changes.length ? [tr, { changes, sequential: true }] : tr; - }); - } - - /** - A facet that registers a code folding service. When called with - the extent of a line, such a function should return a foldable - range that starts on that line (but continues beyond it), if one - can be found. - */ - const foldService = /*@__PURE__*/Facet.define(); - /** - This node prop is used to associate folding information with - syntax node types. Given a syntax node, it should check whether - that tree is foldable and return the range that can be collapsed - when it is. - */ - const foldNodeProp = /*@__PURE__*/new NodeProp(); - /** - [Fold](https://codemirror.net/6/docs/ref/#language.foldNodeProp) function that folds everything but - the first and the last child of a syntax node. Useful for nodes - that start and end with delimiters. - */ - function foldInside$1(node) { - let first = node.firstChild, last = node.lastChild; - return first && first.to < last.from ? { from: first.to, to: last.type.isError ? node.to : last.from } : null; - } - function syntaxFolding(state, start, end) { - let tree = syntaxTree(state); - if (tree.length == 0) - return null; - let inner = tree.resolveInner(end); - let found = null; - for (let cur = inner; cur; cur = cur.parent) { - if (cur.to <= end || cur.from > end) - continue; - if (found && cur.from < start) - break; - let prop = cur.type.prop(foldNodeProp); - if (prop && (cur.to < tree.length - 50 || tree.length == state.doc.length || !isUnfinished(cur))) { - let value = prop(cur, state); - if (value && value.from <= end && value.from >= start && value.to > end) - found = value; - } - } - return found; - } - function isUnfinished(node) { - let ch = node.lastChild; - return ch && ch.to == node.to && ch.type.isError; - } - /** - Check whether the given line is foldable. First asks any fold - services registered through - [`foldService`](https://codemirror.net/6/docs/ref/#language.foldService), and if none of them return - a result, tries to query the [fold node - prop](https://codemirror.net/6/docs/ref/#language.foldNodeProp) of syntax nodes that cover the end - of the line. - */ - function foldable(state, lineStart, lineEnd) { - for (let service of state.facet(foldService)) { - let result = service(state, lineStart, lineEnd); - if (result) - return result; - } - return syntaxFolding(state, lineStart, lineEnd); - } - - /** - A gutter marker represents a bit of information attached to a line - in a specific gutter. Your own custom markers have to extend this - class. - */ - class GutterMarker extends RangeValue { - /** - @internal - */ - compare(other) { - return this == other || this.constructor == other.constructor && this.eq(other); - } - /** - Compare this marker to another marker of the same type. - */ - eq(other) { return false; } - /** - Called if the marker has a `toDOM` method and its representation - was removed from a gutter. - */ - destroy(dom) { } - } - GutterMarker.prototype.elementClass = ""; - GutterMarker.prototype.toDOM = undefined; - GutterMarker.prototype.mapMode = MapMode.TrackBefore; - GutterMarker.prototype.startSide = GutterMarker.prototype.endSide = -1; - GutterMarker.prototype.point = true; - /** - Facet used to add a class to all gutter elements for a given line. - Markers given to this facet should _only_ define an - [`elementclass`](https://codemirror.net/6/docs/ref/#gutter.GutterMarker.elementClass), not a - [`toDOM`](https://codemirror.net/6/docs/ref/#gutter.GutterMarker.toDOM) (or the marker will appear - in all gutters for the line). - */ - const gutterLineClass = /*@__PURE__*/Facet.define(); - const defaults$1 = { - class: "", - renderEmptyElements: false, - elementStyle: "", - markers: () => RangeSet.empty, - lineMarker: () => null, - lineMarkerChange: null, - initialSpacer: null, - updateSpacer: null, - domEventHandlers: {} - }; - const activeGutters = /*@__PURE__*/Facet.define(); - /** - Define an editor gutter. The order in which the gutters appear is - determined by their extension priority. - */ - function gutter(config) { - return [gutters(), activeGutters.of(Object.assign(Object.assign({}, defaults$1), config))]; - } - const baseTheme$7 = /*@__PURE__*/EditorView.baseTheme({ - ".cm-gutters": { - display: "flex", - height: "100%", - boxSizing: "border-box", - left: 0, - zIndex: 200 - }, - "&light .cm-gutters": { - backgroundColor: "#f5f5f5", - color: "#999", - 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" - } - }); - const unfixGutters = /*@__PURE__*/Facet.define({ - combine: values => values.some(x => x) - }); - /** - The gutter-drawing plugin is automatically enabled when you add a - gutter, but you can use this function to explicitly configure it. - - Unless `fixed` is explicitly set to `false`, the gutters are - fixed, meaning they don't scroll along with the content - horizontally (except on Internet Explorer, which doesn't support - CSS [`position: - sticky`](https://developer.mozilla.org/en-US/docs/Web/CSS/position#sticky)). - */ - function gutters(config) { - let result = [ - gutterView, - baseTheme$7 - ]; - if (config && config.fixed === false) - result.push(unfixGutters.of(true)); - return result; - } - const gutterView = /*@__PURE__*/ViewPlugin.fromClass(class { - constructor(view) { - this.view = view; - this.prevViewport = view.viewport; - this.dom = document.createElement("div"); - this.dom.className = "cm-gutters"; - this.dom.setAttribute("aria-hidden", "true"); - this.dom.style.minHeight = this.view.contentHeight + "px"; - this.gutters = view.state.facet(activeGutters).map(conf => new SingleGutterView(view, conf)); - for (let gutter of this.gutters) - this.dom.appendChild(gutter.dom); - this.fixed = !view.state.facet(unfixGutters); - if (this.fixed) { - // FIXME IE11 fallback, which doesn't support position: sticky, - // by using position: relative + event handlers that realign the - // gutter (or just force fixed=false on IE11?) - this.dom.style.position = "sticky"; - } - this.syncGutters(false); - view.scrollDOM.insertBefore(this.dom, view.contentDOM); - } - update(update) { - if (this.updateGutters(update)) { - // Detach during sync when the viewport changed significantly - // (such as during scrolling), since for large updates that is - // faster. - let vpA = this.prevViewport, vpB = update.view.viewport; - let vpOverlap = Math.min(vpA.to, vpB.to) - Math.max(vpA.from, vpB.from); - this.syncGutters(vpOverlap < (vpB.to - vpB.from) * 0.8); - } - if (update.geometryChanged) - this.dom.style.minHeight = this.view.contentHeight + "px"; - if (this.view.state.facet(unfixGutters) != !this.fixed) { - this.fixed = !this.fixed; - this.dom.style.position = this.fixed ? "sticky" : ""; - } - this.prevViewport = update.view.viewport; - } - syncGutters(detach) { - let after = this.dom.nextSibling; - if (detach) - this.dom.remove(); - let lineClasses = RangeSet.iter(this.view.state.facet(gutterLineClass), this.view.viewport.from); - let classSet = []; - let contexts = this.gutters.map(gutter => new UpdateContext(gutter, this.view.viewport, -this.view.documentPadding.top)); - for (let line of this.view.viewportLineBlocks) { - let text; - if (Array.isArray(line.type)) { - for (let b of line.type) - if (b.type == BlockType.Text) { - text = b; - break; - } - } - else { - text = line.type == BlockType.Text ? line : undefined; - } - if (!text) - continue; - if (classSet.length) - classSet = []; - advanceCursor(lineClasses, classSet, line.from); - for (let cx of contexts) - cx.line(this.view, text, classSet); - } - for (let cx of contexts) - cx.finish(); - if (detach) - this.view.scrollDOM.insertBefore(this.dom, after); - } - updateGutters(update) { - let prev = update.startState.facet(activeGutters), cur = update.state.facet(activeGutters); - let change = update.docChanged || update.heightChanged || update.viewportChanged || - !RangeSet.eq(update.startState.facet(gutterLineClass), update.state.facet(gutterLineClass), update.view.viewport.from, update.view.viewport.to); - if (prev == cur) { - for (let gutter of this.gutters) - if (gutter.update(update)) - change = true; - } - else { - change = true; - let gutters = []; - for (let conf of cur) { - let known = prev.indexOf(conf); - if (known < 0) { - gutters.push(new SingleGutterView(this.view, conf)); - } - else { - this.gutters[known].update(update); - gutters.push(this.gutters[known]); - } - } - for (let g of this.gutters) { - g.dom.remove(); - if (gutters.indexOf(g) < 0) - g.destroy(); - } - for (let g of gutters) - this.dom.appendChild(g.dom); - this.gutters = gutters; - } - return change; - } - destroy() { - for (let view of this.gutters) - view.destroy(); - this.dom.remove(); - } - }, { - provide: /*@__PURE__*/PluginField.scrollMargins.from(value => { - if (value.gutters.length == 0 || !value.fixed) - return null; - return value.view.textDirection == Direction.LTR ? { left: value.dom.offsetWidth } : { right: value.dom.offsetWidth }; - }) - }); - function asArray(val) { return (Array.isArray(val) ? val : [val]); } - function advanceCursor(cursor, collect, pos) { - while (cursor.value && cursor.from <= pos) { - if (cursor.from == pos) - collect.push(cursor.value); - cursor.next(); - } - } - class UpdateContext { - constructor(gutter, viewport, height) { - this.gutter = gutter; - this.height = height; - this.localMarkers = []; - this.i = 0; - this.cursor = RangeSet.iter(gutter.markers, viewport.from); - } - line(view, line, extraMarkers) { - if (this.localMarkers.length) - this.localMarkers = []; - advanceCursor(this.cursor, this.localMarkers, line.from); - let localMarkers = extraMarkers.length ? this.localMarkers.concat(extraMarkers) : this.localMarkers; - let forLine = this.gutter.config.lineMarker(view, line, localMarkers); - if (forLine) - localMarkers.unshift(forLine); - let gutter = this.gutter; - if (localMarkers.length == 0 && !gutter.config.renderEmptyElements) - return; - let above = line.top - this.height; - if (this.i == gutter.elements.length) { - let newElt = new GutterElement(view, line.height, above, localMarkers); - gutter.elements.push(newElt); - gutter.dom.appendChild(newElt.dom); - } - else { - gutter.elements[this.i].update(view, line.height, above, localMarkers); - } - this.height = line.bottom; - this.i++; - } - finish() { - let gutter = this.gutter; - while (gutter.elements.length > this.i) { - let last = gutter.elements.pop(); - gutter.dom.removeChild(last.dom); - last.destroy(); - } - } - } - class SingleGutterView { - constructor(view, config) { - this.view = view; - this.config = config; - this.elements = []; - this.spacer = null; - this.dom = document.createElement("div"); - this.dom.className = "cm-gutter" + (this.config.class ? " " + this.config.class : ""); - for (let prop in config.domEventHandlers) { - this.dom.addEventListener(prop, (event) => { - let line = view.lineBlockAtHeight(event.clientY - view.documentTop); - if (config.domEventHandlers[prop](view, line, event)) - event.preventDefault(); - }); - } - this.markers = asArray(config.markers(view)); - if (config.initialSpacer) { - this.spacer = new GutterElement(view, 0, 0, [config.initialSpacer(view)]); - this.dom.appendChild(this.spacer.dom); - this.spacer.dom.style.cssText += "visibility: hidden; pointer-events: none"; - } - } - update(update) { - let prevMarkers = this.markers; - this.markers = asArray(this.config.markers(update.view)); - if (this.spacer && this.config.updateSpacer) { - let updated = this.config.updateSpacer(this.spacer.markers[0], update); - if (updated != this.spacer.markers[0]) - this.spacer.update(update.view, 0, 0, [updated]); - } - let vp = update.view.viewport; - return !RangeSet.eq(this.markers, prevMarkers, vp.from, vp.to) || - (this.config.lineMarkerChange ? this.config.lineMarkerChange(update) : false); - } - destroy() { - for (let elt of this.elements) - elt.destroy(); - } - } - class GutterElement { - constructor(view, height, above, markers) { - this.height = -1; - this.above = 0; - this.markers = []; - this.dom = document.createElement("div"); - this.update(view, height, above, markers); - } - update(view, height, above, markers) { - if (this.height != height) - this.dom.style.height = (this.height = height) + "px"; - if (this.above != above) - this.dom.style.marginTop = (this.above = above) ? above + "px" : ""; - if (!sameMarkers(this.markers, markers)) - this.setMarkers(view, markers); - } - setMarkers(view, markers) { - let cls = "cm-gutterElement", domPos = this.dom.firstChild; - for (let iNew = 0, iOld = 0;;) { - let skipTo = iOld, marker = iNew < markers.length ? markers[iNew++] : null, matched = false; - if (marker) { - let c = marker.elementClass; - if (c) - cls += " " + c; - for (let i = iOld; i < this.markers.length; i++) - if (this.markers[i].compare(marker)) { - skipTo = i; - matched = true; - break; - } - } - else { - skipTo = this.markers.length; - } - while (iOld < skipTo) { - let next = this.markers[iOld++]; - if (next.toDOM) { - next.destroy(domPos); - let after = domPos.nextSibling; - domPos.remove(); - domPos = after; - } - } - if (!marker) - break; - if (marker.toDOM) { - if (matched) - domPos = domPos.nextSibling; - else - this.dom.insertBefore(marker.toDOM(view), domPos); - } - if (matched) - iOld++; - } - this.dom.className = cls; - this.markers = markers; - } - destroy() { - this.setMarkers(null, []); // First argument not used unless creating markers - } - } - function sameMarkers(a, b) { - if (a.length != b.length) - return false; - for (let i = 0; i < a.length; i++) - if (!a[i].compare(b[i])) - return false; - return true; - } - /** - Facet used to provide markers to the line number gutter. - */ - const lineNumberMarkers = /*@__PURE__*/Facet.define(); - const lineNumberConfig = /*@__PURE__*/Facet.define({ - combine(values) { - return combineConfig(values, { formatNumber: String, domEventHandlers: {} }, { - domEventHandlers(a, b) { - let result = Object.assign({}, a); - for (let event in b) { - let exists = result[event], add = b[event]; - result[event] = exists ? (view, line, event) => exists(view, line, event) || add(view, line, event) : add; - } - return result; - } - }); - } - }); - class NumberMarker extends GutterMarker { - constructor(number) { - super(); - this.number = number; - } - eq(other) { return this.number == other.number; } - toDOM() { return document.createTextNode(this.number); } - } - function formatNumber(view, number) { - return view.state.facet(lineNumberConfig).formatNumber(number, view.state); - } - const lineNumberGutter = /*@__PURE__*/activeGutters.compute([lineNumberConfig], state => ({ - class: "cm-lineNumbers", - renderEmptyElements: false, - markers(view) { return view.state.facet(lineNumberMarkers); }, - lineMarker(view, line, others) { - if (others.some(m => m.toDOM)) - return null; - return new NumberMarker(formatNumber(view, view.state.doc.lineAt(line.from).number)); - }, - lineMarkerChange: update => update.startState.facet(lineNumberConfig) != update.state.facet(lineNumberConfig), - initialSpacer(view) { - return new NumberMarker(formatNumber(view, maxLineNumber(view.state.doc.lines))); - }, - updateSpacer(spacer, update) { - let max = formatNumber(update.view, maxLineNumber(update.view.state.doc.lines)); - return max == spacer.number ? spacer : new NumberMarker(max); - }, - domEventHandlers: state.facet(lineNumberConfig).domEventHandlers - })); - /** - Create a line number gutter extension. - */ - function lineNumbers(config = {}) { - return [ - lineNumberConfig.of(config), - gutters(), - lineNumberGutter - ]; - } - function maxLineNumber(lines) { - let last = 9; - while (last < lines) - last = last * 10 + 9; - return last; - } - const activeLineGutterMarker = /*@__PURE__*/new class extends GutterMarker { - constructor() { - super(...arguments); - this.elementClass = "cm-activeLineGutter"; - } - }; - const activeLineGutterHighlighter = /*@__PURE__*/gutterLineClass.compute(["selection"], state => { - let marks = [], last = -1; - for (let range of state.selection.ranges) - if (range.empty) { - let linePos = state.doc.lineAt(range.head).from; - if (linePos > last) { - last = linePos; - marks.push(activeLineGutterMarker.range(linePos)); - } - } - return RangeSet.of(marks); - }); - /** - Returns an extension that adds a `cm-activeLineGutter` class to - all gutter elements on the [active - line](https://codemirror.net/6/docs/ref/#view.highlightActiveLine). - */ - function highlightActiveLineGutter() { - return activeLineGutterHighlighter; - } - - function mapRange(range, mapping) { - let from = mapping.mapPos(range.from, 1), to = mapping.mapPos(range.to, -1); - return from >= to ? undefined : { from, to }; - } - /** - State effect that can be attached to a transaction to fold the - given range. (You probably only need this in exceptional - circumstances—usually you'll just want to let - [`foldCode`](https://codemirror.net/6/docs/ref/#fold.foldCode) and the [fold - gutter](https://codemirror.net/6/docs/ref/#fold.foldGutter) create the transactions.) - */ - const foldEffect = /*@__PURE__*/StateEffect.define({ map: mapRange }); - /** - State effect that unfolds the given range (if it was folded). - */ - const unfoldEffect = /*@__PURE__*/StateEffect.define({ map: mapRange }); - function selectedLines(view) { - let lines = []; - for (let { head } of view.state.selection.ranges) { - if (lines.some(l => l.from <= head && l.to >= head)) - continue; - lines.push(view.lineBlockAt(head)); - } - return lines; - } - const foldState = /*@__PURE__*/StateField.define({ - create() { - return Decoration.none; - }, - update(folded, tr) { - folded = folded.map(tr.changes); - for (let e of tr.effects) { - if (e.is(foldEffect) && !foldExists(folded, e.value.from, e.value.to)) - folded = folded.update({ add: [foldWidget.range(e.value.from, e.value.to)] }); - else if (e.is(unfoldEffect)) - folded = folded.update({ filter: (from, to) => e.value.from != from || e.value.to != to, - filterFrom: e.value.from, filterTo: e.value.to }); - } - // Clear folded ranges that cover the selection head - if (tr.selection) { - let onSelection = false, { head } = tr.selection.main; - folded.between(head, head, (a, b) => { if (a < head && b > head) - onSelection = true; }); - if (onSelection) - folded = folded.update({ - filterFrom: head, - filterTo: head, - filter: (a, b) => b <= head || a >= head - }); - } - return folded; - }, - provide: f => EditorView.decorations.from(f) - }); - function foldInside(state, from, to) { - var _a; - let found = null; - (_a = state.field(foldState, false)) === null || _a === void 0 ? void 0 : _a.between(from, to, (from, to) => { - if (!found || found.from > from) - found = { from, to }; - }); - return found; - } - function foldExists(folded, from, to) { - let found = false; - folded.between(from, from, (a, b) => { if (a == from && b == to) - found = true; }); - return found; - } - function maybeEnable(state, other) { - return state.field(foldState, false) ? other : other.concat(StateEffect.appendConfig.of(codeFolding())); - } - /** - Fold the lines that are selected, if possible. - */ - const foldCode = view => { - for (let line of selectedLines(view)) { - let range = foldable(view.state, line.from, line.to); - if (range) { - view.dispatch({ effects: maybeEnable(view.state, [foldEffect.of(range), announceFold(view, range)]) }); - return true; - } - } - return false; - }; - /** - Unfold folded ranges on selected lines. - */ - const unfoldCode = view => { - if (!view.state.field(foldState, false)) - return false; - let effects = []; - for (let line of selectedLines(view)) { - let folded = foldInside(view.state, line.from, line.to); - if (folded) - effects.push(unfoldEffect.of(folded), announceFold(view, folded, false)); - } - if (effects.length) - view.dispatch({ effects }); - return effects.length > 0; - }; - function announceFold(view, range, fold = true) { - let lineFrom = view.state.doc.lineAt(range.from).number, lineTo = view.state.doc.lineAt(range.to).number; - return EditorView.announce.of(`${view.state.phrase(fold ? "Folded lines" : "Unfolded lines")} ${lineFrom} ${view.state.phrase("to")} ${lineTo}.`); - } - /** - Fold all top-level foldable ranges. - */ - const foldAll = view => { - let { state } = view, effects = []; - for (let pos = 0; pos < state.doc.length;) { - let line = view.lineBlockAt(pos), range = foldable(state, line.from, line.to); - if (range) - effects.push(foldEffect.of(range)); - pos = (range ? view.lineBlockAt(range.to) : line).to + 1; - } - if (effects.length) - view.dispatch({ effects: maybeEnable(view.state, effects) }); - return !!effects.length; - }; - /** - Unfold all folded code. - */ - const unfoldAll = view => { - let field = view.state.field(foldState, false); - if (!field || !field.size) - return false; - let effects = []; - field.between(0, view.state.doc.length, (from, to) => { effects.push(unfoldEffect.of({ from, to })); }); - view.dispatch({ effects }); - return true; - }; - /** - Default fold-related key bindings. - - - Ctrl-Shift-[ (Cmd-Alt-[ on macOS): [`foldCode`](https://codemirror.net/6/docs/ref/#fold.foldCode). - - Ctrl-Shift-] (Cmd-Alt-] on macOS): [`unfoldCode`](https://codemirror.net/6/docs/ref/#fold.unfoldCode). - - Ctrl-Alt-[: [`foldAll`](https://codemirror.net/6/docs/ref/#fold.foldAll). - - Ctrl-Alt-]: [`unfoldAll`](https://codemirror.net/6/docs/ref/#fold.unfoldAll). - */ - const foldKeymap = [ - { key: "Ctrl-Shift-[", mac: "Cmd-Alt-[", run: foldCode }, - { key: "Ctrl-Shift-]", mac: "Cmd-Alt-]", run: unfoldCode }, - { key: "Ctrl-Alt-[", run: foldAll }, - { key: "Ctrl-Alt-]", run: unfoldAll } - ]; - const defaultConfig = { - placeholderDOM: null, - placeholderText: "…" - }; - const foldConfig = /*@__PURE__*/Facet.define({ - combine(values) { return combineConfig(values, defaultConfig); } - }); - /** - Create an extension that configures code folding. - */ - function codeFolding(config) { - let result = [foldState, baseTheme$6]; - if (config) - result.push(foldConfig.of(config)); - return result; - } - const foldWidget = /*@__PURE__*/Decoration.replace({ widget: /*@__PURE__*/new class extends WidgetType { - toDOM(view) { - let { state } = view, conf = state.facet(foldConfig); - let onclick = (event) => { - let line = view.lineBlockAt(view.posAtDOM(event.target)); - let folded = foldInside(view.state, line.from, line.to); - if (folded) - view.dispatch({ effects: unfoldEffect.of(folded) }); - event.preventDefault(); - }; - if (conf.placeholderDOM) - return conf.placeholderDOM(view, onclick); - let element = document.createElement("span"); - element.textContent = conf.placeholderText; - element.setAttribute("aria-label", state.phrase("folded code")); - element.title = state.phrase("unfold"); - element.className = "cm-foldPlaceholder"; - element.onclick = onclick; - return element; - } - } }); - const foldGutterDefaults = { - openText: "⌄", - closedText: "›", - markerDOM: null, - domEventHandlers: {}, - }; - class FoldMarker extends GutterMarker { - constructor(config, open) { - super(); - this.config = config; - this.open = open; - } - eq(other) { return this.config == other.config && this.open == other.open; } - toDOM(view) { - if (this.config.markerDOM) - return this.config.markerDOM(this.open); - let span = document.createElement("span"); - span.textContent = this.open ? this.config.openText : this.config.closedText; - span.title = view.state.phrase(this.open ? "Fold line" : "Unfold line"); - return span; - } - } - /** - Create an extension that registers a fold gutter, which shows a - fold status indicator before foldable lines (which can be clicked - to fold or unfold the line). - */ - function foldGutter(config = {}) { - let fullConfig = Object.assign(Object.assign({}, foldGutterDefaults), config); - let canFold = new FoldMarker(fullConfig, true), canUnfold = new FoldMarker(fullConfig, false); - let markers = ViewPlugin.fromClass(class { - constructor(view) { - this.from = view.viewport.from; - this.markers = this.buildMarkers(view); - } - update(update) { - if (update.docChanged || update.viewportChanged || - update.startState.facet(language) != update.state.facet(language) || - update.startState.field(foldState, false) != update.state.field(foldState, false) || - syntaxTree(update.startState) != syntaxTree(update.state)) - this.markers = this.buildMarkers(update.view); - } - buildMarkers(view) { - let builder = new RangeSetBuilder(); - for (let line of view.viewportLineBlocks) { - let mark = foldInside(view.state, line.from, line.to) ? canUnfold - : foldable(view.state, line.from, line.to) ? canFold : null; - if (mark) - builder.add(line.from, line.from, mark); - } - return builder.finish(); - } - }); - let { domEventHandlers } = fullConfig; - return [ - markers, - gutter({ - class: "cm-foldGutter", - markers(view) { var _a; return ((_a = view.plugin(markers)) === null || _a === void 0 ? void 0 : _a.markers) || RangeSet.empty; }, - initialSpacer() { - return new FoldMarker(fullConfig, false); - }, - domEventHandlers: Object.assign(Object.assign({}, domEventHandlers), { click: (view, line, event) => { - if (domEventHandlers.click && domEventHandlers.click(view, line, event)) - return true; - let folded = foldInside(view.state, line.from, line.to); - if (folded) { - view.dispatch({ effects: unfoldEffect.of(folded) }); - return true; - } - let range = foldable(view.state, line.from, line.to); - if (range) { - view.dispatch({ effects: foldEffect.of(range) }); - return true; - } - return false; - } }) - }), - codeFolding() - ]; - } - const baseTheme$6 = /*@__PURE__*/EditorView.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" - } - }); - - const baseTheme$5 = /*@__PURE__*/EditorView.baseTheme({ - "&.cm-focused .cm-matchingBracket": { backgroundColor: "#328c8252" }, - "&.cm-focused .cm-nonmatchingBracket": { backgroundColor: "#bb555544" } - }); - const DefaultScanDist = 10000, DefaultBrackets = "()[]{}"; - const bracketMatchingConfig = /*@__PURE__*/Facet.define({ - combine(configs) { - return combineConfig(configs, { - afterCursor: true, - brackets: DefaultBrackets, - maxScanDistance: DefaultScanDist - }); - } - }); - const matchingMark = /*@__PURE__*/Decoration.mark({ class: "cm-matchingBracket" }), nonmatchingMark = /*@__PURE__*/Decoration.mark({ class: "cm-nonmatchingBracket" }); - const bracketMatchingState = /*@__PURE__*/StateField.define({ - create() { return Decoration.none; }, - update(deco, tr) { - if (!tr.docChanged && !tr.selection) - return deco; - let decorations = []; - let config = tr.state.facet(bracketMatchingConfig); - for (let range of tr.state.selection.ranges) { - if (!range.empty) - continue; - let match = matchBrackets(tr.state, range.head, -1, config) - || (range.head > 0 && matchBrackets(tr.state, range.head - 1, 1, config)) - || (config.afterCursor && - (matchBrackets(tr.state, range.head, 1, config) || - (range.head < tr.state.doc.length && matchBrackets(tr.state, range.head + 1, -1, config)))); - if (!match) - continue; - let mark = match.matched ? matchingMark : nonmatchingMark; - decorations.push(mark.range(match.start.from, match.start.to)); - if (match.end) - decorations.push(mark.range(match.end.from, match.end.to)); - } - return Decoration.set(decorations, true); - }, - provide: f => EditorView.decorations.from(f) - }); - const bracketMatchingUnique = [ - bracketMatchingState, - baseTheme$5 - ]; - /** - Create an extension that enables bracket matching. Whenever the - cursor is next to a bracket, that bracket and the one it matches - are highlighted. Or, when no matching bracket is found, another - highlighting style is used to indicate this. - */ - function bracketMatching(config = {}) { - return [bracketMatchingConfig.of(config), bracketMatchingUnique]; - } - function matchingNodes(node, dir, brackets) { - let byProp = node.prop(dir < 0 ? NodeProp.openedBy : NodeProp.closedBy); - if (byProp) - return byProp; - if (node.name.length == 1) { - let index = brackets.indexOf(node.name); - if (index > -1 && index % 2 == (dir < 0 ? 1 : 0)) - return [brackets[index + dir]]; - } - return null; - } - /** - Find the matching bracket for the token at `pos`, scanning - direction `dir`. Only the `brackets` and `maxScanDistance` - properties are used from `config`, if given. Returns null if no - bracket was found at `pos`, or a match result otherwise. - */ - function matchBrackets(state, pos, dir, config = {}) { - let maxScanDistance = config.maxScanDistance || DefaultScanDist, brackets = config.brackets || DefaultBrackets; - let tree = syntaxTree(state), node = tree.resolveInner(pos, dir); - for (let cur = node; cur; cur = cur.parent) { - let matches = matchingNodes(cur.type, dir, brackets); - if (matches && cur.from < cur.to) - return matchMarkedBrackets(state, pos, dir, cur, matches, brackets); - } - return matchPlainBrackets(state, pos, dir, tree, node.type, maxScanDistance, brackets); - } - function matchMarkedBrackets(_state, _pos, dir, token, matching, brackets) { - let parent = token.parent, firstToken = { from: token.from, to: token.to }; - let depth = 0, cursor = parent === null || parent === void 0 ? void 0 : parent.cursor; - if (cursor && (dir < 0 ? cursor.childBefore(token.from) : cursor.childAfter(token.to))) - do { - if (dir < 0 ? cursor.to <= token.from : cursor.from >= token.to) { - if (depth == 0 && matching.indexOf(cursor.type.name) > -1 && cursor.from < cursor.to) { - return { start: firstToken, end: { from: cursor.from, to: cursor.to }, matched: true }; - } - else if (matchingNodes(cursor.type, dir, brackets)) { - depth++; - } - else if (matchingNodes(cursor.type, -dir, brackets)) { - depth--; - if (depth == 0) - return { - start: firstToken, - end: cursor.from == cursor.to ? undefined : { from: cursor.from, to: cursor.to }, - matched: false - }; - } - } - } while (dir < 0 ? cursor.prevSibling() : cursor.nextSibling()); - return { start: firstToken, matched: false }; - } - function matchPlainBrackets(state, pos, dir, tree, tokenType, maxScanDistance, brackets) { - let startCh = dir < 0 ? state.sliceDoc(pos - 1, pos) : state.sliceDoc(pos, pos + 1); - let bracket = brackets.indexOf(startCh); - if (bracket < 0 || (bracket % 2 == 0) != (dir > 0)) - return null; - let startToken = { from: dir < 0 ? pos - 1 : pos, to: dir > 0 ? pos + 1 : pos }; - let iter = state.doc.iterRange(pos, dir > 0 ? state.doc.length : 0), depth = 0; - for (let distance = 0; !(iter.next()).done && distance <= maxScanDistance;) { - let text = iter.value; - if (dir < 0) - distance += text.length; - let basePos = pos + distance * dir; - for (let pos = dir > 0 ? 0 : text.length - 1, end = dir > 0 ? text.length : -1; pos != end; pos += dir) { - let found = brackets.indexOf(text[pos]); - if (found < 0 || tree.resolve(basePos + pos, 1).type != tokenType) - continue; - if ((found % 2 == 0) == (dir > 0)) { - depth++; - } - else if (depth == 1) { // Closing - return { start: startToken, end: { from: basePos + pos, to: basePos + pos + 1 }, matched: (found >> 1) == (bracket >> 1) }; - } - else { - depth--; - } - } - if (dir > 0) - distance += text.length; - } - return iter.done ? { start: startToken, matched: false } : null; - } - - function updateSel(sel, by) { - return EditorSelection.create(sel.ranges.map(by), sel.mainIndex); - } - function setSel(state, selection) { - return state.update({ selection, scrollIntoView: true, userEvent: "select" }); - } - function moveSel({ state, dispatch }, how) { - let selection = updateSel(state.selection, how); - if (selection.eq(state.selection)) - return false; - dispatch(setSel(state, selection)); - return true; - } - function rangeEnd(range, forward) { - return EditorSelection.cursor(forward ? range.to : range.from); - } - function cursorByChar(view, forward) { - return moveSel(view, range => range.empty ? view.moveByChar(range, forward) : rangeEnd(range, forward)); - } - /** - Move the selection one character to the left (which is backward in - left-to-right text, forward in right-to-left text). - */ - const cursorCharLeft = view => cursorByChar(view, view.textDirection != Direction.LTR); - /** - Move the selection one character to the right. - */ - const cursorCharRight = view => cursorByChar(view, view.textDirection == Direction.LTR); - function cursorByGroup(view, forward) { - return moveSel(view, range => range.empty ? view.moveByGroup(range, forward) : rangeEnd(range, forward)); - } - /** - Move the selection to the left across one group of word or - non-word (but also non-space) characters. - */ - const cursorGroupLeft = view => cursorByGroup(view, view.textDirection != Direction.LTR); - /** - Move the selection one group to the right. - */ - const cursorGroupRight = view => cursorByGroup(view, view.textDirection == Direction.LTR); - function interestingNode(state, node, bracketProp) { - if (node.type.prop(bracketProp)) - return true; - let len = node.to - node.from; - return len && (len > 2 || /[^\s,.;:]/.test(state.sliceDoc(node.from, node.to))) || node.firstChild; - } - function moveBySyntax(state, start, forward) { - let pos = syntaxTree(state).resolveInner(start.head); - let bracketProp = forward ? NodeProp.closedBy : NodeProp.openedBy; - // Scan forward through child nodes to see if there's an interesting - // node ahead. - for (let at = start.head;;) { - let next = forward ? pos.childAfter(at) : pos.childBefore(at); - if (!next) - break; - if (interestingNode(state, next, bracketProp)) - pos = next; - else - at = forward ? next.to : next.from; - } - let bracket = pos.type.prop(bracketProp), match, newPos; - if (bracket && (match = forward ? matchBrackets(state, pos.from, 1) : matchBrackets(state, pos.to, -1)) && match.matched) - newPos = forward ? match.end.to : match.end.from; - else - newPos = forward ? pos.to : pos.from; - return EditorSelection.cursor(newPos, forward ? -1 : 1); - } - /** - Move the cursor over the next syntactic element to the left. - */ - const cursorSyntaxLeft = view => moveSel(view, range => moveBySyntax(view.state, range, view.textDirection != Direction.LTR)); - /** - Move the cursor over the next syntactic element to the right. - */ - const cursorSyntaxRight = view => moveSel(view, range => moveBySyntax(view.state, range, view.textDirection == Direction.LTR)); - function cursorByLine(view, forward) { - return moveSel(view, range => { - if (!range.empty) - return rangeEnd(range, forward); - let moved = view.moveVertically(range, forward); - return moved.head != range.head ? moved : view.moveToLineBoundary(range, forward); - }); - } - /** - Move the selection one line up. - */ - const cursorLineUp = view => cursorByLine(view, false); - /** - Move the selection one line down. - */ - const cursorLineDown = view => cursorByLine(view, true); - function cursorByPage(view, forward) { - let { state } = view, selection = updateSel(state.selection, range => { - return range.empty ? view.moveVertically(range, forward, view.dom.clientHeight) : rangeEnd(range, forward); - }); - if (selection.eq(state.selection)) - return false; - let startPos = view.coordsAtPos(state.selection.main.head); - let scrollRect = view.scrollDOM.getBoundingClientRect(); - view.dispatch(setSel(state, selection), { - effects: startPos && startPos.top > scrollRect.top && startPos.bottom < scrollRect.bottom - ? EditorView.scrollIntoView(selection.main.head, { y: "start", yMargin: startPos.top - scrollRect.top }) - : undefined - }); - return true; - } - /** - Move the selection one page up. - */ - const cursorPageUp = view => cursorByPage(view, false); - /** - Move the selection one page down. - */ - const cursorPageDown = view => cursorByPage(view, true); - function moveByLineBoundary(view, start, forward) { - let line = view.lineBlockAt(start.head), moved = view.moveToLineBoundary(start, forward); - if (moved.head == start.head && moved.head != (forward ? line.to : line.from)) - moved = view.moveToLineBoundary(start, forward, false); - if (!forward && moved.head == line.from && line.length) { - let space = /^\s*/.exec(view.state.sliceDoc(line.from, Math.min(line.from + 100, line.to)))[0].length; - if (space && start.head != line.from + space) - moved = EditorSelection.cursor(line.from + space); - } - return moved; - } - /** - Move the selection to the next line wrap point, or to the end of - the line if there isn't one left on this line. - */ - const cursorLineBoundaryForward = view => moveSel(view, range => moveByLineBoundary(view, range, true)); - /** - Move the selection to previous line wrap point, or failing that to - the start of the line. If the line is indented, and the cursor - isn't already at the end of the indentation, this will move to the - end of the indentation instead of the start of the line. - */ - const cursorLineBoundaryBackward = view => moveSel(view, range => moveByLineBoundary(view, range, false)); - /** - Move the selection to the start of the line. - */ - const cursorLineStart = view => moveSel(view, range => EditorSelection.cursor(view.lineBlockAt(range.head).from, 1)); - /** - Move the selection to the end of the line. - */ - const cursorLineEnd = view => moveSel(view, range => EditorSelection.cursor(view.lineBlockAt(range.head).to, -1)); - function toMatchingBracket(state, dispatch, extend) { - let found = false, selection = updateSel(state.selection, range => { - let matching = matchBrackets(state, range.head, -1) - || matchBrackets(state, range.head, 1) - || (range.head > 0 && matchBrackets(state, range.head - 1, 1)) - || (range.head < state.doc.length && matchBrackets(state, range.head + 1, -1)); - if (!matching || !matching.end) - return range; - found = true; - let head = matching.start.from == range.head ? matching.end.to : matching.end.from; - return extend ? EditorSelection.range(range.anchor, head) : EditorSelection.cursor(head); - }); - if (!found) - return false; - dispatch(setSel(state, selection)); - return true; - } - /** - Move the selection to the bracket matching the one it is currently - on, if any. - */ - const cursorMatchingBracket = ({ state, dispatch }) => toMatchingBracket(state, dispatch, false); - function extendSel(view, how) { - let selection = updateSel(view.state.selection, range => { - let head = how(range); - return EditorSelection.range(range.anchor, head.head, head.goalColumn); - }); - if (selection.eq(view.state.selection)) - return false; - view.dispatch(setSel(view.state, selection)); - return true; - } - function selectByChar(view, forward) { - return extendSel(view, range => view.moveByChar(range, forward)); - } - /** - Move the selection head one character to the left, while leaving - the anchor in place. - */ - const selectCharLeft = view => selectByChar(view, view.textDirection != Direction.LTR); - /** - Move the selection head one character to the right. - */ - const selectCharRight = view => selectByChar(view, view.textDirection == Direction.LTR); - function selectByGroup(view, forward) { - return extendSel(view, range => view.moveByGroup(range, forward)); - } - /** - Move the selection head one [group](https://codemirror.net/6/docs/ref/#commands.cursorGroupLeft) to - the left. - */ - const selectGroupLeft = view => selectByGroup(view, view.textDirection != Direction.LTR); - /** - Move the selection head one group to the right. - */ - const selectGroupRight = view => selectByGroup(view, view.textDirection == Direction.LTR); - /** - Move the selection head over the next syntactic element to the left. - */ - const selectSyntaxLeft = view => extendSel(view, range => moveBySyntax(view.state, range, view.textDirection != Direction.LTR)); - /** - Move the selection head over the next syntactic element to the right. - */ - const selectSyntaxRight = view => extendSel(view, range => moveBySyntax(view.state, range, view.textDirection == Direction.LTR)); - function selectByLine(view, forward) { - return extendSel(view, range => view.moveVertically(range, forward)); - } - /** - Move the selection head one line up. - */ - const selectLineUp = view => selectByLine(view, false); - /** - Move the selection head one line down. - */ - const selectLineDown = view => selectByLine(view, true); - function selectByPage(view, forward) { - return extendSel(view, range => view.moveVertically(range, forward, view.dom.clientHeight)); - } - /** - Move the selection head one page up. - */ - const selectPageUp = view => selectByPage(view, false); - /** - Move the selection head one page down. - */ - const selectPageDown = view => selectByPage(view, true); - /** - Move the selection head to the next line boundary. - */ - const selectLineBoundaryForward = view => extendSel(view, range => moveByLineBoundary(view, range, true)); - /** - Move the selection head to the previous line boundary. - */ - const selectLineBoundaryBackward = view => extendSel(view, range => moveByLineBoundary(view, range, false)); - /** - Move the selection head to the start of the line. - */ - const selectLineStart = view => extendSel(view, range => EditorSelection.cursor(view.lineBlockAt(range.head).from)); - /** - Move the selection head to the end of the line. - */ - const selectLineEnd = view => extendSel(view, range => EditorSelection.cursor(view.lineBlockAt(range.head).to)); - /** - Move the selection to the start of the document. - */ - const cursorDocStart = ({ state, dispatch }) => { - dispatch(setSel(state, { anchor: 0 })); - return true; - }; - /** - Move the selection to the end of the document. - */ - const cursorDocEnd = ({ state, dispatch }) => { - dispatch(setSel(state, { anchor: state.doc.length })); - return true; - }; - /** - Move the selection head to the start of the document. - */ - const selectDocStart = ({ state, dispatch }) => { - dispatch(setSel(state, { anchor: state.selection.main.anchor, head: 0 })); - return true; - }; - /** - Move the selection head to the end of the document. - */ - const selectDocEnd = ({ state, dispatch }) => { - dispatch(setSel(state, { anchor: state.selection.main.anchor, head: state.doc.length })); - return true; - }; - /** - Select the entire document. - */ - const selectAll = ({ state, dispatch }) => { - dispatch(state.update({ selection: { anchor: 0, head: state.doc.length }, userEvent: "select" })); - return true; - }; - /** - Expand the selection to cover entire lines. - */ - const selectLine = ({ state, dispatch }) => { - let ranges = selectedLineBlocks(state).map(({ from, to }) => EditorSelection.range(from, Math.min(to + 1, state.doc.length))); - dispatch(state.update({ selection: EditorSelection.create(ranges), userEvent: "select" })); - return true; - }; - /** - Select the next syntactic construct that is larger than the - selection. Note that this will only work insofar as the language - [provider](https://codemirror.net/6/docs/ref/#language.language) you use builds up a full - syntax tree. - */ - const selectParentSyntax = ({ state, dispatch }) => { - let selection = updateSel(state.selection, range => { - var _a; - let context = syntaxTree(state).resolveInner(range.head, 1); - while (!((context.from < range.from && context.to >= range.to) || - (context.to > range.to && context.from <= range.from) || - !((_a = context.parent) === null || _a === void 0 ? void 0 : _a.parent))) - context = context.parent; - return EditorSelection.range(context.to, context.from); - }); - dispatch(setSel(state, selection)); - return true; - }; - /** - Simplify the current selection. When multiple ranges are selected, - reduce it to its main range. Otherwise, if the selection is - non-empty, convert it to a cursor selection. - */ - const simplifySelection = ({ state, dispatch }) => { - let cur = state.selection, selection = null; - if (cur.ranges.length > 1) - selection = EditorSelection.create([cur.main]); - else if (!cur.main.empty) - selection = EditorSelection.create([EditorSelection.cursor(cur.main.head)]); - if (!selection) - return false; - dispatch(setSel(state, selection)); - return true; - }; - function deleteBy({ state, dispatch }, by) { - if (state.readOnly) - return false; - let event = "delete.selection"; - let changes = state.changeByRange(range => { - let { from, to } = range; - if (from == to) { - let towards = by(from); - if (towards < from) - event = "delete.backward"; - else if (towards > from) - event = "delete.forward"; - from = Math.min(from, towards); - to = Math.max(to, towards); - } - return from == to ? { range } : { changes: { from, to }, range: EditorSelection.cursor(from) }; - }); - if (changes.changes.empty) - return false; - dispatch(state.update(changes, { scrollIntoView: true, userEvent: event })); - return true; - } - function skipAtomic(target, pos, forward) { - if (target instanceof EditorView) - for (let ranges of target.pluginField(PluginField.atomicRanges)) - ranges.between(pos, pos, (from, to) => { - if (from < pos && to > pos) - pos = forward ? to : from; - }); - return pos; - } - const deleteByChar = (target, forward) => deleteBy(target, pos => { - let { state } = target, line = state.doc.lineAt(pos), before, targetPos; - if (!forward && pos > line.from && pos < line.from + 200 && - !/[^ \t]/.test(before = line.text.slice(0, pos - line.from))) { - if (before[before.length - 1] == "\t") - return pos - 1; - let col = countColumn(before, state.tabSize), drop = col % getIndentUnit(state) || getIndentUnit(state); - for (let i = 0; i < drop && before[before.length - 1 - i] == " "; i++) - pos--; - targetPos = pos; - } - else { - targetPos = findClusterBreak(line.text, pos - line.from, forward, forward) + line.from; - if (targetPos == pos && line.number != (forward ? state.doc.lines : 1)) - targetPos += forward ? 1 : -1; - } - return skipAtomic(target, targetPos, forward); - }); - /** - Delete the selection, or, for cursor selections, the character - before the cursor. - */ - const deleteCharBackward = view => deleteByChar(view, false); - /** - Delete the selection or the character after the cursor. - */ - const deleteCharForward = view => deleteByChar(view, true); - const deleteByGroup = (target, forward) => deleteBy(target, start => { - let pos = start, { state } = target, line = state.doc.lineAt(pos); - let categorize = state.charCategorizer(pos); - for (let cat = null;;) { - if (pos == (forward ? line.to : line.from)) { - if (pos == start && line.number != (forward ? state.doc.lines : 1)) - pos += forward ? 1 : -1; - break; - } - let next = findClusterBreak(line.text, pos - line.from, forward) + line.from; - let nextChar = line.text.slice(Math.min(pos, next) - line.from, Math.max(pos, next) - line.from); - let nextCat = categorize(nextChar); - if (cat != null && nextCat != cat) - break; - if (nextChar != " " || pos != start) - cat = nextCat; - pos = next; - } - return skipAtomic(target, pos, forward); - }); - /** - Delete the selection or backward until the end of the next - [group](https://codemirror.net/6/docs/ref/#view.EditorView.moveByGroup), only skipping groups of - whitespace when they consist of a single space. - */ - const deleteGroupBackward = target => deleteByGroup(target, false); - /** - Delete the selection or forward until the end of the next group. - */ - const deleteGroupForward = target => deleteByGroup(target, true); - /** - Delete the selection, or, if it is a cursor selection, delete to - the end of the line. If the cursor is directly at the end of the - line, delete the line break after it. - */ - const deleteToLineEnd = view => deleteBy(view, pos => { - let lineEnd = view.lineBlockAt(pos).to; - return skipAtomic(view, pos < lineEnd ? lineEnd : Math.min(view.state.doc.length, pos + 1), true); - }); - /** - Delete the selection, or, if it is a cursor selection, delete to - the start of the line. If the cursor is directly at the start of the - line, delete the line break before it. - */ - const deleteToLineStart = view => deleteBy(view, pos => { - let lineStart = view.lineBlockAt(pos).from; - return skipAtomic(view, pos > lineStart ? lineStart : Math.max(0, pos - 1), false); - }); - /** - Replace each selection range with a line break, leaving the cursor - on the line before the break. - */ - const splitLine = ({ state, dispatch }) => { - if (state.readOnly) - return false; - let changes = state.changeByRange(range => { - return { changes: { from: range.from, to: range.to, insert: Text.of(["", ""]) }, - range: EditorSelection.cursor(range.from) }; - }); - dispatch(state.update(changes, { scrollIntoView: true, userEvent: "input" })); - return true; - }; - /** - Flip the characters before and after the cursor(s). - */ - const transposeChars = ({ state, dispatch }) => { - if (state.readOnly) - return false; - let changes = state.changeByRange(range => { - if (!range.empty || range.from == 0 || range.from == state.doc.length) - return { range }; - let pos = range.from, line = state.doc.lineAt(pos); - let from = pos == line.from ? pos - 1 : findClusterBreak(line.text, pos - line.from, false) + line.from; - let to = pos == line.to ? pos + 1 : findClusterBreak(line.text, pos - line.from, true) + line.from; - return { changes: { from, to, insert: state.doc.slice(pos, to).append(state.doc.slice(from, pos)) }, - range: EditorSelection.cursor(to) }; - }); - if (changes.changes.empty) - return false; - dispatch(state.update(changes, { scrollIntoView: true, userEvent: "move.character" })); - return true; - }; - function selectedLineBlocks(state) { - let blocks = [], upto = -1; - for (let range of state.selection.ranges) { - let startLine = state.doc.lineAt(range.from), endLine = state.doc.lineAt(range.to); - if (!range.empty && range.to == endLine.from) - endLine = state.doc.lineAt(range.to - 1); - if (upto >= startLine.number) { - let prev = blocks[blocks.length - 1]; - prev.to = endLine.to; - prev.ranges.push(range); - } - else { - blocks.push({ from: startLine.from, to: endLine.to, ranges: [range] }); - } - upto = endLine.number + 1; - } - return blocks; - } - function moveLine(state, dispatch, forward) { - if (state.readOnly) - return false; - let changes = [], ranges = []; - for (let block of selectedLineBlocks(state)) { - if (forward ? block.to == state.doc.length : block.from == 0) - continue; - let nextLine = state.doc.lineAt(forward ? block.to + 1 : block.from - 1); - let size = nextLine.length + 1; - if (forward) { - changes.push({ from: block.to, to: nextLine.to }, { from: block.from, insert: nextLine.text + state.lineBreak }); - for (let r of block.ranges) - ranges.push(EditorSelection.range(Math.min(state.doc.length, r.anchor + size), Math.min(state.doc.length, r.head + size))); - } - else { - changes.push({ from: nextLine.from, to: block.from }, { from: block.to, insert: state.lineBreak + nextLine.text }); - for (let r of block.ranges) - ranges.push(EditorSelection.range(r.anchor - size, r.head - size)); - } - } - if (!changes.length) - return false; - dispatch(state.update({ - changes, - scrollIntoView: true, - selection: EditorSelection.create(ranges, state.selection.mainIndex), - userEvent: "move.line" - })); - return true; - } - /** - Move the selected lines up one line. - */ - const moveLineUp = ({ state, dispatch }) => moveLine(state, dispatch, false); - /** - Move the selected lines down one line. - */ - const moveLineDown = ({ state, dispatch }) => moveLine(state, dispatch, true); - function copyLine(state, dispatch, forward) { - if (state.readOnly) - return false; - let changes = []; - for (let block of selectedLineBlocks(state)) { - if (forward) - changes.push({ from: block.from, insert: state.doc.slice(block.from, block.to) + state.lineBreak }); - else - changes.push({ from: block.to, insert: state.lineBreak + state.doc.slice(block.from, block.to) }); - } - dispatch(state.update({ changes, scrollIntoView: true, userEvent: "input.copyline" })); - return true; - } - /** - Create a copy of the selected lines. Keep the selection in the top copy. - */ - const copyLineUp = ({ state, dispatch }) => copyLine(state, dispatch, false); - /** - Create a copy of the selected lines. Keep the selection in the bottom copy. - */ - const copyLineDown = ({ state, dispatch }) => copyLine(state, dispatch, true); - /** - Delete selected lines. - */ - const deleteLine = view => { - if (view.state.readOnly) - return false; - let { state } = view, changes = state.changes(selectedLineBlocks(state).map(({ from, to }) => { - if (from > 0) - from--; - else if (to < state.doc.length) - to++; - return { from, to }; - })); - let selection = updateSel(state.selection, range => view.moveVertically(range, true)).map(changes); - view.dispatch({ changes, selection, scrollIntoView: true, userEvent: "delete.line" }); - return true; - }; - function isBetweenBrackets(state, pos) { - if (/\(\)|\[\]|\{\}/.test(state.sliceDoc(pos - 1, pos + 1))) - return { from: pos, to: pos }; - let context = syntaxTree(state).resolveInner(pos); - let before = context.childBefore(pos), after = context.childAfter(pos), closedBy; - if (before && after && before.to <= pos && after.from >= pos && - (closedBy = before.type.prop(NodeProp.closedBy)) && closedBy.indexOf(after.name) > -1 && - state.doc.lineAt(before.to).from == state.doc.lineAt(after.from).from) - return { from: before.to, to: after.from }; - return null; - } - /** - Replace the selection with a newline and indent the newly created - line(s). If the current line consists only of whitespace, this - will also delete that whitespace. When the cursor is between - matching brackets, an additional newline will be inserted after - the cursor. - */ - const insertNewlineAndIndent = /*@__PURE__*/newlineAndIndent(false); - /** - Create a blank, indented line below the current line. - */ - const insertBlankLine = /*@__PURE__*/newlineAndIndent(true); - function newlineAndIndent(atEof) { - return ({ state, dispatch }) => { - if (state.readOnly) - return false; - let changes = state.changeByRange(range => { - let { from, to } = range, line = state.doc.lineAt(from); - let explode = !atEof && from == to && isBetweenBrackets(state, from); - if (atEof) - from = to = (to <= line.to ? line : state.doc.lineAt(to)).to; - let cx = new IndentContext(state, { simulateBreak: from, simulateDoubleBreak: !!explode }); - let indent = getIndentation(cx, from); - if (indent == null) - indent = /^\s*/.exec(state.doc.lineAt(from).text)[0].length; - while (to < line.to && /\s/.test(line.text[to - line.from])) - to++; - if (explode) - ({ from, to } = explode); - else if (from > line.from && from < line.from + 100 && !/\S/.test(line.text.slice(0, from))) - from = line.from; - let insert = ["", indentString(state, indent)]; - if (explode) - insert.push(indentString(state, cx.lineIndent(line.from, -1))); - return { changes: { from, to, insert: Text.of(insert) }, - range: EditorSelection.cursor(from + 1 + insert[1].length) }; - }); - dispatch(state.update(changes, { scrollIntoView: true, userEvent: "input" })); - return true; - }; - } - function changeBySelectedLine(state, f) { - let atLine = -1; - return state.changeByRange(range => { - let changes = []; - for (let pos = range.from; pos <= range.to;) { - let line = state.doc.lineAt(pos); - if (line.number > atLine && (range.empty || range.to > line.from)) { - f(line, changes, range); - atLine = line.number; - } - pos = line.to + 1; - } - let changeSet = state.changes(changes); - return { changes, - range: EditorSelection.range(changeSet.mapPos(range.anchor, 1), changeSet.mapPos(range.head, 1)) }; - }); - } - /** - Auto-indent the selected lines. This uses the [indentation service - facet](https://codemirror.net/6/docs/ref/#language.indentService) as source for auto-indent - information. - */ - const indentSelection = ({ state, dispatch }) => { - if (state.readOnly) - return false; - let updated = Object.create(null); - let context = new IndentContext(state, { overrideIndentation: start => { - let found = updated[start]; - return found == null ? -1 : found; - } }); - let changes = changeBySelectedLine(state, (line, changes, range) => { - let indent = getIndentation(context, line.from); - if (indent == null) - return; - if (!/\S/.test(line.text)) - indent = 0; - let cur = /^\s*/.exec(line.text)[0]; - let norm = indentString(state, indent); - if (cur != norm || range.from < line.from + cur.length) { - updated[line.from] = indent; - changes.push({ from: line.from, to: line.from + cur.length, insert: norm }); - } - }); - if (!changes.changes.empty) - dispatch(state.update(changes, { userEvent: "indent" })); - return true; - }; - /** - Add a [unit](https://codemirror.net/6/docs/ref/#language.indentUnit) of indentation to all selected - lines. - */ - const indentMore = ({ state, dispatch }) => { - if (state.readOnly) - return false; - dispatch(state.update(changeBySelectedLine(state, (line, changes) => { - changes.push({ from: line.from, insert: state.facet(indentUnit) }); - }), { userEvent: "input.indent" })); - return true; - }; - /** - Remove a [unit](https://codemirror.net/6/docs/ref/#language.indentUnit) of indentation from all - selected lines. - */ - const indentLess = ({ state, dispatch }) => { - if (state.readOnly) - return false; - dispatch(state.update(changeBySelectedLine(state, (line, changes) => { - let space = /^\s*/.exec(line.text)[0]; - if (!space) - return; - let col = countColumn(space, state.tabSize), keep = 0; - let insert = indentString(state, Math.max(0, col - getIndentUnit(state))); - while (keep < space.length && keep < insert.length && space.charCodeAt(keep) == insert.charCodeAt(keep)) - keep++; - changes.push({ from: line.from + keep, to: line.from + space.length, insert: insert.slice(keep) }); - }), { userEvent: "delete.dedent" })); - return true; - }; - /** - Array of key bindings containing the Emacs-style bindings that are - available on macOS by default. - - - Ctrl-b: [`cursorCharLeft`](https://codemirror.net/6/docs/ref/#commands.cursorCharLeft) ([`selectCharLeft`](https://codemirror.net/6/docs/ref/#commands.selectCharLeft) with Shift) - - Ctrl-f: [`cursorCharRight`](https://codemirror.net/6/docs/ref/#commands.cursorCharRight) ([`selectCharRight`](https://codemirror.net/6/docs/ref/#commands.selectCharRight) with Shift) - - Ctrl-p: [`cursorLineUp`](https://codemirror.net/6/docs/ref/#commands.cursorLineUp) ([`selectLineUp`](https://codemirror.net/6/docs/ref/#commands.selectLineUp) with Shift) - - Ctrl-n: [`cursorLineDown`](https://codemirror.net/6/docs/ref/#commands.cursorLineDown) ([`selectLineDown`](https://codemirror.net/6/docs/ref/#commands.selectLineDown) with Shift) - - Ctrl-a: [`cursorLineStart`](https://codemirror.net/6/docs/ref/#commands.cursorLineStart) ([`selectLineStart`](https://codemirror.net/6/docs/ref/#commands.selectLineStart) with Shift) - - Ctrl-e: [`cursorLineEnd`](https://codemirror.net/6/docs/ref/#commands.cursorLineEnd) ([`selectLineEnd`](https://codemirror.net/6/docs/ref/#commands.selectLineEnd) with Shift) - - Ctrl-d: [`deleteCharForward`](https://codemirror.net/6/docs/ref/#commands.deleteCharForward) - - Ctrl-h: [`deleteCharBackward`](https://codemirror.net/6/docs/ref/#commands.deleteCharBackward) - - Ctrl-k: [`deleteToLineEnd`](https://codemirror.net/6/docs/ref/#commands.deleteToLineEnd) - - Ctrl-Alt-h: [`deleteGroupBackward`](https://codemirror.net/6/docs/ref/#commands.deleteGroupBackward) - - Ctrl-o: [`splitLine`](https://codemirror.net/6/docs/ref/#commands.splitLine) - - Ctrl-t: [`transposeChars`](https://codemirror.net/6/docs/ref/#commands.transposeChars) - - Ctrl-v: [`cursorPageDown`](https://codemirror.net/6/docs/ref/#commands.cursorPageDown) - - Alt-v: [`cursorPageUp`](https://codemirror.net/6/docs/ref/#commands.cursorPageUp) - */ - const emacsStyleKeymap = [ - { key: "Ctrl-b", run: cursorCharLeft, shift: selectCharLeft, preventDefault: true }, - { key: "Ctrl-f", run: cursorCharRight, shift: selectCharRight }, - { key: "Ctrl-p", run: cursorLineUp, shift: selectLineUp }, - { key: "Ctrl-n", run: cursorLineDown, shift: selectLineDown }, - { key: "Ctrl-a", run: cursorLineStart, shift: selectLineStart }, - { key: "Ctrl-e", run: cursorLineEnd, shift: selectLineEnd }, - { key: "Ctrl-d", run: deleteCharForward }, - { key: "Ctrl-h", run: deleteCharBackward }, - { key: "Ctrl-k", run: deleteToLineEnd }, - { key: "Ctrl-Alt-h", run: deleteGroupBackward }, - { key: "Ctrl-o", run: splitLine }, - { key: "Ctrl-t", run: transposeChars }, - { key: "Ctrl-v", run: cursorPageDown }, - ]; - /** - An array of key bindings closely sticking to platform-standard or - widely used bindings. (This includes the bindings from - [`emacsStyleKeymap`](https://codemirror.net/6/docs/ref/#commands.emacsStyleKeymap), with their `key` - property changed to `mac`.) - - - ArrowLeft: [`cursorCharLeft`](https://codemirror.net/6/docs/ref/#commands.cursorCharLeft) ([`selectCharLeft`](https://codemirror.net/6/docs/ref/#commands.selectCharLeft) with Shift) - - ArrowRight: [`cursorCharRight`](https://codemirror.net/6/docs/ref/#commands.cursorCharRight) ([`selectCharRight`](https://codemirror.net/6/docs/ref/#commands.selectCharRight) with Shift) - - Ctrl-ArrowLeft (Alt-ArrowLeft on macOS): [`cursorGroupLeft`](https://codemirror.net/6/docs/ref/#commands.cursorGroupLeft) ([`selectGroupLeft`](https://codemirror.net/6/docs/ref/#commands.selectGroupLeft) with Shift) - - Ctrl-ArrowRight (Alt-ArrowRight on macOS): [`cursorGroupRight`](https://codemirror.net/6/docs/ref/#commands.cursorGroupRight) ([`selectGroupRight`](https://codemirror.net/6/docs/ref/#commands.selectGroupRight) with Shift) - - Cmd-ArrowLeft (on macOS): [`cursorLineStart`](https://codemirror.net/6/docs/ref/#commands.cursorLineStart) ([`selectLineStart`](https://codemirror.net/6/docs/ref/#commands.selectLineStart) with Shift) - - Cmd-ArrowRight (on macOS): [`cursorLineEnd`](https://codemirror.net/6/docs/ref/#commands.cursorLineEnd) ([`selectLineEnd`](https://codemirror.net/6/docs/ref/#commands.selectLineEnd) with Shift) - - ArrowUp: [`cursorLineUp`](https://codemirror.net/6/docs/ref/#commands.cursorLineUp) ([`selectLineUp`](https://codemirror.net/6/docs/ref/#commands.selectLineUp) with Shift) - - ArrowDown: [`cursorLineDown`](https://codemirror.net/6/docs/ref/#commands.cursorLineDown) ([`selectLineDown`](https://codemirror.net/6/docs/ref/#commands.selectLineDown) with Shift) - - Cmd-ArrowUp (on macOS): [`cursorDocStart`](https://codemirror.net/6/docs/ref/#commands.cursorDocStart) ([`selectDocStart`](https://codemirror.net/6/docs/ref/#commands.selectDocStart) with Shift) - - Cmd-ArrowDown (on macOS): [`cursorDocEnd`](https://codemirror.net/6/docs/ref/#commands.cursorDocEnd) ([`selectDocEnd`](https://codemirror.net/6/docs/ref/#commands.selectDocEnd) with Shift) - - Ctrl-ArrowUp (on macOS): [`cursorPageUp`](https://codemirror.net/6/docs/ref/#commands.cursorPageUp) ([`selectPageUp`](https://codemirror.net/6/docs/ref/#commands.selectPageUp) with Shift) - - Ctrl-ArrowDown (on macOS): [`cursorPageDown`](https://codemirror.net/6/docs/ref/#commands.cursorPageDown) ([`selectPageDown`](https://codemirror.net/6/docs/ref/#commands.selectPageDown) with Shift) - - PageUp: [`cursorPageUp`](https://codemirror.net/6/docs/ref/#commands.cursorPageUp) ([`selectPageUp`](https://codemirror.net/6/docs/ref/#commands.selectPageUp) with Shift) - - PageDown: [`cursorPageDown`](https://codemirror.net/6/docs/ref/#commands.cursorPageDown) ([`selectPageDown`](https://codemirror.net/6/docs/ref/#commands.selectPageDown) with Shift) - - Home: [`cursorLineBoundaryBackward`](https://codemirror.net/6/docs/ref/#commands.cursorLineBoundaryBackward) ([`selectLineBoundaryBackward`](https://codemirror.net/6/docs/ref/#commands.selectLineBoundaryBackward) with Shift) - - End: [`cursorLineBoundaryForward`](https://codemirror.net/6/docs/ref/#commands.cursorLineBoundaryForward) ([`selectLineBoundaryForward`](https://codemirror.net/6/docs/ref/#commands.selectLineBoundaryForward) with Shift) - - Ctrl-Home (Cmd-Home on macOS): [`cursorDocStart`](https://codemirror.net/6/docs/ref/#commands.cursorDocStart) ([`selectDocStart`](https://codemirror.net/6/docs/ref/#commands.selectDocStart) with Shift) - - Ctrl-End (Cmd-Home on macOS): [`cursorDocEnd`](https://codemirror.net/6/docs/ref/#commands.cursorDocEnd) ([`selectDocEnd`](https://codemirror.net/6/docs/ref/#commands.selectDocEnd) with Shift) - - Enter: [`insertNewlineAndIndent`](https://codemirror.net/6/docs/ref/#commands.insertNewlineAndIndent) - - Ctrl-a (Cmd-a on macOS): [`selectAll`](https://codemirror.net/6/docs/ref/#commands.selectAll) - - Backspace: [`deleteCharBackward`](https://codemirror.net/6/docs/ref/#commands.deleteCharBackward) - - Delete: [`deleteCharForward`](https://codemirror.net/6/docs/ref/#commands.deleteCharForward) - - Ctrl-Backspace (Alt-Backspace on macOS): [`deleteGroupBackward`](https://codemirror.net/6/docs/ref/#commands.deleteGroupBackward) - - Ctrl-Delete (Alt-Delete on macOS): [`deleteGroupForward`](https://codemirror.net/6/docs/ref/#commands.deleteGroupForward) - - Cmd-Backspace (macOS): [`deleteToLineStart`](https://codemirror.net/6/docs/ref/#commands.deleteToLineStart). - - Cmd-Delete (macOS): [`deleteToLineEnd`](https://codemirror.net/6/docs/ref/#commands.deleteToLineEnd). - */ - const standardKeymap = /*@__PURE__*/[ - { key: "ArrowLeft", run: cursorCharLeft, shift: selectCharLeft, preventDefault: true }, - { key: "Mod-ArrowLeft", mac: "Alt-ArrowLeft", run: cursorGroupLeft, shift: selectGroupLeft }, - { mac: "Cmd-ArrowLeft", run: cursorLineBoundaryBackward, shift: selectLineBoundaryBackward }, - { key: "ArrowRight", run: cursorCharRight, shift: selectCharRight, preventDefault: true }, - { key: "Mod-ArrowRight", mac: "Alt-ArrowRight", run: cursorGroupRight, shift: selectGroupRight }, - { mac: "Cmd-ArrowRight", run: cursorLineBoundaryForward, shift: selectLineBoundaryForward }, - { key: "ArrowUp", run: cursorLineUp, shift: selectLineUp, preventDefault: true }, - { mac: "Cmd-ArrowUp", run: cursorDocStart, shift: selectDocStart }, - { mac: "Ctrl-ArrowUp", run: cursorPageUp, shift: selectPageUp }, - { key: "ArrowDown", run: cursorLineDown, shift: selectLineDown, preventDefault: true }, - { mac: "Cmd-ArrowDown", run: cursorDocEnd, shift: selectDocEnd }, - { mac: "Ctrl-ArrowDown", run: cursorPageDown, shift: selectPageDown }, - { key: "PageUp", run: cursorPageUp, shift: selectPageUp }, - { key: "PageDown", run: cursorPageDown, shift: selectPageDown }, - { key: "Home", run: cursorLineBoundaryBackward, shift: selectLineBoundaryBackward }, - { key: "Mod-Home", run: cursorDocStart, shift: selectDocStart }, - { key: "End", run: cursorLineBoundaryForward, shift: selectLineBoundaryForward }, - { key: "Mod-End", run: cursorDocEnd, shift: selectDocEnd }, - { key: "Enter", run: insertNewlineAndIndent }, - { key: "Mod-a", run: selectAll }, - { key: "Backspace", run: deleteCharBackward, shift: deleteCharBackward }, - { key: "Delete", run: deleteCharForward }, - { key: "Mod-Backspace", mac: "Alt-Backspace", run: deleteGroupBackward }, - { key: "Mod-Delete", mac: "Alt-Delete", run: deleteGroupForward }, - { mac: "Mod-Backspace", run: deleteToLineStart }, - { mac: "Mod-Delete", run: deleteToLineEnd } - ].concat(/*@__PURE__*/emacsStyleKeymap.map(b => ({ mac: b.key, run: b.run, shift: b.shift }))); - /** - The default keymap. Includes all bindings from - [`standardKeymap`](https://codemirror.net/6/docs/ref/#commands.standardKeymap) plus the following: - - - Alt-ArrowLeft (Ctrl-ArrowLeft on macOS): [`cursorSyntaxLeft`](https://codemirror.net/6/docs/ref/#commands.cursorSyntaxLeft) ([`selectSyntaxLeft`](https://codemirror.net/6/docs/ref/#commands.selectSyntaxLeft) with Shift) - - Alt-ArrowRight (Ctrl-ArrowRight on macOS): [`cursorSyntaxRight`](https://codemirror.net/6/docs/ref/#commands.cursorSyntaxRight) ([`selectSyntaxRight`](https://codemirror.net/6/docs/ref/#commands.selectSyntaxRight) with Shift) - - Alt-ArrowUp: [`moveLineUp`](https://codemirror.net/6/docs/ref/#commands.moveLineUp) - - Alt-ArrowDown: [`moveLineDown`](https://codemirror.net/6/docs/ref/#commands.moveLineDown) - - Shift-Alt-ArrowUp: [`copyLineUp`](https://codemirror.net/6/docs/ref/#commands.copyLineUp) - - Shift-Alt-ArrowDown: [`copyLineDown`](https://codemirror.net/6/docs/ref/#commands.copyLineDown) - - Escape: [`simplifySelection`](https://codemirror.net/6/docs/ref/#commands.simplifySelection) - - Ctrl-Enter (Comd-Enter on macOS): [`insertBlankLine`](https://codemirror.net/6/docs/ref/#commands.insertBlankLine) - - Alt-l (Ctrl-l on macOS): [`selectLine`](https://codemirror.net/6/docs/ref/#commands.selectLine) - - Ctrl-i (Cmd-i on macOS): [`selectParentSyntax`](https://codemirror.net/6/docs/ref/#commands.selectParentSyntax) - - Ctrl-[ (Cmd-[ on macOS): [`indentLess`](https://codemirror.net/6/docs/ref/#commands.indentLess) - - Ctrl-] (Cmd-] on macOS): [`indentMore`](https://codemirror.net/6/docs/ref/#commands.indentMore) - - Ctrl-Alt-\\ (Cmd-Alt-\\ on macOS): [`indentSelection`](https://codemirror.net/6/docs/ref/#commands.indentSelection) - - Shift-Ctrl-k (Shift-Cmd-k on macOS): [`deleteLine`](https://codemirror.net/6/docs/ref/#commands.deleteLine) - - Shift-Ctrl-\\ (Shift-Cmd-\\ on macOS): [`cursorMatchingBracket`](https://codemirror.net/6/docs/ref/#commands.cursorMatchingBracket) - */ - const defaultKeymap = /*@__PURE__*/[ - { key: "Alt-ArrowLeft", mac: "Ctrl-ArrowLeft", run: cursorSyntaxLeft, shift: selectSyntaxLeft }, - { key: "Alt-ArrowRight", mac: "Ctrl-ArrowRight", run: cursorSyntaxRight, shift: selectSyntaxRight }, - { key: "Alt-ArrowUp", run: moveLineUp }, - { key: "Shift-Alt-ArrowUp", run: copyLineUp }, - { key: "Alt-ArrowDown", run: moveLineDown }, - { key: "Shift-Alt-ArrowDown", run: copyLineDown }, - { key: "Escape", run: simplifySelection }, - { key: "Mod-Enter", run: insertBlankLine }, - { key: "Alt-l", mac: "Ctrl-l", run: selectLine }, - { key: "Mod-i", run: selectParentSyntax, preventDefault: true }, - { key: "Mod-[", run: indentLess }, - { key: "Mod-]", run: indentMore }, - { key: "Mod-Alt-\\", run: indentSelection }, - { key: "Shift-Mod-k", run: deleteLine }, - { key: "Shift-Mod-\\", run: cursorMatchingBracket } - ].concat(standardKeymap); - - const defaults = { - brackets: ["(", "[", "{", "'", '"'], - before: ")]}:;>" - }; - const closeBracketEffect = /*@__PURE__*/StateEffect.define({ - map(value, mapping) { - let mapped = mapping.mapPos(value, -1, MapMode.TrackAfter); - return mapped == null ? undefined : mapped; - } - }); - const skipBracketEffect = /*@__PURE__*/StateEffect.define({ - map(value, mapping) { return mapping.mapPos(value); } - }); - const closedBracket = /*@__PURE__*/new class extends RangeValue { - }; - closedBracket.startSide = 1; - closedBracket.endSide = -1; - const bracketState = /*@__PURE__*/StateField.define({ - create() { return RangeSet.empty; }, - update(value, tr) { - if (tr.selection) { - let lineStart = tr.state.doc.lineAt(tr.selection.main.head).from; - let prevLineStart = tr.startState.doc.lineAt(tr.startState.selection.main.head).from; - if (lineStart != tr.changes.mapPos(prevLineStart, -1)) - value = RangeSet.empty; - } - value = value.map(tr.changes); - for (let effect of tr.effects) { - if (effect.is(closeBracketEffect)) - value = value.update({ add: [closedBracket.range(effect.value, effect.value + 1)] }); - else if (effect.is(skipBracketEffect)) - value = value.update({ filter: from => from != effect.value }); - } - return value; - } - }); - /** - Extension to enable bracket-closing behavior. When a closeable - bracket is typed, its closing bracket is immediately inserted - after the cursor. When closing a bracket directly in front of a - closing bracket inserted by the extension, the cursor moves over - that bracket. - */ - function closeBrackets() { - return [inputHandler, bracketState]; - } - const definedClosing = "()[]{}<>"; - function closing(ch) { - for (let i = 0; i < definedClosing.length; i += 2) - if (definedClosing.charCodeAt(i) == ch) - return definedClosing.charAt(i + 1); - return fromCodePoint(ch < 128 ? ch : ch + 1); - } - function config$1(state, pos) { - return state.languageDataAt("closeBrackets", pos)[0] || defaults; - } - const android = typeof navigator == "object" && /*@__PURE__*//Android\b/.test(navigator.userAgent); - const inputHandler = /*@__PURE__*/EditorView.inputHandler.of((view, from, to, insert) => { - if ((android ? view.composing : view.compositionStarted) || view.state.readOnly) - return false; - let sel = view.state.selection.main; - if (insert.length > 2 || insert.length == 2 && codePointSize(codePointAt(insert, 0)) == 1 || - from != sel.from || to != sel.to) - return false; - let tr = insertBracket(view.state, insert); - if (!tr) - return false; - view.dispatch(tr); - return true; - }); - /** - Command that implements deleting a pair of matching brackets when - the cursor is between them. - */ - const deleteBracketPair = ({ state, dispatch }) => { - if (state.readOnly) - return false; - let conf = config$1(state, state.selection.main.head); - let tokens = conf.brackets || defaults.brackets; - let dont = null, changes = state.changeByRange(range => { - if (range.empty) { - let before = prevChar(state.doc, range.head); - for (let token of tokens) { - if (token == before && nextChar(state.doc, range.head) == closing(codePointAt(token, 0))) - return { changes: { from: range.head - token.length, to: range.head + token.length }, - range: EditorSelection.cursor(range.head - token.length), - userEvent: "delete.backward" }; - } - } - return { range: dont = range }; - }); - if (!dont) - dispatch(state.update(changes, { scrollIntoView: true })); - return !dont; - }; - /** - Close-brackets related key bindings. Binds Backspace to - [`deleteBracketPair`](https://codemirror.net/6/docs/ref/#closebrackets.deleteBracketPair). - */ - const closeBracketsKeymap = [ - { key: "Backspace", run: deleteBracketPair } - ]; - /** - Implements the extension's behavior on text insertion. If the - given string counts as a bracket in the language around the - selection, and replacing the selection with it requires custom - behavior (inserting a closing version or skipping past a - previously-closed bracket), this function returns a transaction - representing that custom behavior. (You only need this if you want - to programmatically insert brackets—the - [`closeBrackets`](https://codemirror.net/6/docs/ref/#closebrackets.closeBrackets) extension will - take care of running this for user input.) - */ - function insertBracket(state, bracket) { - let conf = config$1(state, state.selection.main.head); - let tokens = conf.brackets || defaults.brackets; - for (let tok of tokens) { - let closed = closing(codePointAt(tok, 0)); - if (bracket == tok) - return closed == tok ? handleSame(state, tok, tokens.indexOf(tok + tok + tok) > -1) - : handleOpen(state, tok, closed, conf.before || defaults.before); - if (bracket == closed && closedBracketAt(state, state.selection.main.from)) - return handleClose(state, tok, closed); - } - return null; - } - function closedBracketAt(state, pos) { - let found = false; - state.field(bracketState).between(0, state.doc.length, from => { - if (from == pos) - found = true; - }); - return found; - } - function nextChar(doc, pos) { - let next = doc.sliceString(pos, pos + 2); - return next.slice(0, codePointSize(codePointAt(next, 0))); - } - function prevChar(doc, pos) { - let prev = doc.sliceString(pos - 2, pos); - return codePointSize(codePointAt(prev, 0)) == prev.length ? prev : prev.slice(1); - } - function handleOpen(state, open, close, closeBefore) { - let dont = null, changes = state.changeByRange(range => { - if (!range.empty) - return { changes: [{ insert: open, from: range.from }, { insert: close, from: range.to }], - effects: closeBracketEffect.of(range.to + open.length), - range: EditorSelection.range(range.anchor + open.length, range.head + open.length) }; - let next = nextChar(state.doc, range.head); - if (!next || /\s/.test(next) || closeBefore.indexOf(next) > -1) - return { changes: { insert: open + close, from: range.head }, - effects: closeBracketEffect.of(range.head + open.length), - range: EditorSelection.cursor(range.head + open.length) }; - return { range: dont = range }; - }); - return dont ? null : state.update(changes, { - scrollIntoView: true, - userEvent: "input.type" - }); - } - function handleClose(state, _open, close) { - let dont = null, moved = state.selection.ranges.map(range => { - if (range.empty && nextChar(state.doc, range.head) == close) - return EditorSelection.cursor(range.head + close.length); - return dont = range; - }); - return dont ? null : state.update({ - selection: EditorSelection.create(moved, state.selection.mainIndex), - scrollIntoView: true, - effects: state.selection.ranges.map(({ from }) => skipBracketEffect.of(from)) - }); - } - // Handles cases where the open and close token are the same, and - // possibly triple quotes (as in `"""abc"""`-style quoting). - function handleSame(state, token, allowTriple) { - let dont = null, changes = state.changeByRange(range => { - if (!range.empty) - return { changes: [{ insert: token, from: range.from }, { insert: token, from: range.to }], - effects: closeBracketEffect.of(range.to + token.length), - range: EditorSelection.range(range.anchor + token.length, range.head + token.length) }; - let pos = range.head, next = nextChar(state.doc, pos); - if (next == token) { - if (nodeStart(state, pos)) { - return { changes: { insert: token + token, from: pos }, - effects: closeBracketEffect.of(pos + token.length), - range: EditorSelection.cursor(pos + token.length) }; - } - else if (closedBracketAt(state, pos)) { - let isTriple = allowTriple && state.sliceDoc(pos, pos + token.length * 3) == token + token + token; - return { range: EditorSelection.cursor(pos + token.length * (isTriple ? 3 : 1)), - effects: skipBracketEffect.of(pos) }; - } - } - else if (allowTriple && state.sliceDoc(pos - 2 * token.length, pos) == token + token && - nodeStart(state, pos - 2 * token.length)) { - return { changes: { insert: token + token + token + token, from: pos }, - effects: closeBracketEffect.of(pos + token.length), - range: EditorSelection.cursor(pos + token.length) }; - } - else if (state.charCategorizer(pos)(next) != CharCategory.Word) { - let prev = state.sliceDoc(pos - 1, pos); - if (prev != token && state.charCategorizer(pos)(prev) != CharCategory.Word && !probablyInString(state, pos, token)) - return { changes: { insert: token + token, from: pos }, - effects: closeBracketEffect.of(pos + token.length), - range: EditorSelection.cursor(pos + token.length) }; - } - return { range: dont = range }; - }); - return dont ? null : state.update(changes, { - scrollIntoView: true, - userEvent: "input.type" - }); - } - function nodeStart(state, pos) { - let tree = syntaxTree(state).resolveInner(pos + 1); - return tree.parent && tree.from == pos; - } - function probablyInString(state, pos, quoteToken) { - let node = syntaxTree(state).resolveInner(pos, -1); - for (let i = 0; i < 5; i++) { - if (state.sliceDoc(node.from, node.from + quoteToken.length) == quoteToken) - return true; - let parent = node.to == pos && node.parent; - if (!parent) - break; - node = parent; - } - return false; - } - - const panelConfig = /*@__PURE__*/Facet.define({ - combine(configs) { - let topContainer, bottomContainer; - for (let c of configs) { - topContainer = topContainer || c.topContainer; - bottomContainer = bottomContainer || c.bottomContainer; - } - return { topContainer, bottomContainer }; - } - }); - /** - Get the active panel created by the given constructor, if any. - This can be useful when you need access to your panels' DOM - structure. - */ - function getPanel(view, panel) { - let plugin = view.plugin(panelPlugin); - let index = plugin ? plugin.specs.indexOf(panel) : -1; - return index > -1 ? plugin.panels[index] : null; - } - const panelPlugin = /*@__PURE__*/ViewPlugin.fromClass(class { - constructor(view) { - this.input = view.state.facet(showPanel); - this.specs = this.input.filter(s => s); - this.panels = this.specs.map(spec => spec(view)); - let conf = view.state.facet(panelConfig); - this.top = new PanelGroup(view, true, conf.topContainer); - this.bottom = new PanelGroup(view, false, conf.bottomContainer); - this.top.sync(this.panels.filter(p => p.top)); - this.bottom.sync(this.panels.filter(p => !p.top)); - for (let p of this.panels) { - p.dom.classList.add("cm-panel"); - if (p.mount) - p.mount(); - } - } - update(update) { - let conf = update.state.facet(panelConfig); - if (this.top.container != conf.topContainer) { - this.top.sync([]); - this.top = new PanelGroup(update.view, true, conf.topContainer); - } - if (this.bottom.container != conf.bottomContainer) { - this.bottom.sync([]); - this.bottom = new PanelGroup(update.view, false, conf.bottomContainer); - } - this.top.syncClasses(); - this.bottom.syncClasses(); - let input = update.state.facet(showPanel); - if (input != this.input) { - let specs = input.filter(x => x); - let panels = [], top = [], bottom = [], mount = []; - for (let spec of specs) { - let known = this.specs.indexOf(spec), panel; - if (known < 0) { - panel = spec(update.view); - mount.push(panel); - } - else { - panel = this.panels[known]; - if (panel.update) - panel.update(update); - } - panels.push(panel); - (panel.top ? top : bottom).push(panel); - } - this.specs = specs; - this.panels = panels; - this.top.sync(top); - this.bottom.sync(bottom); - for (let p of mount) { - p.dom.classList.add("cm-panel"); - if (p.mount) - p.mount(); - } - } - else { - for (let p of this.panels) - if (p.update) - p.update(update); - } - } - destroy() { - this.top.sync([]); - this.bottom.sync([]); - } - }, { - provide: /*@__PURE__*/PluginField.scrollMargins.from(value => ({ top: value.top.scrollMargin(), bottom: value.bottom.scrollMargin() })) - }); - class PanelGroup { - constructor(view, top, container) { - this.view = view; - this.top = top; - this.container = container; - this.dom = undefined; - this.classes = ""; - this.panels = []; - this.syncClasses(); - } - sync(panels) { - for (let p of this.panels) - if (p.destroy && panels.indexOf(p) < 0) - p.destroy(); - this.panels = panels; - this.syncDOM(); - } - syncDOM() { - if (this.panels.length == 0) { - if (this.dom) { - this.dom.remove(); - this.dom = undefined; - } - return; - } - 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 parent = this.container || this.view.dom; - parent.insertBefore(this.dom, this.top ? parent.firstChild : null); - } - let curDOM = this.dom.firstChild; - for (let panel of this.panels) { - if (panel.dom.parentNode == this.dom) { - while (curDOM != panel.dom) - curDOM = rm(curDOM); - curDOM = curDOM.nextSibling; - } - else { - this.dom.insertBefore(panel.dom, curDOM); - } - } - while (curDOM) - curDOM = rm(curDOM); - } - 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) - return; - for (let cls of this.classes.split(" ")) - if (cls) - this.container.classList.remove(cls); - for (let cls of (this.classes = this.view.themeClasses).split(" ")) - if (cls) - this.container.classList.add(cls); - } - } - function rm(node) { - let next = node.nextSibling; - node.remove(); - return next; - } - const baseTheme$4 = /*@__PURE__*/EditorView.baseTheme({ - ".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" - } - }); - /** - Opening a panel is done by providing a constructor function for - the panel through this facet. (The panel is closed again when its - constructor is no longer provided.) Values of `null` are ignored. - */ - const showPanel = /*@__PURE__*/Facet.define({ - enables: [panelPlugin, baseTheme$4] - }); - - function crelt() { - var elt = arguments[0]; - if (typeof elt == "string") elt = document.createElement(elt); - var i = 1, next = arguments[1]; - if (next && typeof next == "object" && next.nodeType == null && !Array.isArray(next)) { - for (var name in next) if (Object.prototype.hasOwnProperty.call(next, name)) { - var value = next[name]; - if (typeof value == "string") elt.setAttribute(name, value); - else if (value != null) elt[name] = value; - } - i++; + /** + * Fetch python plugins from a filePath, saves it on the FS and import + * it as a module, executing any plugin define the module scope. + * + * @param interpreter - the interpreter that will execute the plugins + * @param filePath - path to the python file to fetch + */ + async fetchPythonPlugin(interpreter, filePath) { + const pathArr = filePath.split('/'); + const filename = pathArr.pop(); + // TODO: Would be probably be better to store plugins somewhere like /plugins/python/ or similar + await interpreter._remote.loadFromFile(filename, filePath); + //refresh module cache before trying to import module files into interpreter + interpreter._remote.invalidate_module_path_cache(); + const modulename = filePath.replace(/^.*[\\/]/, '').replace('.py', ''); + console.log(`importing ${modulename}`); + // TODO: This is very specific to Pyodide API and will not work for other interpreters, + // when we add support for other interpreters we will need to move this to the + // interpreter API level and allow each one to implement it in its own way + const module = interpreter._remote.interface.pyimport(modulename); + if (typeof module.plugin !== 'undefined') { + const py_plugin = module.plugin; + py_plugin.init(this); + this.plugins.addPythonPlugin(py_plugin); + } + else { + logger.error(`Cannot find plugin on Python module ${modulename}! Python plugins \ +modules must contain a "plugin" attribute. For more information check the plugins documentation.`); + } } - for (; i < arguments.length; i++) add(elt, arguments[i]); - return elt - } - - function add(elt, child) { - if (typeof child == "string") { - elt.appendChild(document.createTextNode(child)); - } else if (child == null) ; else if (child.nodeType != null) { - elt.appendChild(child); - } else if (Array.isArray(child)) { - for (var i = 0; i < child.length; i++) add(elt, child[i]); - } else { - throw new RangeError("Unsupported child node: " + child) + // lifecycle (7) + executeScripts(interpreter) { + // make_PyScript takes an interpreter and a PyScriptApp as arguments + this.PyScript = make_PyScript(interpreter, this); + customElements.define('py-script', this.PyScript); } - } - - const basicNormalize = typeof String.prototype.normalize == "function" - ? x => x.normalize("NFKD") : x => x; - /** - A search cursor provides an iterator over text matches in a - document. - */ - class SearchCursor { - /** - Create a text cursor. The query is the search string, `from` to - `to` provides the region to search. - - When `normalize` is given, it will be called, on both the query - string and the content it is matched against, before comparing. - You can, for example, create a case-insensitive search by - passing `s => s.toLowerCase()`. - - Text is always normalized with - [`.normalize("NFKD")`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/normalize) - (when supported). - */ - constructor(text, query, from = 0, to = text.length, normalize) { - /** - The current match (only holds a meaningful value after - [`next`](https://codemirror.net/6/docs/ref/#search.SearchCursor.next) has been called and when - `done` is false). - */ - this.value = { from: 0, to: 0 }; - /** - Whether the end of the iterated region has been reached. - */ - this.done = false; - this.matches = []; - this.buffer = ""; - this.bufferPos = 0; - this.iter = text.iterRange(from, to); - this.bufferStart = from; - this.normalize = normalize ? x => normalize(basicNormalize(x)) : basicNormalize; - this.query = this.normalize(query); - } - peek() { - if (this.bufferPos == this.buffer.length) { - this.bufferStart += this.buffer.length; - this.iter.next(); - if (this.iter.done) - return -1; - this.bufferPos = 0; - this.buffer = this.iter.value; - } - return codePointAt(this.buffer, this.bufferPos); - } - /** - Look for the next match. Updates the iterator's - [`value`](https://codemirror.net/6/docs/ref/#search.SearchCursor.value) and - [`done`](https://codemirror.net/6/docs/ref/#search.SearchCursor.done) properties. Should be called - at least once before using the cursor. - */ - next() { - while (this.matches.length) - this.matches.pop(); - return this.nextOverlapping(); - } - /** - The `next` method will ignore matches that partially overlap a - previous match. This method behaves like `next`, but includes - such matches. - */ - nextOverlapping() { - for (;;) { - let next = this.peek(); - if (next < 0) { - this.done = true; - return this; - } - let str = fromCodePoint(next), start = this.bufferStart + this.bufferPos; - this.bufferPos += codePointSize(next); - let norm = this.normalize(str); - for (let i = 0, pos = start;; i++) { - let code = norm.charCodeAt(i); - let match = this.match(code, pos); - if (match) { - this.value = match; - return this; - } - if (i == norm.length - 1) - break; - if (pos == start && i < str.length && str.charCodeAt(i) == code) - pos++; - } - } - } - match(code, pos) { - let match = null; - for (let i = 0; i < this.matches.length; i += 2) { - let index = this.matches[i], keep = false; - if (this.query.charCodeAt(index) == code) { - if (index == this.query.length - 1) { - match = { from: this.matches[i + 1], to: pos + 1 }; - } - else { - this.matches[i]++; - keep = true; - } - } - if (!keep) { - this.matches.splice(i, 2); - i -= 2; - } - } - if (this.query.charCodeAt(0) == code) { - if (this.query.length == 1) - match = { from: pos, to: pos + 1 }; - else - this.matches.push(1, pos); - } - return match; - } - } - if (typeof Symbol != "undefined") - SearchCursor.prototype[Symbol.iterator] = function () { return this; }; - - const empty = { from: -1, to: -1, match: /*@__PURE__*//.*/.exec("") }; - const baseFlags = "gm" + (/x/.unicode == null ? "" : "u"); - /** - This class is similar to [`SearchCursor`](https://codemirror.net/6/docs/ref/#search.SearchCursor) - but searches for a regular expression pattern instead of a plain - string. - */ - class RegExpCursor { - /** - Create a cursor that will search the given range in the given - document. `query` should be the raw pattern (as you'd pass it to - `new RegExp`). - */ - constructor(text, query, options, from = 0, to = text.length) { - this.to = to; - this.curLine = ""; - /** - Set to `true` when the cursor has reached the end of the search - range. - */ - this.done = false; - /** - Will contain an object with the extent of the match and the - match object when [`next`](https://codemirror.net/6/docs/ref/#search.RegExpCursor.next) - sucessfully finds a match. - */ - this.value = empty; - if (/\\[sWDnr]|\n|\r|\[\^/.test(query)) - return new MultilineRegExpCursor(text, query, options, from, to); - this.re = new RegExp(query, baseFlags + ((options === null || options === void 0 ? void 0 : options.ignoreCase) ? "i" : "")); - this.iter = text.iter(); - let startLine = text.lineAt(from); - this.curLineStart = startLine.from; - this.matchPos = from; - this.getLine(this.curLineStart); - } - getLine(skip) { - this.iter.next(skip); - if (this.iter.lineBreak) { - this.curLine = ""; - } - else { - this.curLine = this.iter.value; - if (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; - if (this.curLineStart > this.to) - this.curLine = ""; - else - this.getLine(0); - } - /** - Move to the next match, if there is one. - */ - next() { - for (let off = this.matchPos - this.curLineStart;;) { - this.re.lastIndex = off; - let match = this.matchPos <= this.to && this.re.exec(this.curLine); - if (match) { - let from = this.curLineStart + match.index, to = from + match[0].length; - this.matchPos = to + (from == to ? 1 : 0); - if (from == this.curLine.length) - this.nextLine(); - if (from < to || from > this.value.to) { - this.value = { from, to, match }; - return this; - } - off = this.matchPos - this.curLineStart; - } - else if (this.curLineStart + this.curLine.length < this.to) { - this.nextLine(); - off = 0; - } - else { - this.done = true; - return this; - } - } - } - } - const flattened = /*@__PURE__*/new WeakMap(); - // Reusable (partially) flattened document strings - class FlattenedDoc { - constructor(from, text) { - this.from = from; - this.text = text; - } - get to() { return this.from + this.text.length; } - static get(doc, from, to) { - let cached = flattened.get(doc); - if (!cached || cached.from >= to || cached.to <= from) { - let flat = new FlattenedDoc(from, doc.sliceString(from, to)); - flattened.set(doc, flat); - return flat; - } - if (cached.from == from && cached.to == to) - return cached; - let { text, from: cachedFrom } = cached; - if (cachedFrom > from) { - text = doc.sliceString(from, cachedFrom) + text; - cachedFrom = from; - } - if (cached.to < to) - text += doc.sliceString(cached.to, to); - flattened.set(doc, new FlattenedDoc(cachedFrom, text)); - return new FlattenedDoc(from, text.slice(from - cachedFrom, to - cachedFrom)); - } - } - class MultilineRegExpCursor { - constructor(text, query, options, from, to) { - this.text = text; - this.to = to; - this.done = false; - this.value = empty; - this.matchPos = from; - this.re = new RegExp(query, baseFlags + ((options === null || options === void 0 ? void 0 : options.ignoreCase) ? "i" : "")); - this.flat = FlattenedDoc.get(text, from, this.chunkEnd(from + 5000 /* Base */)); - } - chunkEnd(pos) { - return pos >= this.to ? this.to : this.text.lineAt(pos).to; - } - next() { - for (;;) { - let off = this.re.lastIndex = this.matchPos - this.flat.from; - let match = this.re.exec(this.flat.text); - // Skip empty matches directly after the last match - if (match && !match[0] && match.index == off) { - this.re.lastIndex = off + 1; - match = this.re.exec(this.flat.text); - } - // If a match goes almost to the end of a noncomplete chunk, try - // again, since it'll likely be able to match more - if (match && this.flat.to < this.to && match.index + match[0].length > this.flat.text.length - 10) - match = null; - if (match) { - let from = this.flat.from + match.index, to = from + match[0].length; - this.value = { from, to, match }; - this.matchPos = to + (from == to ? 1 : 0); - return this; - } - else { - if (this.flat.to == this.to) { - this.done = true; - return this; - } - // Grow the flattened doc - this.flat = FlattenedDoc.get(this.text, this.flat.from, this.chunkEnd(this.flat.from + this.flat.text.length * 2)); - } - } - } - } - if (typeof Symbol != "undefined") { - RegExpCursor.prototype[Symbol.iterator] = MultilineRegExpCursor.prototype[Symbol.iterator] = - function () { return this; }; - } - function validRegExp(source) { - try { - new RegExp(source, baseFlags); - return true; - } - catch (_a) { - return false; - } - } - - function createLineDialog(view) { - let input = crelt("input", { class: "cm-textfield", name: "line" }); - let dom = crelt("form", { - class: "cm-gotoLine", - onkeydown: (event) => { - if (event.keyCode == 27) { // Escape - event.preventDefault(); - view.dispatch({ effects: dialogEffect.of(false) }); - view.focus(); - } - else if (event.keyCode == 13) { // Enter - event.preventDefault(); - go(); - } - }, - onsubmit: (event) => { - event.preventDefault(); - go(); - } - }, crelt("label", view.state.phrase("Go to line"), ": ", input), " ", crelt("button", { class: "cm-button", type: "submit" }, view.state.phrase("go"))); - function go() { - let match = /^([+-])?(\d+)?(:\d+)?(%)?$/.exec(input.value); - if (!match) - return; - let { state } = view, startLine = state.doc.lineAt(state.selection.main.head); - let [, sign, ln, cl, percent] = match; - let col = cl ? +cl.slice(1) : 0; - let line = ln ? +ln : startLine.number; - if (ln && percent) { - let pc = line / 100; - if (sign) - pc = pc * (sign == "-" ? -1 : 1) + (startLine.number / state.doc.lines); - line = Math.round(state.doc.lines * pc); - } - else if (ln && sign) { - line = line * (sign == "-" ? -1 : 1) + startLine.number; - } - let docLine = state.doc.line(Math.max(1, Math.min(state.doc.lines, line))); - view.dispatch({ - effects: dialogEffect.of(false), - selection: EditorSelection.cursor(docLine.from + Math.max(0, Math.min(col, docLine.length))), - scrollIntoView: true - }); - view.focus(); - } - return { dom, pos: -10 }; - } - const dialogEffect = /*@__PURE__*/StateEffect.define(); - const dialogField = /*@__PURE__*/StateField.define({ - create() { return true; }, - update(value, tr) { - for (let e of tr.effects) - if (e.is(dialogEffect)) - value = e.value; - return value; - }, - provide: f => showPanel.from(f, val => val ? createLineDialog : null) - }); - /** - Command that shows a dialog asking the user for a line number, and - when a valid position is provided, moves the cursor to that line. - - Supports line numbers, relative line offsets prefixed with `+` or - `-`, document percentages suffixed with `%`, and an optional - column position by adding `:` and a second number after the line - number. - - The dialog can be styled with the `panel.gotoLine` theme - selector. - */ - const gotoLine = view => { - let panel = getPanel(view, createLineDialog); - if (!panel) { - let effects = [dialogEffect.of(true)]; - if (view.state.field(dialogField, false) == null) - effects.push(StateEffect.appendConfig.of([dialogField, baseTheme$1$1])); - view.dispatch({ effects }); - panel = getPanel(view, createLineDialog); - } - if (panel) - panel.dom.querySelector("input").focus(); - return true; - }; - const baseTheme$1$1 = /*@__PURE__*/EditorView.baseTheme({ - ".cm-panel.cm-gotoLine": { - padding: "2px 6px 4px", - "& label": { fontSize: "80%" } - } - }); - - const defaultHighlightOptions = { - highlightWordAroundCursor: false, - minSelectionLength: 1, - maxMatches: 100, - wholeWords: true - }; - const highlightConfig = /*@__PURE__*/Facet.define({ - combine(options) { - return combineConfig(options, defaultHighlightOptions, { - highlightWordAroundCursor: (a, b) => a || b, - minSelectionLength: Math.min, - maxMatches: Math.min - }); - } - }); - /** - This extension highlights text that matches the selection. It uses - the `"cm-selectionMatch"` class for the highlighting. When - `highlightWordAroundCursor` is enabled, the word at the cursor - itself will be highlighted with `"cm-selectionMatch-main"`. - */ - function highlightSelectionMatches(options) { - let ext = [defaultTheme, matchHighlighter]; - if (options) - ext.push(highlightConfig.of(options)); - return ext; - } - const matchDeco = /*@__PURE__*/Decoration.mark({ class: "cm-selectionMatch" }); - const mainMatchDeco = /*@__PURE__*/Decoration.mark({ class: "cm-selectionMatch cm-selectionMatch-main" }); - // Whether the characters directly outside the given positions are non-word characters - function insideWordBoundaries(check, state, from, to) { - return (from == 0 || check(state.sliceDoc(from - 1, from)) != CharCategory.Word) && - (to == state.doc.length || check(state.sliceDoc(to, to + 1)) != CharCategory.Word); - } - // Whether the characters directly at the given positions are word characters - function insideWord(check, state, from, to) { - return check(state.sliceDoc(from, from + 1)) == CharCategory.Word - && check(state.sliceDoc(to - 1, to)) == CharCategory.Word; - } - const matchHighlighter = /*@__PURE__*/ViewPlugin.fromClass(class { - constructor(view) { - this.decorations = this.getDeco(view); - } - update(update) { - if (update.selectionSet || update.docChanged || update.viewportChanged) - this.decorations = this.getDeco(update.view); - } - getDeco(view) { - let conf = view.state.facet(highlightConfig); - let { state } = view, sel = state.selection; - if (sel.ranges.length > 1) - return Decoration.none; - let range = sel.main, query, check = null; - if (range.empty) { - if (!conf.highlightWordAroundCursor) - return Decoration.none; - let word = state.wordAt(range.head); - if (!word) - return Decoration.none; - check = state.charCategorizer(range.head); - query = state.sliceDoc(word.from, word.to); - } - else { - let len = range.to - range.from; - if (len < conf.minSelectionLength || len > 200) - return Decoration.none; - if (conf.wholeWords) { - query = state.sliceDoc(range.from, range.to); // TODO: allow and include leading/trailing space? - check = state.charCategorizer(range.head); - if (!(insideWordBoundaries(check, state, range.from, range.to) - && insideWord(check, state, range.from, range.to))) - return Decoration.none; - } - else { - query = state.sliceDoc(range.from, range.to).trim(); - if (!query) - return Decoration.none; - } - } - let deco = []; - for (let part of view.visibleRanges) { - let cursor = new SearchCursor(state.doc, query, part.from, part.to); - while (!cursor.next().done) { - let { from, to } = cursor.value; - if (!check || insideWordBoundaries(check, state, from, to)) { - if (range.empty && from <= range.from && to >= range.to) - deco.push(mainMatchDeco.range(from, to)); - else if (from >= range.to || to <= range.from) - deco.push(matchDeco.range(from, to)); - if (deco.length > conf.maxMatches) - return Decoration.none; - } - } - } - return Decoration.set(deco); - } - }, { - decorations: v => v.decorations - }); - const defaultTheme = /*@__PURE__*/EditorView.baseTheme({ - ".cm-selectionMatch": { backgroundColor: "#99ff7780" }, - ".cm-searchMatch .cm-selectionMatch": { backgroundColor: "transparent" } - }); - // Select the words around the cursors. - const selectWord = ({ state, dispatch }) => { - let { selection } = state; - let newSel = EditorSelection.create(selection.ranges.map(range => state.wordAt(range.head) || EditorSelection.cursor(range.head)), selection.mainIndex); - if (newSel.eq(selection)) - return false; - dispatch(state.update({ selection: newSel })); - return true; - }; - // Find next occurrence of query relative to last cursor. Wrap around - // the document if there are no more matches. - function findNextOccurrence(state, query) { - let { main, ranges } = state.selection; - let word = state.wordAt(main.head), fullWord = word && word.from == main.from && word.to == main.to; - for (let cycled = false, cursor = new SearchCursor(state.doc, query, ranges[ranges.length - 1].to);;) { - cursor.next(); - if (cursor.done) { - if (cycled) - return null; - cursor = new SearchCursor(state.doc, query, 0, Math.max(0, ranges[ranges.length - 1].from - 1)); - cycled = true; - } - else { - if (cycled && ranges.some(r => r.from == cursor.value.from)) - continue; - if (fullWord) { - let word = state.wordAt(cursor.value.from); - if (!word || word.from != cursor.value.from || word.to != cursor.value.to) - continue; - } - return cursor.value; - } - } - } - /** - Select next occurrence of the current selection. - Expand selection to the word when selection range is empty. - */ - const selectNextOccurrence = ({ state, dispatch }) => { - let { ranges } = state.selection; - if (ranges.some(sel => sel.from === sel.to)) - return selectWord({ state, dispatch }); - let searchedText = state.sliceDoc(ranges[0].from, ranges[0].to); - if (state.selection.ranges.some(r => state.sliceDoc(r.from, r.to) != searchedText)) - return false; - let range = findNextOccurrence(state, searchedText); - if (!range) - return false; - dispatch(state.update({ - selection: state.selection.addRange(EditorSelection.range(range.from, range.to), false), - effects: EditorView.scrollIntoView(range.to) - })); - return true; - }; - - const searchConfigFacet = /*@__PURE__*/Facet.define({ - combine(configs) { - var _a; - return { - top: configs.reduce((val, conf) => val !== null && val !== void 0 ? val : conf.top, undefined) || false, - caseSensitive: configs.reduce((val, conf) => val !== null && val !== void 0 ? val : (conf.caseSensitive || conf.matchCase), undefined) || false, - createPanel: ((_a = configs.find(c => c.createPanel)) === null || _a === void 0 ? void 0 : _a.createPanel) || (view => new SearchPanel(view)) - }; - } - }); - /** - A search query. Part of the editor's search state. - */ - class SearchQuery { - /** - Create a query object. - */ - constructor(config) { - this.search = config.search; - this.caseSensitive = !!config.caseSensitive; - this.regexp = !!config.regexp; - this.replace = config.replace || ""; - this.valid = !!this.search && (!this.regexp || validRegExp(this.search)); - this.unquoted = this.search.replace(/\\([nrt\\])/g, (_, ch) => ch == "n" ? "\n" : ch == "r" ? "\r" : ch == "t" ? "\t" : "\\"); - } - /** - Compare this query to another query. - */ - eq(other) { - return this.search == other.search && this.replace == other.replace && - this.caseSensitive == other.caseSensitive && this.regexp == other.regexp; - } - /** - @internal - */ - create() { - return this.regexp ? new RegExpQuery(this) : new StringQuery(this); - } - getCursor(doc, from = 0, to = doc.length) { - return this.regexp ? regexpCursor(this, doc, from, to) : stringCursor(this, doc, from, to); - } - } - class QueryType { - constructor(spec) { - this.spec = spec; - } - } - function stringCursor(spec, doc, from, to) { - return new SearchCursor(doc, spec.unquoted, from, to, spec.caseSensitive ? undefined : x => x.toLowerCase()); - } - class StringQuery extends QueryType { - constructor(spec) { - super(spec); - } - nextMatch(doc, curFrom, curTo) { - let cursor = stringCursor(this.spec, doc, curTo, doc.length).nextOverlapping(); - if (cursor.done) - cursor = stringCursor(this.spec, doc, 0, curFrom).nextOverlapping(); - return cursor.done ? null : cursor.value; - } - // Searching in reverse is, rather than implementing inverted search - // cursor, done by scanning chunk after chunk forward. - prevMatchInRange(doc, from, to) { - for (let pos = to;;) { - let start = Math.max(from, pos - 10000 /* ChunkSize */ - this.spec.unquoted.length); - let cursor = stringCursor(this.spec, doc, start, pos), range = null; - while (!cursor.nextOverlapping().done) - range = cursor.value; - if (range) - return range; - if (start == from) - return null; - pos -= 10000 /* ChunkSize */; - } - } - prevMatch(doc, curFrom, curTo) { - return this.prevMatchInRange(doc, 0, curFrom) || - this.prevMatchInRange(doc, curTo, doc.length); - } - getReplacement(_result) { return this.spec.replace; } - matchAll(doc, limit) { - let cursor = stringCursor(this.spec, doc, 0, doc.length), ranges = []; - while (!cursor.next().done) { - if (ranges.length >= limit) - return null; - ranges.push(cursor.value); - } - return ranges; - } - highlight(doc, from, to, add) { - let cursor = stringCursor(this.spec, doc, Math.max(0, from - this.spec.unquoted.length), Math.min(to + this.spec.unquoted.length, doc.length)); - while (!cursor.next().done) - add(cursor.value.from, cursor.value.to); - } - } - function regexpCursor(spec, doc, from, to) { - return new RegExpCursor(doc, spec.search, spec.caseSensitive ? undefined : { ignoreCase: true }, from, to); - } - class RegExpQuery extends QueryType { - nextMatch(doc, curFrom, curTo) { - let cursor = regexpCursor(this.spec, doc, curTo, doc.length).next(); - if (cursor.done) - cursor = regexpCursor(this.spec, doc, 0, curFrom).next(); - return cursor.done ? null : cursor.value; - } - prevMatchInRange(doc, from, to) { - for (let size = 1;; size++) { - let start = Math.max(from, to - size * 10000 /* ChunkSize */); - let cursor = regexpCursor(this.spec, doc, start, to), range = null; - while (!cursor.next().done) - range = cursor.value; - if (range && (start == from || range.from > start + 10)) - return range; - if (start == from) - return null; - } - } - prevMatch(doc, curFrom, curTo) { - return this.prevMatchInRange(doc, 0, curFrom) || - this.prevMatchInRange(doc, curTo, doc.length); - } - getReplacement(result) { - return this.spec.replace.replace(/\$([$&\d+])/g, (m, i) => i == "$" ? "$" - : i == "&" ? result.match[0] - : i != "0" && +i < result.match.length ? result.match[i] - : m); - } - matchAll(doc, limit) { - let cursor = regexpCursor(this.spec, doc, 0, doc.length), ranges = []; - while (!cursor.next().done) { - if (ranges.length >= limit) - return null; - ranges.push(cursor.value); - } - return ranges; - } - highlight(doc, from, to, add) { - let cursor = regexpCursor(this.spec, doc, Math.max(0, from - 250 /* HighlightMargin */), Math.min(to + 250 /* HighlightMargin */, doc.length)); - while (!cursor.next().done) - add(cursor.value.from, cursor.value.to); - } - } - /** - A state effect that updates the current search query. Note that - this only has an effect if the search state has been initialized - (by including [`search`](https://codemirror.net/6/docs/ref/#search.search) in your configuration or - by running [`openSearchPanel`](https://codemirror.net/6/docs/ref/#search.openSearchPanel) at least - once). - */ - const setSearchQuery = /*@__PURE__*/StateEffect.define(); - const togglePanel$1 = /*@__PURE__*/StateEffect.define(); - const searchState = /*@__PURE__*/StateField.define({ - create(state) { - return new SearchState(defaultQuery(state).create(), null); - }, - update(value, tr) { - for (let effect of tr.effects) { - if (effect.is(setSearchQuery)) - value = new SearchState(effect.value.create(), value.panel); - else if (effect.is(togglePanel$1)) - value = new SearchState(value.query, effect.value ? createSearchPanel : null); - } - return value; - }, - provide: f => showPanel.from(f, val => val.panel) - }); - class SearchState { - constructor(query, panel) { - this.query = query; - this.panel = panel; - } - } - const matchMark = /*@__PURE__*/Decoration.mark({ class: "cm-searchMatch" }), selectedMatchMark = /*@__PURE__*/Decoration.mark({ class: "cm-searchMatch cm-searchMatch-selected" }); - const searchHighlighter = /*@__PURE__*/ViewPlugin.fromClass(class { - constructor(view) { - this.view = view; - this.decorations = this.highlight(view.state.field(searchState)); - } - update(update) { - let state = update.state.field(searchState); - if (state != update.startState.field(searchState) || update.docChanged || update.selectionSet || update.viewportChanged) - this.decorations = this.highlight(state); - } - highlight({ query, panel }) { - if (!panel || !query.spec.valid) - return Decoration.none; - let { view } = this; - let builder = new RangeSetBuilder(); - for (let i = 0, ranges = view.visibleRanges, l = ranges.length; i < l; i++) { - let { from, to } = ranges[i]; - while (i < l - 1 && to > ranges[i + 1].from - 2 * 250 /* HighlightMargin */) - to = ranges[++i].to; - query.highlight(view.state.doc, from, to, (from, to) => { - let selected = view.state.selection.ranges.some(r => r.from == from && r.to == to); - builder.add(from, to, selected ? selectedMatchMark : matchMark); - }); - } - return builder.finish(); - } - }, { - decorations: v => v.decorations - }); - function searchCommand(f) { - return view => { - let state = view.state.field(searchState, false); - return state && state.query.spec.valid ? f(view, state) : openSearchPanel(view); - }; - } - /** - Open the search panel if it isn't already open, and move the - selection to the first match after the current main selection. - Will wrap around to the start of the document when it reaches the - end. - */ - const findNext = /*@__PURE__*/searchCommand((view, { query }) => { - let { from, to } = view.state.selection.main; - let next = query.nextMatch(view.state.doc, from, to); - if (!next || next.from == from && next.to == to) - return false; - view.dispatch({ - selection: { anchor: next.from, head: next.to }, - scrollIntoView: true, - effects: announceMatch(view, next), - userEvent: "select.search" - }); - return true; - }); - /** - Move the selection to the previous instance of the search query, - before the current main selection. Will wrap past the start - of the document to start searching at the end again. - */ - const findPrevious = /*@__PURE__*/searchCommand((view, { query }) => { - let { state } = view, { from, to } = state.selection.main; - let range = query.prevMatch(state.doc, from, to); - if (!range) - return false; - view.dispatch({ - selection: { anchor: range.from, head: range.to }, - scrollIntoView: true, - effects: announceMatch(view, range), - userEvent: "select.search" - }); - return true; - }); - /** - Select all instances of the search query. - */ - const selectMatches = /*@__PURE__*/searchCommand((view, { query }) => { - let ranges = query.matchAll(view.state.doc, 1000); - if (!ranges || !ranges.length) - return false; - view.dispatch({ - selection: EditorSelection.create(ranges.map(r => EditorSelection.range(r.from, r.to))), - userEvent: "select.search.matches" - }); - return true; - }); - /** - Select all instances of the currently selected text. - */ - const selectSelectionMatches = ({ state, dispatch }) => { - let sel = state.selection; - if (sel.ranges.length > 1 || sel.main.empty) - return false; - let { from, to } = sel.main; - let ranges = [], main = 0; - for (let cur = new SearchCursor(state.doc, state.sliceDoc(from, to)); !cur.next().done;) { - if (ranges.length > 1000) - return false; - if (cur.value.from == from) - main = ranges.length; - ranges.push(EditorSelection.range(cur.value.from, cur.value.to)); - } - dispatch(state.update({ - selection: EditorSelection.create(ranges, main), - userEvent: "select.search.matches" - })); - return true; - }; - /** - Replace the current match of the search query. - */ - const replaceNext = /*@__PURE__*/searchCommand((view, { query }) => { - let { state } = view, { from, to } = state.selection.main; - if (state.readOnly) - return false; - let next = query.nextMatch(state.doc, from, from); - if (!next) - return false; - let changes = [], selection, replacement; - if (next.from == from && next.to == to) { - replacement = state.toText(query.getReplacement(next)); - changes.push({ from: next.from, to: next.to, insert: replacement }); - next = query.nextMatch(state.doc, next.from, next.to); - } - if (next) { - let off = changes.length == 0 || changes[0].from >= next.to ? 0 : next.to - next.from - replacement.length; - selection = { anchor: next.from - off, head: next.to - off }; - } - view.dispatch({ - changes, selection, - scrollIntoView: !!selection, - effects: next ? announceMatch(view, next) : undefined, - userEvent: "input.replace" - }); - return true; - }); - /** - Replace all instances of the search query with the given - replacement. - */ - const replaceAll = /*@__PURE__*/searchCommand((view, { query }) => { - if (view.state.readOnly) - return false; - let changes = query.matchAll(view.state.doc, 1e9).map(match => { - let { from, to } = match; - return { from, to, insert: query.getReplacement(match) }; - }); - if (!changes.length) - return false; - view.dispatch({ - changes, - userEvent: "input.replace.all" - }); - return true; - }); - function createSearchPanel(view) { - return view.state.facet(searchConfigFacet).createPanel(view); - } - function defaultQuery(state, fallback) { - var _a; - let sel = state.selection.main; - let selText = sel.empty || sel.to > sel.from + 100 ? "" : state.sliceDoc(sel.from, sel.to); - let caseSensitive = (_a = fallback === null || fallback === void 0 ? void 0 : fallback.caseSensitive) !== null && _a !== void 0 ? _a : state.facet(searchConfigFacet).caseSensitive; - return fallback && !selText ? fallback : new SearchQuery({ search: selText.replace(/\n/g, "\\n"), caseSensitive }); - } - /** - Make sure the search panel is open and focused. - */ - const openSearchPanel = view => { - let state = view.state.field(searchState, false); - if (state && state.panel) { - let panel = getPanel(view, createSearchPanel); - if (!panel) - return false; - let searchInput = panel.dom.querySelector("[name=search]"); - if (searchInput != view.root.activeElement) { - let query = defaultQuery(view.state, state.query.spec); - if (query.valid) - view.dispatch({ effects: setSearchQuery.of(query) }); - searchInput.focus(); - searchInput.select(); - } - } - else { - view.dispatch({ effects: [ - togglePanel$1.of(true), - state ? setSearchQuery.of(defaultQuery(view.state, state.query.spec)) : StateEffect.appendConfig.of(searchExtensions) - ] }); - } - return true; - }; - /** - Close the search panel. - */ - const closeSearchPanel = view => { - let state = view.state.field(searchState, false); - if (!state || !state.panel) - return false; - let panel = getPanel(view, createSearchPanel); - if (panel && panel.dom.contains(view.root.activeElement)) - view.focus(); - view.dispatch({ effects: togglePanel$1.of(false) }); - return true; - }; - /** - Default search-related key bindings. - - - Mod-f: [`openSearchPanel`](https://codemirror.net/6/docs/ref/#search.openSearchPanel) - - F3, Mod-g: [`findNext`](https://codemirror.net/6/docs/ref/#search.findNext) - - Shift-F3, Shift-Mod-g: [`findPrevious`](https://codemirror.net/6/docs/ref/#search.findPrevious) - - Alt-g: [`gotoLine`](https://codemirror.net/6/docs/ref/#search.gotoLine) - - Mod-d: [`selectNextOccurrence`](https://codemirror.net/6/docs/ref/#search.selectNextOccurrence) - */ - const searchKeymap = [ - { key: "Mod-f", run: openSearchPanel, scope: "editor search-panel" }, - { key: "F3", run: findNext, shift: findPrevious, scope: "editor search-panel", preventDefault: true }, - { key: "Mod-g", run: findNext, shift: findPrevious, scope: "editor search-panel", preventDefault: true }, - { key: "Escape", run: closeSearchPanel, scope: "editor search-panel" }, - { key: "Mod-Shift-l", run: selectSelectionMatches }, - { key: "Alt-g", run: gotoLine }, - { key: "Mod-d", run: selectNextOccurrence, preventDefault: true }, - ]; - class SearchPanel { - constructor(view) { - this.view = view; - let query = this.query = view.state.field(searchState).query.spec; - this.commit = this.commit.bind(this); - this.searchField = crelt("input", { - value: query.search, - placeholder: phrase(view, "Find"), - "aria-label": phrase(view, "Find"), - class: "cm-textfield", - name: "search", - onchange: this.commit, - onkeyup: this.commit - }); - this.replaceField = crelt("input", { - value: query.replace, - placeholder: phrase(view, "Replace"), - "aria-label": phrase(view, "Replace"), - class: "cm-textfield", - name: "replace", - onchange: this.commit, - onkeyup: this.commit - }); - this.caseField = crelt("input", { - type: "checkbox", - name: "case", - checked: query.caseSensitive, - onchange: this.commit - }); - this.reField = crelt("input", { - type: "checkbox", - name: "re", - checked: query.regexp, - onchange: this.commit - }); - function button(name, onclick, content) { - return crelt("button", { class: "cm-button", name, onclick, type: "button" }, content); - } - this.dom = crelt("div", { onkeydown: (e) => this.keydown(e), class: "cm-search" }, [ - this.searchField, - button("next", () => findNext(view), [phrase(view, "next")]), - button("prev", () => findPrevious(view), [phrase(view, "previous")]), - button("select", () => selectMatches(view), [phrase(view, "all")]), - crelt("label", null, [this.caseField, phrase(view, "match case")]), - crelt("label", null, [this.reField, phrase(view, "regexp")]), - ...view.state.readOnly ? [] : [ - crelt("br"), - this.replaceField, - button("replace", () => replaceNext(view), [phrase(view, "replace")]), - button("replaceAll", () => replaceAll(view), [phrase(view, "replace all")]), - crelt("button", { - name: "close", - onclick: () => closeSearchPanel(view), - "aria-label": phrase(view, "close"), - type: "button" - }, ["×"]) - ] - ]); - } - commit() { - let query = new SearchQuery({ - search: this.searchField.value, - caseSensitive: this.caseField.checked, - regexp: this.reField.checked, - replace: this.replaceField.value - }); - if (!query.eq(this.query)) { - this.query = query; - this.view.dispatch({ effects: setSearchQuery.of(query) }); - } - } - keydown(e) { - if (runScopeHandlers(this.view, e, "search-panel")) { - e.preventDefault(); - } - else if (e.keyCode == 13 && e.target == this.searchField) { - e.preventDefault(); - (e.shiftKey ? findPrevious : findNext)(this.view); - } - else if (e.keyCode == 13 && e.target == this.replaceField) { - e.preventDefault(); - replaceNext(this.view); - } - } - update(update) { - for (let tr of update.transactions) - for (let effect of tr.effects) { - if (effect.is(setSearchQuery) && !effect.value.eq(this.query)) - this.setQuery(effect.value); - } - } - setQuery(query) { - this.query = query; - this.searchField.value = query.search; - this.replaceField.value = query.replace; - this.caseField.checked = query.caseSensitive; - this.reField.checked = query.regexp; - } - mount() { - this.searchField.select(); - } - get pos() { return 80; } - get top() { return this.view.state.facet(searchConfigFacet).top; } - } - function phrase(view, phrase) { return view.state.phrase(phrase); } - const AnnounceMargin = 30; - const Break = /[\s\.,:;?!]/; - function announceMatch(view, { from, to }) { - let lineStart = view.state.doc.lineAt(from).from, lineEnd = view.state.doc.lineAt(to).to; - let start = Math.max(lineStart, from - AnnounceMargin), end = Math.min(lineEnd, to + AnnounceMargin); - let text = view.state.sliceDoc(start, end); - if (start != lineStart) { - for (let i = 0; i < AnnounceMargin; i++) - if (!Break.test(text[i + 1]) && Break.test(text[i])) { - text = text.slice(i); - break; - } - } - if (end != lineEnd) { - for (let i = text.length - 1; i > text.length - AnnounceMargin; i--) - if (!Break.test(text[i - 1]) && Break.test(text[i])) { - text = text.slice(0, i); - break; - } - } - return EditorView.announce.of(`${view.state.phrase("current match")}. ${text} ${view.state.phrase("on line")} ${view.state.doc.lineAt(from).number}`); - } - const baseTheme$3 = /*@__PURE__*/EditorView.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" } - }); - const searchExtensions = [ - searchState, - /*@__PURE__*/Prec.lowest(searchHighlighter), - baseTheme$3 - ]; - - const ios = typeof navigator != "undefined" && - !/*@__PURE__*//Edge\/(\d+)/.exec(navigator.userAgent) && /*@__PURE__*//Apple Computer/.test(navigator.vendor) && - (/*@__PURE__*//Mobile\/\w+/.test(navigator.userAgent) || navigator.maxTouchPoints > 2); - const Outside = "-10000px"; - class TooltipViewManager { - constructor(view, facet, createTooltipView) { - this.facet = facet; - this.createTooltipView = createTooltipView; - this.input = view.state.facet(facet); - this.tooltips = this.input.filter(t => t); - this.tooltipViews = this.tooltips.map(createTooltipView); - } - update(update) { - let input = update.state.facet(this.facet); - let tooltips = input.filter(x => x); - if (input === this.input) { - for (let t of this.tooltipViews) - if (t.update) - t.update(update); - return false; - } - let tooltipViews = []; - for (let i = 0; i < tooltips.length; i++) { - let tip = tooltips[i], known = -1; - if (!tip) - continue; - for (let i = 0; i < this.tooltips.length; i++) { - let other = this.tooltips[i]; - if (other && other.create == tip.create) - known = i; - } - if (known < 0) { - tooltipViews[i] = this.createTooltipView(tip); - } - else { - let tooltipView = tooltipViews[i] = this.tooltipViews[known]; - if (tooltipView.update) - tooltipView.update(update); - } - } - for (let t of this.tooltipViews) - if (tooltipViews.indexOf(t) < 0) - t.dom.remove(); - this.input = input; - this.tooltips = tooltips; - this.tooltipViews = tooltipViews; - return true; - } - } - function windowSpace() { - return { top: 0, left: 0, bottom: innerHeight, right: innerWidth }; - } - const tooltipConfig = /*@__PURE__*/Facet.define({ - combine: values => { - var _a, _b, _c; - return ({ - position: ios ? "absolute" : ((_a = values.find(conf => conf.position)) === null || _a === void 0 ? void 0 : _a.position) || "fixed", - parent: ((_b = values.find(conf => conf.parent)) === null || _b === void 0 ? void 0 : _b.parent) || null, - tooltipSpace: ((_c = values.find(conf => conf.tooltipSpace)) === null || _c === void 0 ? void 0 : _c.tooltipSpace) || windowSpace, - }); - } - }); - const tooltipPlugin = /*@__PURE__*/ViewPlugin.fromClass(class { - constructor(view) { - var _a; - this.view = view; - this.inView = true; - this.lastTransaction = 0; - this.measureTimeout = -1; - let config = view.state.facet(tooltipConfig); - this.position = config.position; - this.parent = config.parent; - this.classes = view.themeClasses; - this.createContainer(); - this.measureReq = { read: this.readMeasure.bind(this), write: this.writeMeasure.bind(this), key: this }; - this.manager = new TooltipViewManager(view, showTooltip, t => this.createTooltip(t)); - this.intersectionObserver = typeof IntersectionObserver == "function" ? new IntersectionObserver(entries => { - if (Date.now() > this.lastTransaction - 50 && - entries.length > 0 && entries[entries.length - 1].intersectionRatio < 1) - this.measureSoon(); - }, { threshold: [1] }) : null; - this.observeIntersection(); - (_a = view.dom.ownerDocument.defaultView) === null || _a === void 0 ? void 0 : _a.addEventListener("resize", this.measureSoon = this.measureSoon.bind(this)); - this.maybeMeasure(); - } - createContainer() { - if (this.parent) { - this.container = document.createElement("div"); - this.container.style.position = "relative"; - this.container.className = this.view.themeClasses; - this.parent.appendChild(this.container); - } - else { - this.container = this.view.dom; - } - } - observeIntersection() { - if (this.intersectionObserver) { - this.intersectionObserver.disconnect(); - for (let tooltip of this.manager.tooltipViews) - this.intersectionObserver.observe(tooltip.dom); - } - } - measureSoon() { - if (this.measureTimeout < 0) - this.measureTimeout = setTimeout(() => { - this.measureTimeout = -1; - this.maybeMeasure(); - }, 50); - } - update(update) { - if (update.transactions.length) - this.lastTransaction = Date.now(); - let updated = this.manager.update(update); - if (updated) - this.observeIntersection(); - let shouldMeasure = updated || update.geometryChanged; - let newConfig = update.state.facet(tooltipConfig); - if (newConfig.position != this.position) { - this.position = newConfig.position; - for (let t of this.manager.tooltipViews) - t.dom.style.position = this.position; - shouldMeasure = true; - } - if (newConfig.parent != this.parent) { - if (this.parent) - this.container.remove(); - this.parent = newConfig.parent; - this.createContainer(); - for (let t of this.manager.tooltipViews) - this.container.appendChild(t.dom); - shouldMeasure = true; - } - else if (this.parent && this.view.themeClasses != this.classes) { - this.classes = this.container.className = this.view.themeClasses; - } - if (shouldMeasure) - this.maybeMeasure(); - } - createTooltip(tooltip) { - let tooltipView = tooltip.create(this.view); - tooltipView.dom.classList.add("cm-tooltip"); - if (tooltip.arrow && !tooltipView.dom.querySelector(".cm-tooltip > .cm-tooltip-arrow")) { - let arrow = document.createElement("div"); - arrow.className = "cm-tooltip-arrow"; - tooltipView.dom.appendChild(arrow); - } - tooltipView.dom.style.position = this.position; - tooltipView.dom.style.top = Outside; - this.container.appendChild(tooltipView.dom); - if (tooltipView.mount) - tooltipView.mount(this.view); - return tooltipView; - } - destroy() { - var _a, _b; - (_a = this.view.dom.ownerDocument.defaultView) === null || _a === void 0 ? void 0 : _a.removeEventListener("resize", this.measureSoon); - for (let { dom } of this.manager.tooltipViews) - dom.remove(); - (_b = this.intersectionObserver) === null || _b === void 0 ? void 0 : _b.disconnect(); - clearTimeout(this.measureTimeout); - } - readMeasure() { - let editor = this.view.dom.getBoundingClientRect(); - return { - editor, - parent: this.parent ? this.container.getBoundingClientRect() : editor, - pos: this.manager.tooltips.map((t, i) => { - let tv = this.manager.tooltipViews[i]; - return tv.getCoords ? tv.getCoords(t.pos) : this.view.coordsAtPos(t.pos); - }), - size: this.manager.tooltipViews.map(({ dom }) => dom.getBoundingClientRect()), - space: this.view.state.facet(tooltipConfig).tooltipSpace(this.view), - }; - } - writeMeasure(measured) { - let { editor, space } = measured; - let others = []; - for (let i = 0; i < this.manager.tooltips.length; i++) { - let tooltip = this.manager.tooltips[i], tView = this.manager.tooltipViews[i], { dom } = tView; - let pos = measured.pos[i], size = measured.size[i]; - // Hide tooltips that are outside of the editor. - if (!pos || pos.bottom <= Math.max(editor.top, space.top) || - pos.top >= Math.min(editor.bottom, space.bottom) || - pos.right < Math.max(editor.left, space.left) - .1 || - pos.left > Math.min(editor.right, space.right) + .1) { - dom.style.top = Outside; - continue; - } - let arrow = tooltip.arrow ? tView.dom.querySelector(".cm-tooltip-arrow") : null; - let arrowHeight = arrow ? 7 /* Size */ : 0; - let width = size.right - size.left, height = size.bottom - size.top; - let offset = tView.offset || noOffset, ltr = this.view.textDirection == Direction.LTR; - let left = size.width > space.right - space.left ? (ltr ? space.left : space.right - size.width) - : ltr ? Math.min(pos.left - (arrow ? 14 /* Offset */ : 0) + offset.x, space.right - width) - : Math.max(space.left, pos.left - width + (arrow ? 14 /* Offset */ : 0) - offset.x); - let above = !!tooltip.above; - if (!tooltip.strictSide && (above - ? pos.top - (size.bottom - size.top) - offset.y < space.top - : pos.bottom + (size.bottom - size.top) + offset.y > space.bottom) && - above == (space.bottom - pos.bottom > pos.top - space.top)) - above = !above; - let top = above ? pos.top - height - arrowHeight - offset.y : pos.bottom + arrowHeight + offset.y; - let right = left + width; - if (tView.overlap !== true) - for (let r of others) - if (r.left < right && r.right > left && r.top < top + height && r.bottom > top) - top = above ? r.top - height - 2 - arrowHeight : r.bottom + arrowHeight + 2; - if (this.position == "absolute") { - dom.style.top = (top - measured.parent.top) + "px"; - dom.style.left = (left - measured.parent.left) + "px"; - } - else { - dom.style.top = top + "px"; - dom.style.left = left + "px"; - } - if (arrow) - arrow.style.left = `${pos.left + (ltr ? offset.x : -offset.x) - (left + 14 /* Offset */ - 7 /* Size */)}px`; - if (tView.overlap !== true) - others.push({ left, top, right, bottom: top + height }); - dom.classList.toggle("cm-tooltip-above", above); - dom.classList.toggle("cm-tooltip-below", !above); - if (tView.positioned) - tView.positioned(); - } - } - maybeMeasure() { - if (this.manager.tooltips.length) { - if (this.view.inView) - this.view.requestMeasure(this.measureReq); - if (this.inView != this.view.inView) { - this.inView = this.view.inView; - if (!this.inView) - for (let tv of this.manager.tooltipViews) - tv.dom.style.top = Outside; - } - } - } - }, { - eventHandlers: { - scroll() { this.maybeMeasure(); } - } - }); - const baseTheme$2 = /*@__PURE__*/EditorView.baseTheme({ - ".cm-tooltip": { - zIndex: 100 - }, - "&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: `${7 /* Size */}px`, - width: `${7 /* Size */ * 2}px`, - position: "absolute", - zIndex: -1, - overflow: "hidden", - "&:before, &:after": { - content: "''", - position: "absolute", - width: 0, - height: 0, - borderLeft: `${7 /* Size */}px solid transparent`, - borderRight: `${7 /* Size */}px solid transparent`, - }, - ".cm-tooltip-above &": { - bottom: `-${7 /* Size */}px`, - "&:before": { - borderTop: `${7 /* Size */}px solid #bbb`, - }, - "&:after": { - borderTop: `${7 /* Size */}px solid #f5f5f5`, - bottom: "1px" - } - }, - ".cm-tooltip-below &": { - top: `-${7 /* Size */}px`, - "&:before": { - borderBottom: `${7 /* Size */}px solid #bbb`, - }, - "&:after": { - borderBottom: `${7 /* Size */}px solid #f5f5f5`, - top: "1px" - } - }, - }, - "&dark .cm-tooltip .cm-tooltip-arrow": { - "&:before": { - borderTopColor: "#333338", - borderBottomColor: "#333338" - }, - "&:after": { - borderTopColor: "transparent", - borderBottomColor: "transparent" - } - } - }); - const noOffset = { x: 0, y: 0 }; - /** - Behavior by which an extension can provide a tooltip to be shown. - */ - const showTooltip = /*@__PURE__*/Facet.define({ - enables: [tooltipPlugin, baseTheme$2] - }); - const showHoverTooltip = /*@__PURE__*/Facet.define(); - class HoverTooltipHost { - constructor(view) { - this.view = view; - this.mounted = false; - this.dom = document.createElement("div"); - this.dom.classList.add("cm-tooltip-hover"); - this.manager = new TooltipViewManager(view, showHoverTooltip, t => this.createHostedView(t)); - } - // Needs to be static so that host tooltip instances always match - static create(view) { - return new HoverTooltipHost(view); - } - createHostedView(tooltip) { - let hostedView = tooltip.create(this.view); - hostedView.dom.classList.add("cm-tooltip-section"); - this.dom.appendChild(hostedView.dom); - if (this.mounted && hostedView.mount) - hostedView.mount(this.view); - return hostedView; - } - mount(view) { - for (let hostedView of this.manager.tooltipViews) { - if (hostedView.mount) - hostedView.mount(view); - } - this.mounted = true; - } - positioned() { - for (let hostedView of this.manager.tooltipViews) { - if (hostedView.positioned) - hostedView.positioned(); - } - } - update(update) { - this.manager.update(update); - } - } - const showHoverTooltipHost = /*@__PURE__*/showTooltip.compute([showHoverTooltip], state => { - let tooltips = state.facet(showHoverTooltip).filter(t => t); - if (tooltips.length === 0) - return null; - return { - pos: Math.min(...tooltips.map(t => t.pos)), - end: Math.max(...tooltips.filter(t => t.end != null).map(t => t.end)), - create: HoverTooltipHost.create, - above: tooltips[0].above, - arrow: tooltips.some(t => t.arrow), - }; - }); - class HoverPlugin { - constructor(view, source, field, setHover, hoverTime) { - this.view = view; - this.source = source; - this.field = field; - this.setHover = setHover; - this.hoverTime = hoverTime; - this.hoverTimeout = -1; - this.restartTimeout = -1; - this.pending = null; - this.lastMove = { x: 0, y: 0, target: view.dom, time: 0 }; - this.checkHover = this.checkHover.bind(this); - view.dom.addEventListener("mouseleave", this.mouseleave = this.mouseleave.bind(this)); - view.dom.addEventListener("mousemove", this.mousemove = this.mousemove.bind(this)); - } - update() { - if (this.pending) { - this.pending = null; - clearTimeout(this.restartTimeout); - this.restartTimeout = setTimeout(() => this.startHover(), 20); - } - } - get active() { - return this.view.state.field(this.field); - } - checkHover() { - this.hoverTimeout = -1; - if (this.active) - return; - let hovered = Date.now() - this.lastMove.time; - if (hovered < this.hoverTime) - this.hoverTimeout = setTimeout(this.checkHover, this.hoverTime - hovered); - else - this.startHover(); - } - startHover() { - var _a; - clearTimeout(this.restartTimeout); - let { lastMove } = this; - let pos = this.view.contentDOM.contains(lastMove.target) ? this.view.posAtCoords(lastMove) : null; - if (pos == null) - return; - let posCoords = this.view.coordsAtPos(pos); - if (posCoords == null || lastMove.y < posCoords.top || lastMove.y > posCoords.bottom || - lastMove.x < posCoords.left - this.view.defaultCharacterWidth || - lastMove.x > posCoords.right + this.view.defaultCharacterWidth) - return; - let bidi = this.view.bidiSpans(this.view.state.doc.lineAt(pos)).find(s => s.from <= pos && s.to >= pos); - let rtl = bidi && bidi.dir == Direction.RTL ? -1 : 1; - let open = this.source(this.view, pos, (lastMove.x < posCoords.left ? -rtl : rtl)); - if ((_a = open) === null || _a === void 0 ? void 0 : _a.then) { - let pending = this.pending = { pos }; - open.then(result => { - if (this.pending == pending) { - this.pending = null; - if (result) - this.view.dispatch({ effects: this.setHover.of(result) }); - } - }, e => logException(this.view.state, e, "hover tooltip")); - } - else if (open) { - this.view.dispatch({ effects: this.setHover.of(open) }); - } - } - mousemove(event) { - var _a; - this.lastMove = { x: event.clientX, y: event.clientY, target: event.target, time: Date.now() }; - if (this.hoverTimeout < 0) - this.hoverTimeout = setTimeout(this.checkHover, this.hoverTime); - let tooltip = this.active; - if (tooltip && !isInTooltip(this.lastMove.target) || this.pending) { - let { pos } = tooltip || this.pending, end = (_a = tooltip === null || tooltip === void 0 ? void 0 : tooltip.end) !== null && _a !== void 0 ? _a : pos; - if ((pos == end ? this.view.posAtCoords(this.lastMove) != pos - : !isOverRange(this.view, pos, end, event.clientX, event.clientY, 6 /* MaxDist */))) { - this.view.dispatch({ effects: this.setHover.of(null) }); - this.pending = null; - } - } - } - mouseleave() { - clearTimeout(this.hoverTimeout); - this.hoverTimeout = -1; - if (this.active) - this.view.dispatch({ effects: this.setHover.of(null) }); - } - destroy() { - clearTimeout(this.hoverTimeout); - this.view.dom.removeEventListener("mouseleave", this.mouseleave); - this.view.dom.removeEventListener("mousemove", this.mousemove); - } - } - function isInTooltip(elt) { - for (let cur = elt; cur; cur = cur.parentNode) - if (cur.nodeType == 1 && cur.classList.contains("cm-tooltip")) - return true; - return false; - } - function isOverRange(view, from, to, x, y, margin) { - let range = document.createRange(); - let fromDOM = view.domAtPos(from), toDOM = view.domAtPos(to); - range.setEnd(toDOM.node, toDOM.offset); - range.setStart(fromDOM.node, fromDOM.offset); - let rects = range.getClientRects(); - range.detach(); - for (let i = 0; i < rects.length; i++) { - let rect = rects[i]; - let dist = Math.max(rect.top - y, y - rect.bottom, rect.left - x, x - rect.right); - if (dist <= margin) - return true; - } - return false; - } - /** - Enable a hover tooltip, which shows up when the pointer hovers - over ranges of text. The callback is called when the mouse hovers - over the document text. It should, if there is a tooltip - associated with position `pos` return the tooltip description - (either directly or in a promise). The `side` argument indicates - on which side of the position the pointer is—it will be -1 if the - pointer is before the position, 1 if after the position. - - Note that all hover tooltips are hosted within a single tooltip - container element. This allows multiple tooltips over the same - range to be "merged" together without overlapping. - */ - function hoverTooltip(source, options = {}) { - let setHover = StateEffect.define(); - let hoverState = StateField.define({ - create() { return null; }, - update(value, tr) { - if (value && (options.hideOnChange && (tr.docChanged || tr.selection))) - return null; - for (let effect of tr.effects) { - if (effect.is(setHover)) - return effect.value; - if (effect.is(closeHoverTooltipEffect)) - return null; - } - if (value && tr.docChanged) { - let newPos = tr.changes.mapPos(value.pos, -1, MapMode.TrackDel); - if (newPos == null) - return null; - let copy = Object.assign(Object.create(null), value); - copy.pos = newPos; - if (value.end != null) - copy.end = tr.changes.mapPos(value.end); - return copy; - } - return value; - }, - provide: f => showHoverTooltip.from(f) - }); - return [ - hoverState, - ViewPlugin.define(view => new HoverPlugin(view, source, hoverState, setHover, options.hoverTime || 300 /* Time */)), - showHoverTooltipHost - ]; - } - /** - Get the active tooltip view for a given tooltip, if available. - */ - function getTooltip(view, tooltip) { - let plugin = view.plugin(tooltipPlugin); - if (!plugin) - return null; - let found = plugin.manager.tooltips.indexOf(tooltip); - return found < 0 ? null : plugin.manager.tooltipViews[found]; - } - const closeHoverTooltipEffect = /*@__PURE__*/StateEffect.define(); - - /** - An instance of this is passed to completion source functions. - */ - class CompletionContext { - /** - Create a new completion context. (Mostly useful for testing - completion sources—in the editor, the extension will create - these for you.) - */ - constructor( - /** - The editor state that the completion happens in. - */ - state, - /** - The position at which the completion is happening. - */ - pos, - /** - Indicates whether completion was activated explicitly, or - implicitly by typing. The usual way to respond to this is to - only return completions when either there is part of a - completable entity before the cursor, or `explicit` is true. - */ - explicit) { - this.state = state; - this.pos = pos; - this.explicit = explicit; - /** - @internal - */ - this.abortListeners = []; - } - /** - Get the extent, content, and (if there is a token) type of the - token before `this.pos`. - */ - tokenBefore(types) { - let token = syntaxTree(this.state).resolveInner(this.pos, -1); - while (token && types.indexOf(token.name) < 0) - token = token.parent; - return token ? { from: token.from, to: this.pos, - text: this.state.sliceDoc(token.from, this.pos), - type: token.type } : null; - } - /** - Get the match of the given expression directly before the - cursor. - */ - matchBefore(expr) { - let line = this.state.doc.lineAt(this.pos); - let start = Math.max(line.from, this.pos - 250); - let str = line.text.slice(start - line.from, this.pos - line.from); - let found = str.search(ensureAnchor(expr, false)); - return found < 0 ? null : { from: start + found, to: this.pos, text: str.slice(found) }; - } - /** - Yields true when the query has been aborted. Can be useful in - asynchronous queries to avoid doing work that will be ignored. - */ - get aborted() { return this.abortListeners == null; } - /** - Allows you to register abort handlers, which will be called when - the query is - [aborted](https://codemirror.net/6/docs/ref/#autocomplete.CompletionContext.aborted). - */ - addEventListener(type, listener) { - if (type == "abort" && this.abortListeners) - this.abortListeners.push(listener); - } - } - function toSet(chars) { - let flat = Object.keys(chars).join(""); - let words = /\w/.test(flat); - if (words) - flat = flat.replace(/\w/g, ""); - return `[${words ? "\\w" : ""}${flat.replace(/[^\w\s]/g, "\\$&")}]`; - } - function prefixMatch(options) { - let first = Object.create(null), rest = Object.create(null); - for (let { label } of options) { - first[label[0]] = true; - for (let i = 1; i < label.length; i++) - rest[label[i]] = true; - } - let source = toSet(first) + toSet(rest) + "*$"; - return [new RegExp("^" + source), new RegExp(source)]; - } - /** - Given a a fixed array of options, return an autocompleter that - completes them. - */ - function completeFromList(list) { - let options = list.map(o => typeof o == "string" ? { label: o } : o); - let [span, match] = options.every(o => /^\w+$/.test(o.label)) ? [/\w*$/, /\w+$/] : prefixMatch(options); - return (context) => { - let token = context.matchBefore(match); - return token || context.explicit ? { from: token ? token.from : context.pos, options, span } : null; - }; - } - class Option { - constructor(completion, source, match) { - this.completion = completion; - this.source = source; - this.match = match; - } - } - function cur(state) { return state.selection.main.head; } - // Make sure the given regexp has a $ at its end and, if `start` is - // true, a ^ at its start. - function ensureAnchor(expr, start) { - var _a; - let { source } = expr; - let addStart = start && source[0] != "^", addEnd = source[source.length - 1] != "$"; - if (!addStart && !addEnd) - return expr; - return new RegExp(`${addStart ? "^" : ""}(?:${source})${addEnd ? "$" : ""}`, (_a = expr.flags) !== null && _a !== void 0 ? _a : (expr.ignoreCase ? "i" : "")); - } - /** - This annotation is added to transactions that are produced by - picking a completion. - */ - const pickedCompletion = /*@__PURE__*/Annotation.define(); - function applyCompletion(view, option) { - let apply = option.completion.apply || option.completion.label; - let result = option.source; - if (typeof apply == "string") { - view.dispatch({ - changes: { from: result.from, to: result.to, insert: apply }, - selection: { anchor: result.from + apply.length }, - userEvent: "input.complete", - annotations: pickedCompletion.of(option.completion) - }); - } - else { - apply(view, option.completion, result.from, result.to); - } - } - const SourceCache = /*@__PURE__*/new WeakMap(); - function asSource(source) { - if (!Array.isArray(source)) - return source; - let known = SourceCache.get(source); - if (!known) - SourceCache.set(source, known = completeFromList(source)); - return known; - } - - // A pattern matcher for fuzzy completion matching. Create an instance - // once for a pattern, and then use that to match any number of - // completions. - class FuzzyMatcher { - constructor(pattern) { - this.pattern = pattern; - this.chars = []; - this.folded = []; - // Buffers reused by calls to `match` to track matched character - // positions. - this.any = []; - this.precise = []; - this.byWord = []; - for (let p = 0; p < pattern.length;) { - let char = codePointAt(pattern, p), size = codePointSize(char); - this.chars.push(char); - let part = pattern.slice(p, p + size), upper = part.toUpperCase(); - this.folded.push(codePointAt(upper == part ? part.toLowerCase() : upper, 0)); - p += size; - } - this.astral = pattern.length != this.chars.length; - } - // Matches a given word (completion) against the pattern (input). - // Will return null for no match, and otherwise an array that starts - // with the match score, followed by any number of `from, to` pairs - // indicating the matched parts of `word`. - // - // The score is a number that is more negative the worse the match - // is. See `Penalty` above. - match(word) { - if (this.pattern.length == 0) - return [0]; - if (word.length < this.pattern.length) - return null; - let { chars, folded, any, precise, byWord } = this; - // For single-character queries, only match when they occur right - // at the start - if (chars.length == 1) { - let first = codePointAt(word, 0); - return first == chars[0] ? [0, 0, codePointSize(first)] - : first == folded[0] ? [-200 /* CaseFold */, 0, codePointSize(first)] : null; - } - let direct = word.indexOf(this.pattern); - if (direct == 0) - return [0, 0, this.pattern.length]; - let len = chars.length, anyTo = 0; - if (direct < 0) { - for (let i = 0, e = Math.min(word.length, 200); i < e && anyTo < len;) { - let next = codePointAt(word, i); - if (next == chars[anyTo] || next == folded[anyTo]) - any[anyTo++] = i; - i += codePointSize(next); - } - // No match, exit immediately - if (anyTo < len) - return null; - } - // This tracks the extent of the precise (non-folded, not - // necessarily adjacent) match - let preciseTo = 0; - // Tracks whether there is a match that hits only characters that - // appear to be starting words. `byWordFolded` is set to true when - // a case folded character is encountered in such a match - let byWordTo = 0, byWordFolded = false; - // If we've found a partial adjacent match, these track its state - let adjacentTo = 0, adjacentStart = -1, adjacentEnd = -1; - let hasLower = /[a-z]/.test(word), wordAdjacent = true; - // Go over the option's text, scanning for the various kinds of matches - for (let i = 0, e = Math.min(word.length, 200), prevType = 0 /* NonWord */; i < e && byWordTo < len;) { - let next = codePointAt(word, i); - if (direct < 0) { - if (preciseTo < len && next == chars[preciseTo]) - precise[preciseTo++] = i; - if (adjacentTo < len) { - if (next == chars[adjacentTo] || next == folded[adjacentTo]) { - if (adjacentTo == 0) - adjacentStart = i; - adjacentEnd = i + 1; - adjacentTo++; - } - else { - adjacentTo = 0; - } - } - } - let ch, type = next < 0xff - ? (next >= 48 && next <= 57 || next >= 97 && next <= 122 ? 2 /* Lower */ : next >= 65 && next <= 90 ? 1 /* Upper */ : 0 /* NonWord */) - : ((ch = fromCodePoint(next)) != ch.toLowerCase() ? 1 /* Upper */ : ch != ch.toUpperCase() ? 2 /* Lower */ : 0 /* NonWord */); - if (!i || type == 1 /* Upper */ && hasLower || prevType == 0 /* NonWord */ && type != 0 /* NonWord */) { - if (chars[byWordTo] == next || (folded[byWordTo] == next && (byWordFolded = true))) - byWord[byWordTo++] = i; - else if (byWord.length) - wordAdjacent = false; - } - prevType = type; - i += codePointSize(next); - } - if (byWordTo == len && byWord[0] == 0 && wordAdjacent) - return this.result(-100 /* ByWord */ + (byWordFolded ? -200 /* CaseFold */ : 0), byWord, word); - if (adjacentTo == len && adjacentStart == 0) - return [-200 /* CaseFold */ - word.length, 0, adjacentEnd]; - if (direct > -1) - return [-700 /* NotStart */ - word.length, direct, direct + this.pattern.length]; - if (adjacentTo == len) - return [-200 /* CaseFold */ + -700 /* NotStart */ - word.length, adjacentStart, adjacentEnd]; - if (byWordTo == len) - return this.result(-100 /* ByWord */ + (byWordFolded ? -200 /* CaseFold */ : 0) + -700 /* NotStart */ + - (wordAdjacent ? 0 : -1100 /* Gap */), byWord, word); - return chars.length == 2 ? null : this.result((any[0] ? -700 /* NotStart */ : 0) + -200 /* CaseFold */ + -1100 /* Gap */, any, word); - } - result(score, positions, word) { - let result = [score - word.length], i = 1; - for (let pos of positions) { - let to = pos + (this.astral ? codePointSize(codePointAt(word, pos)) : 1); - if (i > 1 && result[i - 1] == pos) - result[i - 1] = to; - else { - result[i++] = pos; - result[i++] = to; - } - } - return result; - } - } - - const completionConfig = /*@__PURE__*/Facet.define({ - combine(configs) { - return combineConfig(configs, { - activateOnTyping: true, - override: null, - maxRenderedOptions: 100, - defaultKeymap: true, - optionClass: () => "", - aboveCursor: false, - icons: true, - addToOptions: [] - }, { - defaultKeymap: (a, b) => a && b, - icons: (a, b) => a && b, - optionClass: (a, b) => c => joinClass(a(c), b(c)), - addToOptions: (a, b) => a.concat(b) - }); - } - }); - function joinClass(a, b) { - return a ? b ? a + " " + b : a : b; - } - - function optionContent(config) { - let content = config.addToOptions.slice(); - if (config.icons) - content.push({ - render(completion) { - let icon = document.createElement("div"); - icon.classList.add("cm-completionIcon"); - if (completion.type) - icon.classList.add(...completion.type.split(/\s+/g).map(cls => "cm-completionIcon-" + cls)); - icon.setAttribute("aria-hidden", "true"); - return icon; - }, - position: 20 - }); - content.push({ - render(completion, _s, match) { - let labelElt = document.createElement("span"); - labelElt.className = "cm-completionLabel"; - let { label } = completion, off = 0; - for (let j = 1; j < match.length;) { - let from = match[j++], to = match[j++]; - if (from > off) - labelElt.appendChild(document.createTextNode(label.slice(off, from))); - let span = labelElt.appendChild(document.createElement("span")); - span.appendChild(document.createTextNode(label.slice(from, to))); - span.className = "cm-completionMatchedText"; - off = to; - } - if (off < label.length) - labelElt.appendChild(document.createTextNode(label.slice(off))); - return labelElt; - }, - position: 50 - }, { - render(completion) { - if (!completion.detail) - return null; - let detailElt = document.createElement("span"); - detailElt.className = "cm-completionDetail"; - detailElt.textContent = completion.detail; - return detailElt; - }, - position: 80 - }); - return content.sort((a, b) => a.position - b.position).map(a => a.render); - } - function rangeAroundSelected(total, selected, max) { - if (total <= max) - return { from: 0, to: total }; - if (selected <= (total >> 1)) { - let off = Math.floor(selected / max); - return { from: off * max, to: (off + 1) * max }; - } - let off = Math.floor((total - selected) / max); - return { from: total - (off + 1) * max, to: total - off * max }; - } - class CompletionTooltip { - constructor(view, stateField) { - this.view = view; - this.stateField = stateField; - this.info = null; - this.placeInfo = { - read: () => this.measureInfo(), - write: (pos) => this.positionInfo(pos), - key: this - }; - let cState = view.state.field(stateField); - let { options, selected } = cState.open; - let config = view.state.facet(completionConfig); - this.optionContent = optionContent(config); - this.optionClass = config.optionClass; - this.range = rangeAroundSelected(options.length, selected, config.maxRenderedOptions); - this.dom = document.createElement("div"); - this.dom.className = "cm-tooltip-autocomplete"; - this.dom.addEventListener("mousedown", (e) => { - for (let dom = e.target, match; dom && dom != this.dom; dom = dom.parentNode) { - if (dom.nodeName == "LI" && (match = /-(\d+)$/.exec(dom.id)) && +match[1] < options.length) { - applyCompletion(view, options[+match[1]]); - e.preventDefault(); - return; - } - } - }); - this.list = this.dom.appendChild(this.createListBox(options, cState.id, this.range)); - this.list.addEventListener("scroll", () => { - if (this.info) - this.view.requestMeasure(this.placeInfo); - }); - } - mount() { this.updateSel(); } - update(update) { - if (update.state.field(this.stateField) != update.startState.field(this.stateField)) - this.updateSel(); - } - positioned() { - if (this.info) - this.view.requestMeasure(this.placeInfo); - } - updateSel() { - let cState = this.view.state.field(this.stateField), open = cState.open; - if (open.selected < this.range.from || open.selected >= this.range.to) { - this.range = rangeAroundSelected(open.options.length, open.selected, this.view.state.facet(completionConfig).maxRenderedOptions); - this.list.remove(); - this.list = this.dom.appendChild(this.createListBox(open.options, cState.id, this.range)); - this.list.addEventListener("scroll", () => { - if (this.info) - this.view.requestMeasure(this.placeInfo); - }); - } - if (this.updateSelectedOption(open.selected)) { - if (this.info) { - this.info.remove(); - this.info = null; - } - let { completion } = open.options[open.selected]; - let { info } = completion; - if (!info) - return; - let infoResult = typeof info === 'string' ? document.createTextNode(info) : info(completion); - if (!infoResult) - return; - if ('then' in infoResult) { - infoResult.then(node => { - if (node && this.view.state.field(this.stateField, false) == cState) - this.addInfoPane(node); - }).catch(e => logException(this.view.state, e, "completion info")); - } - else { - this.addInfoPane(infoResult); - } - } - } - addInfoPane(content) { - let dom = this.info = document.createElement("div"); - dom.className = "cm-tooltip cm-completionInfo"; - dom.appendChild(content); - this.dom.appendChild(dom); - this.view.requestMeasure(this.placeInfo); - } - updateSelectedOption(selected) { - let set = null; - for (let opt = this.list.firstChild, i = this.range.from; opt; opt = opt.nextSibling, i++) { - if (i == selected) { - if (!opt.hasAttribute("aria-selected")) { - opt.setAttribute("aria-selected", "true"); - set = opt; - } - } - else { - if (opt.hasAttribute("aria-selected")) - opt.removeAttribute("aria-selected"); - } - } - if (set) - scrollIntoView(this.list, set); - return set; - } - measureInfo() { - let sel = this.dom.querySelector("[aria-selected]"); - if (!sel || !this.info) - return null; - let listRect = this.dom.getBoundingClientRect(); - let infoRect = this.info.getBoundingClientRect(); - let selRect = sel.getBoundingClientRect(); - if (selRect.top > Math.min(innerHeight, listRect.bottom) - 10 || selRect.bottom < Math.max(0, listRect.top) + 10) - return null; - let top = Math.max(0, Math.min(selRect.top, innerHeight - infoRect.height)) - listRect.top; - let left = this.view.textDirection == Direction.RTL; - let spaceLeft = listRect.left, spaceRight = innerWidth - listRect.right; - if (left && spaceLeft < Math.min(infoRect.width, spaceRight)) - left = false; - else if (!left && spaceRight < Math.min(infoRect.width, spaceLeft)) - left = true; - return { top, left }; - } - positionInfo(pos) { - if (this.info) { - this.info.style.top = (pos ? pos.top : -1e6) + "px"; - if (pos) { - this.info.classList.toggle("cm-completionInfo-left", pos.left); - this.info.classList.toggle("cm-completionInfo-right", !pos.left); - } - } - } - createListBox(options, id, range) { - const ul = document.createElement("ul"); - ul.id = id; - ul.setAttribute("role", "listbox"); - ul.setAttribute("aria-expanded", "true"); - for (let i = range.from; i < range.to; i++) { - let { completion, match } = options[i]; - const li = ul.appendChild(document.createElement("li")); - li.id = id + "-" + i; - li.setAttribute("role", "option"); - let cls = this.optionClass(completion); - if (cls) - li.className = cls; - for (let source of this.optionContent) { - let node = source(completion, this.view.state, match); - if (node) - li.appendChild(node); - } - } - if (range.from) - ul.classList.add("cm-completionListIncompleteTop"); - if (range.to < options.length) - ul.classList.add("cm-completionListIncompleteBottom"); - return ul; - } - } - // We allocate a new function instance every time the completion - // changes to force redrawing/repositioning of the tooltip - function completionTooltip(stateField) { - return (view) => new CompletionTooltip(view, stateField); - } - function scrollIntoView(container, element) { - let parent = container.getBoundingClientRect(); - let self = element.getBoundingClientRect(); - if (self.top < parent.top) - container.scrollTop -= parent.top - self.top; - else if (self.bottom > parent.bottom) - container.scrollTop += self.bottom - parent.bottom; - } - - const MaxOptions = 300; - // Used to pick a preferred option when two options with the same - // label occur in the result. - function score(option) { - return (option.boost || 0) * 100 + (option.apply ? 10 : 0) + (option.info ? 5 : 0) + - (option.type ? 1 : 0); - } - function sortOptions(active, state) { - let options = [], i = 0; - for (let a of active) - if (a.hasResult()) { - if (a.result.filter === false) { - for (let option of a.result.options) - options.push(new Option(option, a, [1e9 - i++])); - } - else { - let matcher = new FuzzyMatcher(state.sliceDoc(a.from, a.to)), match; - for (let option of a.result.options) - if (match = matcher.match(option.label)) { - if (option.boost != null) - match[0] += option.boost; - options.push(new Option(option, a, match)); - } - } - } - let result = [], prev = null; - for (let opt of options.sort(cmpOption)) { - if (result.length == MaxOptions) - break; - if (!prev || prev.label != opt.completion.label || prev.detail != opt.completion.detail || - prev.type != opt.completion.type || prev.apply != opt.completion.apply) - result.push(opt); - else if (score(opt.completion) > score(prev)) - result[result.length - 1] = opt; - prev = opt.completion; - } - return result; - } - class CompletionDialog { - constructor(options, attrs, tooltip, timestamp, selected) { - this.options = options; - this.attrs = attrs; - this.tooltip = tooltip; - this.timestamp = timestamp; - this.selected = selected; - } - setSelected(selected, id) { - return selected == this.selected || selected >= this.options.length ? this - : new CompletionDialog(this.options, makeAttrs(id, selected), this.tooltip, this.timestamp, selected); - } - static build(active, state, id, prev, conf) { - let options = sortOptions(active, state); - if (!options.length) - return null; - let selected = 0; - if (prev && prev.selected) { - let selectedValue = prev.options[prev.selected].completion; - for (let i = 0; i < options.length; i++) - if (options[i].completion == selectedValue) { - selected = i; - break; - } - } - return new CompletionDialog(options, makeAttrs(id, selected), { - pos: active.reduce((a, b) => b.hasResult() ? Math.min(a, b.from) : a, 1e8), - create: completionTooltip(completionState), - above: conf.aboveCursor, - }, prev ? prev.timestamp : Date.now(), selected); - } - map(changes) { - return new CompletionDialog(this.options, this.attrs, Object.assign(Object.assign({}, this.tooltip), { pos: changes.mapPos(this.tooltip.pos) }), this.timestamp, this.selected); - } - } - class CompletionState { - constructor(active, id, open) { - this.active = active; - this.id = id; - this.open = open; - } - static start() { - return new CompletionState(none, "cm-ac-" + Math.floor(Math.random() * 2e6).toString(36), null); - } - update(tr) { - let { state } = tr, conf = state.facet(completionConfig); - let sources = conf.override || - state.languageDataAt("autocomplete", cur(state)).map(asSource); - let active = sources.map(source => { - let value = this.active.find(s => s.source == source) || - new ActiveSource(source, this.active.some(a => a.state != 0 /* Inactive */) ? 1 /* Pending */ : 0 /* Inactive */); - return value.update(tr, conf); - }); - if (active.length == this.active.length && active.every((a, i) => a == this.active[i])) - active = this.active; - let open = tr.selection || active.some(a => a.hasResult() && tr.changes.touchesRange(a.from, a.to)) || - !sameResults(active, this.active) ? CompletionDialog.build(active, state, this.id, this.open, conf) - : this.open && tr.docChanged ? this.open.map(tr.changes) : this.open; - if (!open && active.every(a => a.state != 1 /* Pending */) && active.some(a => a.hasResult())) - active = active.map(a => a.hasResult() ? new ActiveSource(a.source, 0 /* Inactive */) : a); - for (let effect of tr.effects) - if (effect.is(setSelectedEffect)) - open = open && open.setSelected(effect.value, this.id); - return active == this.active && open == this.open ? this : new CompletionState(active, this.id, open); - } - get tooltip() { return this.open ? this.open.tooltip : null; } - get attrs() { return this.open ? this.open.attrs : baseAttrs; } - } - function sameResults(a, b) { - if (a == b) - return true; - for (let iA = 0, iB = 0;;) { - while (iA < a.length && !a[iA].hasResult) - iA++; - while (iB < b.length && !b[iB].hasResult) - iB++; - let endA = iA == a.length, endB = iB == b.length; - if (endA || endB) - return endA == endB; - if (a[iA++].result != b[iB++].result) - return false; - } - } - const baseAttrs = { - "aria-autocomplete": "list" - }; - function makeAttrs(id, selected) { - return { - "aria-autocomplete": "list", - "aria-haspopup": "listbox", - "aria-activedescendant": id + "-" + selected, - "aria-controls": id - }; - } - const none = []; - function cmpOption(a, b) { - let dScore = b.match[0] - a.match[0]; - if (dScore) - return dScore; - return a.completion.label.localeCompare(b.completion.label); - } - function getUserEvent(tr) { - return tr.isUserEvent("input.type") ? "input" : tr.isUserEvent("delete.backward") ? "delete" : null; - } - class ActiveSource { - constructor(source, state, explicitPos = -1) { - this.source = source; - this.state = state; - this.explicitPos = explicitPos; - } - hasResult() { return false; } - update(tr, conf) { - let event = getUserEvent(tr), value = this; - if (event) - value = value.handleUserEvent(tr, event, conf); - else if (tr.docChanged) - value = value.handleChange(tr); - else if (tr.selection && value.state != 0 /* Inactive */) - value = new ActiveSource(value.source, 0 /* Inactive */); - for (let effect of tr.effects) { - if (effect.is(startCompletionEffect)) - value = new ActiveSource(value.source, 1 /* Pending */, effect.value ? cur(tr.state) : -1); - else if (effect.is(closeCompletionEffect)) - value = new ActiveSource(value.source, 0 /* Inactive */); - else if (effect.is(setActiveEffect)) - for (let active of effect.value) - if (active.source == value.source) - value = active; - } - return value; - } - handleUserEvent(tr, type, conf) { - return type == "delete" || !conf.activateOnTyping ? this.map(tr.changes) : new ActiveSource(this.source, 1 /* Pending */); - } - handleChange(tr) { - return tr.changes.touchesRange(cur(tr.startState)) ? new ActiveSource(this.source, 0 /* Inactive */) : this.map(tr.changes); - } - map(changes) { - return changes.empty || this.explicitPos < 0 ? this : new ActiveSource(this.source, this.state, changes.mapPos(this.explicitPos)); - } - } - class ActiveResult extends ActiveSource { - constructor(source, explicitPos, result, from, to, span) { - super(source, 2 /* Result */, explicitPos); - this.result = result; - this.from = from; - this.to = to; - this.span = span; - } - hasResult() { return true; } - handleUserEvent(tr, type, conf) { - let from = tr.changes.mapPos(this.from), to = tr.changes.mapPos(this.to, 1); - let pos = cur(tr.state); - if ((this.explicitPos < 0 ? pos <= from : pos < this.from) || - pos > to || - type == "delete" && cur(tr.startState) == this.from) - return new ActiveSource(this.source, type == "input" && conf.activateOnTyping ? 1 /* Pending */ : 0 /* Inactive */); - let explicitPos = this.explicitPos < 0 ? -1 : tr.changes.mapPos(this.explicitPos); - if (this.span && (from == to || this.span.test(tr.state.sliceDoc(from, to)))) - return new ActiveResult(this.source, explicitPos, this.result, from, to, this.span); - return new ActiveSource(this.source, 1 /* Pending */, explicitPos); - } - handleChange(tr) { - return tr.changes.touchesRange(this.from, this.to) ? new ActiveSource(this.source, 0 /* Inactive */) : this.map(tr.changes); - } - map(mapping) { - return mapping.empty ? this : - new ActiveResult(this.source, this.explicitPos < 0 ? -1 : mapping.mapPos(this.explicitPos), this.result, mapping.mapPos(this.from), mapping.mapPos(this.to, 1), this.span); - } - } - const startCompletionEffect = /*@__PURE__*/StateEffect.define(); - const closeCompletionEffect = /*@__PURE__*/StateEffect.define(); - const setActiveEffect = /*@__PURE__*/StateEffect.define({ - map(sources, mapping) { return sources.map(s => s.map(mapping)); } - }); - const setSelectedEffect = /*@__PURE__*/StateEffect.define(); - const completionState = /*@__PURE__*/StateField.define({ - create() { return CompletionState.start(); }, - update(value, tr) { return value.update(tr); }, - provide: f => [ - showTooltip.from(f, val => val.tooltip), - EditorView.contentAttributes.from(f, state => state.attrs) - ] - }); - - const CompletionInteractMargin = 75; - /** - Returns a command that moves the completion selection forward or - backward by the given amount. - */ - function moveCompletionSelection(forward, by = "option") { - return (view) => { - let cState = view.state.field(completionState, false); - if (!cState || !cState.open || Date.now() - cState.open.timestamp < CompletionInteractMargin) - return false; - let step = 1, tooltip; - if (by == "page" && (tooltip = getTooltip(view, cState.open.tooltip))) - step = Math.max(2, Math.floor(tooltip.dom.offsetHeight / - tooltip.dom.querySelector("li").offsetHeight) - 1); - let selected = cState.open.selected + step * (forward ? 1 : -1), { length } = cState.open.options; - if (selected < 0) - selected = by == "page" ? 0 : length - 1; - else if (selected >= length) - selected = by == "page" ? length - 1 : 0; - view.dispatch({ effects: setSelectedEffect.of(selected) }); - return true; - }; - } - /** - Accept the current completion. - */ - const acceptCompletion = (view) => { - let cState = view.state.field(completionState, false); - if (view.state.readOnly || !cState || !cState.open || Date.now() - cState.open.timestamp < CompletionInteractMargin) - return false; - applyCompletion(view, cState.open.options[cState.open.selected]); - return true; - }; - /** - Explicitly start autocompletion. - */ - const startCompletion = (view) => { - let cState = view.state.field(completionState, false); - if (!cState) - return false; - view.dispatch({ effects: startCompletionEffect.of(true) }); - return true; - }; - /** - Close the currently active completion. - */ - const closeCompletion = (view) => { - let cState = view.state.field(completionState, false); - if (!cState || !cState.active.some(a => a.state != 0 /* Inactive */)) - return false; - view.dispatch({ effects: closeCompletionEffect.of(null) }); - return true; - }; - class RunningQuery { - constructor(active, context) { - this.active = active; - this.context = context; - this.time = Date.now(); - this.updates = []; - // Note that 'undefined' means 'not done yet', whereas 'null' means - // 'query returned null'. - this.done = undefined; - } - } - const DebounceTime = 50, MaxUpdateCount = 50, MinAbortTime = 1000; - const completionPlugin = /*@__PURE__*/ViewPlugin.fromClass(class { - constructor(view) { - this.view = view; - this.debounceUpdate = -1; - this.running = []; - this.debounceAccept = -1; - this.composing = 0 /* None */; - for (let active of view.state.field(completionState).active) - if (active.state == 1 /* Pending */) - this.startQuery(active); - } - update(update) { - let cState = update.state.field(completionState); - if (!update.selectionSet && !update.docChanged && update.startState.field(completionState) == cState) - return; - let doesReset = update.transactions.some(tr => { - return (tr.selection || tr.docChanged) && !getUserEvent(tr); - }); - for (let i = 0; i < this.running.length; i++) { - let query = this.running[i]; - if (doesReset || - query.updates.length + update.transactions.length > MaxUpdateCount && Date.now() - query.time > MinAbortTime) { - for (let handler of query.context.abortListeners) { - try { - handler(); - } - catch (e) { - logException(this.view.state, e); - } - } - query.context.abortListeners = null; - this.running.splice(i--, 1); - } - else { - query.updates.push(...update.transactions); - } - } - if (this.debounceUpdate > -1) - clearTimeout(this.debounceUpdate); - this.debounceUpdate = cState.active.some(a => a.state == 1 /* Pending */ && !this.running.some(q => q.active.source == a.source)) - ? setTimeout(() => this.startUpdate(), DebounceTime) : -1; - if (this.composing != 0 /* None */) - for (let tr of update.transactions) { - if (getUserEvent(tr) == "input") - this.composing = 2 /* Changed */; - else if (this.composing == 2 /* Changed */ && tr.selection) - this.composing = 3 /* ChangedAndMoved */; - } - } - startUpdate() { - this.debounceUpdate = -1; - let { state } = this.view, cState = state.field(completionState); - for (let active of cState.active) { - if (active.state == 1 /* Pending */ && !this.running.some(r => r.active.source == active.source)) - this.startQuery(active); - } - } - startQuery(active) { - let { state } = this.view, pos = cur(state); - let context = new CompletionContext(state, pos, active.explicitPos == pos); - let pending = new RunningQuery(active, context); - this.running.push(pending); - Promise.resolve(active.source(context)).then(result => { - if (!pending.context.aborted) { - pending.done = result || null; - this.scheduleAccept(); - } - }, err => { - this.view.dispatch({ effects: closeCompletionEffect.of(null) }); - logException(this.view.state, err); - }); - } - scheduleAccept() { - if (this.running.every(q => q.done !== undefined)) - this.accept(); - else if (this.debounceAccept < 0) - this.debounceAccept = setTimeout(() => this.accept(), DebounceTime); - } - // For each finished query in this.running, try to create a result - // or, if appropriate, restart the query. - accept() { - var _a; - if (this.debounceAccept > -1) - clearTimeout(this.debounceAccept); - this.debounceAccept = -1; - let updated = []; - let conf = this.view.state.facet(completionConfig); - for (let i = 0; i < this.running.length; i++) { - let query = this.running[i]; - if (query.done === undefined) - continue; - this.running.splice(i--, 1); - if (query.done) { - let active = new ActiveResult(query.active.source, query.active.explicitPos, query.done, query.done.from, (_a = query.done.to) !== null && _a !== void 0 ? _a : cur(query.updates.length ? query.updates[0].startState : this.view.state), query.done.span && query.done.filter !== false ? ensureAnchor(query.done.span, true) : null); - // Replay the transactions that happened since the start of - // the request and see if that preserves the result - for (let tr of query.updates) - active = active.update(tr, conf); - if (active.hasResult()) { - updated.push(active); - continue; - } - } - let current = this.view.state.field(completionState).active.find(a => a.source == query.active.source); - if (current && current.state == 1 /* Pending */) { - if (query.done == null) { - // Explicitly failed. Should clear the pending status if it - // hasn't been re-set in the meantime. - let active = new ActiveSource(query.active.source, 0 /* Inactive */); - for (let tr of query.updates) - active = active.update(tr, conf); - if (active.state != 1 /* Pending */) - updated.push(active); - } - else { - // Cleared by subsequent transactions. Restart. - this.startQuery(current); - } - } - } - if (updated.length) - this.view.dispatch({ effects: setActiveEffect.of(updated) }); - } - }, { - eventHandlers: { - compositionstart() { - this.composing = 1 /* Started */; - }, - compositionend() { - if (this.composing == 3 /* ChangedAndMoved */) { - // Safari fires compositionend events synchronously, possibly - // from inside an update, so dispatch asynchronously to avoid reentrancy - setTimeout(() => this.view.dispatch({ effects: startCompletionEffect.of(false) }), 20); - } - this.composing = 0 /* None */; - } - } - }); - - const baseTheme$1 = /*@__PURE__*/EditorView.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", - listStyle: "none", - margin: 0, - padding: 0, - "& > li": { - overflowX: "hidden", - textOverflow: "ellipsis", - cursor: "pointer", - padding: "1px 3px", - lineHeight: 1.2 - }, - } - }, - "&light .cm-tooltip-autocomplete ul li[aria-selected]": { - background: "#17c", - color: "white", - }, - "&dark .cm-tooltip-autocomplete ul li[aria-selected]": { - background: "#347", - color: "white", - }, - ".cm-completionListIncompleteTop:before, .cm-completionListIncompleteBottom:after": { - content: '"···"', - opacity: 0.5, - display: "block", - textAlign: "center" - }, - ".cm-tooltip.cm-completionInfo": { - position: "absolute", - padding: "3px 9px", - width: "max-content", - maxWidth: "300px", - }, - ".cm-completionInfo.cm-completionInfo-left": { right: "100%" }, - ".cm-completionInfo.cm-completionInfo-right": { left: "100%" }, - "&light .cm-snippetField": { backgroundColor: "#00000022" }, - "&dark .cm-snippetField": { backgroundColor: "#ffffff22" }, - ".cm-snippetFieldPosition": { - verticalAlign: "text-top", - width: 0, - height: "1.15em", - 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" - }, - ".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: "'🔑\uFE0E'" } // Disable emoji rendering - }, - ".cm-completionIcon-namespace": { - "&:after": { content: "'▢'" } - }, - ".cm-completionIcon-text": { - "&:after": { content: "'abc'", fontSize: "50%", verticalAlign: "middle" } - } - }); - - /** - Returns an extension that enables autocompletion. - */ - function autocompletion(config = {}) { - return [ - completionState, - completionConfig.of(config), - completionPlugin, - completionKeymapExt, - baseTheme$1 - ]; - } - /** - Basic keybindings for autocompletion. - - - Ctrl-Space: [`startCompletion`](https://codemirror.net/6/docs/ref/#autocomplete.startCompletion) - - Escape: [`closeCompletion`](https://codemirror.net/6/docs/ref/#autocomplete.closeCompletion) - - ArrowDown: [`moveCompletionSelection`](https://codemirror.net/6/docs/ref/#autocomplete.moveCompletionSelection)`(true)` - - ArrowUp: [`moveCompletionSelection`](https://codemirror.net/6/docs/ref/#autocomplete.moveCompletionSelection)`(false)` - - PageDown: [`moveCompletionSelection`](https://codemirror.net/6/docs/ref/#autocomplete.moveCompletionSelection)`(true, "page")` - - PageDown: [`moveCompletionSelection`](https://codemirror.net/6/docs/ref/#autocomplete.moveCompletionSelection)`(true, "page")` - - Enter: [`acceptCompletion`](https://codemirror.net/6/docs/ref/#autocomplete.acceptCompletion) - */ - const completionKeymap = [ - { key: "Ctrl-Space", run: startCompletion }, - { key: "Escape", run: closeCompletion }, - { key: "ArrowDown", run: /*@__PURE__*/moveCompletionSelection(true) }, - { key: "ArrowUp", run: /*@__PURE__*/moveCompletionSelection(false) }, - { key: "PageDown", run: /*@__PURE__*/moveCompletionSelection(true, "page") }, - { key: "PageUp", run: /*@__PURE__*/moveCompletionSelection(false, "page") }, - { key: "Enter", run: acceptCompletion } - ]; - const completionKeymapExt = /*@__PURE__*/Prec.highest(/*@__PURE__*/keymap.computeN([completionConfig], state => state.facet(completionConfig).defaultKeymap ? [completionKeymap] : [])); - - /** - Comment or uncomment the current selection. Will use line comments - if available, otherwise falling back to block comments. - */ - const toggleComment = target => { - let config = getConfig(target.state); - return config.line ? toggleLineComment(target) : config.block ? toggleBlockCommentByLine(target) : false; - }; - function command(f, option) { - return ({ state, dispatch }) => { - if (state.readOnly) - return false; - let tr = f(option, state); - if (!tr) - return false; - dispatch(state.update(tr)); - return true; - }; - } - /** - Comment or uncomment the current selection using line comments. - The line comment syntax is taken from the - [`commentTokens`](https://codemirror.net/6/docs/ref/#comment.CommentTokens) [language - data](https://codemirror.net/6/docs/ref/#state.EditorState.languageDataAt). - */ - const toggleLineComment = /*@__PURE__*/command(changeLineComment, 0 /* Toggle */); - /** - Comment or uncomment the current selection using block comments. - The block comment syntax is taken from the - [`commentTokens`](https://codemirror.net/6/docs/ref/#comment.CommentTokens) [language - data](https://codemirror.net/6/docs/ref/#state.EditorState.languageDataAt). - */ - const toggleBlockComment = /*@__PURE__*/command(changeBlockComment, 0 /* Toggle */); - /** - Comment or uncomment the lines around the current selection using - block comments. - */ - const toggleBlockCommentByLine = /*@__PURE__*/command((o, s) => changeBlockComment(o, s, selectedLineRanges(s)), 0 /* Toggle */); - /** - Default key bindings for this package. - - - Ctrl-/ (Cmd-/ on macOS): [`toggleComment`](https://codemirror.net/6/docs/ref/#comment.toggleComment). - - Shift-Alt-a: [`toggleBlockComment`](https://codemirror.net/6/docs/ref/#comment.toggleBlockComment). - */ - const commentKeymap = [ - { key: "Mod-/", run: toggleComment }, - { key: "Alt-A", run: toggleBlockComment } - ]; - function getConfig(state, pos = state.selection.main.head) { - let data = state.languageDataAt("commentTokens", pos); - return data.length ? data[0] : {}; - } - const SearchMargin = 50; - /** - Determines if the given range is block-commented in the given - state. - */ - function findBlockComment(state, { open, close }, from, to) { - let textBefore = state.sliceDoc(from - SearchMargin, from); - let textAfter = state.sliceDoc(to, to + SearchMargin); - let spaceBefore = /\s*$/.exec(textBefore)[0].length, spaceAfter = /^\s*/.exec(textAfter)[0].length; - let beforeOff = textBefore.length - spaceBefore; - if (textBefore.slice(beforeOff - open.length, beforeOff) == open && - textAfter.slice(spaceAfter, spaceAfter + close.length) == close) { - return { open: { pos: from - spaceBefore, margin: spaceBefore && 1 }, - close: { pos: to + spaceAfter, margin: spaceAfter && 1 } }; - } - let startText, endText; - if (to - from <= 2 * SearchMargin) { - startText = endText = state.sliceDoc(from, to); - } - else { - startText = state.sliceDoc(from, from + SearchMargin); - endText = state.sliceDoc(to - SearchMargin, to); - } - let startSpace = /^\s*/.exec(startText)[0].length, endSpace = /\s*$/.exec(endText)[0].length; - let endOff = endText.length - endSpace - close.length; - if (startText.slice(startSpace, startSpace + open.length) == open && - endText.slice(endOff, endOff + close.length) == close) { - return { open: { pos: from + startSpace + open.length, - margin: /\s/.test(startText.charAt(startSpace + open.length)) ? 1 : 0 }, - close: { pos: to - endSpace - close.length, - margin: /\s/.test(endText.charAt(endOff - 1)) ? 1 : 0 } }; - } - return null; - } - function selectedLineRanges(state) { - let ranges = []; - for (let r of state.selection.ranges) { - let fromLine = state.doc.lineAt(r.from); - let toLine = r.to <= fromLine.to ? fromLine : state.doc.lineAt(r.to); - let last = ranges.length - 1; - if (last >= 0 && ranges[last].to > fromLine.from) - ranges[last].to = toLine.to; - else - ranges.push({ from: fromLine.from, to: toLine.to }); - } - return ranges; - } - // Performs toggle, comment and uncomment of block comments in - // languages that support them. - function changeBlockComment(option, state, ranges = state.selection.ranges) { - let tokens = ranges.map(r => getConfig(state, r.from).block); - if (!tokens.every(c => c)) - return null; - let comments = ranges.map((r, i) => findBlockComment(state, tokens[i], r.from, r.to)); - if (option != 2 /* Uncomment */ && !comments.every(c => c)) { - return { changes: state.changes(ranges.map((range, i) => { - if (comments[i]) - return []; - return [{ from: range.from, insert: tokens[i].open + " " }, { from: range.to, insert: " " + tokens[i].close }]; - })) }; - } - else if (option != 1 /* Comment */ && comments.some(c => c)) { - let changes = []; - for (let i = 0, comment; i < comments.length; i++) - if (comment = comments[i]) { - let token = tokens[i], { open, close } = comment; - changes.push({ from: open.pos - token.open.length, to: open.pos + open.margin }, { from: close.pos - close.margin, to: close.pos + token.close.length }); - } - return { changes }; - } - return null; - } - // Performs toggle, comment and uncomment of line comments. - function changeLineComment(option, state, ranges = state.selection.ranges) { - let lines = []; - let prevLine = -1; - for (let { from, to } of ranges) { - let startI = lines.length, minIndent = 1e9; - for (let pos = from; pos <= to;) { - let line = state.doc.lineAt(pos); - if (line.from > prevLine && (from == to || to > line.from)) { - prevLine = line.from; - let token = getConfig(state, pos).line; - if (!token) - continue; - let indent = /^\s*/.exec(line.text)[0].length; - let empty = indent == line.length; - let comment = line.text.slice(indent, indent + token.length) == token ? indent : -1; - if (indent < line.text.length && indent < minIndent) - minIndent = indent; - lines.push({ line, comment, token, indent, empty, single: false }); - } - pos = line.to + 1; - } - if (minIndent < 1e9) - for (let i = startI; i < lines.length; i++) - if (lines[i].indent < lines[i].line.text.length) - lines[i].indent = minIndent; - if (lines.length == startI + 1) - lines[startI].single = true; - } - if (option != 2 /* Uncomment */ && lines.some(l => l.comment < 0 && (!l.empty || l.single))) { - let changes = []; - for (let { line, token, indent, empty, single } of lines) - if (single || !empty) - changes.push({ from: line.from + indent, insert: token + " " }); - let changeSet = state.changes(changes); - return { changes: changeSet, selection: state.selection.map(changeSet, 1) }; - } - else if (option != 1 /* Comment */ && lines.some(l => l.comment >= 0)) { - let changes = []; - for (let { line, comment, token } of lines) - if (comment >= 0) { - let from = line.from + comment, to = from + token.length; - if (line.text[to - line.from] == " ") - to++; - changes.push({ from, to }); - } - return { changes }; - } - return null; - } - - // Don't compute precise column positions for line offsets above this - // (since it could get expensive). Assume offset==column for them. - const MaxOff = 2000; - function rectangleFor(state, a, b) { - let startLine = Math.min(a.line, b.line), endLine = Math.max(a.line, b.line); - let ranges = []; - if (a.off > MaxOff || b.off > MaxOff || a.col < 0 || b.col < 0) { - let startOff = Math.min(a.off, b.off), endOff = Math.max(a.off, b.off); - for (let i = startLine; i <= endLine; i++) { - let line = state.doc.line(i); - if (line.length <= endOff) - ranges.push(EditorSelection.range(line.from + startOff, line.to + endOff)); - } - } - else { - let startCol = Math.min(a.col, b.col), endCol = Math.max(a.col, b.col); - for (let i = startLine; i <= endLine; i++) { - let line = state.doc.line(i); - let start = findColumn(line.text, startCol, state.tabSize, true); - if (start > -1) { - let end = findColumn(line.text, endCol, state.tabSize); - ranges.push(EditorSelection.range(line.from + start, line.from + end)); - } - } - } - return ranges; - } - function absoluteColumn(view, x) { - let ref = view.coordsAtPos(view.viewport.from); - return ref ? Math.round(Math.abs((ref.left - x) / view.defaultCharacterWidth)) : -1; - } - function getPos(view, event) { - let offset = view.posAtCoords({ x: event.clientX, y: event.clientY }, false); - let line = view.state.doc.lineAt(offset), off = offset - line.from; - let col = off > MaxOff ? -1 - : off == line.length ? absoluteColumn(view, event.clientX) - : countColumn(line.text, view.state.tabSize, offset - line.from); - return { line: line.number, col, off }; - } - function rectangleSelectionStyle(view, event) { - let start = getPos(view, event), startSel = view.state.selection; - if (!start) - return null; - return { - update(update) { - if (update.docChanged) { - let newStart = update.changes.mapPos(update.startState.doc.line(start.line).from); - let newLine = update.state.doc.lineAt(newStart); - start = { line: newLine.number, col: start.col, off: Math.min(start.off, newLine.length) }; - startSel = startSel.map(update.changes); - } - }, - get(event, _extend, multiple) { - let cur = getPos(view, event); - if (!cur) - return startSel; - let ranges = rectangleFor(view.state, start, cur); - if (!ranges.length) - return startSel; - if (multiple) - return EditorSelection.create(ranges.concat(startSel.ranges)); - else - return EditorSelection.create(ranges); - } - }; - } - /** - Create an extension that enables rectangular selections. By - default, it will react to left mouse drag with the Alt key held - down. When such a selection occurs, the text within the rectangle - that was dragged over will be selected, as one selection - [range](https://codemirror.net/6/docs/ref/#state.SelectionRange) per line. - */ - function rectangularSelection(options) { - let filter = (options === null || options === void 0 ? void 0 : options.eventFilter) || (e => e.altKey && e.button == 0); - return EditorView.mouseSelectionStyle.of((view, event) => filter(event) ? rectangleSelectionStyle(view, event) : null); - } - const keys = { - Alt: [18, e => e.altKey], - Control: [17, e => e.ctrlKey], - Shift: [16, e => e.shiftKey], - Meta: [91, e => e.metaKey] - }; - const showCrosshair = { style: "cursor: crosshair" }; - /** - Returns an extension that turns the pointer cursor into a - crosshair when a given modifier key, defaulting to Alt, is held - down. Can serve as a visual hint that rectangular selection is - going to happen when paired with - [`rectangularSelection`](https://codemirror.net/6/docs/ref/#rectangular-selection.rectangularSelection). - */ - function crosshairCursor(options = {}) { - let [code, getter] = keys[options.key || "Alt"]; - let plugin = ViewPlugin.fromClass(class { - constructor(view) { - this.view = view; - this.isDown = false; - } - set(isDown) { - if (this.isDown != isDown) { - this.isDown = isDown; - this.view.update([]); - } - } - }, { - eventHandlers: { - keydown(e) { - this.set(e.keyCode == code || getter(e)); - }, - keyup(e) { - if (e.keyCode == code || !getter(e)) - this.set(false); - } - } - }); - return [ - plugin, - EditorView.contentAttributes.of(view => { var _a; return ((_a = view.plugin(plugin)) === null || _a === void 0 ? void 0 : _a.isDown) ? showCrosshair : null; }) - ]; - } - - let nextTagID = 0; - /** - Highlighting tags are markers that denote a highlighting category. - They are [associated](https://codemirror.net/6/docs/ref/#highlight.styleTags) with parts of a syntax - tree by a language mode, and then mapped to an actual CSS style by - a [highlight style](https://codemirror.net/6/docs/ref/#highlight.HighlightStyle). - - Because syntax tree node types and highlight styles have to be - able to talk the same language, CodeMirror uses a mostly _closed_ - [vocabulary](https://codemirror.net/6/docs/ref/#highlight.tags) of syntax tags (as opposed to - traditional open string-based systems, which make it hard for - highlighting themes to cover all the tokens produced by the - various languages). - - It _is_ possible to [define](https://codemirror.net/6/docs/ref/#highlight.Tag^define) your own - highlighting tags for system-internal use (where you control both - the language package and the highlighter), but such tags will not - be picked up by regular highlighters (though you can derive them - from standard tags to allow highlighters to fall back to those). - */ - class Tag { - /** - @internal - */ - constructor( - /** - The set of tags that match this tag, starting with this one - itself, sorted in order of decreasing specificity. @internal - */ - set, - /** - The base unmodified tag that this one is based on, if it's - modified @internal - */ - base, - /** - The modifiers applied to this.base @internal - */ - modified) { - this.set = set; - this.base = base; - this.modified = modified; - /** - @internal - */ - this.id = nextTagID++; - } - /** - Define a new tag. If `parent` is given, the tag is treated as a - sub-tag of that parent, and [highlight - styles](https://codemirror.net/6/docs/ref/#highlight.HighlightStyle) that don't mention this tag - will try to fall back to the parent tag (or grandparent tag, - etc). - */ - static define(parent) { - if (parent === null || parent === void 0 ? void 0 : parent.base) - throw new Error("Can not derive from a modified tag"); - let tag = new Tag([], null, []); - tag.set.push(tag); - if (parent) - for (let t of parent.set) - tag.set.push(t); - return tag; - } - /** - Define a tag _modifier_, which is a function that, given a tag, - will return a tag that is a subtag of the original. Applying the - same modifier to a twice tag will return the same value (`m1(t1) - == m1(t1)`) and applying multiple modifiers will, regardless or - order, produce the same tag (`m1(m2(t1)) == m2(m1(t1))`). - - When multiple modifiers are applied to a given base tag, each - smaller set of modifiers is registered as a parent, so that for - example `m1(m2(m3(t1)))` is a subtype of `m1(m2(t1))`, - `m1(m3(t1)`, and so on. - */ - static defineModifier() { - let mod = new Modifier; - return (tag) => { - if (tag.modified.indexOf(mod) > -1) - return tag; - return Modifier.get(tag.base || tag, tag.modified.concat(mod).sort((a, b) => a.id - b.id)); - }; - } - } - let nextModifierID = 0; - class Modifier { - constructor() { - this.instances = []; - this.id = nextModifierID++; - } - static get(base, mods) { - if (!mods.length) - return base; - let exists = mods[0].instances.find(t => t.base == base && sameArray(mods, t.modified)); - if (exists) - return exists; - let set = [], tag = new Tag(set, base, mods); - for (let m of mods) - m.instances.push(tag); - let configs = permute(mods); - for (let parent of base.set) - for (let config of configs) - set.push(Modifier.get(parent, config)); - return tag; - } - } - function sameArray(a, b) { - return a.length == b.length && a.every((x, i) => x == b[i]); - } - function permute(array) { - let result = [array]; - for (let i = 0; i < array.length; i++) { - for (let a of permute(array.slice(0, i).concat(array.slice(i + 1)))) - result.push(a); - } - return result; - } - /** - This function is used to add a set of tags to a language syntax - via - [`LRParser.configure`](https://lezer.codemirror.net/docs/ref#lr.LRParser.configure). - - The argument object maps node selectors to [highlighting - tags](https://codemirror.net/6/docs/ref/#highlight.Tag) or arrays of tags. - - Node selectors may hold one or more (space-separated) node paths. - Such a path can be a [node - name](https://lezer.codemirror.net/docs/ref#common.NodeType.name), - or multiple node names (or `*` wildcards) separated by slash - characters, as in `"Block/Declaration/VariableName"`. Such a path - matches the final node but only if its direct parent nodes are the - other nodes mentioned. A `*` in such a path matches any parent, - but only a single level—wildcards that match multiple parents - aren't supported, both for efficiency reasons and because Lezer - trees make it rather hard to reason about what they would match.) - - A path can be ended with `/...` to indicate that the tag assigned - to the node should also apply to all child nodes, even if they - match their own style (by default, only the innermost style is - used). - - When a path ends in `!`, as in `Attribute!`, no further matching - happens for the node's child nodes, and the entire node gets the - given style. - - In this notation, node names that contain `/`, `!`, `*`, or `...` - must be quoted as JSON strings. - - For example: - - ```javascript - parser.withProps( - styleTags({ - // Style Number and BigNumber nodes - "Number BigNumber": tags.number, - // Style Escape nodes whose parent is String - "String/Escape": tags.escape, - // Style anything inside Attributes nodes - "Attributes!": tags.meta, - // Add a style to all content inside Italic nodes - "Italic/...": tags.emphasis, - // Style InvalidString nodes as both `string` and `invalid` - "InvalidString": [tags.string, tags.invalid], - // Style the node named "/" as punctuation - '"/"': tags.punctuation - }) - ) - ``` - */ - function styleTags(spec) { - let byName = Object.create(null); - for (let prop in spec) { - let tags = spec[prop]; - if (!Array.isArray(tags)) - tags = [tags]; - for (let part of prop.split(" ")) - if (part) { - let pieces = [], mode = 2 /* Normal */, rest = part; - for (let pos = 0;;) { - if (rest == "..." && pos > 0 && pos + 3 == part.length) { - mode = 1 /* Inherit */; - break; - } - let m = /^"(?:[^"\\]|\\.)*?"|[^\/!]+/.exec(rest); - if (!m) - throw new RangeError("Invalid path: " + part); - pieces.push(m[0] == "*" ? null : m[0][0] == '"' ? JSON.parse(m[0]) : m[0]); - pos += m[0].length; - if (pos == part.length) - break; - let next = part[pos++]; - if (pos == part.length && next == "!") { - mode = 0 /* Opaque */; - break; - } - if (next != "/") - throw new RangeError("Invalid path: " + part); - rest = part.slice(pos); - } - let last = pieces.length - 1, inner = pieces[last]; - if (!inner) - throw new RangeError("Invalid path: " + part); - let rule = new Rule(tags, mode, last > 0 ? pieces.slice(0, last) : null); - byName[inner] = rule.sort(byName[inner]); - } - } - return ruleNodeProp.add(byName); - } - const ruleNodeProp = /*@__PURE__*/new NodeProp(); - const highlightStyle = /*@__PURE__*/Facet.define({ - combine(stylings) { return stylings.length ? HighlightStyle.combinedMatch(stylings) : null; } - }); - const fallbackHighlightStyle = /*@__PURE__*/Facet.define({ - combine(values) { return values.length ? values[0].match : null; } - }); - function getHighlightStyle(state) { - return state.facet(highlightStyle) || state.facet(fallbackHighlightStyle); - } - class Rule { - constructor(tags, mode, context, next) { - this.tags = tags; - this.mode = mode; - this.context = context; - this.next = next; - } - sort(other) { - if (!other || other.depth < this.depth) { - this.next = other; - return this; - } - other.next = this.sort(other.next); - return other; - } - get depth() { return this.context ? this.context.length : 0; } - } - /** - A highlight style associates CSS styles with higlighting - [tags](https://codemirror.net/6/docs/ref/#highlight.Tag). - */ - class HighlightStyle { - constructor(spec, options) { - this.map = Object.create(null); - let modSpec; - function def(spec) { - let cls = StyleModule.newName(); - (modSpec || (modSpec = Object.create(null)))["." + cls] = spec; - return cls; - } - this.all = typeof options.all == "string" ? options.all : options.all ? def(options.all) : null; - for (let style of spec) { - let cls = (style.class || def(Object.assign({}, style, { tag: null }))) + - (this.all ? " " + this.all : ""); - let tags = style.tag; - if (!Array.isArray(tags)) - this.map[tags.id] = cls; - else - for (let tag of tags) - this.map[tag.id] = cls; - } - this.module = modSpec ? new StyleModule(modSpec) : null; - this.scope = options.scope || null; - this.match = this.match.bind(this); - let ext = [treeHighlighter]; - if (this.module) - ext.push(EditorView.styleModule.of(this.module)); - this.extension = ext.concat(options.themeType == null ? highlightStyle.of(this) : - highlightStyle.computeN([EditorView.darkTheme], state => { - return state.facet(EditorView.darkTheme) == (options.themeType == "dark") ? [this] : []; - })); - this.fallback = ext.concat(fallbackHighlightStyle.of(this)); - } - /** - Returns the CSS class associated with the given tag, if any. - This method is bound to the instance by the constructor. - */ - match(tag, scope) { - if (this.scope && scope != this.scope) - return null; - for (let t of tag.set) { - let match = this.map[t.id]; - if (match !== undefined) { - if (t != tag) - this.map[tag.id] = match; - return match; - } - } - return this.map[tag.id] = this.all; - } - /** - Combines an array of highlight styles into a single match - function that returns all of the classes assigned by the styles - for a given tag. - */ - static combinedMatch(styles) { - if (styles.length == 1) - return styles[0].match; - let cache = styles.some(s => s.scope) ? undefined : Object.create(null); - return (tag, scope) => { - let cached = cache && cache[tag.id]; - if (cached !== undefined) - return cached; - let result = null; - for (let style of styles) { - let value = style.match(tag, scope); - if (value) - result = result ? result + " " + value : value; - } - if (cache) - cache[tag.id] = result; - return result; - }; - } - /** - Create a highlighter style that associates the given styles to - the given tags. The spec must be objects that hold a style tag - or array of tags in their `tag` property, and either a single - `class` property providing a static CSS class (for highlighters - like [`classHighlightStyle`](https://codemirror.net/6/docs/ref/#highlight.classHighlightStyle) - that rely on external styling), or a - [`style-mod`](https://github.com/marijnh/style-mod#documentation)-style - set of CSS properties (which define the styling for those tags). - - The CSS rules created for a highlighter will be emitted in the - order of the spec's properties. That means that for elements that - have multiple tags associated with them, styles defined further - down in the list will have a higher CSS precedence than styles - defined earlier. - */ - static define(specs, options) { - return new HighlightStyle(specs, options || {}); - } - /** - Returns the CSS classes (if any) that the highlight styles - active in the given state would assign to the given a style - [tag](https://codemirror.net/6/docs/ref/#highlight.Tag) and (optional) language - [scope](https://codemirror.net/6/docs/ref/#highlight.HighlightStyle^define^options.scope). - */ - static get(state, tag, scope) { - let style = getHighlightStyle(state); - return style && style(tag, scope || NodeType.none); - } - } - class TreeHighlighter { - constructor(view) { - this.markCache = Object.create(null); - this.tree = syntaxTree(view.state); - this.decorations = this.buildDeco(view, getHighlightStyle(view.state)); - } - update(update) { - let tree = syntaxTree(update.state), style = getHighlightStyle(update.state); - let styleChange = style != update.startState.facet(highlightStyle); - if (tree.length < update.view.viewport.to && !styleChange && tree.type == this.tree.type) { - this.decorations = this.decorations.map(update.changes); - } - else if (tree != this.tree || update.viewportChanged || styleChange) { - this.tree = tree; - this.decorations = this.buildDeco(update.view, style); - } - } - buildDeco(view, match) { - if (!match || !this.tree.length) - return Decoration.none; - let builder = new RangeSetBuilder(); - for (let { from, to } of view.visibleRanges) { - highlightTreeRange(this.tree, from, to, match, (from, to, style) => { - builder.add(from, to, this.markCache[style] || (this.markCache[style] = Decoration.mark({ class: style }))); - }); - } - return builder.finish(); - } - } - // This extension installs a highlighter that highlights based on the - // syntax tree and highlight style. - const treeHighlighter = /*@__PURE__*/Prec.high(/*@__PURE__*/ViewPlugin.fromClass(TreeHighlighter, { - decorations: v => v.decorations - })); - const nodeStack = [""]; - class HighlightBuilder { - constructor(at, style, span) { - this.at = at; - this.style = style; - this.span = span; - this.class = ""; - } - startSpan(at, cls) { - if (cls != this.class) { - this.flush(at); - if (at > this.at) - this.at = at; - this.class = cls; - } - } - flush(to) { - if (to > this.at && this.class) - this.span(this.at, to, this.class); - } - highlightRange(cursor, from, to, inheritedClass, depth, scope) { - let { type, from: start, to: end } = cursor; - if (start >= to || end <= from) - return; - nodeStack[depth] = type.name; - if (type.isTop) - scope = type; - let cls = inheritedClass; - let rule = type.prop(ruleNodeProp), opaque = false; - while (rule) { - if (!rule.context || matchContext(rule.context, nodeStack, depth)) { - for (let tag of rule.tags) { - let st = this.style(tag, scope); - if (st) { - if (cls) - cls += " "; - cls += st; - if (rule.mode == 1 /* Inherit */) - inheritedClass += (inheritedClass ? " " : "") + st; - else if (rule.mode == 0 /* Opaque */) - opaque = true; - } - } - break; - } - rule = rule.next; - } - this.startSpan(cursor.from, cls); - if (opaque) - return; - let mounted = cursor.tree && cursor.tree.prop(NodeProp.mounted); - if (mounted && mounted.overlay) { - let inner = cursor.node.enter(mounted.overlay[0].from + start, 1); - let hasChild = cursor.firstChild(); - for (let i = 0, pos = start;; i++) { - let next = i < mounted.overlay.length ? mounted.overlay[i] : null; - let nextPos = next ? next.from + start : end; - let rangeFrom = Math.max(from, pos), rangeTo = Math.min(to, nextPos); - if (rangeFrom < rangeTo && hasChild) { - while (cursor.from < rangeTo) { - this.highlightRange(cursor, rangeFrom, rangeTo, inheritedClass, depth + 1, scope); - this.startSpan(Math.min(to, cursor.to), cls); - if (cursor.to >= nextPos || !cursor.nextSibling()) - break; - } - } - if (!next || nextPos > to) - break; - pos = next.to + start; - if (pos > from) { - this.highlightRange(inner.cursor, Math.max(from, next.from + start), Math.min(to, pos), inheritedClass, depth, mounted.tree.type); - this.startSpan(pos, cls); - } - } - if (hasChild) - cursor.parent(); - } - else if (cursor.firstChild()) { - do { - if (cursor.to <= from) - continue; - if (cursor.from >= to) - break; - this.highlightRange(cursor, from, to, inheritedClass, depth + 1, scope); - this.startSpan(Math.min(to, cursor.to), cls); - } while (cursor.nextSibling()); - cursor.parent(); - } - } - } - function highlightTreeRange(tree, from, to, style, span) { - let builder = new HighlightBuilder(from, style, span); - builder.highlightRange(tree.cursor(), from, to, "", 0, tree.type); - builder.flush(to); - } - function matchContext(context, stack, depth) { - if (context.length > depth - 1) - return false; - for (let d = depth - 1, i = context.length - 1; i >= 0; i--, d--) { - let check = context[i]; - if (check && check != stack[d]) - return false; - } - return true; - } - const t = Tag.define; - const comment = /*@__PURE__*/t(), name = /*@__PURE__*/t(), typeName = /*@__PURE__*/t(name), propertyName = /*@__PURE__*/t(name), literal = /*@__PURE__*/t(), string = /*@__PURE__*/t(literal), number = /*@__PURE__*/t(literal), content = /*@__PURE__*/t(), heading = /*@__PURE__*/t(content), keyword = /*@__PURE__*/t(), operator = /*@__PURE__*/t(), punctuation = /*@__PURE__*/t(), bracket = /*@__PURE__*/t(punctuation), meta = /*@__PURE__*/t(); - /** - The default set of highlighting [tags](https://codemirror.net/6/docs/ref/#highlight.Tag^define) used - by regular language packages and themes. - - This collection is heavily biased towards programming languages, - and necessarily incomplete. A full ontology of syntactic - constructs would fill a stack of books, and be impractical to - write themes for. So try to make do with this set. If all else - fails, [open an - issue](https://github.com/codemirror/codemirror.next) to propose a - new tag, or [define](https://codemirror.net/6/docs/ref/#highlight.Tag^define) a local custom tag for - your use case. - - Note that it is not obligatory to always attach the most specific - tag possible to an element—if your grammar can't easily - distinguish a certain type of element (such as a local variable), - it is okay to style it as its more general variant (a variable). - - For tags that extend some parent tag, the documentation links to - the parent. - */ - const tags = { - /** - A comment. - */ - comment, - /** - A line [comment](https://codemirror.net/6/docs/ref/#highlight.tags.comment). - */ - lineComment: /*@__PURE__*/t(comment), - /** - A block [comment](https://codemirror.net/6/docs/ref/#highlight.tags.comment). - */ - blockComment: /*@__PURE__*/t(comment), - /** - A documentation [comment](https://codemirror.net/6/docs/ref/#highlight.tags.comment). - */ - docComment: /*@__PURE__*/t(comment), - /** - Any kind of identifier. - */ - name, - /** - The [name](https://codemirror.net/6/docs/ref/#highlight.tags.name) of a variable. - */ - variableName: /*@__PURE__*/t(name), - /** - A type [name](https://codemirror.net/6/docs/ref/#highlight.tags.name). - */ - typeName: typeName, - /** - A tag name (subtag of [`typeName`](https://codemirror.net/6/docs/ref/#highlight.tags.typeName)). - */ - tagName: /*@__PURE__*/t(typeName), - /** - A property or field [name](https://codemirror.net/6/docs/ref/#highlight.tags.name). - */ - propertyName: propertyName, - /** - An attribute name (subtag of [`propertyName`](https://codemirror.net/6/docs/ref/#highlight.tags.propertyName)). - */ - attributeName: /*@__PURE__*/t(propertyName), - /** - The [name](https://codemirror.net/6/docs/ref/#highlight.tags.name) of a class. - */ - className: /*@__PURE__*/t(name), - /** - A label [name](https://codemirror.net/6/docs/ref/#highlight.tags.name). - */ - labelName: /*@__PURE__*/t(name), - /** - A namespace [name](https://codemirror.net/6/docs/ref/#highlight.tags.name). - */ - namespace: /*@__PURE__*/t(name), - /** - The [name](https://codemirror.net/6/docs/ref/#highlight.tags.name) of a macro. - */ - macroName: /*@__PURE__*/t(name), - /** - A literal value. - */ - literal, - /** - A string [literal](https://codemirror.net/6/docs/ref/#highlight.tags.literal). - */ - string, - /** - A documentation [string](https://codemirror.net/6/docs/ref/#highlight.tags.string). - */ - docString: /*@__PURE__*/t(string), - /** - A character literal (subtag of [string](https://codemirror.net/6/docs/ref/#highlight.tags.string)). - */ - character: /*@__PURE__*/t(string), - /** - An attribute value (subtag of [string](https://codemirror.net/6/docs/ref/#highlight.tags.string)). - */ - attributeValue: /*@__PURE__*/t(string), - /** - A number [literal](https://codemirror.net/6/docs/ref/#highlight.tags.literal). - */ - number, - /** - An integer [number](https://codemirror.net/6/docs/ref/#highlight.tags.number) literal. - */ - integer: /*@__PURE__*/t(number), - /** - A floating-point [number](https://codemirror.net/6/docs/ref/#highlight.tags.number) literal. - */ - float: /*@__PURE__*/t(number), - /** - A boolean [literal](https://codemirror.net/6/docs/ref/#highlight.tags.literal). - */ - bool: /*@__PURE__*/t(literal), - /** - Regular expression [literal](https://codemirror.net/6/docs/ref/#highlight.tags.literal). - */ - regexp: /*@__PURE__*/t(literal), - /** - An escape [literal](https://codemirror.net/6/docs/ref/#highlight.tags.literal), for example a - backslash escape in a string. - */ - escape: /*@__PURE__*/t(literal), - /** - A color [literal](https://codemirror.net/6/docs/ref/#highlight.tags.literal). - */ - color: /*@__PURE__*/t(literal), - /** - A URL [literal](https://codemirror.net/6/docs/ref/#highlight.tags.literal). - */ - url: /*@__PURE__*/t(literal), - /** - A language keyword. - */ - keyword, - /** - The [keyword](https://codemirror.net/6/docs/ref/#highlight.tags.keyword) for the self or this - object. - */ - self: /*@__PURE__*/t(keyword), - /** - The [keyword](https://codemirror.net/6/docs/ref/#highlight.tags.keyword) for null. - */ - null: /*@__PURE__*/t(keyword), - /** - A [keyword](https://codemirror.net/6/docs/ref/#highlight.tags.keyword) denoting some atomic value. - */ - atom: /*@__PURE__*/t(keyword), - /** - A [keyword](https://codemirror.net/6/docs/ref/#highlight.tags.keyword) that represents a unit. - */ - unit: /*@__PURE__*/t(keyword), - /** - A modifier [keyword](https://codemirror.net/6/docs/ref/#highlight.tags.keyword). - */ - modifier: /*@__PURE__*/t(keyword), - /** - A [keyword](https://codemirror.net/6/docs/ref/#highlight.tags.keyword) that acts as an operator. - */ - operatorKeyword: /*@__PURE__*/t(keyword), - /** - A control-flow related [keyword](https://codemirror.net/6/docs/ref/#highlight.tags.keyword). - */ - controlKeyword: /*@__PURE__*/t(keyword), - /** - A [keyword](https://codemirror.net/6/docs/ref/#highlight.tags.keyword) that defines something. - */ - definitionKeyword: /*@__PURE__*/t(keyword), - /** - A [keyword](https://codemirror.net/6/docs/ref/#highlight.tags.keyword) related to defining or - interfacing with modules. - */ - moduleKeyword: /*@__PURE__*/t(keyword), - /** - An operator. - */ - operator, - /** - An [operator](https://codemirror.net/6/docs/ref/#highlight.tags.operator) that defines something. - */ - derefOperator: /*@__PURE__*/t(operator), - /** - Arithmetic-related [operator](https://codemirror.net/6/docs/ref/#highlight.tags.operator). - */ - arithmeticOperator: /*@__PURE__*/t(operator), - /** - Logical [operator](https://codemirror.net/6/docs/ref/#highlight.tags.operator). - */ - logicOperator: /*@__PURE__*/t(operator), - /** - Bit [operator](https://codemirror.net/6/docs/ref/#highlight.tags.operator). - */ - bitwiseOperator: /*@__PURE__*/t(operator), - /** - Comparison [operator](https://codemirror.net/6/docs/ref/#highlight.tags.operator). - */ - compareOperator: /*@__PURE__*/t(operator), - /** - [Operator](https://codemirror.net/6/docs/ref/#highlight.tags.operator) that updates its operand. - */ - updateOperator: /*@__PURE__*/t(operator), - /** - [Operator](https://codemirror.net/6/docs/ref/#highlight.tags.operator) that defines something. - */ - definitionOperator: /*@__PURE__*/t(operator), - /** - Type-related [operator](https://codemirror.net/6/docs/ref/#highlight.tags.operator). - */ - typeOperator: /*@__PURE__*/t(operator), - /** - Control-flow [operator](https://codemirror.net/6/docs/ref/#highlight.tags.operator). - */ - controlOperator: /*@__PURE__*/t(operator), - /** - Program or markup punctuation. - */ - punctuation, - /** - [Punctuation](https://codemirror.net/6/docs/ref/#highlight.tags.punctuation) that separates - things. - */ - separator: /*@__PURE__*/t(punctuation), - /** - Bracket-style [punctuation](https://codemirror.net/6/docs/ref/#highlight.tags.punctuation). - */ - bracket, - /** - Angle [brackets](https://codemirror.net/6/docs/ref/#highlight.tags.bracket) (usually `<` and `>` - tokens). - */ - angleBracket: /*@__PURE__*/t(bracket), - /** - Square [brackets](https://codemirror.net/6/docs/ref/#highlight.tags.bracket) (usually `[` and `]` - tokens). - */ - squareBracket: /*@__PURE__*/t(bracket), - /** - Parentheses (usually `(` and `)` tokens). Subtag of - [bracket](https://codemirror.net/6/docs/ref/#highlight.tags.bracket). - */ - paren: /*@__PURE__*/t(bracket), - /** - Braces (usually `{` and `}` tokens). Subtag of - [bracket](https://codemirror.net/6/docs/ref/#highlight.tags.bracket). - */ - brace: /*@__PURE__*/t(bracket), - /** - Content, for example plain text in XML or markup documents. - */ - content, - /** - [Content](https://codemirror.net/6/docs/ref/#highlight.tags.content) that represents a heading. - */ - heading, - /** - A level 1 [heading](https://codemirror.net/6/docs/ref/#highlight.tags.heading). - */ - heading1: /*@__PURE__*/t(heading), - /** - A level 2 [heading](https://codemirror.net/6/docs/ref/#highlight.tags.heading). - */ - heading2: /*@__PURE__*/t(heading), - /** - A level 3 [heading](https://codemirror.net/6/docs/ref/#highlight.tags.heading). - */ - heading3: /*@__PURE__*/t(heading), - /** - A level 4 [heading](https://codemirror.net/6/docs/ref/#highlight.tags.heading). - */ - heading4: /*@__PURE__*/t(heading), - /** - A level 5 [heading](https://codemirror.net/6/docs/ref/#highlight.tags.heading). - */ - heading5: /*@__PURE__*/t(heading), - /** - A level 6 [heading](https://codemirror.net/6/docs/ref/#highlight.tags.heading). - */ - heading6: /*@__PURE__*/t(heading), - /** - A prose separator (such as a horizontal rule). - */ - contentSeparator: /*@__PURE__*/t(content), - /** - [Content](https://codemirror.net/6/docs/ref/#highlight.tags.content) that represents a list. - */ - list: /*@__PURE__*/t(content), - /** - [Content](https://codemirror.net/6/docs/ref/#highlight.tags.content) that represents a quote. - */ - quote: /*@__PURE__*/t(content), - /** - [Content](https://codemirror.net/6/docs/ref/#highlight.tags.content) that is emphasized. - */ - emphasis: /*@__PURE__*/t(content), - /** - [Content](https://codemirror.net/6/docs/ref/#highlight.tags.content) that is styled strong. - */ - strong: /*@__PURE__*/t(content), - /** - [Content](https://codemirror.net/6/docs/ref/#highlight.tags.content) that is part of a link. - */ - link: /*@__PURE__*/t(content), - /** - [Content](https://codemirror.net/6/docs/ref/#highlight.tags.content) that is styled as code or - monospace. - */ - monospace: /*@__PURE__*/t(content), - /** - [Content](https://codemirror.net/6/docs/ref/#highlight.tags.content) that has a strike-through - style. - */ - strikethrough: /*@__PURE__*/t(content), - /** - Inserted text in a change-tracking format. - */ - inserted: /*@__PURE__*/t(), - /** - Deleted text. - */ - deleted: /*@__PURE__*/t(), - /** - Changed text. - */ - changed: /*@__PURE__*/t(), - /** - An invalid or unsyntactic element. - */ - invalid: /*@__PURE__*/t(), - /** - Metadata or meta-instruction. - */ - meta, - /** - [Metadata](https://codemirror.net/6/docs/ref/#highlight.tags.meta) that applies to the entire - document. - */ - documentMeta: /*@__PURE__*/t(meta), - /** - [Metadata](https://codemirror.net/6/docs/ref/#highlight.tags.meta) that annotates or adds - attributes to a given syntactic element. - */ - annotation: /*@__PURE__*/t(meta), - /** - Processing instruction or preprocessor directive. Subtag of - [meta](https://codemirror.net/6/docs/ref/#highlight.tags.meta). - */ - processingInstruction: /*@__PURE__*/t(meta), - /** - [Modifier](https://codemirror.net/6/docs/ref/#highlight.Tag^defineModifier) that indicates that a - given element is being defined. Expected to be used with the - various [name](https://codemirror.net/6/docs/ref/#highlight.tags.name) tags. - */ - definition: /*@__PURE__*/Tag.defineModifier(), - /** - [Modifier](https://codemirror.net/6/docs/ref/#highlight.Tag^defineModifier) that indicates that - something is constant. Mostly expected to be used with - [variable names](https://codemirror.net/6/docs/ref/#highlight.tags.variableName). - */ - constant: /*@__PURE__*/Tag.defineModifier(), - /** - [Modifier](https://codemirror.net/6/docs/ref/#highlight.Tag^defineModifier) used to indicate that - a [variable](https://codemirror.net/6/docs/ref/#highlight.tags.variableName) or [property - name](https://codemirror.net/6/docs/ref/#highlight.tags.propertyName) is being called or defined - as a function. - */ - function: /*@__PURE__*/Tag.defineModifier(), - /** - [Modifier](https://codemirror.net/6/docs/ref/#highlight.Tag^defineModifier) that can be applied to - [names](https://codemirror.net/6/docs/ref/#highlight.tags.name) to indicate that they belong to - the language's standard environment. - */ - standard: /*@__PURE__*/Tag.defineModifier(), - /** - [Modifier](https://codemirror.net/6/docs/ref/#highlight.Tag^defineModifier) that indicates a given - [names](https://codemirror.net/6/docs/ref/#highlight.tags.name) is local to some scope. - */ - local: /*@__PURE__*/Tag.defineModifier(), - /** - A generic variant [modifier](https://codemirror.net/6/docs/ref/#highlight.Tag^defineModifier) that - can be used to tag language-specific alternative variants of - some common tag. It is recommended for themes to define special - forms of at least the [string](https://codemirror.net/6/docs/ref/#highlight.tags.string) and - [variable name](https://codemirror.net/6/docs/ref/#highlight.tags.variableName) tags, since those - come up a lot. - */ - special: /*@__PURE__*/Tag.defineModifier() - }; - /** - A default highlight style (works well with light themes). - */ - const defaultHighlightStyle = /*@__PURE__*/HighlightStyle.define([ - { tag: tags.link, - textDecoration: "underline" }, - { tag: tags.heading, - textDecoration: "underline", - fontWeight: "bold" }, - { tag: tags.emphasis, - fontStyle: "italic" }, - { tag: tags.strong, - fontWeight: "bold" }, - { tag: tags.strikethrough, - textDecoration: "line-through" }, - { tag: tags.keyword, - color: "#708" }, - { tag: [tags.atom, tags.bool, tags.url, tags.contentSeparator, tags.labelName], - color: "#219" }, - { tag: [tags.literal, tags.inserted], - color: "#164" }, - { tag: [tags.string, tags.deleted], - color: "#a11" }, - { tag: [tags.regexp, tags.escape, /*@__PURE__*/tags.special(tags.string)], - color: "#e40" }, - { tag: /*@__PURE__*/tags.definition(tags.variableName), - color: "#00f" }, - { tag: /*@__PURE__*/tags.local(tags.variableName), - color: "#30a" }, - { tag: [tags.typeName, tags.namespace], - color: "#085" }, - { tag: tags.className, - color: "#167" }, - { tag: [/*@__PURE__*/tags.special(tags.variableName), tags.macroName], - color: "#256" }, - { tag: /*@__PURE__*/tags.definition(tags.propertyName), - color: "#00c" }, - { tag: tags.comment, - color: "#940" }, - { tag: tags.meta, - color: "#7a757a" }, - { tag: tags.invalid, - color: "#f00" } - ]); - /** - This is a highlight style that adds stable, predictable classes to - tokens, for styling with external CSS. - - These tags are mapped to their name prefixed with `"cmt-"` (for - example `"cmt-comment"`): - - * [`link`](https://codemirror.net/6/docs/ref/#highlight.tags.link) - * [`heading`](https://codemirror.net/6/docs/ref/#highlight.tags.heading) - * [`emphasis`](https://codemirror.net/6/docs/ref/#highlight.tags.emphasis) - * [`strong`](https://codemirror.net/6/docs/ref/#highlight.tags.strong) - * [`keyword`](https://codemirror.net/6/docs/ref/#highlight.tags.keyword) - * [`atom`](https://codemirror.net/6/docs/ref/#highlight.tags.atom) - * [`bool`](https://codemirror.net/6/docs/ref/#highlight.tags.bool) - * [`url`](https://codemirror.net/6/docs/ref/#highlight.tags.url) - * [`labelName`](https://codemirror.net/6/docs/ref/#highlight.tags.labelName) - * [`inserted`](https://codemirror.net/6/docs/ref/#highlight.tags.inserted) - * [`deleted`](https://codemirror.net/6/docs/ref/#highlight.tags.deleted) - * [`literal`](https://codemirror.net/6/docs/ref/#highlight.tags.literal) - * [`string`](https://codemirror.net/6/docs/ref/#highlight.tags.string) - * [`number`](https://codemirror.net/6/docs/ref/#highlight.tags.number) - * [`variableName`](https://codemirror.net/6/docs/ref/#highlight.tags.variableName) - * [`typeName`](https://codemirror.net/6/docs/ref/#highlight.tags.typeName) - * [`namespace`](https://codemirror.net/6/docs/ref/#highlight.tags.namespace) - * [`className`](https://codemirror.net/6/docs/ref/#highlight.tags.className) - * [`macroName`](https://codemirror.net/6/docs/ref/#highlight.tags.macroName) - * [`propertyName`](https://codemirror.net/6/docs/ref/#highlight.tags.propertyName) - * [`operator`](https://codemirror.net/6/docs/ref/#highlight.tags.operator) - * [`comment`](https://codemirror.net/6/docs/ref/#highlight.tags.comment) - * [`meta`](https://codemirror.net/6/docs/ref/#highlight.tags.meta) - * [`punctuation`](https://codemirror.net/6/docs/ref/#highlight.tags.puncutation) - * [`invalid`](https://codemirror.net/6/docs/ref/#highlight.tags.invalid) - - In addition, these mappings are provided: - - * [`regexp`](https://codemirror.net/6/docs/ref/#highlight.tags.regexp), - [`escape`](https://codemirror.net/6/docs/ref/#highlight.tags.escape), and - [`special`](https://codemirror.net/6/docs/ref/#highlight.tags.special)[`(string)`](https://codemirror.net/6/docs/ref/#highlight.tags.string) - are mapped to `"cmt-string2"` - * [`special`](https://codemirror.net/6/docs/ref/#highlight.tags.special)[`(variableName)`](https://codemirror.net/6/docs/ref/#highlight.tags.variableName) - to `"cmt-variableName2"` - * [`local`](https://codemirror.net/6/docs/ref/#highlight.tags.local)[`(variableName)`](https://codemirror.net/6/docs/ref/#highlight.tags.variableName) - to `"cmt-variableName cmt-local"` - * [`definition`](https://codemirror.net/6/docs/ref/#highlight.tags.definition)[`(variableName)`](https://codemirror.net/6/docs/ref/#highlight.tags.variableName) - to `"cmt-variableName cmt-definition"` - * [`definition`](https://codemirror.net/6/docs/ref/#highlight.tags.definition)[`(propertyName)`](https://codemirror.net/6/docs/ref/#highlight.tags.propertyName) - to `"cmt-propertyName cmt-definition"` - */ - /*@__PURE__*/HighlightStyle.define([ - { tag: tags.link, class: "cmt-link" }, - { tag: tags.heading, class: "cmt-heading" }, - { tag: tags.emphasis, class: "cmt-emphasis" }, - { tag: tags.strong, class: "cmt-strong" }, - { tag: tags.keyword, class: "cmt-keyword" }, - { tag: tags.atom, class: "cmt-atom" }, - { tag: tags.bool, class: "cmt-bool" }, - { tag: tags.url, class: "cmt-url" }, - { tag: tags.labelName, class: "cmt-labelName" }, - { tag: tags.inserted, class: "cmt-inserted" }, - { tag: tags.deleted, class: "cmt-deleted" }, - { tag: tags.literal, class: "cmt-literal" }, - { tag: tags.string, class: "cmt-string" }, - { tag: tags.number, class: "cmt-number" }, - { tag: [tags.regexp, tags.escape, /*@__PURE__*/tags.special(tags.string)], class: "cmt-string2" }, - { tag: tags.variableName, class: "cmt-variableName" }, - { tag: /*@__PURE__*/tags.local(tags.variableName), class: "cmt-variableName cmt-local" }, - { tag: /*@__PURE__*/tags.definition(tags.variableName), class: "cmt-variableName cmt-definition" }, - { tag: /*@__PURE__*/tags.special(tags.variableName), class: "cmt-variableName2" }, - { tag: /*@__PURE__*/tags.definition(tags.propertyName), class: "cmt-propertyName cmt-definition" }, - { tag: tags.typeName, class: "cmt-typeName" }, - { tag: tags.namespace, class: "cmt-namespace" }, - { tag: tags.className, class: "cmt-className" }, - { tag: tags.macroName, class: "cmt-macroName" }, - { tag: tags.propertyName, class: "cmt-propertyName" }, - { tag: tags.operator, class: "cmt-operator" }, - { tag: tags.comment, class: "cmt-comment" }, - { tag: tags.meta, class: "cmt-meta" }, - { tag: tags.invalid, class: "cmt-invalid" }, - { tag: tags.punctuation, class: "cmt-punctuation" } - ]); - - class SelectedDiagnostic { - constructor(from, to, diagnostic) { - this.from = from; - this.to = to; - this.diagnostic = diagnostic; - } - } - class LintState { - constructor(diagnostics, panel, selected) { - this.diagnostics = diagnostics; - this.panel = panel; - this.selected = selected; - } - static init(diagnostics, panel, state) { - let ranges = Decoration.set(diagnostics.map((d) => { - // For zero-length ranges or ranges covering only a line break, create a widget - return d.from == d.to || (d.from == d.to - 1 && state.doc.lineAt(d.from).to == d.from) - ? Decoration.widget({ - widget: new DiagnosticWidget(d), - diagnostic: d - }).range(d.from) - : Decoration.mark({ - attributes: { class: "cm-lintRange cm-lintRange-" + d.severity }, - diagnostic: d - }).range(d.from, d.to); - }), true); - return new LintState(ranges, panel, findDiagnostic(ranges)); - } - } - function findDiagnostic(diagnostics, diagnostic = null, after = 0) { - let found = null; - diagnostics.between(after, 1e9, (from, to, { spec }) => { - if (diagnostic && spec.diagnostic != diagnostic) - return; - found = new SelectedDiagnostic(from, to, spec.diagnostic); - return false; - }); - return found; - } - function maybeEnableLint(state, effects) { - return state.field(lintState, false) ? effects : effects.concat(StateEffect.appendConfig.of([ - lintState, - EditorView.decorations.compute([lintState], state => { - let { selected, panel } = state.field(lintState); - return !selected || !panel || selected.from == selected.to ? Decoration.none : Decoration.set([ - activeMark.range(selected.from, selected.to) - ]); - }), - hoverTooltip(lintTooltip), - baseTheme - ])); - } - /** - The state effect that updates the set of active diagnostics. Can - be useful when writing an extension that needs to track these. - */ - const setDiagnosticsEffect = /*@__PURE__*/StateEffect.define(); - const togglePanel = /*@__PURE__*/StateEffect.define(); - const movePanelSelection = /*@__PURE__*/StateEffect.define(); - const lintState = /*@__PURE__*/StateField.define({ - create() { - return new LintState(Decoration.none, null, null); - }, - update(value, tr) { - if (tr.docChanged) { - let mapped = value.diagnostics.map(tr.changes), selected = null; - if (value.selected) { - let selPos = tr.changes.mapPos(value.selected.from, 1); - selected = findDiagnostic(mapped, value.selected.diagnostic, selPos) || findDiagnostic(mapped, null, selPos); - } - value = new LintState(mapped, value.panel, selected); - } - for (let effect of tr.effects) { - if (effect.is(setDiagnosticsEffect)) { - value = LintState.init(effect.value, value.panel, tr.state); - } - else if (effect.is(togglePanel)) { - value = new LintState(value.diagnostics, effect.value ? LintPanel.open : null, value.selected); - } - else if (effect.is(movePanelSelection)) { - value = new LintState(value.diagnostics, value.panel, effect.value); - } - } - return value; - }, - provide: f => [showPanel.from(f, val => val.panel), - EditorView.decorations.from(f, s => s.diagnostics)] - }); - const activeMark = /*@__PURE__*/Decoration.mark({ class: "cm-lintRange cm-lintRange-active" }); - function lintTooltip(view, pos, side) { - let { diagnostics } = view.state.field(lintState); - let found = [], stackStart = 2e8, stackEnd = 0; - diagnostics.between(pos - (side < 0 ? 1 : 0), pos + (side > 0 ? 1 : 0), (from, to, { spec }) => { - if (pos >= from && pos <= to && - (from == to || ((pos > from || side > 0) && (pos < to || side < 0)))) { - found.push(spec.diagnostic); - stackStart = Math.min(from, stackStart); - stackEnd = Math.max(to, stackEnd); - } - }); - if (!found.length) - return null; - return { - pos: stackStart, - end: stackEnd, - above: view.state.doc.lineAt(stackStart).to < stackEnd, - create() { - return { dom: diagnosticsTooltip(view, found) }; - } - }; - } - function diagnosticsTooltip(view, diagnostics) { - return crelt("ul", { class: "cm-tooltip-lint" }, diagnostics.map(d => renderDiagnostic(view, d, false))); - } - /** - Command to open and focus the lint panel. - */ - const openLintPanel = (view) => { - let field = view.state.field(lintState, false); - if (!field || !field.panel) - view.dispatch({ effects: maybeEnableLint(view.state, [togglePanel.of(true)]) }); - let panel = getPanel(view, LintPanel.open); - if (panel) - panel.dom.querySelector(".cm-panel-lint ul").focus(); - return true; - }; - /** - Command to close the lint panel, when open. - */ - const closeLintPanel = (view) => { - let field = view.state.field(lintState, false); - if (!field || !field.panel) - return false; - view.dispatch({ effects: togglePanel.of(false) }); - return true; - }; - /** - Move the selection to the next diagnostic. - */ - const nextDiagnostic = (view) => { - let field = view.state.field(lintState, false); - if (!field) - return false; - let sel = view.state.selection.main, next = field.diagnostics.iter(sel.to + 1); - if (!next.value) { - next = field.diagnostics.iter(0); - if (!next.value || next.from == sel.from && next.to == sel.to) - return false; - } - view.dispatch({ selection: { anchor: next.from, head: next.to }, scrollIntoView: true }); - return true; - }; - /** - A set of default key bindings for the lint functionality. - - - Ctrl-Shift-m (Cmd-Shift-m on macOS): [`openLintPanel`](https://codemirror.net/6/docs/ref/#lint.openLintPanel) - - F8: [`nextDiagnostic`](https://codemirror.net/6/docs/ref/#lint.nextDiagnostic) - */ - const lintKeymap = [ - { key: "Mod-Shift-m", run: openLintPanel }, - { key: "F8", run: nextDiagnostic } - ]; - function assignKeys(actions) { - let assigned = []; - if (actions) - actions: for (let { name } of actions) { - for (let i = 0; i < name.length; i++) { - let ch = name[i]; - if (/[a-zA-Z]/.test(ch) && !assigned.some(c => c.toLowerCase() == ch.toLowerCase())) { - assigned.push(ch); - continue actions; - } - } - assigned.push(""); - } - return assigned; - } - function renderDiagnostic(view, diagnostic, inPanel) { - var _a; - let keys = inPanel ? assignKeys(diagnostic.actions) : []; - return crelt("li", { class: "cm-diagnostic cm-diagnostic-" + diagnostic.severity }, crelt("span", { class: "cm-diagnosticText" }, diagnostic.message), (_a = diagnostic.actions) === null || _a === void 0 ? void 0 : _a.map((action, i) => { - let click = (e) => { - e.preventDefault(); - let found = findDiagnostic(view.state.field(lintState).diagnostics, diagnostic); - if (found) - action.apply(view, found.from, found.to); - }; - let { name } = action, keyIndex = keys[i] ? name.indexOf(keys[i]) : -1; - let nameElt = keyIndex < 0 ? name : [name.slice(0, keyIndex), - crelt("u", name.slice(keyIndex, keyIndex + 1)), - name.slice(keyIndex + 1)]; - return crelt("button", { - type: "button", - class: "cm-diagnosticAction", - onclick: click, - onmousedown: click, - "aria-label": ` Action: ${name}${keyIndex < 0 ? "" : ` (access key "${keys[i]})"`}.` - }, nameElt); - }), diagnostic.source && crelt("div", { class: "cm-diagnosticSource" }, diagnostic.source)); - } - class DiagnosticWidget extends WidgetType { - constructor(diagnostic) { - super(); - this.diagnostic = diagnostic; - } - eq(other) { return other.diagnostic == this.diagnostic; } - toDOM() { - return crelt("span", { class: "cm-lintPoint cm-lintPoint-" + this.diagnostic.severity }); - } - } - class PanelItem { - constructor(view, diagnostic) { - this.diagnostic = diagnostic; - this.id = "item_" + Math.floor(Math.random() * 0xffffffff).toString(16); - this.dom = renderDiagnostic(view, diagnostic, true); - this.dom.id = this.id; - this.dom.setAttribute("role", "option"); - } - } - class LintPanel { - constructor(view) { - this.view = view; - this.items = []; - let onkeydown = (event) => { - if (event.keyCode == 27) { // Escape - closeLintPanel(this.view); - this.view.focus(); - } - else if (event.keyCode == 38 || event.keyCode == 33) { // ArrowUp, PageUp - this.moveSelection((this.selectedIndex - 1 + this.items.length) % this.items.length); - } - else if (event.keyCode == 40 || event.keyCode == 34) { // ArrowDown, PageDown - this.moveSelection((this.selectedIndex + 1) % this.items.length); - } - else if (event.keyCode == 36) { // Home - this.moveSelection(0); - } - else if (event.keyCode == 35) { // End - this.moveSelection(this.items.length - 1); - } - else if (event.keyCode == 13) { // Enter - this.view.focus(); - } - else if (event.keyCode >= 65 && event.keyCode <= 90 && this.selectedIndex >= 0) { // A-Z - let { diagnostic } = this.items[this.selectedIndex], keys = assignKeys(diagnostic.actions); - for (let i = 0; i < keys.length; i++) - if (keys[i].toUpperCase().charCodeAt(0) == event.keyCode) { - let found = findDiagnostic(this.view.state.field(lintState).diagnostics, diagnostic); - if (found) - diagnostic.actions[i].apply(view, found.from, found.to); - } - } - else { - return; - } - event.preventDefault(); - }; - let onclick = (event) => { - for (let i = 0; i < this.items.length; i++) { - if (this.items[i].dom.contains(event.target)) - this.moveSelection(i); - } - }; - this.list = crelt("ul", { - tabIndex: 0, - role: "listbox", - "aria-label": this.view.state.phrase("Diagnostics"), - onkeydown, - onclick - }); - this.dom = crelt("div", { class: "cm-panel-lint" }, this.list, crelt("button", { - type: "button", - name: "close", - "aria-label": this.view.state.phrase("close"), - onclick: () => closeLintPanel(this.view) - }, "×")); - this.update(); - } - get selectedIndex() { - let selected = this.view.state.field(lintState).selected; - if (!selected) - return -1; - for (let i = 0; i < this.items.length; i++) - if (this.items[i].diagnostic == selected.diagnostic) - return i; - return -1; - } - update() { - let { diagnostics, selected } = this.view.state.field(lintState); - let i = 0, needsSync = false, newSelectedItem = null; - diagnostics.between(0, this.view.state.doc.length, (_start, _end, { spec }) => { - let found = -1, item; - for (let j = i; j < this.items.length; j++) - if (this.items[j].diagnostic == spec.diagnostic) { - found = j; - break; - } - if (found < 0) { - item = new PanelItem(this.view, spec.diagnostic); - this.items.splice(i, 0, item); - needsSync = true; - } - else { - item = this.items[found]; - if (found > i) { - this.items.splice(i, found - i); - needsSync = true; - } - } - if (selected && item.diagnostic == selected.diagnostic) { - if (!item.dom.hasAttribute("aria-selected")) { - item.dom.setAttribute("aria-selected", "true"); - newSelectedItem = item; - } - } - else if (item.dom.hasAttribute("aria-selected")) { - item.dom.removeAttribute("aria-selected"); - } - i++; - }); - while (i < this.items.length && !(this.items.length == 1 && this.items[0].diagnostic.from < 0)) { - needsSync = true; - this.items.pop(); - } - if (this.items.length == 0) { - this.items.push(new PanelItem(this.view, { - from: -1, to: -1, - severity: "info", - message: this.view.state.phrase("No diagnostics") - })); - needsSync = true; - } - if (newSelectedItem) { - this.list.setAttribute("aria-activedescendant", newSelectedItem.id); - this.view.requestMeasure({ - key: this, - read: () => ({ sel: newSelectedItem.dom.getBoundingClientRect(), panel: this.list.getBoundingClientRect() }), - write: ({ sel, panel }) => { - if (sel.top < panel.top) - this.list.scrollTop -= panel.top - sel.top; - else if (sel.bottom > panel.bottom) - this.list.scrollTop += sel.bottom - panel.bottom; - } - }); - } - else if (this.selectedIndex < 0) { - this.list.removeAttribute("aria-activedescendant"); - } - if (needsSync) - this.sync(); - } - sync() { - let domPos = this.list.firstChild; - function rm() { - let prev = domPos; - domPos = prev.nextSibling; - prev.remove(); - } - for (let item of this.items) { - if (item.dom.parentNode == this.list) { - while (domPos != item.dom) - rm(); - domPos = item.dom.nextSibling; - } - else { - this.list.insertBefore(item.dom, domPos); - } - } - while (domPos) - rm(); - } - moveSelection(selectedIndex) { - if (this.selectedIndex < 0) - return; - let field = this.view.state.field(lintState); - let selection = findDiagnostic(field.diagnostics, this.items[selectedIndex].diagnostic); - if (!selection) - return; - this.view.dispatch({ - selection: { anchor: selection.from, head: selection.to }, - scrollIntoView: true, - effects: movePanelSelection.of(selection) - }); - } - static open(view) { return new LintPanel(view); } - } - function svg(content, attrs = `viewBox="0 0 40 40"`) { - return `url('data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" ${attrs}>${encodeURIComponent(content)}</svg>')`; - } - function underline(color) { - return svg(`<path d="m0 2.5 l2 -1.5 l1 0 l2 1.5 l1 0" stroke="${color}" fill="none" stroke-width=".7"/>`, `width="6" height="3"`); - } - const baseTheme = /*@__PURE__*/EditorView.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-diagnosticAction": { - font: "inherit", - border: "none", - padding: "2px 4px", - backgroundColor: "#444", - color: "white", - borderRadius: "3px", - marginLeft: "8px" - }, - ".cm-diagnosticSource": { - fontSize: "70%", - opacity: .7 - }, - ".cm-lintRange": { - backgroundPosition: "left bottom", - backgroundRepeat: "repeat-x", - paddingBottom: "0.7px", - }, - ".cm-lintRange-error": { backgroundImage: /*@__PURE__*/underline("#d11") }, - ".cm-lintRange-warning": { backgroundImage: /*@__PURE__*/underline("orange") }, - ".cm-lintRange-info": { backgroundImage: /*@__PURE__*/underline("#999") }, - ".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-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 - } - } - }); - - /** - This is an extension value that just pulls together a whole lot of - extensions that you might want in a basic editor. It is meant as a - convenient helper to quickly set up CodeMirror without installing - and importing a lot of packages. - - Specifically, it includes... - - - [the default command bindings](https://codemirror.net/6/docs/ref/#commands.defaultKeymap) - - [line numbers](https://codemirror.net/6/docs/ref/#gutter.lineNumbers) - - [special character highlighting](https://codemirror.net/6/docs/ref/#view.highlightSpecialChars) - - [the undo history](https://codemirror.net/6/docs/ref/#history.history) - - [a fold gutter](https://codemirror.net/6/docs/ref/#fold.foldGutter) - - [custom selection drawing](https://codemirror.net/6/docs/ref/#view.drawSelection) - - [drop cursor](https://codemirror.net/6/docs/ref/#view.dropCursor) - - [multiple selections](https://codemirror.net/6/docs/ref/#state.EditorState^allowMultipleSelections) - - [reindentation on input](https://codemirror.net/6/docs/ref/#language.indentOnInput) - - [the default highlight style](https://codemirror.net/6/docs/ref/#highlight.defaultHighlightStyle) (as fallback) - - [bracket matching](https://codemirror.net/6/docs/ref/#matchbrackets.bracketMatching) - - [bracket closing](https://codemirror.net/6/docs/ref/#closebrackets.closeBrackets) - - [autocompletion](https://codemirror.net/6/docs/ref/#autocomplete.autocompletion) - - [rectangular selection](https://codemirror.net/6/docs/ref/#rectangular-selection.rectangularSelection) and [crosshair cursor](https://codemirror.net/6/docs/ref/#rectangular-selection.crosshairCursor) - - [active line highlighting](https://codemirror.net/6/docs/ref/#view.highlightActiveLine) - - [active line gutter highlighting](https://codemirror.net/6/docs/ref/#gutter.highlightActiveLineGutter) - - [selection match highlighting](https://codemirror.net/6/docs/ref/#search.highlightSelectionMatches) - - [search](https://codemirror.net/6/docs/ref/#search.searchKeymap) - - [commenting](https://codemirror.net/6/docs/ref/#comment.commentKeymap) - - [linting](https://codemirror.net/6/docs/ref/#lint.lintKeymap) - - (You'll probably want to add some language package to your setup - too.) - - This package does not allow customization. The idea is that, once - you decide you want to configure your editor more precisely, you - take this package's source (which is just a bunch of imports and - an array literal), copy it into your own code, and adjust it as - desired. - */ - const basicSetup = [ - /*@__PURE__*/lineNumbers(), - /*@__PURE__*/highlightActiveLineGutter(), - /*@__PURE__*/highlightSpecialChars(), - /*@__PURE__*/history(), - /*@__PURE__*/foldGutter(), - /*@__PURE__*/drawSelection(), - /*@__PURE__*/dropCursor(), - /*@__PURE__*/EditorState.allowMultipleSelections.of(true), - /*@__PURE__*/indentOnInput(), - defaultHighlightStyle.fallback, - /*@__PURE__*/bracketMatching(), - /*@__PURE__*/closeBrackets(), - /*@__PURE__*/autocompletion(), - /*@__PURE__*/rectangularSelection(), - /*@__PURE__*/crosshairCursor(), - /*@__PURE__*/highlightActiveLine(), - /*@__PURE__*/highlightSelectionMatches(), - /*@__PURE__*/keymap.of([ - ...closeBracketsKeymap, - ...defaultKeymap, - ...searchKeymap, - ...historyKeymap, - ...foldKeymap, - ...commentKeymap, - ...completionKeymap, - ...lintKeymap - ]) - ]; - - /// A parse stack. These are used internally by the parser to track - /// parsing progress. They also provide some properties and methods - /// that external code such as a tokenizer can use to get information - /// about the parse state. - class Stack { - /// @internal - constructor( - /// The parse that this stack is part of @internal - p, - /// Holds state, input pos, buffer index triplets for all but the - /// top state @internal - stack, - /// The current parse state @internal - state, - // The position at which the next reduce should take place. This - // can be less than `this.pos` when skipped expressions have been - // added to the stack (which should be moved outside of the next - // reduction) - /// @internal - reducePos, - /// The input position up to which this stack has parsed. - pos, - /// The dynamic score of the stack, including dynamic precedence - /// and error-recovery penalties - /// @internal - score, - // The output buffer. Holds (type, start, end, size) quads - // representing nodes created by the parser, where `size` is - // amount of buffer array entries covered by this node. - /// @internal - buffer, - // The base offset of the buffer. When stacks are split, the split - // instance shared the buffer history with its parent up to - // `bufferBase`, which is the absolute offset (including the - // offset of previous splits) into the buffer at which this stack - // starts writing. - /// @internal - bufferBase, - /// @internal - curContext, - /// @internal - lookAhead = 0, - // A parent stack from which this was split off, if any. This is - // set up so that it always points to a stack that has some - // additional buffer content, never to a stack with an equal - // `bufferBase`. - /// @internal - parent) { - this.p = p; - this.stack = stack; - this.state = state; - this.reducePos = reducePos; - this.pos = pos; - this.score = score; - this.buffer = buffer; - this.bufferBase = bufferBase; - this.curContext = curContext; - this.lookAhead = lookAhead; - this.parent = parent; - } - /// @internal - toString() { - return `[${this.stack.filter((_, i) => i % 3 == 0).concat(this.state)}]@${this.pos}${this.score ? "!" + this.score : ""}`; - } - // Start an empty stack - /// @internal - static start(p, state, pos = 0) { - let cx = p.parser.context; - return new Stack(p, [], state, pos, pos, 0, [], 0, cx ? new StackContext(cx, cx.start) : null, 0, null); - } - /// The stack's current [context](#lr.ContextTracker) value, if - /// any. Its type will depend on the context tracker's type - /// parameter, or it will be `null` if there is no context - /// tracker. - get context() { return this.curContext ? this.curContext.context : null; } - // Push a state onto the stack, tracking its start position as well - // as the buffer base at that point. - /// @internal - pushState(state, start) { - this.stack.push(this.state, start, this.bufferBase + this.buffer.length); - this.state = state; - } - // Apply a reduce action - /// @internal - reduce(action) { - let depth = action >> 19 /* ReduceDepthShift */, type = action & 65535 /* ValueMask */; - let { parser } = this.p; - let dPrec = parser.dynamicPrecedence(type); - if (dPrec) - this.score += dPrec; - if (depth == 0) { - this.pushState(parser.getGoto(this.state, type, true), this.reducePos); - // Zero-depth reductions are a special case—they add stuff to - // the stack without popping anything off. - if (type < parser.minRepeatTerm) - this.storeNode(type, this.reducePos, this.reducePos, 4, true); - this.reduceContext(type, this.reducePos); - return; - } - // Find the base index into `this.stack`, content after which will - // be dropped. Note that with `StayFlag` reductions we need to - // consume two extra frames (the dummy parent node for the skipped - // expression and the state that we'll be staying in, which should - // be moved to `this.state`). - let base = this.stack.length - ((depth - 1) * 3) - (action & 262144 /* StayFlag */ ? 6 : 0); - let start = this.stack[base - 2]; - let bufferBase = this.stack[base - 1], count = this.bufferBase + this.buffer.length - bufferBase; - // Store normal terms or `R -> R R` repeat reductions - if (type < parser.minRepeatTerm || (action & 131072 /* RepeatFlag */)) { - let pos = parser.stateFlag(this.state, 1 /* Skipped */) ? this.pos : this.reducePos; - this.storeNode(type, start, pos, count + 4, true); - } - if (action & 262144 /* StayFlag */) { - this.state = this.stack[base]; - } - else { - let baseStateID = this.stack[base - 3]; - this.state = parser.getGoto(baseStateID, type, true); - } - while (this.stack.length > base) - this.stack.pop(); - this.reduceContext(type, start); - } - // Shift a value into the buffer - /// @internal - storeNode(term, start, end, size = 4, isReduce = false) { - if (term == 0 /* Err */) { // Try to omit/merge adjacent error nodes - let cur = this, top = this.buffer.length; - if (top == 0 && cur.parent) { - top = cur.bufferBase - cur.parent.bufferBase; - cur = cur.parent; - } - if (top > 0 && cur.buffer[top - 4] == 0 /* Err */ && cur.buffer[top - 1] > -1) { - if (start == end) - return; - if (cur.buffer[top - 2] >= start) { - cur.buffer[top - 2] = end; - return; - } - } - } - if (!isReduce || this.pos == end) { // Simple case, just append - this.buffer.push(term, start, end, size); - } - else { // There may be skipped nodes that have to be moved forward - let index = this.buffer.length; - if (index > 0 && this.buffer[index - 4] != 0 /* Err */) - while (index > 0 && this.buffer[index - 2] > end) { - // Move this record forward - this.buffer[index] = this.buffer[index - 4]; - this.buffer[index + 1] = this.buffer[index - 3]; - this.buffer[index + 2] = this.buffer[index - 2]; - this.buffer[index + 3] = this.buffer[index - 1]; - index -= 4; - if (size > 4) - size -= 4; - } - this.buffer[index] = term; - this.buffer[index + 1] = start; - this.buffer[index + 2] = end; - this.buffer[index + 3] = size; - } - } - // Apply a shift action - /// @internal - shift(action, next, nextEnd) { - let start = this.pos; - if (action & 131072 /* GotoFlag */) { - this.pushState(action & 65535 /* ValueMask */, this.pos); - } - else if ((action & 262144 /* StayFlag */) == 0) { // Regular shift - let nextState = action, { parser } = this.p; - if (nextEnd > this.pos || next <= parser.maxNode) { - this.pos = nextEnd; - if (!parser.stateFlag(nextState, 1 /* Skipped */)) - this.reducePos = nextEnd; - } - this.pushState(nextState, start); - this.shiftContext(next, start); - if (next <= parser.maxNode) - this.buffer.push(next, start, nextEnd, 4); - } - else { // Shift-and-stay, which means this is a skipped token - this.pos = nextEnd; - this.shiftContext(next, start); - if (next <= this.p.parser.maxNode) - this.buffer.push(next, start, nextEnd, 4); - } - } - // Apply an action - /// @internal - apply(action, next, nextEnd) { - if (action & 65536 /* ReduceFlag */) - this.reduce(action); - else - this.shift(action, next, nextEnd); - } - // Add a prebuilt (reused) node into the buffer. - /// @internal - useNode(value, next) { - let index = this.p.reused.length - 1; - if (index < 0 || this.p.reused[index] != value) { - this.p.reused.push(value); - index++; - } - let start = this.pos; - this.reducePos = this.pos = start + value.length; - this.pushState(next, start); - this.buffer.push(index, start, this.reducePos, -1 /* size == -1 means this is a reused value */); - if (this.curContext) - this.updateContext(this.curContext.tracker.reuse(this.curContext.context, value, this, this.p.stream.reset(this.pos - value.length))); - } - // Split the stack. Due to the buffer sharing and the fact - // that `this.stack` tends to stay quite shallow, this isn't very - // expensive. - /// @internal - split() { - let parent = this; - let off = parent.buffer.length; - // Because the top of the buffer (after this.pos) may be mutated - // to reorder reductions and skipped tokens, and shared buffers - // should be immutable, this copies any outstanding skipped tokens - // to the new buffer, and puts the base pointer before them. - while (off > 0 && parent.buffer[off - 2] > parent.reducePos) - off -= 4; - let buffer = parent.buffer.slice(off), base = parent.bufferBase + off; - // Make sure parent points to an actual parent with content, if there is such a parent. - while (parent && base == parent.bufferBase) - parent = parent.parent; - return new Stack(this.p, this.stack.slice(), this.state, this.reducePos, this.pos, this.score, buffer, base, this.curContext, this.lookAhead, parent); - } - // Try to recover from an error by 'deleting' (ignoring) one token. - /// @internal - recoverByDelete(next, nextEnd) { - let isNode = next <= this.p.parser.maxNode; - if (isNode) - this.storeNode(next, this.pos, nextEnd, 4); - this.storeNode(0 /* Err */, this.pos, nextEnd, isNode ? 8 : 4); - this.pos = this.reducePos = nextEnd; - this.score -= 190 /* Delete */; - } - /// Check if the given term would be able to be shifted (optionally - /// after some reductions) on this stack. This can be useful for - /// external tokenizers that want to make sure they only provide a - /// given token when it applies. - canShift(term) { - for (let sim = new SimulatedStack(this);;) { - let action = this.p.parser.stateSlot(sim.state, 4 /* DefaultReduce */) || this.p.parser.hasAction(sim.state, term); - if ((action & 65536 /* ReduceFlag */) == 0) - return true; - if (action == 0) - return false; - sim.reduce(action); - } - } - // Apply up to Recover.MaxNext recovery actions that conceptually - // inserts some missing token or rule. - /// @internal - recoverByInsert(next) { - if (this.stack.length >= 300 /* MaxInsertStackDepth */) - return []; - let nextStates = this.p.parser.nextStates(this.state); - if (nextStates.length > 4 /* MaxNext */ << 1 || this.stack.length >= 120 /* DampenInsertStackDepth */) { - let best = []; - for (let i = 0, s; i < nextStates.length; i += 2) { - if ((s = nextStates[i + 1]) != this.state && this.p.parser.hasAction(s, next)) - best.push(nextStates[i], s); - } - if (this.stack.length < 120 /* DampenInsertStackDepth */) - for (let i = 0; best.length < 4 /* MaxNext */ << 1 && i < nextStates.length; i += 2) { - let s = nextStates[i + 1]; - if (!best.some((v, i) => (i & 1) && v == s)) - best.push(nextStates[i], s); - } - nextStates = best; - } - let result = []; - for (let i = 0; i < nextStates.length && result.length < 4 /* MaxNext */; i += 2) { - let s = nextStates[i + 1]; - if (s == this.state) - continue; - let stack = this.split(); - stack.storeNode(0 /* Err */, stack.pos, stack.pos, 4, true); - stack.pushState(s, this.pos); - stack.shiftContext(nextStates[i], this.pos); - stack.score -= 200 /* Insert */; - result.push(stack); - } - return result; - } - // Force a reduce, if possible. Return false if that can't - // be done. - /// @internal - forceReduce() { - let reduce = this.p.parser.stateSlot(this.state, 5 /* ForcedReduce */); - if ((reduce & 65536 /* ReduceFlag */) == 0) - return false; - let { parser } = this.p; - if (!parser.validAction(this.state, reduce)) { - let depth = reduce >> 19 /* ReduceDepthShift */, term = reduce & 65535 /* ValueMask */; - let target = this.stack.length - depth * 3; - if (target < 0 || parser.getGoto(this.stack[target], term, false) < 0) - return false; - this.storeNode(0 /* Err */, this.reducePos, this.reducePos, 4, true); - this.score -= 100 /* Reduce */; - } - this.reduce(reduce); - return true; - } - /// @internal - forceAll() { - while (!this.p.parser.stateFlag(this.state, 2 /* Accepting */)) { - if (!this.forceReduce()) { - this.storeNode(0 /* Err */, this.pos, this.pos, 4, true); - break; - } - } - return this; - } - /// Check whether this state has no further actions (assumed to be a direct descendant of the - /// top state, since any other states must be able to continue - /// somehow). @internal - get deadEnd() { - if (this.stack.length != 3) - return false; - let { parser } = this.p; - return parser.data[parser.stateSlot(this.state, 1 /* Actions */)] == 65535 /* End */ && - !parser.stateSlot(this.state, 4 /* DefaultReduce */); - } - /// Restart the stack (put it back in its start state). Only safe - /// when this.stack.length == 3 (state is directly below the top - /// state). @internal - restart() { - this.state = this.stack[0]; - this.stack.length = 0; - } - /// @internal - sameState(other) { - if (this.state != other.state || this.stack.length != other.stack.length) - return false; - for (let i = 0; i < this.stack.length; i += 3) - if (this.stack[i] != other.stack[i]) - return false; - return true; - } - /// Get the parser used by this stack. - get parser() { return this.p.parser; } - /// Test whether a given dialect (by numeric ID, as exported from - /// the terms file) is enabled. - dialectEnabled(dialectID) { return this.p.parser.dialect.flags[dialectID]; } - shiftContext(term, start) { - if (this.curContext) - this.updateContext(this.curContext.tracker.shift(this.curContext.context, term, this, this.p.stream.reset(start))); - } - reduceContext(term, start) { - if (this.curContext) - this.updateContext(this.curContext.tracker.reduce(this.curContext.context, term, this, this.p.stream.reset(start))); - } - /// @internal - emitContext() { - let last = this.buffer.length - 1; - if (last < 0 || this.buffer[last] != -3) - this.buffer.push(this.curContext.hash, this.reducePos, this.reducePos, -3); - } - /// @internal - emitLookAhead() { - let last = this.buffer.length - 1; - if (last < 0 || this.buffer[last] != -4) - this.buffer.push(this.lookAhead, this.reducePos, this.reducePos, -4); - } - updateContext(context) { - if (context != this.curContext.context) { - let newCx = new StackContext(this.curContext.tracker, context); - if (newCx.hash != this.curContext.hash) - this.emitContext(); - this.curContext = newCx; - } - } - /// @internal - setLookAhead(lookAhead) { - if (lookAhead > this.lookAhead) { - this.emitLookAhead(); - this.lookAhead = lookAhead; - } - } - /// @internal - close() { - if (this.curContext && this.curContext.tracker.strict) - this.emitContext(); - if (this.lookAhead > 0) - this.emitLookAhead(); - } - } - class StackContext { - constructor(tracker, context) { - this.tracker = tracker; - this.context = context; - this.hash = tracker.strict ? tracker.hash(context) : 0; - } - } - var Recover; - (function (Recover) { - Recover[Recover["Insert"] = 200] = "Insert"; - Recover[Recover["Delete"] = 190] = "Delete"; - Recover[Recover["Reduce"] = 100] = "Reduce"; - Recover[Recover["MaxNext"] = 4] = "MaxNext"; - Recover[Recover["MaxInsertStackDepth"] = 300] = "MaxInsertStackDepth"; - Recover[Recover["DampenInsertStackDepth"] = 120] = "DampenInsertStackDepth"; - })(Recover || (Recover = {})); - // Used to cheaply run some reductions to scan ahead without mutating - // an entire stack - class SimulatedStack { - constructor(start) { - this.start = start; - this.state = start.state; - this.stack = start.stack; - this.base = this.stack.length; - } - reduce(action) { - let term = action & 65535 /* ValueMask */, depth = action >> 19 /* ReduceDepthShift */; - if (depth == 0) { - if (this.stack == this.start.stack) - this.stack = this.stack.slice(); - this.stack.push(this.state, 0, 0); - this.base += 3; - } - else { - this.base -= (depth - 1) * 3; - } - let goto = this.start.p.parser.getGoto(this.stack[this.base - 3], term, true); - this.state = goto; - } - } - // This is given to `Tree.build` to build a buffer, and encapsulates - // the parent-stack-walking necessary to read the nodes. - class StackBufferCursor { - constructor(stack, pos, index) { - this.stack = stack; - this.pos = pos; - this.index = index; - this.buffer = stack.buffer; - if (this.index == 0) - this.maybeNext(); - } - static create(stack, pos = stack.bufferBase + stack.buffer.length) { - return new StackBufferCursor(stack, pos, pos - stack.bufferBase); - } - maybeNext() { - let next = this.stack.parent; - if (next != null) { - this.index = this.stack.bufferBase - next.bufferBase; - this.stack = next; - this.buffer = next.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; - if (this.index == 0) - this.maybeNext(); - } - fork() { - return new StackBufferCursor(this.stack, this.pos, this.index); - } - } - - class CachedToken { - constructor() { - this.start = -1; - this.value = -1; - this.end = -1; - this.extended = -1; - this.lookAhead = 0; - this.mask = 0; - this.context = 0; - } - } - const nullToken = new CachedToken; - /// [Tokenizers](#lr.ExternalTokenizer) interact with the input - /// through this interface. It presents the input as a stream of - /// characters, tracking lookahead and hiding the complexity of - /// [ranges](#common.Parser.parse^ranges) from tokenizer code. - class InputStream { - /// @internal - constructor( - /// @internal - input, - /// @internal - ranges) { - this.input = input; - this.ranges = ranges; - /// @internal - this.chunk = ""; - /// @internal - this.chunkOff = 0; - /// Backup chunk - this.chunk2 = ""; - this.chunk2Pos = 0; - /// The character code of the next code unit in the input, or -1 - /// when the stream is at the end of the input. - this.next = -1; - /// @internal - this.token = nullToken; - this.rangeIndex = 0; - this.pos = this.chunkPos = ranges[0].from; - this.range = ranges[0]; - this.end = ranges[ranges.length - 1].to; - this.readNext(); - } - resolveOffset(offset, assoc) { - let range = this.range, index = this.rangeIndex; - let pos = this.pos + offset; - while (pos < range.from) { - if (!index) - return null; - let next = this.ranges[--index]; - pos -= range.from - next.to; - range = next; - } - while (assoc < 0 ? pos > range.to : pos >= range.to) { - if (index == this.ranges.length - 1) - return null; - let next = this.ranges[++index]; - pos += next.from - range.to; - range = next; - } - return pos; - } - /// Look at a code unit near the stream position. `.peek(0)` equals - /// `.next`, `.peek(-1)` gives you the previous character, and so - /// on. - /// - /// Note that looking around during tokenizing creates dependencies - /// on potentially far-away content, which may reduce the - /// effectiveness incremental parsing—when looking forward—or even - /// cause invalid reparses when looking backward more than 25 code - /// units, since the library does not track lookbehind. - peek(offset) { - let idx = this.chunkOff + offset, pos, result; - if (idx >= 0 && idx < this.chunk.length) { - pos = this.pos + offset; - result = this.chunk.charCodeAt(idx); - } - else { - let resolved = this.resolveOffset(offset, 1); - if (resolved == null) - return -1; - pos = resolved; - if (pos >= this.chunk2Pos && pos < this.chunk2Pos + this.chunk2.length) { - result = this.chunk2.charCodeAt(pos - this.chunk2Pos); - } - else { - let i = this.rangeIndex, range = this.range; - while (range.to <= pos) - range = this.ranges[++i]; - this.chunk2 = this.input.chunk(this.chunk2Pos = pos); - if (pos + this.chunk2.length > range.to) - this.chunk2 = this.chunk2.slice(0, range.to - pos); - result = this.chunk2.charCodeAt(0); - } - } - if (pos >= this.token.lookAhead) - this.token.lookAhead = pos + 1; - return result; - } - /// Accept a token. By default, the end of the token is set to the - /// current stream position, but you can pass an offset (relative to - /// the stream position) to change that. - acceptToken(token, endOffset = 0) { - let end = endOffset ? this.resolveOffset(endOffset, -1) : this.pos; - if (end == null || end < this.token.start) - throw new RangeError("Token end out of bounds"); - this.token.value = token; - this.token.end = end; - } - getChunk() { - if (this.pos >= this.chunk2Pos && this.pos < this.chunk2Pos + this.chunk2.length) { - let { chunk, chunkPos } = this; - this.chunk = this.chunk2; - this.chunkPos = this.chunk2Pos; - this.chunk2 = chunk; - this.chunk2Pos = chunkPos; - this.chunkOff = this.pos - this.chunkPos; - } - else { - this.chunk2 = this.chunk; - this.chunk2Pos = this.chunkPos; - let nextChunk = this.input.chunk(this.pos); - let end = this.pos + nextChunk.length; - this.chunk = end > this.range.to ? nextChunk.slice(0, this.range.to - this.pos) : nextChunk; - this.chunkPos = this.pos; - this.chunkOff = 0; - } - } - readNext() { - if (this.chunkOff >= this.chunk.length) { - this.getChunk(); - if (this.chunkOff == this.chunk.length) - return this.next = -1; - } - return this.next = this.chunk.charCodeAt(this.chunkOff); - } - /// Move the stream forward N (defaults to 1) code units. Returns - /// the new value of [`next`](#lr.InputStream.next). - advance(n = 1) { - this.chunkOff += n; - while (this.pos + n >= this.range.to) { - if (this.rangeIndex == this.ranges.length - 1) - return this.setDone(); - n -= this.range.to - this.pos; - this.range = this.ranges[++this.rangeIndex]; - this.pos = this.range.from; - } - this.pos += n; - if (this.pos >= this.token.lookAhead) - this.token.lookAhead = this.pos + 1; - return this.readNext(); - } - setDone() { - this.pos = this.chunkPos = this.end; - this.range = this.ranges[this.rangeIndex = this.ranges.length - 1]; - this.chunk = ""; - return this.next = -1; - } - /// @internal - reset(pos, token) { - if (token) { - this.token = token; - token.start = pos; - token.lookAhead = pos + 1; - token.value = token.extended = -1; - } - else { - this.token = nullToken; - } - if (this.pos != pos) { - this.pos = pos; - if (pos == this.end) { - this.setDone(); - return this; - } - while (pos < this.range.from) - this.range = this.ranges[--this.rangeIndex]; - while (pos >= this.range.to) - this.range = this.ranges[++this.rangeIndex]; - if (pos >= this.chunkPos && pos < this.chunkPos + this.chunk.length) { - this.chunkOff = pos - this.chunkPos; - } - else { - this.chunk = ""; - this.chunkOff = 0; - } - this.readNext(); - } - return this; - } - /// @internal - read(from, to) { - if (from >= this.chunkPos && to <= this.chunkPos + this.chunk.length) - return this.chunk.slice(from - this.chunkPos, to - this.chunkPos); - if (from >= this.chunk2Pos && to <= this.chunk2Pos + this.chunk2.length) - return this.chunk2.slice(from - this.chunk2Pos, to - this.chunk2Pos); - if (from >= this.range.from && to <= this.range.to) - return this.input.read(from, to); - let result = ""; - for (let r of this.ranges) { - if (r.from >= to) - break; - if (r.to > from) - result += this.input.read(Math.max(r.from, from), Math.min(r.to, to)); - } - return result; - } - } - /// @internal - class TokenGroup { - constructor(data, id) { - this.data = data; - this.id = id; - } - token(input, stack) { readToken(this.data, input, stack, this.id); } - } - TokenGroup.prototype.contextual = TokenGroup.prototype.fallback = TokenGroup.prototype.extend = false; - /// `@external tokens` declarations in the grammar should resolve to - /// an instance of this class. - class ExternalTokenizer { - /// Create a tokenizer. The first argument is the function that, - /// given an input stream, scans for the types of tokens it - /// recognizes at the stream's position, and calls - /// [`acceptToken`](#lr.InputStream.acceptToken) when it finds - /// one. - constructor( - /// @internal - token, options = {}) { - this.token = token; - this.contextual = !!options.contextual; - this.fallback = !!options.fallback; - this.extend = !!options.extend; - } - } - // Tokenizer data is stored a big uint16 array containing, for each - // state: - // - // - A group bitmask, indicating what token groups are reachable from - // this state, so that paths that can only lead to tokens not in - // any of the current groups can be cut off early. - // - // - The position of the end of the state's sequence of accepting - // tokens - // - // - The number of outgoing edges for the state - // - // - The accepting tokens, as (token id, group mask) pairs - // - // - The outgoing edges, as (start character, end character, state - // index) triples, with end character being exclusive - // - // This function interprets that data, running through a stream as - // long as new states with the a matching group mask can be reached, - // and updating `token` when it matches a token. - function readToken(data, input, stack, group) { - let state = 0, groupMask = 1 << group, { parser } = stack.p, { dialect } = parser; - scan: for (;;) { - if ((groupMask & data[state]) == 0) - break; - let accEnd = data[state + 1]; - // Check whether this state can lead to a token in the current group - // Accept tokens in this state, possibly overwriting - // lower-precedence / shorter tokens - for (let i = state + 3; i < accEnd; i += 2) - if ((data[i + 1] & groupMask) > 0) { - let term = data[i]; - if (dialect.allows(term) && - (input.token.value == -1 || input.token.value == term || parser.overrides(term, input.token.value))) { - input.acceptToken(term); - break; - } - } - // Do a binary search on the state's edges - for (let next = input.next, low = 0, high = data[state + 2]; low < high;) { - let mid = (low + high) >> 1; - let index = accEnd + mid + (mid << 1); - let from = data[index], to = data[index + 1]; - if (next < from) - high = mid; - else if (next >= to) - low = mid + 1; - else { - state = data[index + 2]; - input.advance(); - continue scan; - } - } - break; - } - } - - // See lezer-generator/src/encode.ts for comments about the encoding - // used here - function decodeArray(input, Type = Uint16Array) { - if (typeof input != "string") - return input; - let array = null; - for (let pos = 0, out = 0; pos < input.length;) { - let value = 0; - for (;;) { - let next = input.charCodeAt(pos++), stop = false; - if (next == 126 /* BigValCode */) { - value = 65535 /* BigVal */; - break; - } - if (next >= 92 /* Gap2 */) - next--; - if (next >= 34 /* Gap1 */) - next--; - let digit = next - 32 /* Start */; - if (digit >= 46 /* Base */) { - digit -= 46 /* Base */; - stop = true; - } - value += digit; - if (stop) - break; - value *= 46 /* Base */; - } - if (array) - array[out++] = value; - else - array = new Type(value); - } - return array; - } - - // FIXME find some way to reduce recovery work done when the input - // doesn't match the grammar at all. - // Environment variable used to control console output - const verbose = typeof process != "undefined" && /\bparse\b/.test(process.env.LOG); - let stackIDs = null; - var Safety; - (function (Safety) { - Safety[Safety["Margin"] = 25] = "Margin"; - })(Safety || (Safety = {})); - function cutAt(tree, pos, side) { - let cursor = tree.fullCursor(); - cursor.moveTo(pos); - for (;;) { - if (!(side < 0 ? cursor.childBefore(pos) : cursor.childAfter(pos))) - for (;;) { - if ((side < 0 ? cursor.to < pos : cursor.from > pos) && !cursor.type.isError) - return side < 0 ? Math.max(0, Math.min(cursor.to - 1, pos - 25 /* Margin */)) - : Math.min(tree.length, Math.max(cursor.from + 1, pos + 25 /* Margin */)); - if (side < 0 ? cursor.prevSibling() : cursor.nextSibling()) - break; - if (!cursor.parent()) - return side < 0 ? 0 : tree.length; - } - } - } - class FragmentCursor { - constructor(fragments, nodeSet) { - this.fragments = fragments; - this.nodeSet = nodeSet; - this.i = 0; - this.fragment = null; - this.safeFrom = -1; - this.safeTo = -1; - this.trees = []; - this.start = []; - this.index = []; - this.nextFragment(); - } - nextFragment() { - let fr = this.fragment = this.i == this.fragments.length ? null : this.fragments[this.i++]; - if (fr) { - this.safeFrom = fr.openStart ? cutAt(fr.tree, fr.from + fr.offset, 1) - fr.offset : fr.from; - this.safeTo = fr.openEnd ? cutAt(fr.tree, fr.to + fr.offset, -1) - fr.offset : fr.to; - while (this.trees.length) { - this.trees.pop(); - this.start.pop(); - this.index.pop(); - } - this.trees.push(fr.tree); - this.start.push(-fr.offset); - this.index.push(0); - this.nextStart = this.safeFrom; - } - else { - this.nextStart = 1e9; - } - } - // `pos` must be >= any previously given `pos` for this cursor - nodeAt(pos) { - if (pos < this.nextStart) - return null; - while (this.fragment && this.safeTo <= pos) - this.nextFragment(); - if (!this.fragment) - return null; - for (;;) { - let last = this.trees.length - 1; - if (last < 0) { // End of tree - this.nextFragment(); - return null; - } - let top = this.trees[last], index = this.index[last]; - if (index == top.children.length) { - this.trees.pop(); - this.start.pop(); - this.index.pop(); - continue; - } - let next = top.children[index]; - let start = this.start[last] + top.positions[index]; - if (start > pos) { - this.nextStart = start; - return null; - } - if (next instanceof Tree) { - if (start == pos) { - if (start < this.safeFrom) - return null; - let end = start + next.length; - if (end <= this.safeTo) { - let lookAhead = next.prop(NodeProp.lookAhead); - if (!lookAhead || end + lookAhead < this.fragment.to) - return next; - } - } - this.index[last]++; - if (start + next.length >= Math.max(this.safeFrom, pos)) { // Enter this node - this.trees.push(next); - this.start.push(start); - this.index.push(0); - } - } - else { - this.index[last]++; - this.nextStart = start + next.length; - } - } - } - } - class TokenCache { - constructor(parser, stream) { - this.stream = stream; - this.tokens = []; - this.mainToken = null; - this.actions = []; - this.tokens = parser.tokenizers.map(_ => new CachedToken); - } - getActions(stack) { - let actionIndex = 0; - let main = null; - let { parser } = stack.p, { tokenizers } = parser; - let mask = parser.stateSlot(stack.state, 3 /* TokenizerMask */); - let context = stack.curContext ? stack.curContext.hash : 0; - let lookAhead = 0; - for (let i = 0; i < tokenizers.length; i++) { - if (((1 << i) & mask) == 0) - continue; - let tokenizer = tokenizers[i], token = this.tokens[i]; - if (main && !tokenizer.fallback) - continue; - if (tokenizer.contextual || token.start != stack.pos || token.mask != mask || token.context != context) { - this.updateCachedToken(token, tokenizer, stack); - token.mask = mask; - token.context = context; - } - if (token.lookAhead > token.end + 25 /* Margin */) - lookAhead = Math.max(token.lookAhead, lookAhead); - if (token.value != 0 /* Err */) { - let startIndex = actionIndex; - if (token.extended > -1) - actionIndex = this.addActions(stack, token.extended, token.end, actionIndex); - actionIndex = this.addActions(stack, token.value, token.end, actionIndex); - if (!tokenizer.extend) { - main = token; - if (actionIndex > startIndex) - break; - } - } - } - while (this.actions.length > actionIndex) - this.actions.pop(); - if (lookAhead) - stack.setLookAhead(lookAhead); - if (!main && stack.pos == this.stream.end) { - main = new CachedToken; - main.value = stack.p.parser.eofTerm; - main.start = main.end = stack.pos; - actionIndex = this.addActions(stack, main.value, main.end, actionIndex); - } - this.mainToken = main; - return this.actions; - } - getMainToken(stack) { - if (this.mainToken) - return this.mainToken; - let main = new CachedToken, { pos, p } = stack; - main.start = pos; - main.end = Math.min(pos + 1, p.stream.end); - main.value = pos == p.stream.end ? p.parser.eofTerm : 0 /* Err */; - return main; - } - updateCachedToken(token, tokenizer, stack) { - tokenizer.token(this.stream.reset(stack.pos, token), stack); - if (token.value > -1) { - let { parser } = stack.p; - for (let i = 0; i < parser.specialized.length; i++) - if (parser.specialized[i] == token.value) { - let result = parser.specializers[i](this.stream.read(token.start, token.end), stack); - if (result >= 0 && stack.p.parser.dialect.allows(result >> 1)) { - if ((result & 1) == 0 /* Specialize */) - token.value = result >> 1; - else - token.extended = result >> 1; - break; - } - } - } - else { - token.value = 0 /* Err */; - token.end = Math.min(stack.p.stream.end, stack.pos + 1); - } - } - putAction(action, token, end, index) { - // Don't add duplicate actions - for (let i = 0; i < index; i += 3) - if (this.actions[i] == action) - return index; - this.actions[index++] = action; - this.actions[index++] = token; - this.actions[index++] = end; - return index; - } - addActions(stack, token, end, index) { - let { state } = stack, { parser } = stack.p, { data } = parser; - for (let set = 0; set < 2; set++) { - for (let i = parser.stateSlot(state, set ? 2 /* Skip */ : 1 /* Actions */);; i += 3) { - if (data[i] == 65535 /* End */) { - if (data[i + 1] == 1 /* Next */) { - i = pair(data, i + 2); - } - else { - if (index == 0 && data[i + 1] == 2 /* Other */) - index = this.putAction(pair(data, i + 2), token, end, index); - break; - } - } - if (data[i] == token) - index = this.putAction(pair(data, i + 1), token, end, index); - } - } - return index; - } - } - var Rec; - (function (Rec) { - Rec[Rec["Distance"] = 5] = "Distance"; - Rec[Rec["MaxRemainingPerStep"] = 3] = "MaxRemainingPerStep"; - // When two stacks have been running independently long enough to - // add this many elements to their buffers, prune one. - Rec[Rec["MinBufferLengthPrune"] = 500] = "MinBufferLengthPrune"; - Rec[Rec["ForceReduceLimit"] = 10] = "ForceReduceLimit"; - // Once a stack reaches this depth (in .stack.length) force-reduce - // it back to CutTo to avoid creating trees that overflow the stack - // on recursive traversal. - Rec[Rec["CutDepth"] = 15000] = "CutDepth"; - Rec[Rec["CutTo"] = 9000] = "CutTo"; - })(Rec || (Rec = {})); - class Parse { - constructor(parser, input, fragments, ranges) { - this.parser = parser; - this.input = input; - this.ranges = ranges; - this.recovering = 0; - this.nextStackID = 0x2654; // ♔, ♕, ♖, ♗, ♘, ♙, ♠, ♡, ♢, ♣, ♤, ♥, ♦, ♧ - this.minStackPos = 0; - this.reused = []; - this.stoppedAt = null; - this.stream = new InputStream(input, ranges); - this.tokens = new TokenCache(parser, this.stream); - this.topTerm = parser.top[1]; - let { from } = ranges[0]; - this.stacks = [Stack.start(this, parser.top[0], from)]; - this.fragments = fragments.length && this.stream.end - from > parser.bufferLength * 4 - ? new FragmentCursor(fragments, parser.nodeSet) : null; - } - get parsedPos() { - return this.minStackPos; - } - // Move the parser forward. This will process all parse stacks at - // `this.pos` and try to advance them to a further position. If no - // stack for such a position is found, it'll start error-recovery. - // - // When the parse is finished, this will return a syntax tree. When - // not, it returns `null`. - advance() { - let stacks = this.stacks, pos = this.minStackPos; - // This will hold stacks beyond `pos`. - let newStacks = this.stacks = []; - let stopped, stoppedTokens; - // Keep advancing any stacks at `pos` until they either move - // forward or can't be advanced. Gather stacks that can't be - // advanced further in `stopped`. - for (let i = 0; i < stacks.length; i++) { - let stack = stacks[i]; - for (;;) { - this.tokens.mainToken = null; - if (stack.pos > pos) { - newStacks.push(stack); - } - else if (this.advanceStack(stack, newStacks, stacks)) { - continue; - } - else { - if (!stopped) { - stopped = []; - stoppedTokens = []; - } - stopped.push(stack); - let tok = this.tokens.getMainToken(stack); - stoppedTokens.push(tok.value, tok.end); - } - break; - } - } - if (!newStacks.length) { - let finished = stopped && findFinished(stopped); - if (finished) - return this.stackToTree(finished); - if (this.parser.strict) { - if (verbose && stopped) - console.log("Stuck with token " + (this.tokens.mainToken ? this.parser.getName(this.tokens.mainToken.value) : "none")); - throw new SyntaxError("No parse at " + pos); - } - if (!this.recovering) - this.recovering = 5 /* Distance */; - } - if (this.recovering && stopped) { - let finished = this.stoppedAt != null && stopped[0].pos > this.stoppedAt ? stopped[0] - : this.runRecovery(stopped, stoppedTokens, newStacks); - if (finished) - return this.stackToTree(finished.forceAll()); - } - if (this.recovering) { - let maxRemaining = this.recovering == 1 ? 1 : this.recovering * 3 /* MaxRemainingPerStep */; - if (newStacks.length > maxRemaining) { - newStacks.sort((a, b) => b.score - a.score); - while (newStacks.length > maxRemaining) - newStacks.pop(); - } - if (newStacks.some(s => s.reducePos > pos)) - this.recovering--; - } - else if (newStacks.length > 1) { - // Prune stacks that are in the same state, or that have been - // running without splitting for a while, to avoid getting stuck - // with multiple successful stacks running endlessly on. - outer: for (let i = 0; i < newStacks.length - 1; i++) { - let stack = newStacks[i]; - for (let j = i + 1; j < newStacks.length; j++) { - let other = newStacks[j]; - if (stack.sameState(other) || - stack.buffer.length > 500 /* MinBufferLengthPrune */ && other.buffer.length > 500 /* MinBufferLengthPrune */) { - if (((stack.score - other.score) || (stack.buffer.length - other.buffer.length)) > 0) { - newStacks.splice(j--, 1); - } - else { - newStacks.splice(i--, 1); - continue outer; - } - } - } - } - } - this.minStackPos = newStacks[0].pos; - for (let i = 1; i < newStacks.length; i++) - if (newStacks[i].pos < this.minStackPos) - this.minStackPos = newStacks[i].pos; - return null; - } - stopAt(pos) { - if (this.stoppedAt != null && this.stoppedAt < pos) - throw new RangeError("Can't move stoppedAt forward"); - this.stoppedAt = pos; - } - // Returns an updated version of the given stack, or null if the - // stack can't advance normally. When `split` and `stacks` are - // given, stacks split off by ambiguous operations will be pushed to - // `split`, or added to `stacks` if they move `pos` forward. - advanceStack(stack, stacks, split) { - let start = stack.pos, { parser } = this; - let base = verbose ? this.stackID(stack) + " -> " : ""; - if (this.stoppedAt != null && start > this.stoppedAt) - return stack.forceReduce() ? stack : null; - if (this.fragments) { - let strictCx = stack.curContext && stack.curContext.tracker.strict, cxHash = strictCx ? stack.curContext.hash : 0; - for (let cached = this.fragments.nodeAt(start); cached;) { - let match = this.parser.nodeSet.types[cached.type.id] == cached.type ? parser.getGoto(stack.state, cached.type.id) : -1; - if (match > -1 && cached.length && (!strictCx || (cached.prop(NodeProp.contextHash) || 0) == cxHash)) { - stack.useNode(cached, match); - if (verbose) - console.log(base + this.stackID(stack) + ` (via reuse of ${parser.getName(cached.type.id)})`); - return true; - } - if (!(cached instanceof Tree) || cached.children.length == 0 || cached.positions[0] > 0) - break; - let inner = cached.children[0]; - if (inner instanceof Tree && cached.positions[0] == 0) - cached = inner; - else - break; - } - } - let defaultReduce = parser.stateSlot(stack.state, 4 /* DefaultReduce */); - if (defaultReduce > 0) { - stack.reduce(defaultReduce); - if (verbose) - console.log(base + this.stackID(stack) + ` (via always-reduce ${parser.getName(defaultReduce & 65535 /* ValueMask */)})`); - return true; - } - if (stack.stack.length >= 15000 /* CutDepth */) { - while (stack.stack.length > 9000 /* CutTo */ && stack.forceReduce()) { } - } - let actions = this.tokens.getActions(stack); - for (let i = 0; i < actions.length;) { - let action = actions[i++], term = actions[i++], end = actions[i++]; - let last = i == actions.length || !split; - let localStack = last ? stack : stack.split(); - localStack.apply(action, term, end); - if (verbose) - console.log(base + this.stackID(localStack) + ` (via ${(action & 65536 /* ReduceFlag */) == 0 ? "shift" - : `reduce of ${parser.getName(action & 65535 /* ValueMask */)}`} for ${parser.getName(term)} @ ${start}${localStack == stack ? "" : ", split"})`); - if (last) - return true; - else if (localStack.pos > start) - stacks.push(localStack); - else - split.push(localStack); - } - return false; - } - // Advance a given stack forward as far as it will go. Returns the - // (possibly updated) stack if it got stuck, or null if it moved - // forward and was given to `pushStackDedup`. - advanceFully(stack, newStacks) { - let pos = stack.pos; - for (;;) { - if (!this.advanceStack(stack, null, null)) - return false; - if (stack.pos > pos) { - pushStackDedup(stack, newStacks); - return true; - } - } - } - runRecovery(stacks, tokens, newStacks) { - let finished = null, restarted = false; - for (let i = 0; i < stacks.length; i++) { - let stack = stacks[i], token = tokens[i << 1], tokenEnd = tokens[(i << 1) + 1]; - let base = verbose ? this.stackID(stack) + " -> " : ""; - if (stack.deadEnd) { - if (restarted) - continue; - restarted = true; - stack.restart(); - if (verbose) - console.log(base + this.stackID(stack) + " (restarted)"); - let done = this.advanceFully(stack, newStacks); - if (done) - continue; - } - let force = stack.split(), forceBase = base; - for (let j = 0; force.forceReduce() && j < 10 /* ForceReduceLimit */; j++) { - if (verbose) - console.log(forceBase + this.stackID(force) + " (via force-reduce)"); - let done = this.advanceFully(force, newStacks); - if (done) - break; - if (verbose) - forceBase = this.stackID(force) + " -> "; - } - for (let insert of stack.recoverByInsert(token)) { - if (verbose) - console.log(base + this.stackID(insert) + " (via recover-insert)"); - this.advanceFully(insert, newStacks); - } - if (this.stream.end > stack.pos) { - if (tokenEnd == stack.pos) { - tokenEnd++; - token = 0 /* Err */; - } - stack.recoverByDelete(token, tokenEnd); - if (verbose) - console.log(base + this.stackID(stack) + ` (via recover-delete ${this.parser.getName(token)})`); - pushStackDedup(stack, newStacks); - } - else if (!finished || finished.score < stack.score) { - finished = stack; - } - } - return finished; - } - // Convert the stack's buffer to a syntax tree. - stackToTree(stack) { - stack.close(); - return Tree.build({ buffer: StackBufferCursor.create(stack), - nodeSet: this.parser.nodeSet, - topID: this.topTerm, - maxBufferLength: this.parser.bufferLength, - reused: this.reused, - start: this.ranges[0].from, - length: stack.pos - this.ranges[0].from, - minRepeatType: this.parser.minRepeatTerm }); - } - stackID(stack) { - let id = (stackIDs || (stackIDs = new WeakMap)).get(stack); - if (!id) - stackIDs.set(stack, id = String.fromCodePoint(this.nextStackID++)); - return id + stack; - } - } - function pushStackDedup(stack, newStacks) { - for (let i = 0; i < newStacks.length; i++) { - let other = newStacks[i]; - if (other.pos == stack.pos && other.sameState(stack)) { - if (newStacks[i].score < stack.score) - newStacks[i] = stack; - return; - } - } - newStacks.push(stack); - } - class Dialect { - constructor(source, flags, disabled) { - this.source = source; - this.flags = flags; - this.disabled = disabled; - } - allows(term) { return !this.disabled || this.disabled[term] == 0; } - } - const id = x => x; - /// Context trackers are used to track stateful context (such as - /// indentation in the Python grammar, or parent elements in the XML - /// grammar) needed by external tokenizers. You declare them in a - /// grammar file as `@context exportName from "module"`. - /// - /// Context values should be immutable, and can be updated (replaced) - /// on shift or reduce actions. - /// - /// The export used in a `@context` declaration should be of this - /// type. - class ContextTracker { - /// Define a context tracker. - constructor(spec) { - this.start = spec.start; - this.shift = spec.shift || id; - this.reduce = spec.reduce || id; - this.reuse = spec.reuse || id; - this.hash = spec.hash || (() => 0); - this.strict = spec.strict !== false; - } - } - /// A parser holds the parse tables for a given grammar, as generated - /// by `lezer-generator`. - class LRParser extends Parser { - /// @internal - constructor(spec) { - super(); - /// @internal - this.wrappers = []; - if (spec.version != 13 /* Version */) - throw new RangeError(`Parser version (${spec.version}) doesn't match runtime version (${13 /* Version */})`); - let nodeNames = spec.nodeNames.split(" "); - this.minRepeatTerm = nodeNames.length; - for (let i = 0; i < spec.repeatNodeCount; i++) - nodeNames.push(""); - let topTerms = Object.keys(spec.topRules).map(r => spec.topRules[r][1]); - let nodeProps = []; - for (let i = 0; i < nodeNames.length; i++) - nodeProps.push([]); - function setProp(nodeID, prop, value) { - nodeProps[nodeID].push([prop, prop.deserialize(String(value))]); - } - if (spec.nodeProps) - for (let propSpec of spec.nodeProps) { - let prop = propSpec[0]; - for (let i = 1; i < propSpec.length;) { - let next = propSpec[i++]; - if (next >= 0) { - setProp(next, prop, propSpec[i++]); - } - else { - let value = propSpec[i + -next]; - for (let j = -next; j > 0; j--) - setProp(propSpec[i++], prop, value); - i++; - } - } - } - this.nodeSet = new NodeSet(nodeNames.map((name, i) => NodeType.define({ - name: i >= this.minRepeatTerm ? undefined : name, - id: i, - props: nodeProps[i], - top: topTerms.indexOf(i) > -1, - error: i == 0, - skipped: spec.skippedNodes && spec.skippedNodes.indexOf(i) > -1 - }))); - this.strict = false; - this.bufferLength = DefaultBufferLength; - let tokenArray = decodeArray(spec.tokenData); - this.context = spec.context; - this.specialized = new Uint16Array(spec.specialized ? spec.specialized.length : 0); - this.specializers = []; - if (spec.specialized) - for (let i = 0; i < spec.specialized.length; i++) { - this.specialized[i] = spec.specialized[i].term; - this.specializers[i] = spec.specialized[i].get; - } - this.states = decodeArray(spec.states, Uint32Array); - this.data = decodeArray(spec.stateData); - this.goto = decodeArray(spec.goto); - this.maxTerm = spec.maxTerm; - this.tokenizers = spec.tokenizers.map(value => typeof value == "number" ? new TokenGroup(tokenArray, value) : value); - this.topRules = spec.topRules; - this.dialects = spec.dialects || {}; - this.dynamicPrecedences = spec.dynamicPrecedences || null; - this.tokenPrecTable = spec.tokenPrec; - this.termNames = spec.termNames || null; - this.maxNode = this.nodeSet.types.length - 1; - this.dialect = this.parseDialect(); - this.top = this.topRules[Object.keys(this.topRules)[0]]; - } - createParse(input, fragments, ranges) { - let parse = new Parse(this, input, fragments, ranges); - for (let w of this.wrappers) - parse = w(parse, input, fragments, ranges); - return parse; - } - /// Get a goto table entry @internal - getGoto(state, term, loose = false) { - let table = this.goto; - if (term >= table[0]) - return -1; - for (let pos = table[term + 1];;) { - let groupTag = table[pos++], last = groupTag & 1; - let target = table[pos++]; - if (last && loose) - return target; - for (let end = pos + (groupTag >> 1); pos < end; pos++) - if (table[pos] == state) - return target; - if (last) - return -1; - } - } - /// Check if this state has an action for a given terminal @internal - hasAction(state, terminal) { - let data = this.data; - for (let set = 0; set < 2; set++) { - for (let i = this.stateSlot(state, set ? 2 /* Skip */ : 1 /* Actions */), next;; i += 3) { - if ((next = data[i]) == 65535 /* End */) { - if (data[i + 1] == 1 /* Next */) - next = data[i = pair(data, i + 2)]; - else if (data[i + 1] == 2 /* Other */) - return pair(data, i + 2); - else - break; - } - if (next == terminal || next == 0 /* Err */) - return pair(data, i + 1); - } - } - return 0; - } - /// @internal - stateSlot(state, slot) { - return this.states[(state * 6 /* Size */) + slot]; - } - /// @internal - stateFlag(state, flag) { - return (this.stateSlot(state, 0 /* Flags */) & flag) > 0; - } - /// @internal - validAction(state, action) { - if (action == this.stateSlot(state, 4 /* DefaultReduce */)) - return true; - for (let i = this.stateSlot(state, 1 /* Actions */);; i += 3) { - if (this.data[i] == 65535 /* End */) { - if (this.data[i + 1] == 1 /* Next */) - i = pair(this.data, i + 2); - else - return false; - } - if (action == pair(this.data, i + 1)) - return true; - } - } - /// Get the states that can follow this one through shift actions or - /// goto jumps. @internal - nextStates(state) { - let result = []; - for (let i = this.stateSlot(state, 1 /* Actions */);; i += 3) { - if (this.data[i] == 65535 /* End */) { - if (this.data[i + 1] == 1 /* Next */) - i = pair(this.data, i + 2); - else - break; - } - if ((this.data[i + 2] & (65536 /* ReduceFlag */ >> 16)) == 0) { - let value = this.data[i + 1]; - if (!result.some((v, i) => (i & 1) && v == value)) - result.push(this.data[i], value); - } - } - return result; - } - /// @internal - overrides(token, prev) { - let iPrev = findOffset(this.data, this.tokenPrecTable, prev); - return iPrev < 0 || findOffset(this.data, this.tokenPrecTable, token) < iPrev; - } - /// Configure the parser. Returns a new parser instance that has the - /// given settings modified. Settings not provided in `config` are - /// kept from the original parser. - configure(config) { - // Hideous reflection-based kludge to make it easy to create a - // slightly modified copy of a parser. - let copy = Object.assign(Object.create(LRParser.prototype), this); - if (config.props) - copy.nodeSet = this.nodeSet.extend(...config.props); - if (config.top) { - let info = this.topRules[config.top]; - if (!info) - throw new RangeError(`Invalid top rule name ${config.top}`); - copy.top = info; - } - if (config.tokenizers) - copy.tokenizers = this.tokenizers.map(t => { - let found = config.tokenizers.find(r => r.from == t); - return found ? found.to : t; - }); - if (config.contextTracker) - copy.context = config.contextTracker; - if (config.dialect) - copy.dialect = this.parseDialect(config.dialect); - if (config.strict != null) - copy.strict = config.strict; - if (config.wrap) - copy.wrappers = copy.wrappers.concat(config.wrap); - if (config.bufferLength != null) - copy.bufferLength = config.bufferLength; - return copy; - } - /// Returns the name associated with a given term. This will only - /// work for all terms when the parser was generated with the - /// `--names` option. By default, only the names of tagged terms are - /// stored. - getName(term) { - return this.termNames ? this.termNames[term] : String(term <= this.maxNode && this.nodeSet.types[term].name || term); - } - /// The eof term id is always allocated directly after the node - /// types. @internal - get eofTerm() { return this.maxNode + 1; } - /// The type of top node produced by the parser. - get topNode() { return this.nodeSet.types[this.top[1]]; } - /// @internal - dynamicPrecedence(term) { - let prec = this.dynamicPrecedences; - return prec == null ? 0 : prec[term] || 0; - } - /// @internal - parseDialect(dialect) { - let values = Object.keys(this.dialects), flags = values.map(() => false); - if (dialect) - for (let part of dialect.split(" ")) { - let id = values.indexOf(part); - if (id >= 0) - flags[id] = true; - } - let disabled = null; - for (let i = 0; i < values.length; i++) - if (!flags[i]) { - for (let j = this.dialects[values[i]], id; (id = this.data[j++]) != 65535 /* End */;) - (disabled || (disabled = new Uint8Array(this.maxTerm + 1)))[id] = 1; - } - return new Dialect(dialect, flags, disabled); - } - /// (used by the output of the parser generator) @internal - static deserialize(spec) { - return new LRParser(spec); - } - } - function pair(data, off) { return data[off] | (data[off + 1] << 16); } - function findOffset(data, start, term) { - for (let i = start, next; (next = data[i]) != 65535 /* End */; i++) - if (next == term) - return i - start; - return -1; - } - function findFinished(stacks) { - let best = null; - for (let stack of stacks) { - let stopped = stack.p.stoppedAt; - if ((stack.pos == stack.p.stream.end || stopped != null && stack.pos > stopped) && - stack.p.parser.stateFlag(stack.state, 2 /* Accepting */) && - (!best || best.score < stack.score)) - best = stack; - } - return best; - } - - // This file was generated by lezer-generator. You probably shouldn't edit it. - const printKeyword = 1, - indent = 162, - dedent = 163, - newline$1 = 164, - newlineBracketed = 165, - newlineEmpty = 166, - eof = 167, - ParenthesizedExpression = 21, - ParenL = 22, - TupleExpression = 47, - ComprehensionExpression = 48, - ArrayExpression = 52, - BracketL = 53, - ArrayComprehensionExpression = 55, - DictionaryExpression = 56, - BraceL = 57, - DictionaryComprehensionExpression = 59, - SetExpression = 60, - SetComprehensionExpression = 61, - ArgList = 63, - subscript = 203, - FormatReplacement = 71, - importList = 228, - ParamList = 121; - - const newline = 10, carriageReturn = 13, space = 32, tab = 9, hash = 35, parenOpen = 40, dot = 46; - - const bracketed = [ - ParenthesizedExpression, TupleExpression, ComprehensionExpression, importList, ArgList, ParamList, - ArrayExpression, ArrayComprehensionExpression, subscript, - SetExpression, SetComprehensionExpression, - DictionaryExpression, DictionaryComprehensionExpression, FormatReplacement - ]; - - const newlines = new ExternalTokenizer((input, stack) => { - if (input.next < 0) { - input.acceptToken(eof); - } else if (input.next != newline && input.next != carriageReturn) ; else if (stack.context.depth < 0) { - input.acceptToken(newlineBracketed, 1); - } else { - input.advance(); - let spaces = 0; - while (input.next == space || input.next == tab) { input.advance(); spaces++; } - let empty = input.next == newline || input.next == carriageReturn || input.next == hash; - input.acceptToken(empty ? newlineEmpty : newline$1, -spaces); + // ================= registraton API ==================== + logStatus(msg) { + logger.info(msg); + const ev = new CustomEvent('py-status-message', { detail: msg }); + document.dispatchEvent(ev); } - }, {contextual: true, fallback: true}); - - const indentation = new ExternalTokenizer((input, stack) => { - let cDepth = stack.context.depth; - if (cDepth < 0) return - let prev = input.peek(-1); - if ((prev == newline || prev == carriageReturn) && stack.context.depth >= 0) { - let depth = 0, chars = 0; - for (;;) { - if (input.next == space) depth++; - else if (input.next == tab) depth += 8 - (depth % 8); - else break - input.advance(); - chars++; - } - if (depth != cDepth && - input.next != newline && input.next != carriageReturn && input.next != hash) { - if (depth < cDepth) input.acceptToken(dedent, -chars); - else input.acceptToken(indent); - } + registerStdioListener(stdio) { + this._stdioMultiplexer.addListener(stdio); } - }); + } + function pyscript_get_config() { + return globalApp.config; + } + globalExport('pyscript_get_config', pyscript_get_config); + // main entry point of execution + const globalApp = new PyScriptApp(); + globalApp.main(); + const interpreter = globalApp.interpreter; + // TODO: This is for backwards compatibility, it should be removed + // when we finish the deprecation cycle of `runtime` + const runtime = globalApp.interpreter; - function IndentLevel(parent, depth) { - this.parent = parent; - // -1 means this is not an actual indent level but a set of brackets - this.depth = depth; - this.hash = (parent ? parent.hash + parent.hash << 8 : 0) + depth + (depth << 4); - } + exports.PyScriptApp = PyScriptApp; + exports.interpreter = interpreter; + exports.runtime = runtime; + exports.version = version; - const topIndent = new IndentLevel(null, 0); + Object.defineProperty(exports, '__esModule', { value: true }); - function countIndent(space) { - let depth = 0; - for (let i = 0; i < space.length; i++) - depth += space.charCodeAt(i) == tab ? 8 - (depth % 8) : 1; - return depth - } + return exports; - const trackIndent = new ContextTracker({ - start: topIndent, - reduce(context, term) { - return context.depth < 0 && bracketed.indexOf(term) > -1 ? context.parent : context - }, - shift(context, term, stack, input) { - if (term == indent) return new IndentLevel(context, countIndent(input.read(input.pos, stack.pos))) - if (term == dedent) return context.parent - if (term == ParenL || term == BracketL || term == BraceL) return new IndentLevel(context, -1) - return context - }, - hash(context) { return context.hash } - }); - - const legacyPrint = new ExternalTokenizer(input => { - for (let i = 0; i < 5; i++) { - if (input.next != "print".charCodeAt(i)) return - input.advance(); - } - if (/\w/.test(String.fromCharCode(input.next))) return - for (let off = 0;; off++) { - let next = input.peek(off); - if (next == space || next == tab) continue - if (next != parenOpen && next != dot && next != newline && next != carriageReturn && next != hash) - input.acceptToken(printKeyword); - return - } - }); - - // This file was generated by lezer-generator. You probably shouldn't edit it. - const spec_identifier = {__proto__:null,await:40, or:48, and:50, in:54, not:56, is:58, if:64, else:66, lambda:70, yield:88, from:90, async:98, for:100, None:152, True:154, False:154, del:168, pass:172, break:176, continue:180, return:184, raise:192, import:196, as:198, global:202, nonlocal:204, assert:208, elif:218, while:222, try:228, except:230, finally:232, with:236, def:240, class:250}; - const parser = LRParser.deserialize({ - version: 13, - states: "!?pO`Q$IXOOO%cQ$I[O'#GaOOQ$IS'#Cm'#CmOOQ$IS'#Cn'#CnO'RQ$IWO'#ClO(tQ$I[O'#G`OOQ$IS'#Ga'#GaOOQ$IS'#DR'#DROOQ$IS'#G`'#G`O)bQ$IWO'#CqO)rQ$IWO'#DbO*SQ$IWO'#DfOOQ$IS'#Ds'#DsO*gO`O'#DsO*oOpO'#DsO*wO!bO'#DtO+SO#tO'#DtO+_O&jO'#DtO+jO,UO'#DtO-lQ$I[O'#GQOOQ$IS'#GQ'#GQO'RQ$IWO'#GPO/OQ$I[O'#GPOOQ$IS'#E]'#E]O/gQ$IWO'#E^OOQ$IS'#GO'#GOO/qQ$IWO'#F}OOQ$IV'#F}'#F}O/|Q$IWO'#FPOOQ$IS'#Fr'#FrO0RQ$IWO'#FOOOQ$IV'#H]'#H]OOQ$IV'#F|'#F|OOQ$IT'#FR'#FRQ`Q$IXOOO'RQ$IWO'#CoO0aQ$IWO'#CzO0hQ$IWO'#DOO0vQ$IWO'#GeO1WQ$I[O'#EQO'RQ$IWO'#EROOQ$IS'#ET'#ETOOQ$IS'#EV'#EVOOQ$IS'#EX'#EXO1lQ$IWO'#EZO2SQ$IWO'#E_O/|Q$IWO'#EaO2gQ$I[O'#EaO/|Q$IWO'#EdO/gQ$IWO'#EgO/gQ$IWO'#EkO/gQ$IWO'#EnO2rQ$IWO'#EpO2yQ$IWO'#EuO3UQ$IWO'#EqO/gQ$IWO'#EuO/|Q$IWO'#EwO/|Q$IWO'#E|OOQ$IS'#Cc'#CcOOQ$IS'#Cd'#CdOOQ$IS'#Ce'#CeOOQ$IS'#Cf'#CfOOQ$IS'#Cg'#CgOOQ$IS'#Ch'#ChOOQ$IS'#Cj'#CjO'RQ$IWO,58|O'RQ$IWO,58|O'RQ$IWO,58|O'RQ$IWO,58|O'RQ$IWO,58|O'RQ$IWO,58|O3ZQ$IWO'#DmOOQ$IS,5:W,5:WO3nQ$IWO'#GoOOQ$IS,5:Z,5:ZO3{Q%1`O,5:ZO4QQ$I[O,59WO0aQ$IWO,59_O0aQ$IWO,59_O0aQ$IWO,59_O6pQ$IWO,59_O6uQ$IWO,59_O6|Q$IWO,59gO7TQ$IWO'#G`O8ZQ$IWO'#G_OOQ$IS'#G_'#G_OOQ$IS'#DX'#DXO8rQ$IWO,59]O'RQ$IWO,59]O9QQ$IWO,59]O9VQ$IWO,5:PO'RQ$IWO,5:POOQ$IS,59|,59|O9eQ$IWO,59|O9jQ$IWO,5:VO'RQ$IWO,5:VO'RQ$IWO,5:TOOQ$IS,5:Q,5:QO9{Q$IWO,5:QO:QQ$IWO,5:UOOOO'#FZ'#FZO:VO`O,5:_OOQ$IS,5:_,5:_OOOO'#F['#F[O:_OpO,5:_O:gQ$IWO'#DuOOOO'#F]'#F]O:wO!bO,5:`OOQ$IS,5:`,5:`OOOO'#F`'#F`O;SO#tO,5:`OOOO'#Fa'#FaO;_O&jO,5:`OOOO'#Fb'#FbO;jO,UO,5:`OOQ$IS'#Fc'#FcO;uQ$I[O,5:dO>gQ$I[O,5<kO?QQ%GlO,5<kO?qQ$I[O,5<kOOQ$IS,5:x,5:xO@YQ$IXO'#FkOAiQ$IWO,5;TOOQ$IV,5<i,5<iOAtQ$I[O'#HXOB]Q$IWO,5;kOOQ$IS-E9p-E9pOOQ$IV,5;j,5;jO3PQ$IWO'#EwOOQ$IT-E9P-E9POBeQ$I[O,59ZODlQ$I[O,59fOEVQ$IWO'#GbOEbQ$IWO'#GbO/|Q$IWO'#GbOEmQ$IWO'#DQOEuQ$IWO,59jOEzQ$IWO'#GfO'RQ$IWO'#GfO/gQ$IWO,5=POOQ$IS,5=P,5=PO/gQ$IWO'#D|OOQ$IS'#D}'#D}OFiQ$IWO'#FeOFyQ$IWO,58zOFyQ$IWO,58zO)eQ$IWO,5:jOGXQ$I[O'#GhOOQ$IS,5:m,5:mOOQ$IS,5:u,5:uOGlQ$IWO,5:yOG}Q$IWO,5:{OOQ$IS'#Fh'#FhOH]Q$I[O,5:{OHkQ$IWO,5:{OHpQ$IWO'#H[OOQ$IS,5;O,5;OOIOQ$IWO'#HWOOQ$IS,5;R,5;RO3UQ$IWO,5;VO3UQ$IWO,5;YOIaQ$I[O'#H^O'RQ$IWO'#H^OIkQ$IWO,5;[O2rQ$IWO,5;[O/gQ$IWO,5;aO/|Q$IWO,5;cOIpQ$IXO'#ElOJyQ$IZO,5;]ON[Q$IWO'#H_O3UQ$IWO,5;aONgQ$IWO,5;cONlQ$IWO,5;hO!#aQ$I[O1G.hO!#hQ$I[O1G.hO!&XQ$I[O1G.hO!&cQ$I[O1G.hO!(|Q$I[O1G.hO!)aQ$I[O1G.hO!)tQ$IWO'#GnO!*SQ$I[O'#GQO/gQ$IWO'#GnO!*^Q$IWO'#GmOOQ$IS,5:X,5:XO!*fQ$IWO,5:XO!*kQ$IWO'#GpO!*vQ$IWO'#GpO!+ZQ$IWO,5=ZOOQ$IS'#Dq'#DqOOQ$IS1G/u1G/uOOQ$IS1G.y1G.yO!,ZQ$I[O1G.yO!,bQ$I[O1G.yO0aQ$IWO1G.yO!,}Q$IWO1G/ROOQ$IS'#DW'#DWO/gQ$IWO,59qOOQ$IS1G.w1G.wO!-UQ$IWO1G/cO!-fQ$IWO1G/cO!-nQ$IWO1G/dO'RQ$IWO'#GgO!-sQ$IWO'#GgO!-xQ$I[O1G.wO!.YQ$IWO,59fO!/`Q$IWO,5=VO!/pQ$IWO,5=VO!/xQ$IWO1G/kO!/}Q$I[O1G/kOOQ$IS1G/h1G/hO!0_Q$IWO,5=QO!1UQ$IWO,5=QO/gQ$IWO1G/oO!1sQ$IWO1G/qO!1xQ$I[O1G/qO!2YQ$I[O1G/oOOQ$IS1G/l1G/lOOQ$IS1G/p1G/pOOOO-E9X-E9XOOQ$IS1G/y1G/yOOOO-E9Y-E9YO!2jQ$IWO'#G{O/gQ$IWO'#G{O!2xQ$IWO,5:aOOOO-E9Z-E9ZOOQ$IS1G/z1G/zOOOO-E9^-E9^OOOO-E9_-E9_OOOO-E9`-E9`OOQ$IS-E9a-E9aO!3TQ%GlO1G2VO!3tQ$I[O1G2VO'RQ$IWO,5<OOOQ$IS,5<O,5<OOOQ$IS-E9b-E9bOOQ$IS,5<V,5<VOOQ$IS-E9i-E9iOOQ$IV1G0o1G0oO/|Q$IWO'#FgO!4]Q$I[O,5=sOOQ$IS1G1V1G1VO!4tQ$IWO1G1VOOQ$IS'#DS'#DSO/gQ$IWO,5<|OOQ$IS,5<|,5<|O!4yQ$IWO'#FSO!5UQ$IWO,59lO!5^Q$IWO1G/UO!5hQ$I[O,5=QOOQ$IS1G2k1G2kOOQ$IS,5:h,5:hO!6XQ$IWO'#GPOOQ$IS,5<P,5<POOQ$IS-E9c-E9cO!6jQ$IWO1G.fOOQ$IS1G0U1G0UO!6xQ$IWO,5=SO!7YQ$IWO,5=SO/gQ$IWO1G0eO/gQ$IWO1G0eO/|Q$IWO1G0gOOQ$IS-E9f-E9fO!7kQ$IWO1G0gO!7vQ$IWO1G0gO!7{Q$IWO,5=vO!8ZQ$IWO,5=vO!8iQ$IWO,5=rO!9PQ$IWO,5=rO!9bQ$IZO1G0qO!<pQ$IZO1G0tO!?{Q$IWO,5=xO!@VQ$IWO,5=xO!@_Q$I[O,5=xO/gQ$IWO1G0vO!@iQ$IWO1G0vO3UQ$IWO1G0{ONgQ$IWO1G0}OOQ$IV,5;W,5;WO!@nQ$IYO,5;WO!@sQ$IZO1G0wO!DUQ$IWO'#FoO3UQ$IWO1G0wO3UQ$IWO1G0wO!DcQ$IWO,5=yO!DpQ$IWO,5=yO/|Q$IWO,5=yOOQ$IV1G0{1G0{O!DxQ$IWO'#EyO!EZQ%1`O1G0}OOQ$IV1G1S1G1SO3UQ$IWO1G1SOOQ$IS,5=Y,5=YOOQ$IS'#Dn'#DnO/gQ$IWO,5=YO!EcQ$IWO,5=XO!EvQ$IWO,5=XOOQ$IS1G/s1G/sO!FOQ$IWO,5=[O!F`Q$IWO,5=[O!FhQ$IWO,5=[O!F{Q$IWO,5=[O!G]Q$IWO,5=[OOQ$IS1G2u1G2uOOQ$IS7+$e7+$eO!5^Q$IWO7+$mO!IOQ$IWO1G.yO!IVQ$IWO1G.yOOQ$IS1G/]1G/]OOQ$IS,5;p,5;pO'RQ$IWO,5;pOOQ$IS7+$}7+$}O!I^Q$IWO7+$}OOQ$IS-E9S-E9SOOQ$IS7+%O7+%OO!InQ$IWO,5=RO'RQ$IWO,5=ROOQ$IS7+$c7+$cO!IsQ$IWO7+$}O!I{Q$IWO7+%OO!JQQ$IWO1G2qOOQ$IS7+%V7+%VO!JbQ$IWO1G2qO!JjQ$IWO7+%VOOQ$IS,5;o,5;oO'RQ$IWO,5;oO!JoQ$IWO1G2lOOQ$IS-E9R-E9RO!KfQ$IWO7+%ZOOQ$IS7+%]7+%]O!KtQ$IWO1G2lO!LcQ$IWO7+%]O!LhQ$IWO1G2rO!LxQ$IWO1G2rO!MQQ$IWO7+%ZO!MVQ$IWO,5=gO!MmQ$IWO,5=gO!MmQ$IWO,5=gO!M{O!LQO'#DwO!NWOSO'#G|OOOO1G/{1G/{O!N]Q$IWO1G/{O!NeQ%GlO7+'qO# UQ$I[O1G1jP# oQ$IWO'#FdOOQ$IS,5<R,5<ROOQ$IS-E9e-E9eOOQ$IS7+&q7+&qOOQ$IS1G2h1G2hOOQ$IS,5;n,5;nOOQ$IS-E9Q-E9QOOQ$IS7+$p7+$pO# |Q$IWO,5<kO#!gQ$IWO,5<kO#!xQ$I[O,5;qO##]Q$IWO1G2nOOQ$IS-E9T-E9TOOQ$IS7+&P7+&PO##mQ$IWO7+&POOQ$IS7+&R7+&RO##{Q$IWO'#HZO/|Q$IWO'#HYO#$aQ$IWO7+&ROOQ$IS,5<U,5<UO#$lQ$IWO1G3bOOQ$IS-E9h-E9hOOQ$IS,5<Q,5<QO#$zQ$IWO1G3^OOQ$IS-E9d-E9dO#%bQ$IZO7+&]O!DUQ$IWO'#FmO3UQ$IWO7+&]O3UQ$IWO7+&`O#(pQ$I[O,5<YO'RQ$IWO,5<YO#(zQ$IWO1G3dOOQ$IS-E9l-E9lO#)UQ$IWO1G3dO3UQ$IWO7+&bO/gQ$IWO7+&bOOQ$IV7+&g7+&gO!EZQ%1`O7+&iO#)^Q$IXO1G0rOOQ$IV-E9m-E9mO3UQ$IWO7+&cO3UQ$IWO7+&cOOQ$IV,5<Z,5<ZO#+PQ$IWO,5<ZOOQ$IV7+&c7+&cO#+[Q$IZO7+&cO#.gQ$IWO,5<[O#.rQ$IWO1G3eOOQ$IS-E9n-E9nO#/PQ$IWO1G3eO#/XQ$IWO'#HaO#/gQ$IWO'#HaO/|Q$IWO'#HaOOQ$IS'#Ha'#HaO#/rQ$IWO'#H`OOQ$IS,5;e,5;eO#/zQ$IWO,5;eO/gQ$IWO'#E{OOQ$IV7+&i7+&iO3UQ$IWO7+&iOOQ$IV7+&n7+&nOOQ$IS1G2t1G2tOOQ$IS,5;s,5;sO#0PQ$IWO1G2sOOQ$IS-E9V-E9VO#0dQ$IWO,5;tO#0oQ$IWO,5;tO#1SQ$IWO1G2vOOQ$IS-E9W-E9WO#1dQ$IWO1G2vO#1lQ$IWO1G2vO#1|Q$IWO1G2vO#1dQ$IWO1G2vOOQ$IS<<HX<<HXO#2XQ$I[O1G1[OOQ$IS<<Hi<<HiP#2fQ$IWO'#FUO6|Q$IWO1G2mO#2sQ$IWO1G2mO#2xQ$IWO<<HiOOQ$IS<<Hj<<HjO#3YQ$IWO7+(]OOQ$IS<<Hq<<HqO#3jQ$I[O1G1ZP#4ZQ$IWO'#FTO#4hQ$IWO7+(^O#4xQ$IWO7+(^O#5QQ$IWO<<HuO#5VQ$IWO7+(WOOQ$IS<<Hw<<HwO#5|Q$IWO,5;rO'RQ$IWO,5;rOOQ$IS-E9U-E9UOOQ$IS<<Hu<<HuOOQ$IS,5;x,5;xO/gQ$IWO,5;xO#6RQ$IWO1G3ROOQ$IS-E9[-E9[O#6iQ$IWO1G3ROOOO'#F_'#F_O#6wO!LQO,5:cOOOO,5=h,5=hOOOO7+%g7+%gO#7SQ$IWO1G2VO#7mQ$IWO1G2VP'RQ$IWO'#FVO/gQ$IWO<<IkO#8OQ$IWO,5=uO#8aQ$IWO,5=uO/|Q$IWO,5=uO#8rQ$IWO,5=tOOQ$IS<<Im<<ImP/|Q$IWO'#FjP/gQ$IWO'#FfOOQ$IV-E9k-E9kO3UQ$IWO<<IwOOQ$IV,5<X,5<XO3UQ$IWO,5<XOOQ$IV<<Iw<<IwOOQ$IV<<Iz<<IzO#8wQ$I[O1G1tP#9RQ$IWO'#FnO#9YQ$IWO7+)OO#9dQ$IZO<<I|O3UQ$IWO<<I|OOQ$IV<<JT<<JTO3UQ$IWO<<JTOOQ$IV'#Fl'#FlO#<oQ$IZO7+&^OOQ$IV<<I}<<I}O#>hQ$IZO<<I}OOQ$IV1G1u1G1uO/|Q$IWO1G1uO3UQ$IWO<<I}O/|Q$IWO1G1vP/gQ$IWO'#FpO#AsQ$IWO7+)PO#BQQ$IWO7+)POOQ$IS'#Ez'#EzO/gQ$IWO,5={O#BYQ$IWO,5={OOQ$IS,5={,5={O#BeQ$IWO,5=zO#BvQ$IWO,5=zOOQ$IS1G1P1G1POOQ$IS,5;g,5;gP#COQ$IWO'#FXO#C`Q$IWO1G1`O#CsQ$IWO1G1`O#DTQ$IWO1G1`P#D`Q$IWO'#FYO#DmQ$IWO7+(bO#D}Q$IWO7+(bO#D}Q$IWO7+(bO#EVQ$IWO7+(bO#EgQ$IWO7+(XO6|Q$IWO7+(XOOQ$ISAN>TAN>TO#FQQ$IWO<<KxOOQ$ISAN>aAN>aO/gQ$IWO1G1^O#FbQ$I[O1G1^P#FlQ$IWO'#FWOOQ$IS1G1d1G1dP#FyQ$IWO'#F^O#GWQ$IWO7+(mOOOO-E9]-E9]O#GnQ$IWO7+'qOOQ$ISAN?VAN?VO#HXQ$IWO,5<TO#HmQ$IWO1G3aOOQ$IS-E9g-E9gO#IOQ$IWO1G3aOOQ$IS1G3`1G3`OOQ$IVAN?cAN?cOOQ$IV1G1s1G1sO3UQ$IWOAN?hO#IaQ$IZOAN?hOOQ$IVAN?oAN?oOOQ$IV-E9j-E9jOOQ$IV<<Ix<<IxO3UQ$IWOAN?iO3UQ$IWO7+'aOOQ$IVAN?iAN?iOOQ$IS7+'b7+'bO#LlQ$IWO<<LkOOQ$IS1G3g1G3gO/gQ$IWO1G3gOOQ$IS,5<],5<]O#LyQ$IWO1G3fOOQ$IS-E9o-E9oO#M[Q$IWO7+&zO#MlQ$IWO7+&zOOQ$IS7+&z7+&zO#MwQ$IWO<<K|O#NXQ$IWO<<K|O#NXQ$IWO<<K|O#NaQ$IWO'#GiOOQ$IS<<Ks<<KsO#NkQ$IWO<<KsOOQ$IS7+&x7+&xO/|Q$IWO1G1oP/|Q$IWO'#FiO$ UQ$IWO7+({O$ gQ$IWO7+({OOQ$IVG25SG25SO3UQ$IWOG25SOOQ$IVG25TG25TOOQ$IV<<J{<<J{OOQ$IS7+)R7+)RP$ xQ$IWO'#FqOOQ$IS<<Jf<<JfO$!WQ$IWO<<JfO$!hQ$IWOANAhO$!xQ$IWOANAhO$#QQ$IWO'#GjOOQ$IS'#Gj'#GjO0hQ$IWO'#DaO$#kQ$IWO,5=TOOQ$ISANA_ANA_OOQ$IS7+'Z7+'ZO$$SQ$IWO<<LgOOQ$IVLD*nLD*nOOQ$ISAN@QAN@QO$$eQ$IWOG27SO$$uQ$IWO,59{OOQ$IS1G2o1G2oO#NaQ$IWO1G/gOOQ$IS7+%R7+%RO6|Q$IWO'#CzO6|Q$IWO,59_O6|Q$IWO,59_O6|Q$IWO,59_O$$zQ$I[O,5<kO6|Q$IWO1G.yO/gQ$IWO1G/UO/gQ$IWO7+$mP$%_Q$IWO'#FdO'RQ$IWO'#GPO$%lQ$IWO,59_O$%qQ$IWO,59_O$%xQ$IWO,59jO$%}Q$IWO1G/RO0hQ$IWO'#DOO6|Q$IWO,59g", - stateData: "$&e~O$oOS$lOS$kOSQOS~OPhOTeOdsOfXOltOp!SOsuO|vO}!PO!R!VO!S!UO!VYO!ZZO!fdO!mdO!ndO!odO!vxO!xyO!zzO!|{O#O|O#S}O#U!OO#X!QO#Y!QO#[!RO#c!TO#f!WO#j!XO#l!YO#q!ZO#tlO$jqO$zQO${QO%PRO%QVO%f[O%g]O%j^O%m_O%s`O%vaO%xbO~OT!aO]!aO_!bOf!iO!V!kO!d!mO$u![O$v!]O$w!^O$x!_O$y!_O$z!`O${!`O$|!aO$}!aO%O!aO~Oh%TXi%TXj%TXk%TXl%TXm%TXp%TXw%TXx%TX!s%TX#^%TX$j%TX$m%TX%V%TX!O%TX!R%TX!S%TX%W%TX!W%TX![%TX}%TX#V%TXq%TX!j%TX~P$_OdsOfXO!VYO!ZZO!fdO!mdO!ndO!odO$zQO${QO%PRO%QVO%f[O%g]O%j^O%m_O%s`O%vaO%xbO~Ow%SXx%SX#^%SX$j%SX$m%SX%V%SX~Oh!pOi!qOj!oOk!oOl!rOm!sOp!tO!s%SX~P(`OT!zOl-dOs-rO|vO~P'ROT!}Ol-dOs-rO!W#OO~P'ROT#RO_#SOl-dOs-rO![#TO~P'RO%h#WO%i#YO~O%k#ZO%l#YO~O!Z#]O%n#^O%r#`O~O!Z#]O%t#aO%u#`O~O!Z#]O%i#`O%w#cO~O!Z#]O%l#`O%y#eO~OT$tX]$tX_$tXf$tXh$tXi$tXj$tXk$tXl$tXm$tXp$tXw$tX!V$tX!d$tX$u$tX$v$tX$w$tX$x$tX$y$tX$z$tX${$tX$|$tX$}$tX%O$tX!O$tX!R$tX!S$tX~O%f[O%g]O%j^O%m_O%s`O%vaO%xbOx$tX!s$tX#^$tX$j$tX$m$tX%V$tX%W$tX!W$tX![$tX}$tX#V$tXq$tX!j$tX~P+uOw#jOx$sX!s$sX#^$sX$j$sX$m$sX%V$sX~Ol-dOs-rO~P'RO#^#mO$j#oO$m#oO~O%QVO~O!R#tO#l!YO#q!ZO#tlO~OltO~P'ROT#yO_#zO%QVOxtP~OT$OOl-dOs-rO}$PO~P'ROx$RO!s$WO%V$SO#^!tX$j!tX$m!tX~OT$OOl-dOs-rO#^!}X$j!}X$m!}X~P'ROl-dOs-rO#^#RX$j#RX$m#RX~P'RO!d$^O!m$^O%QVO~OT$hO~P'RO!S$jO#j$kO#l$lO~Ox$mO~OT${O_${Ol-dOs-rO!O$}O~P'ROl-dOs-rOx%QO~P'RO%e%SO~O_!bOf!iO!V!kO!d!mOT`a]`ah`ai`aj`ak`al`am`ap`aw`ax`a!s`a#^`a$j`a$m`a$u`a$v`a$w`a$x`a$y`a$z`a${`a$|`a$}`a%O`a%V`a!O`a!R`a!S`a%W`a!W`a![`a}`a#V`aq`a!j`a~Ok%XO~Ol%XO~P'ROl-dO~P'ROh-fOi-gOj-eOk-eOl-nOm-oOp-sO!O%SX!R%SX!S%SX%W%SX!W%SX![%SX}%SX#V%SX!j%SX~P(`O%W%ZOw%RX!O%RX!R%RX!S%RX!W%RXx%RX~Ow%^O!O%]O!R%bO!S%aO~O!O%]O~Ow%eO!R%bO!S%aO!W%_X~O!W%iO~Ow%jOx%lO!R%bO!S%aO![%YX~O![%pO~O![%qO~O%h#WO%i%sO~O%k#ZO%l%sO~OT%vOl-dOs-rO|vO~P'RO!Z#]O%n#^O%r%yO~O!Z#]O%t#aO%u%yO~O!Z#]O%i%yO%w#cO~O!Z#]O%l%yO%y#eO~OT!la]!la_!laf!lah!lai!laj!lak!lal!lam!lap!law!lax!la!V!la!d!la!s!la#^!la$j!la$m!la$u!la$v!la$w!la$x!la$y!la$z!la${!la$|!la$}!la%O!la%V!la!O!la!R!la!S!la%W!la!W!la![!la}!la#V!laq!la!j!la~P#vOw&OOx$sa!s$sa#^$sa$j$sa$m$sa%V$sa~P$_OT&QOltOsuOx$sa!s$sa#^$sa$j$sa$m$sa%V$sa~P'ROw&OOx$sa!s$sa#^$sa$j$sa$m$sa%V$sa~OPhOTeOltOsuO|vO}!PO!vxO!xyO!zzO!|{O#O|O#S}O#U!OO#X!QO#Y!QO#[!RO#^$_X$j$_X$m$_X~P'RO#^#mO$j&VO$m&VO~O!d&WOf%{X$j%{X#V%{X#^%{X$m%{X#U%{X~Of!iO$j&YO~Ohcaicajcakcalcamcapcawcaxca!sca#^ca$jca$mca%Vca!Oca!Rca!Sca%Wca!Wca![ca}ca#Vcaqca!jca~P$_Opnawnaxna#^na$jna$mna%Vna~Oh!pOi!qOj!oOk!oOl!rOm!sO!sna~PDTO%V&[Ow%UXx%UX~O%QVOw%UXx%UX~Ow&_OxtX~Ox&aO~Ow%jO#^%YX$j%YX$m%YX!O%YXx%YX![%YX!j%YX%V%YX~OT-mOl-dOs-rO|vO~P'RO%V$SO#^Sa$jSa$mSa~Ow&jO#^%[X$j%[X$m%[Xk%[X~P$_Ow&mO}&lO#^#Ra$j#Ra$m#Ra~O#V&nO#^#Ta$j#Ta$m#Ta~O!d$^O!m$^O#U&pO%QVO~O#U&pO~Ow&rO#^&OX$j&OX$m&OX~Ow&tO#^%zX$j%zX$m%zXx%zX~Ow&xOk&QX~P$_Ok&{O~OPhOTeOltOsuO|vO}!PO!vxO!xyO!zzO!|{O#O|O#S}O#U!OO#X!QO#Y!QO#[!RO$j'QO~P'ROq'UO#g'SO#h'TOP#eaT#ead#eaf#eal#eap#eas#ea|#ea}#ea!R#ea!S#ea!V#ea!Z#ea!f#ea!m#ea!n#ea!o#ea!v#ea!x#ea!z#ea!|#ea#O#ea#S#ea#U#ea#X#ea#Y#ea#[#ea#c#ea#f#ea#j#ea#l#ea#q#ea#t#ea$g#ea$j#ea$z#ea${#ea%P#ea%Q#ea%f#ea%g#ea%j#ea%m#ea%s#ea%v#ea%x#ea$i#ea$m#ea~Ow'VO#V'XOx&RX~Of'ZO~Of!iOx$mO~OT!aO]!aO_!bOf!iO!V!kO!d!mO$w!^O$x!_O$y!_O$z!`O${!`O$|!aO$}!aO%O!aOhUiiUijUikUilUimUipUiwUixUi!sUi#^Ui$jUi$mUi$uUi%VUi!OUi!RUi!SUi%WUi!WUi![Ui}Ui#VUiqUi!jUi~O$v!]O~PNtO$vUi~PNtOT!aO]!aO_!bOf!iO!V!kO!d!mO$z!`O${!`O$|!aO$}!aO%O!aOhUiiUijUikUilUimUipUiwUixUi!sUi#^Ui$jUi$mUi$uUi$vUi$wUi%VUi!OUi!RUi!SUi%WUi!WUi![Ui}Ui#VUiqUi!jUi~O$x!_O$y!_O~P!#oO$xUi$yUi~P!#oO_!bOf!iO!V!kO!d!mOhUiiUijUikUilUimUipUiwUixUi!sUi#^Ui$jUi$mUi$uUi$vUi$wUi$xUi$yUi$zUi${Ui%VUi!OUi!RUi!SUi%WUi!WUi![Ui}Ui#VUiqUi!jUi~OT!aO]!aO$|!aO$}!aO%O!aO~P!&mOTUi]Ui$|Ui$}Ui%OUi~P!&mO!R%bO!S%aOw%bX!O%bX~O%V'`O%W'`O~P+uOw'bO!O%aX~O!O'dO~Ow'eOx'gO!W%dX~Ol-dOs-rOw'eOx'hO!W%dX~P'RO!W'jO~Oj!oOk!oOl!rOm!sOhgipgiwgixgi!sgi#^gi$jgi$mgi%Vgi~Oi!qO~P!+`Oigi~P!+`Oh-fOi-gOj-eOk-eOl-nOm-oO~Oq'lO~P!,iOT'qOl-dOs-rO!O'rO~P'ROw'sO!O'rO~O!O'uO~O!S'wO~Ow'sO!O'xO!R%bO!S%aO~P$_Oh-fOi-gOj-eOk-eOl-nOm-oO!Ona!Rna!Sna%Wna!Wna![na}na#Vnaqna!jna~PDTOT'qOl-dOs-rO!W%_a~P'ROw'{O!W%_a~O!W'|O~Ow'{O!R%bO!S%aO!W%_a~P$_OT(QOl-dOs-rO![%Ya#^%Ya$j%Ya$m%Ya!O%Yax%Ya!j%Ya%V%Ya~P'ROw(RO![%Ya#^%Ya$j%Ya$m%Ya!O%Yax%Ya!j%Ya%V%Ya~O![(UO~Ow(RO!R%bO!S%aO![%Ya~P$_Ow(XO!R%bO!S%aO![%`a~P$_Ow([Ox%oX![%oX!j%oX~Ox(_O![(aO!j(bO~OT&QOltOsuOx$si!s$si#^$si$j$si$m$si%V$si~P'ROw(cOx$si!s$si#^$si$j$si$m$si%V$si~O!d&WOf%{a$j%{a#V%{a#^%{a$m%{a#U%{a~O$j(hO~OT#yO_#zO%QVO~Ow&_Oxta~OltOsuO~P'ROw(RO#^%Ya$j%Ya$m%Ya!O%Yax%Ya![%Ya!j%Ya%V%Ya~P$_Ow(mO#^$sX$j$sX$m$sX%V$sX~O%V$SO#^Si$jSi$mSi~O#^%[a$j%[a$m%[ak%[a~P'ROw(pO#^%[a$j%[a$m%[ak%[a~OT(tOf(vO%QVO~O#U(wO~O%QVO#^&Oa$j&Oa$m&Oa~Ow(yO#^&Oa$j&Oa$m&Oa~Ol-dOs-rO#^%za$j%za$m%zax%za~P'ROw(|O#^%za$j%za$m%zax%za~Oq)QO#a)POP#_iT#_id#_if#_il#_ip#_is#_i|#_i}#_i!R#_i!S#_i!V#_i!Z#_i!f#_i!m#_i!n#_i!o#_i!v#_i!x#_i!z#_i!|#_i#O#_i#S#_i#U#_i#X#_i#Y#_i#[#_i#c#_i#f#_i#j#_i#l#_i#q#_i#t#_i$g#_i$j#_i$z#_i${#_i%P#_i%Q#_i%f#_i%g#_i%j#_i%m#_i%s#_i%v#_i%x#_i$i#_i$m#_i~Oq)ROP#biT#bid#bif#bil#bip#bis#bi|#bi}#bi!R#bi!S#bi!V#bi!Z#bi!f#bi!m#bi!n#bi!o#bi!v#bi!x#bi!z#bi!|#bi#O#bi#S#bi#U#bi#X#bi#Y#bi#[#bi#c#bi#f#bi#j#bi#l#bi#q#bi#t#bi$g#bi$j#bi$z#bi${#bi%P#bi%Q#bi%f#bi%g#bi%j#bi%m#bi%s#bi%v#bi%x#bi$i#bi$m#bi~OT)TOk&Qa~P'ROw)UOk&Qa~Ow)UOk&Qa~P$_Ok)YO~O$h)]O~Oq)`O#g'SO#h)_OP#eiT#eid#eif#eil#eip#eis#ei|#ei}#ei!R#ei!S#ei!V#ei!Z#ei!f#ei!m#ei!n#ei!o#ei!v#ei!x#ei!z#ei!|#ei#O#ei#S#ei#U#ei#X#ei#Y#ei#[#ei#c#ei#f#ei#j#ei#l#ei#q#ei#t#ei$g#ei$j#ei$z#ei${#ei%P#ei%Q#ei%f#ei%g#ei%j#ei%m#ei%s#ei%v#ei%x#ei$i#ei$m#ei~Ol-dOs-rOx$mO~P'ROl-dOs-rOx&Ra~P'ROw)fOx&Ra~OT)jO_)kO!O)nO$|)lO%QVO~Ox$mO&U)pO~OT${O_${Ol-dOs-rO!O%aa~P'ROw)vO!O%aa~Ol-dOs-rOx)yO!W%da~P'ROw)zO!W%da~Ol-dOs-rOw)zOx)}O!W%da~P'ROl-dOs-rOw)zO!W%da~P'ROw)zOx)}O!W%da~Oj-eOk-eOl-nOm-oOhgipgiwgi!Ogi!Rgi!Sgi%Wgi!Wgixgi![gi#^gi$jgi$mgi}gi#Vgiqgi!jgi%Vgi~Oi-gO~P!GhOigi~P!GhOT'qOl-dOs-rO!O*SO~P'ROk*UO~Ow*WO!O*SO~O!O*XO~OT'qOl-dOs-rO!W%_i~P'ROw*YO!W%_i~O!W*ZO~OT(QOl-dOs-rO![%Yi#^%Yi$j%Yi$m%Yi!O%Yix%Yi!j%Yi%V%Yi~P'ROw*^O!R%bO!S%aO![%`i~Ow*aO![%Yi#^%Yi$j%Yi$m%Yi!O%Yix%Yi!j%Yi%V%Yi~O![*bO~O_*dOl-dOs-rO![%`i~P'ROw*^O![%`i~O![*fO~OT*hOl-dOs-rOx%oa![%oa!j%oa~P'ROw*iOx%oa![%oa!j%oa~O!Z#]O%q*lO![!kX~O![*nO~Ox(_O![*oO~OT&QOltOsuOx$sq!s$sq#^$sq$j$sq$m$sq%V$sq~P'ROw$Wix$Wi!s$Wi#^$Wi$j$Wi$m$Wi%V$Wi~P$_OT&QOltOsuO~P'ROT&QOl-dOs-rO#^$sa$j$sa$m$sa%V$sa~P'ROw*pO#^$sa$j$sa$m$sa%V$sa~Ow#ya#^#ya$j#ya$m#yak#ya~P$_O#^%[i$j%[i$m%[ik%[i~P'ROw*sO#^#Rq$j#Rq$m#Rq~Ow*tO#V*vO#^%}X$j%}X$m%}X!O%}X~OT*xOf(vO%QVO~O%QVO#^&Oi$j&Oi$m&Oi~Ol-dOs-rO#^%zi$j%zi$m%zix%zi~P'ROq*|O#a)POP#_qT#_qd#_qf#_ql#_qp#_qs#_q|#_q}#_q!R#_q!S#_q!V#_q!Z#_q!f#_q!m#_q!n#_q!o#_q!v#_q!x#_q!z#_q!|#_q#O#_q#S#_q#U#_q#X#_q#Y#_q#[#_q#c#_q#f#_q#j#_q#l#_q#q#_q#t#_q$g#_q$j#_q$z#_q${#_q%P#_q%Q#_q%f#_q%g#_q%j#_q%m#_q%s#_q%v#_q%x#_q$i#_q$m#_q~Ok$baw$ba~P$_OT)TOk&Qi~P'ROw+TOk&Qi~OPhOTeOltOp!SOsuO|vO}!PO!R!VO!S!UO!vxO!xyO!zzO!|{O#O|O#S}O#U!OO#X!QO#Y!QO#[!RO#c!TO#f!WO#j!XO#l!YO#q!ZO#tlO~P'ROw+_Ox$mO#V+_O~O#h+`OP#eqT#eqd#eqf#eql#eqp#eqs#eq|#eq}#eq!R#eq!S#eq!V#eq!Z#eq!f#eq!m#eq!n#eq!o#eq!v#eq!x#eq!z#eq!|#eq#O#eq#S#eq#U#eq#X#eq#Y#eq#[#eq#c#eq#f#eq#j#eq#l#eq#q#eq#t#eq$g#eq$j#eq$z#eq${#eq%P#eq%Q#eq%f#eq%g#eq%j#eq%m#eq%s#eq%v#eq%x#eq$i#eq$m#eq~O#V+aOw$dax$da~Ol-dOs-rOx&Ri~P'ROw+cOx&Ri~Ox$RO%V+eOw&TX!O&TX~O%QVOw&TX!O&TX~Ow+iO!O&SX~O!O+kO~OT${O_${Ol-dOs-rO!O%ai~P'ROx+nOw#|a!W#|a~Ol-dOs-rOx+oOw#|a!W#|a~P'ROl-dOs-rOx)yO!W%di~P'ROw+rO!W%di~Ol-dOs-rOw+rO!W%di~P'ROw+rOx+uO!W%di~Ow#xi!O#xi!W#xi~P$_OT'qOl-dOs-rO~P'ROk+wO~OT'qOl-dOs-rO!O+xO~P'ROT'qOl-dOs-rO!W%_q~P'ROw#wi![#wi#^#wi$j#wi$m#wi!O#wix#wi!j#wi%V#wi~P$_OT(QOl-dOs-rO~P'RO_*dOl-dOs-rO![%`q~P'ROw+yO![%`q~O![+zO~OT(QOl-dOs-rO![%Yq#^%Yq$j%Yq$m%Yq!O%Yqx%Yq!j%Yq%V%Yq~P'ROx+{O~OT*hOl-dOs-rOx%oi![%oi!j%oi~P'ROw,QOx%oi![%oi!j%oi~O!Z#]O%q*lO![!ka~OT&QOl-dOs-rO#^$si$j$si$m$si%V$si~P'ROw,SO#^$si$j$si$m$si%V$si~O%QVO#^%}a$j%}a$m%}a!O%}a~Ow,VO#^%}a$j%}a$m%}a!O%}a~O!O,YO~Ok$biw$bi~P$_OT)TO~P'ROT)TOk&Qq~P'ROq,]OP#dyT#dyd#dyf#dyl#dyp#dys#dy|#dy}#dy!R#dy!S#dy!V#dy!Z#dy!f#dy!m#dy!n#dy!o#dy!v#dy!x#dy!z#dy!|#dy#O#dy#S#dy#U#dy#X#dy#Y#dy#[#dy#c#dy#f#dy#j#dy#l#dy#q#dy#t#dy$g#dy$j#dy$z#dy${#dy%P#dy%Q#dy%f#dy%g#dy%j#dy%m#dy%s#dy%v#dy%x#dy$i#dy$m#dy~OPhOTeOltOp!SOsuO|vO}!PO!R!VO!S!UO!vxO!xyO!zzO!|{O#O|O#S}O#U!OO#X!QO#Y!QO#[!RO#c!TO#f!WO#j!XO#l!YO#q!ZO#tlO$i,aO$m,aO~P'RO#h,bOP#eyT#eyd#eyf#eyl#eyp#eys#ey|#ey}#ey!R#ey!S#ey!V#ey!Z#ey!f#ey!m#ey!n#ey!o#ey!v#ey!x#ey!z#ey!|#ey#O#ey#S#ey#U#ey#X#ey#Y#ey#[#ey#c#ey#f#ey#j#ey#l#ey#q#ey#t#ey$g#ey$j#ey$z#ey${#ey%P#ey%Q#ey%f#ey%g#ey%j#ey%m#ey%s#ey%v#ey%x#ey$i#ey$m#ey~Ol-dOs-rOx&Rq~P'ROw,fOx&Rq~O%V+eOw&Ta!O&Ta~OT)jO_)kO$|)lO%QVO!O&Sa~Ow,jO!O&Sa~OT${O_${Ol-dOs-rO~P'ROl-dOs-rOx,lOw#|i!W#|i~P'ROl-dOs-rOw#|i!W#|i~P'ROx,lOw#|i!W#|i~Ol-dOs-rOx)yO~P'ROl-dOs-rOx)yO!W%dq~P'ROw,oO!W%dq~Ol-dOs-rOw,oO!W%dq~P'ROp,rO!R%bO!S%aO!O%Zq!W%Zq![%Zqw%Zq~P!,iO_*dOl-dOs-rO![%`y~P'ROw#zi![#zi~P$_O_*dOl-dOs-rO~P'ROT*hOl-dOs-rO~P'ROT*hOl-dOs-rOx%oq![%oq!j%oq~P'ROT&QOl-dOs-rO#^$sq$j$sq$m$sq%V$sq~P'RO#V,vOw$]a#^$]a$j$]a$m$]a!O$]a~O%QVO#^%}i$j%}i$m%}i!O%}i~Ow,xO#^%}i$j%}i$m%}i!O%}i~Oq,{OP#d!RT#d!Rd#d!Rf#d!Rl#d!Rp#d!Rs#d!R|#d!R}#d!R!R#d!R!S#d!R!V#d!R!Z#d!R!f#d!R!m#d!R!n#d!R!o#d!R!v#d!R!x#d!R!z#d!R!|#d!R#O#d!R#S#d!R#U#d!R#X#d!R#Y#d!R#[#d!R#c#d!R#f#d!R#j#d!R#l#d!R#q#d!R#t#d!R$g#d!R$j#d!R$z#d!R${#d!R%P#d!R%Q#d!R%f#d!R%g#d!R%j#d!R%m#d!R%s#d!R%v#d!R%x#d!R$i#d!R$m#d!R~Ol-dOs-rOx&Ry~P'ROT)jO_)kO$|)lO%QVO!O&Si~Ol-dOs-rOw#|q!W#|q~P'ROx-ROw#|q!W#|q~Ol-dOs-rOx)yO!W%dy~P'ROw-SO!W%dy~Ol-dOs-WO~P'ROp,rO!R%bO!S%aO!O%Zy!W%Zy![%Zyw%Zy~P!,iO%QVO#^%}q$j%}q$m%}q!O%}q~Ow-[O#^%}q$j%}q$m%}q!O%}q~OT)jO_)kO$|)lO%QVO~Ol-dOs-rOw#|y!W#|y~P'ROl-dOs-rOx)yO!W%d!R~P'ROw-_O!W%d!R~Op%^X!O%^X!R%^X!S%^X!W%^X![%^Xw%^X~P!,iOp,rO!R%bO!S%aO!O%]a!W%]a![%]aw%]a~O%QVO#^%}y$j%}y$m%}y!O%}y~Ol-dOs-rOx)yO!W%d!Z~P'ROx-bO~Ow*pO#^$sa$j$sa$m$sa%V$sa~P$_OT&QOl-dOs-rO~P'ROk-iO~Ol-iO~P'ROx-jO~Oq-kO~P!,iO%g%j%v%x%f!Z%n%t%w%y%m%s%m%Q~", - goto: "!-g&UPPPP&VP&_)p*V*m+U+n,XP,sP&_-a-a&_P&_P0rPPPPPP0r3bPP3bP5n5w:zPP:};];`PPP&_&_PP;l&_PP&_&_PP&_&_&_&_;p<d&_P<gP<j<j@PP@e&_PPP@i@o&VP&V&VP&VP&VP&VP&VP&V&V&VP&VPP&VPP&VP@uP@|ASP@|P@|@|PPP@|PB{PCUC[CbB{P@|ChPCoCuC{DXDkDqD{EREoEuE{FRF]FcFiFoFuF{G_GiGoGuG{HVH]HcHiHoHyIPIZIaPPPPPPPPPIjIrI{JVJbPPPPPPPPPPPPNw! a!%o!({PP!)T!)c!)l!*b!*X!*k!*q!*t!*w!*z!+S!+pPPPPPPPPPP!+s!+vPPPPPPPPP!+|!,Y!,f!,l!,u!,x!-O!-U!-[!-_]iOr#m$m)]+Z'odOSXYZehrstvx|}!R!S!T!U!X!c!d!e!f!g!h!i!k!o!p!q!s!t!z!}#R#S#]#j#m$O$P$R$T$W$h$j$k$m${%Q%X%[%^%a%e%j%l%v&O&Q&]&a&j&l&m&t&x&{'S'V'a'b'e'g'h'l'q's'w'{(Q(R(X([(c(e(m(p(|)P)T)U)Y)])f)p)v)y)z)}*T*U*W*Y*]*^*a*d*h*i*p*r*s*z+S+T+Z+b+c+f+m+n+o+q+r+u+w+y+{+},P,Q,S,f,h,l,o,r-R-S-_-b-d-e-f-g-i-j-k-l-m-o-sw!cP#i#v$X$g%c%h%n%o&b&z(d(o)S*R*[+R+|-hy!dP#i#v$X$g$s%c%h%n%o&b&z(d(o)S*R*[+R+|-h{!eP#i#v$X$g$s$t%c%h%n%o&b&z(d(o)S*R*[+R+|-h}!fP#i#v$X$g$s$t$u%c%h%n%o&b&z(d(o)S*R*[+R+|-h!P!gP#i#v$X$g$s$t$u$v%c%h%n%o&b&z(d(o)S*R*[+R+|-h!R!hP#i#v$X$g$s$t$u$v$w%c%h%n%o&b&z(d(o)S*R*[+R+|-h!V!hP!n#i#v$X$g$s$t$u$v$w$x%c%h%n%o&b&z(d(o)S*R*[+R+|-h'oSOSXYZehrstvx|}!R!S!T!U!X!c!d!e!f!g!h!i!k!o!p!q!s!t!z!}#R#S#]#j#m$O$P$R$T$W$h$j$k$m${%Q%X%[%^%a%e%j%l%v&O&Q&]&a&j&l&m&t&x&{'S'V'a'b'e'g'h'l'q's'w'{(Q(R(X([(c(e(m(p(|)P)T)U)Y)])f)p)v)y)z)}*T*U*W*Y*]*^*a*d*h*i*p*r*s*z+S+T+Z+b+c+f+m+n+o+q+r+u+w+y+{+},P,Q,S,f,h,l,o,r-R-S-_-b-d-e-f-g-i-j-k-l-m-o-s&ZUOXYZhrtv|}!R!S!T!X!i!k!o!p!q!s!t#]#j#m$P$R$T$W$k$m${%Q%X%[%^%e%j%l%v&O&]&a&l&m&t&{'S'V'a'b'e'g'h'l's'{(R(X([(c(e(m(|)P)Y)])f)p)v)y)z)}*T*U*W*Y*]*^*a*h*i*p*s*z+Z+b+c+f+m+n+o+q+r+u+w+y+{+},P,Q,S,f,h,l,o,r-R-S-_-b-d-e-f-g-i-j-k-l-o-s%eWOXYZhrv|}!R!S!T!X!i!k#]#j#m$P$R$T$W$k$m${%Q%[%^%e%j%l%v&O&]&a&l&m&t&{'S'V'a'b'e'g'h'l's'{(R(X([(c(e(m(|)P)Y)])f)p)v)y)z)}*T*W*Y*]*^*a*h*i*p*s*z+Z+b+c+f+m+n+o+q+r+u+y+{+},P,Q,S,f,h,l,o-R-S-_-j-k-lQ#|uQ-`-WR-p-r'fdOSXYZehrstvx|}!R!S!T!U!X!c!d!e!f!g!h!k!o!p!q!s!t!z!}#R#S#]#j#m$O$P$R$T$W$h$j$k$m${%Q%X%[%^%a%e%j%l%v&O&Q&]&a&j&l&m&t&x&{'S'V'a'e'g'h'l'q's'w'{(Q(R(X([(c(e(m(p(|)P)T)U)Y)])f)p)y)z)}*T*U*W*Y*]*^*a*d*h*i*p*r*s*z+S+T+Z+b+c+f+n+o+q+r+u+w+y+{+},P,Q,S,f,h,l,o,r-R-S-_-b-d-e-f-g-i-j-k-l-m-o-sW#pl!O!P$_W#xu&_-W-rQ$a!QQ$q!YQ$r!ZW$z!i'b)v+mS&^#y#zQ'O$lQ(f&WQ(t&nU(u&p(v(wU(x&r(y*yQ)h'XW)i'Z+i,j-PS+h)j)kY,U*t,V,w,x-[Q,X*vQ,c+_Q,e+aR-Z,vR&]#xi!wXY!S!T%^%e's'{)P*T*W*YR%[!vQ!{XQ%w#]Q&f$TR&i$WT-V,r-b!U!jP!n#i#v$X$g$s$t$u$v$w$x%c%h%n%o&b&z(d(o)S*R*[+R+|-hQ&Z#qR'^$rR'a$zR%T!m'ncOSXYZehrstvx|}!R!S!T!U!X!c!d!e!f!g!h!i!k!o!p!q!s!t!z!}#R#S#]#j#m$O$P$R$T$W$h$j$k$m${%Q%X%[%^%a%e%j%l%v&O&Q&]&a&j&l&m&t&x&{'S'V'a'b'e'g'h'l'q's'w'{(Q(R(X([(c(e(m(p(|)P)T)U)Y)])f)p)v)y)z)}*T*U*W*Y*]*^*a*d*h*i*p*r*s*z+S+T+Z+b+c+f+m+n+o+q+r+u+w+y+{+},P,Q,S,f,h,l,o,r-R-S-_-b-d-e-f-g-i-j-k-l-m-o-sT#gc#hS#^_#_S#a`#bS#ca#dS#eb#fT*l(_*mT(`%w(bQ$VwR+g)iX$Tw$U$V&hZkOr$m)]+ZXoOr)]+ZQ$n!WQ&v$eQ&w$fQ'Y$pQ']$rQ)Z&}Q)a'SQ)c'TQ)d'UQ)q'[Q)s'^Q*})PQ+P)QQ+Q)RQ+U)XS+W)[)rQ+[)_Q+])`Q+^)bQ,Z*|Q,[+OQ,^+VQ,_+XQ,d+`Q,z,]Q,|,bQ,},cR-],{WoOr)]+ZR#snQ'[$qR)['OQ+f)iR,h+gQ)r'[R+X)[ZmOnr)]+ZQrOR#urQ&`#{R(k&`S%k#Q#}S(S%k(VT(V%n&bQ%_!yQ%f!|W't%_%f'y'}Q'y%cR'}%hQ&k$XR(q&kQ(Y%oQ*_(TT*e(Y*_Q'c$|R)w'cS'f%P%QY){'f)|+s,p-TU)|'g'h'iU+s)}*O*PS,p+t+uR-T,qQ#X]R%r#XQ#[^R%t#[Q#__R%x#_Q(]%uS*j(]*kR*k(^Q*m(_R,R*mQ#b`R%z#bQ#daR%{#dQ#fbR%|#fQ#hcR%}#hQ#kfQ&P#iW&S#k&P(n*qQ(n&eR*q-hQ$UwS&g$U&hR&h$VQ&u$cR(}&uQ&X#pR(g&XQ$_!PR&o$_Q*u(uS,W*u,yR,y,XQ&s$aR(z&sQ#njR&U#nQ+Z)]R,`+ZQ)O&vR*{)OQ&y$gS)V&y)WR)W&zQ'R$nR)^'RQ'W$oS)g'W+dR+d)hQ+j)mR,k+jWnOr)]+ZR#rnSqOrT+Y)]+ZWpOr)]+ZR'P$mYjOr$m)]+ZR&T#m[wOr#m$m)]+ZR&f$T&YPOXYZhrtv|}!R!S!T!X!i!k!o!p!q!s!t#]#j#m$P$R$T$W$k$m${%Q%X%[%^%e%j%l%v&O&]&a&l&m&t&{'S'V'a'b'e'g'h'l's'{(R(X([(c(e(m(|)P)Y)])f)p)v)y)z)}*T*U*W*Y*]*^*a*h*i*p*s*z+Z+b+c+f+m+n+o+q+r+u+w+y+{+},P,Q,S,f,h,l,o,r-R-S-_-b-d-e-f-g-i-j-k-l-o-sQ!nSQ#ieQ#vsU$Xx%a'wS$g!U$jQ$s!cQ$t!dQ$u!eQ$v!fQ$w!gQ$x!hQ%c!zQ%h!}Q%n#RQ%o#SQ&b$OQ&z$hQ(d&QU(o&j(p*rW)S&x)U+S+TQ*R'qQ*[(QQ+R)TQ+|*dR-h-mQ!yXQ!|YQ$e!SQ$f!T^'p%^%e's'{*T*W*YR+O)P[fOr#m$m)]+Zh!vXY!S!T%^%e's'{)P*T*W*YQ#QZQ#lhS#}v|Q$[}W$c!R$W&{)YS$o!X$kW$y!i'b)v+mQ%P!kQ%u#]`&R#j&O(c(e(m*p,S-lQ&c$PQ&d$RQ&e$TQ'_${Q'i%QQ'o%[W(P%j(R*]*aQ(T%lQ(^%vQ(i&]S(l&a-jQ(r&lQ(s&mU({&t(|*zQ)b'SY)e'V)f+b+c,fQ)t'a^)x'e)z+q+r,o-S-_Q*O'gQ*P'hS*Q'l-kW*c(X*^+y+}W*g([*i,P,QQ+l)pQ+p)yQ+t)}Q,O*hQ,T*sQ,g+fQ,m+nQ,n+oQ,q+uQ,u+{Q-O,hQ-Q,lR-^-RhTOr#j#m$m&O&a'l(c(e)]+Z$z!uXYZhv|}!R!S!T!X!i!k#]$P$R$T$W$k${%Q%[%^%e%j%l%v&]&l&m&t&{'S'V'a'b'e'g'h's'{(R(X([(m(|)P)Y)f)p)v)y)z)}*T*W*Y*]*^*a*h*i*p*s*z+b+c+f+m+n+o+q+r+u+y+{+},P,Q,S,f,h,l,o-R-S-_-j-k-lQ#wtW%U!o!s-e-oQ%V!pQ%W!qQ%Y!tQ%d-dS'k%X-iQ'm-fQ'n-gQ+v*UQ,t+wS-U,r-bR-q-sU#{u-W-rR(j&_[gOr#m$m)]+ZX!xX#]$T$WQ#VZQ$QvR$Z|Q%`!yQ%g!|Q%m#QQ'_$yQ'z%cQ(O%hQ(W%nQ(Z%oQ*`(TQ,s+vQ-Y,tR-a-XQ$YxQ'v%aR*V'wQ-X,rR-c-bR#PYR#UZR%O!iQ$|!iV)u'b)v+m!V!lP!n#i#v$X$g$s$t$u$v$w$x%c%h%n%o&b&z(d(o)S*R*[+R+|-hR%R!kR%w#]Q(a%wR*o(bQ$d!RQ&i$WQ)X&{R+V)YQ#qlQ$]!OQ$`!PR&q$_Q(t&pR*x(wQ(t&pQ*w(vR*x(wR$b!QXpOr)]+ZQ$i!UR&|$jQ$p!XR&}$kR)o'ZQ)m'ZV,i+i,j-P", - nodeNames: "⚠ print Comment Script AssignStatement * BinaryExpression BitOp BitOp BitOp BitOp ArithOp ArithOp @ ArithOp ** UnaryExpression ArithOp BitOp AwaitExpression await ParenthesizedExpression ( BinaryExpression or and CompareOp in not is UnaryExpression ConditionalExpression if else LambdaExpression lambda ParamList VariableName AssignOp , : NamedExpression AssignOp YieldExpression yield from ) TupleExpression ComprehensionExpression async for LambdaExpression ArrayExpression [ ] ArrayComprehensionExpression DictionaryExpression { } DictionaryComprehensionExpression SetExpression SetComprehensionExpression CallExpression ArgList AssignOp MemberExpression . PropertyName Number String FormatString FormatReplacement FormatConversion FormatSpec ContinuedString Ellipsis None Boolean TypeDef AssignOp UpdateStatement UpdateOp ExpressionStatement DeleteStatement del PassStatement pass BreakStatement break ContinueStatement continue ReturnStatement return YieldStatement PrintStatement RaiseStatement raise ImportStatement import as ScopeStatement global nonlocal AssertStatement assert StatementGroup ; IfStatement Body elif WhileStatement while ForStatement TryStatement try except finally WithStatement with FunctionDefinition def ParamList AssignOp TypeDef ClassDefinition class DecoratedStatement Decorator At", - maxTerm: 236, - context: trackIndent, - nodeProps: [ - [NodeProp.group, -14,4,80,82,83,85,87,89,91,93,94,95,97,100,103,"Statement Statement",-22,6,16,19,21,37,47,48,52,55,56,59,60,61,62,65,68,69,70,74,75,76,77,"Expression",-9,105,107,110,112,113,117,119,124,126,"Statement"] - ], - skippedNodes: [0,2], - repeatNodeCount: 32, - tokenData: "&AaMgR!^OX$}XY!#xY[$}[]!#x]p$}pq!#xqr!&Srs!)yst!C{tu$}uv$+}vw$.awx$/mxy$Lgyz$Mmz{$Ns{|%#c|}%$o}!O%%u!O!P%([!P!Q%3b!Q!R%6Q!R![%:S![!]%EO!]!^%Gb!^!_%Hh!_!`%KW!`!a%Ld!a!b$}!b!c& P!c!d&!_!d!e&$P!e!h&!_!h!i&.R!i!t&!_!t!u&7g!u!w&!_!w!x&,a!x!}&!_!}#O&9q#O#P!%b#P#Q&:w#Q#R&;}#R#S&!_#S#T$}#T#U&!_#U#V&$P#V#Y&!_#Y#Z&.R#Z#f&!_#f#g&7g#g#i&!_#i#j&,a#j#o&!_#o#p&=Z#p#q&>P#q#r&?]#r#s&@Z#s$g$}$g~&!_<r%`Z%q7[%hS%kW%n`%tp%w!b%y#tOr$}rs&Rsw$}wxFSx#O$}#O#P! n#P#o$}#o#p!#U#p#q$}#q#r!!S#r~$}9[&^Z%q7[%hS%n`%w!bOr'PrsCxsw'Pwx(Px#O'P#O#P>v#P#o'P#o#pCU#p#q'P#q#r?[#r~'P9['^Z%q7[%hS%kW%n`%w!bOr'Prs&Rsw'Pwx(Px#O'P#O#P>v#P#o'P#o#pCU#p#q'P#q#r?[#r~'P8z(WZ%q7[%kWOr(yrs)wsw(ywx;bx#O(y#O#P2V#P#o(y#o#p7n#p#q(y#q#r2k#r~(y8z)UZ%q7[%hS%kW%w!bOr(yrs)wsw(ywx(Px#O(y#O#P2V#P#o(y#o#p7n#p#q(y#q#r2k#r~(y8z*QZ%q7[%hS%w!bOr(yrs*ssw(ywx(Px#O(y#O#P2V#P#o(y#o#p7n#p#q(y#q#r2k#r~(y8z*|Z%q7[%hS%w!bOr(yrs+osw(ywx(Px#O(y#O#P2V#P#o(y#o#p7n#p#q(y#q#r2k#r~(y8r+xX%q7[%hS%w!bOw+owx,ex#O+o#O#P.V#P#o+o#o#p0^#p#q+o#q#r.k#r~+o8r,jX%q7[Ow+owx-Vx#O+o#O#P.V#P#o+o#o#p0^#p#q+o#q#r.k#r~+o8r-[X%q7[Ow+owx-wx#O+o#O#P.V#P#o+o#o#p0^#p#q+o#q#r.k#r~+o7[-|R%q7[O#o-w#p#q-w#r~-w8r.[T%q7[O#o+o#o#p.k#p#q+o#q#r.k#r~+o!f.rV%hS%w!bOw.kwx/Xx#O.k#O#P0W#P#o.k#o#p0^#p~.k!f/[VOw.kwx/qx#O.k#O#P0W#P#o.k#o#p0^#p~.k!f/tUOw.kx#O.k#O#P0W#P#o.k#o#p0^#p~.k!f0ZPO~.k!f0cV%hSOw0xwx1^x#O0x#O#P2P#P#o0x#o#p.k#p~0xS0}T%hSOw0xwx1^x#O0x#O#P2P#P~0xS1aTOw0xwx1px#O0x#O#P2P#P~0xS1sSOw0xx#O0x#O#P2P#P~0xS2SPO~0x8z2[T%q7[O#o(y#o#p2k#p#q(y#q#r2k#r~(y!n2tX%hS%kW%w!bOr2krs3asw2kwx4wx#O2k#O#P7h#P#o2k#o#p7n#p~2k!n3hX%hS%w!bOr2krs4Tsw2kwx4wx#O2k#O#P7h#P#o2k#o#p7n#p~2k!n4[X%hS%w!bOr2krs.ksw2kwx4wx#O2k#O#P7h#P#o2k#o#p7n#p~2k!n4|X%kWOr2krs3asw2kwx5ix#O2k#O#P7h#P#o2k#o#p7n#p~2k!n5nX%kWOr2krs3asw2kwx6Zx#O2k#O#P7h#P#o2k#o#p7n#p~2kW6`T%kWOr6Zrs6os#O6Z#O#P7b#P~6ZW6rTOr6Zrs7Rs#O6Z#O#P7b#P~6ZW7USOr6Zs#O6Z#O#P7b#P~6ZW7ePO~6Z!n7kPO~2k!n7uX%hS%kWOr8brs9Osw8bwx:Ux#O8b#O#P;[#P#o8b#o#p2k#p~8b[8iV%hS%kWOr8brs9Osw8bwx:Ux#O8b#O#P;[#P~8b[9TV%hSOr8brs9jsw8bwx:Ux#O8b#O#P;[#P~8b[9oV%hSOr8brs0xsw8bwx:Ux#O8b#O#P;[#P~8b[:ZV%kWOr8brs9Osw8bwx:px#O8b#O#P;[#P~8b[:uV%kWOr8brs9Osw8bwx6Zx#O8b#O#P;[#P~8b[;_PO~8b8z;iZ%q7[%kWOr(yrs)wsw(ywx<[x#O(y#O#P2V#P#o(y#o#p7n#p#q(y#q#r2k#r~(y7d<cX%q7[%kWOr<[rs=Os#O<[#O#P>b#P#o<[#o#p6Z#p#q<[#q#r6Z#r~<[7d=TX%q7[Or<[rs=ps#O<[#O#P>b#P#o<[#o#p6Z#p#q<[#q#r6Z#r~<[7d=uX%q7[Or<[rs-ws#O<[#O#P>b#P#o<[#o#p6Z#p#q<[#q#r6Z#r~<[7d>gT%q7[O#o<[#o#p6Z#p#q<[#q#r6Z#r~<[9[>{T%q7[O#o'P#o#p?[#p#q'P#q#r?[#r~'P#O?gX%hS%kW%n`%w!bOr?[rs@Ssw?[wx4wx#O?[#O#PCO#P#o?[#o#pCU#p~?[#O@]X%hS%n`%w!bOr?[rs@xsw?[wx4wx#O?[#O#PCO#P#o?[#o#pCU#p~?[#OARX%hS%n`%w!bOr?[rsAnsw?[wx4wx#O?[#O#PCO#P#o?[#o#pCU#p~?[!vAwV%hS%n`%w!bOwAnwx/Xx#OAn#O#PB^#P#oAn#o#pBd#p~An!vBaPO~An!vBiV%hSOw0xwx1^x#O0x#O#P2P#P#o0x#o#pAn#p~0x#OCRPO~?[#OC]X%hS%kWOr8brs9Osw8bwx:Ux#O8b#O#P;[#P#o8b#o#p?[#p~8b9[DTZ%q7[%hS%n`%w!bOr'PrsDvsw'Pwx(Px#O'P#O#P>v#P#o'P#o#pCU#p#q'P#q#r?[#r~'P9SERX%q7[%hS%n`%w!bOwDvwx,ex#ODv#O#PEn#P#oDv#o#pBd#p#qDv#q#rAn#r~Dv9SEsT%q7[O#oDv#o#pAn#p#qDv#q#rAn#r~Dv<bF_Z%q7[%kW%tp%y#tOrGQrs)wswGQwxM^x#OGQ#O#PHS#P#oGQ#o#pLj#p#qGQ#q#rHh#r~GQ<bGaZ%q7[%hS%kW%tp%w!b%y#tOrGQrs)wswGQwxFSx#OGQ#O#PHS#P#oGQ#o#pLj#p#qGQ#q#rHh#r~GQ<bHXT%q7[O#oGQ#o#pHh#p#qGQ#q#rHh#r~GQ&UHuX%hS%kW%tp%w!b%y#tOrHhrs3aswHhwxIbx#OHh#O#PLd#P#oHh#o#pLj#p~Hh&UIkX%kW%tp%y#tOrHhrs3aswHhwxJWx#OHh#O#PLd#P#oHh#o#pLj#p~Hh&UJaX%kW%tp%y#tOrHhrs3aswHhwxJ|x#OHh#O#PLd#P#oHh#o#pLj#p~Hh$nKVX%kW%tp%y#tOrJ|rs6oswJ|wxJ|x#OJ|#O#PKr#P#oJ|#o#pKx#p~J|$nKuPO~J|$nK}V%kWOr6Zrs6os#O6Z#O#P7b#P#o6Z#o#pJ|#p~6Z&ULgPO~Hh&ULqX%hS%kWOr8brs9Osw8bwx:Ux#O8b#O#P;[#P#o8b#o#pHh#p~8b<bMiZ%q7[%kW%tp%y#tOrGQrs)wswGQwxN[x#OGQ#O#PHS#P#oGQ#o#pLj#p#qGQ#q#rHh#r~GQ:zNgZ%q7[%kW%tp%y#tOrN[rs=OswN[wxN[x#ON[#O#P! Y#P#oN[#o#pKx#p#qN[#q#rJ|#r~N[:z! _T%q7[O#oN[#o#pJ|#p#qN[#q#rJ|#r~N[<r! sT%q7[O#o$}#o#p!!S#p#q$}#q#r!!S#r~$}&f!!cX%hS%kW%n`%tp%w!b%y#tOr!!Srs@Ssw!!SwxIbx#O!!S#O#P!#O#P#o!!S#o#p!#U#p~!!S&f!#RPO~!!S&f!#]X%hS%kWOr8brs9Osw8bwx:Ux#O8b#O#P;[#P#o8b#o#p!!S#p~8bMg!$]a%q7[%hS%kW$o1s%n`%tp%w!b%y#tOX$}XY!#xY[$}[]!#x]p$}pq!#xqr$}rs&Rsw$}wxFSx#O$}#O#P!%b#P#o$}#o#p!#U#p#q$}#q#r!!S#r~$}Mg!%gX%q7[OY$}YZ!#xZ]$}]^!#x^#o$}#o#p!!S#p#q$}#q#r!!S#r~$}<u!&eb%q7[%hS%kW%n`%tp%w!b%y#tOr$}rs&Rsw$}wxFSx!_$}!_!`!'m!`#O$}#O#P! n#P#T$}#T#U!(s#U#f$}#f#g!(s#g#h!(s#h#o$}#o#p!#U#p#q$}#q#r!!S#r~$}<u!(QZjR%q7[%hS%kW%n`%tp%w!b%y#tOr$}rs&Rsw$}wxFSx#O$}#O#P! n#P#o$}#o#p!#U#p#q$}#q#r!!S#r~$}<u!)WZ!jR%q7[%hS%kW%n`%tp%w!b%y#tOr$}rs&Rsw$}wxFSx#O$}#O#P! n#P#o$}#o#p!#U#p#q$}#q#r!!S#r~$}G{!*Y_%up%q7[%hS%f,X%n`%w!bOY!+XYZ'PZ]!+X]^'P^r!+Xrs!BPsw!+Xwx!-gx#O!+X#O#P!>e#P#o!+X#o#p!@}#p#q!+X#q#r!>y#r~!+XDe!+h_%q7[%hS%kW%f,X%n`%w!bOY!+XYZ'PZ]!+X]^'P^r!+Xrs!,gsw!+Xwx!-gx#O!+X#O#P!>e#P#o!+X#o#p!@}#p#q!+X#q#r!>y#r~!+XDe!,tZ%q7[%hS%f,X%n`%w!bOr'PrsCxsw'Pwx(Px#O'P#O#P>v#P#o'P#o#pCU#p#q'P#q#r?[#r~'PDT!-p_%q7[%kW%f,XOY!.oYZ(yZ]!.o]^(y^r!.ors!/{sw!.owx!;Rx#O!.o#O#P!0y#P#o!.o#o#p!6m#p#q!.o#q#r!1_#r~!.oDT!.|_%q7[%hS%kW%f,X%w!bOY!.oYZ(yZ]!.o]^(y^r!.ors!/{sw!.owx!-gx#O!.o#O#P!0y#P#o!.o#o#p!6m#p#q!.o#q#r!1_#r~!.oDT!0WZ%q7[%hS%f,X%w!bOr(yrs*ssw(ywx(Px#O(y#O#P2V#P#o(y#o#p7n#p#q(y#q#r2k#r~(yDT!1OT%q7[O#o!.o#o#p!1_#p#q!.o#q#r!1_#r~!.o-w!1j]%hS%kW%f,X%w!bOY!1_YZ2kZ]!1_]^2k^r!1_rs!2csw!1_wx!3Xx#O!1_#O#P!6g#P#o!1_#o#p!6m#p~!1_-w!2lX%hS%f,X%w!bOr2krs4Tsw2kwx4wx#O2k#O#P7h#P#o2k#o#p7n#p~2k-w!3`]%kW%f,XOY!1_YZ2kZ]!1_]^2k^r!1_rs!2csw!1_wx!4Xx#O!1_#O#P!6g#P#o!1_#o#p!6m#p~!1_-w!4`]%kW%f,XOY!1_YZ2kZ]!1_]^2k^r!1_rs!2csw!1_wx!5Xx#O!1_#O#P!6g#P#o!1_#o#p!6m#p~!1_,a!5`X%kW%f,XOY!5XYZ6ZZ]!5X]^6Z^r!5Xrs!5{s#O!5X#O#P!6a#P~!5X,a!6QT%f,XOr6Zrs7Rs#O6Z#O#P7b#P~6Z,a!6dPO~!5X-w!6jPO~!1_-w!6v]%hS%kW%f,XOY!7oYZ8bZ]!7o]^8b^r!7ors!8ksw!7owx!9Xx#O!7o#O#P!:{#P#o!7o#o#p!1_#p~!7o,e!7xZ%hS%kW%f,XOY!7oYZ8bZ]!7o]^8b^r!7ors!8ksw!7owx!9Xx#O!7o#O#P!:{#P~!7o,e!8rV%hS%f,XOr8brs9jsw8bwx:Ux#O8b#O#P;[#P~8b,e!9`Z%kW%f,XOY!7oYZ8bZ]!7o]^8b^r!7ors!8ksw!7owx!:Rx#O!7o#O#P!:{#P~!7o,e!:YZ%kW%f,XOY!7oYZ8bZ]!7o]^8b^r!7ors!8ksw!7owx!5Xx#O!7o#O#P!:{#P~!7o,e!;OPO~!7oDT!;[_%q7[%kW%f,XOY!.oYZ(yZ]!.o]^(y^r!.ors!/{sw!.owx!<Zx#O!.o#O#P!0y#P#o!.o#o#p!6m#p#q!.o#q#r!1_#r~!.oBm!<d]%q7[%kW%f,XOY!<ZYZ<[Z]!<Z]^<[^r!<Zrs!=]s#O!<Z#O#P!>P#P#o!<Z#o#p!5X#p#q!<Z#q#r!5X#r~!<ZBm!=dX%q7[%f,XOr<[rs=ps#O<[#O#P>b#P#o<[#o#p6Z#p#q<[#q#r6Z#r~<[Bm!>UT%q7[O#o!<Z#o#p!5X#p#q!<Z#q#r!5X#r~!<ZDe!>jT%q7[O#o!+X#o#p!>y#p#q!+X#q#r!>y#r~!+X.X!?W]%hS%kW%f,X%n`%w!bOY!>yYZ?[Z]!>y]^?[^r!>yrs!@Psw!>ywx!3Xx#O!>y#O#P!@w#P#o!>y#o#p!@}#p~!>y.X!@[X%hS%f,X%n`%w!bOr?[rs@xsw?[wx4wx#O?[#O#PCO#P#o?[#o#pCU#p~?[.X!@zPO~!>y.X!AW]%hS%kW%f,XOY!7oYZ8bZ]!7o]^8b^r!7ors!8ksw!7owx!9Xx#O!7o#O#P!:{#P#o!7o#o#p!>y#p~!7oGZ!B^Z%q7[%hS%f,X%n`%w!bOr'Prs!CPsw'Pwx(Px#O'P#O#P>v#P#o'P#o#pCU#p#q'P#q#r?[#r~'PGZ!C`X%l#|%q7[%hS%j,X%n`%w!bOwDvwx,ex#ODv#O#PEn#P#oDv#o#pBd#p#qDv#q#rAn#r~DvMg!D`_Q1s%q7[%hS%kW%n`%tp%w!b%y#tOY!C{YZ$}Z]!C{]^$}^r!C{rs!E_sw!C{wx#Hqx#O!C{#O#P$(i#P#o!C{#o#p$*{#p#q!C{#q#r$)]#r~!C{JP!El_Q1s%q7[%hS%n`%w!bOY!FkYZ'PZ]!Fk]^'P^r!Fkrs#Eksw!Fkwx!Gyx#O!Fk#O#P#=u#P#o!Fk#o#p#Di#p#q!Fk#q#r#>i#r~!FkJP!Fz_Q1s%q7[%hS%kW%n`%w!bOY!FkYZ'PZ]!Fk]^'P^r!Fkrs!E_sw!Fkwx!Gyx#O!Fk#O#P#=u#P#o!Fk#o#p#Di#p#q!Fk#q#r#>i#r~!FkIo!HS_Q1s%q7[%kWOY!IRYZ(yZ]!IR]^(y^r!IRrs!J_sw!IRwx#8wx#O!IR#O#P#*R#P#o!IR#o#p#2}#p#q!IR#q#r#*u#r~!IRIo!I`_Q1s%q7[%hS%kW%w!bOY!IRYZ(yZ]!IR]^(y^r!IRrs!J_sw!IRwx!Gyx#O!IR#O#P#*R#P#o!IR#o#p#2}#p#q!IR#q#r#*u#r~!IRIo!Jj_Q1s%q7[%hS%w!bOY!IRYZ(yZ]!IR]^(y^r!IRrs!Kisw!IRwx!Gyx#O!IR#O#P#*R#P#o!IR#o#p#2}#p#q!IR#q#r#*u#r~!IRIo!Kt_Q1s%q7[%hS%w!bOY!IRYZ(yZ]!IR]^(y^r!IRrs!Lssw!IRwx!Gyx#O!IR#O#P#*R#P#o!IR#o#p#2}#p#q!IR#q#r#*u#r~!IRIg!MO]Q1s%q7[%hS%w!bOY!LsYZ+oZ]!Ls]^+o^w!Lswx!Mwx#O!Ls#O#P#!y#P#o!Ls#o#p#&m#p#q!Ls#q#r##m#r~!LsIg!NO]Q1s%q7[OY!LsYZ+oZ]!Ls]^+o^w!Lswx!Nwx#O!Ls#O#P#!y#P#o!Ls#o#p#&m#p#q!Ls#q#r##m#r~!LsIg# O]Q1s%q7[OY!LsYZ+oZ]!Ls]^+o^w!Lswx# wx#O!Ls#O#P#!y#P#o!Ls#o#p#&m#p#q!Ls#q#r##m#r~!LsHP#!OXQ1s%q7[OY# wYZ-wZ]# w]^-w^#o# w#o#p#!k#p#q# w#q#r#!k#r~# w1s#!pRQ1sOY#!kZ]#!k^~#!kIg##QXQ1s%q7[OY!LsYZ+oZ]!Ls]^+o^#o!Ls#o#p##m#p#q!Ls#q#r##m#r~!Ls3Z##vZQ1s%hS%w!bOY##mYZ.kZ]##m]^.k^w##mwx#$ix#O##m#O#P#&X#P#o##m#o#p#&m#p~##m3Z#$nZQ1sOY##mYZ.kZ]##m]^.k^w##mwx#%ax#O##m#O#P#&X#P#o##m#o#p#&m#p~##m3Z#%fZQ1sOY##mYZ.kZ]##m]^.k^w##mwx#!kx#O##m#O#P#&X#P#o##m#o#p#&m#p~##m3Z#&^TQ1sOY##mYZ.kZ]##m]^.k^~##m3Z#&tZQ1s%hSOY#'gYZ0xZ]#'g]^0x^w#'gwx#(Zx#O#'g#O#P#)m#P#o#'g#o#p##m#p~#'g1w#'nXQ1s%hSOY#'gYZ0xZ]#'g]^0x^w#'gwx#(Zx#O#'g#O#P#)m#P~#'g1w#(`XQ1sOY#'gYZ0xZ]#'g]^0x^w#'gwx#({x#O#'g#O#P#)m#P~#'g1w#)QXQ1sOY#'gYZ0xZ]#'g]^0x^w#'gwx#!kx#O#'g#O#P#)m#P~#'g1w#)rTQ1sOY#'gYZ0xZ]#'g]^0x^~#'gIo#*YXQ1s%q7[OY!IRYZ(yZ]!IR]^(y^#o!IR#o#p#*u#p#q!IR#q#r#*u#r~!IR3c#+Q]Q1s%hS%kW%w!bOY#*uYZ2kZ]#*u]^2k^r#*urs#+ysw#*uwx#-}x#O#*u#O#P#2i#P#o#*u#o#p#2}#p~#*u3c#,S]Q1s%hS%w!bOY#*uYZ2kZ]#*u]^2k^r#*urs#,{sw#*uwx#-}x#O#*u#O#P#2i#P#o#*u#o#p#2}#p~#*u3c#-U]Q1s%hS%w!bOY#*uYZ2kZ]#*u]^2k^r#*urs##msw#*uwx#-}x#O#*u#O#P#2i#P#o#*u#o#p#2}#p~#*u3c#.U]Q1s%kWOY#*uYZ2kZ]#*u]^2k^r#*urs#+ysw#*uwx#.}x#O#*u#O#P#2i#P#o#*u#o#p#2}#p~#*u3c#/U]Q1s%kWOY#*uYZ2kZ]#*u]^2k^r#*urs#+ysw#*uwx#/}x#O#*u#O#P#2i#P#o#*u#o#p#2}#p~#*u1{#0UXQ1s%kWOY#/}YZ6ZZ]#/}]^6Z^r#/}rs#0qs#O#/}#O#P#2T#P~#/}1{#0vXQ1sOY#/}YZ6ZZ]#/}]^6Z^r#/}rs#1cs#O#/}#O#P#2T#P~#/}1{#1hXQ1sOY#/}YZ6ZZ]#/}]^6Z^r#/}rs#!ks#O#/}#O#P#2T#P~#/}1{#2YTQ1sOY#/}YZ6ZZ]#/}]^6Z^~#/}3c#2nTQ1sOY#*uYZ2kZ]#*u]^2k^~#*u3c#3W]Q1s%hS%kWOY#4PYZ8bZ]#4P]^8b^r#4Prs#4{sw#4Pwx#6ox#O#4P#O#P#8c#P#o#4P#o#p#*u#p~#4P2P#4YZQ1s%hS%kWOY#4PYZ8bZ]#4P]^8b^r#4Prs#4{sw#4Pwx#6ox#O#4P#O#P#8c#P~#4P2P#5SZQ1s%hSOY#4PYZ8bZ]#4P]^8b^r#4Prs#5usw#4Pwx#6ox#O#4P#O#P#8c#P~#4P2P#5|ZQ1s%hSOY#4PYZ8bZ]#4P]^8b^r#4Prs#'gsw#4Pwx#6ox#O#4P#O#P#8c#P~#4P2P#6vZQ1s%kWOY#4PYZ8bZ]#4P]^8b^r#4Prs#4{sw#4Pwx#7ix#O#4P#O#P#8c#P~#4P2P#7pZQ1s%kWOY#4PYZ8bZ]#4P]^8b^r#4Prs#4{sw#4Pwx#/}x#O#4P#O#P#8c#P~#4P2P#8hTQ1sOY#4PYZ8bZ]#4P]^8b^~#4PIo#9Q_Q1s%q7[%kWOY!IRYZ(yZ]!IR]^(y^r!IRrs!J_sw!IRwx#:Px#O!IR#O#P#*R#P#o!IR#o#p#2}#p#q!IR#q#r#*u#r~!IRHX#:Y]Q1s%q7[%kWOY#:PYZ<[Z]#:P]^<[^r#:Prs#;Rs#O#:P#O#P#=R#P#o#:P#o#p#/}#p#q#:P#q#r#/}#r~#:PHX#;Y]Q1s%q7[OY#:PYZ<[Z]#:P]^<[^r#:Prs#<Rs#O#:P#O#P#=R#P#o#:P#o#p#/}#p#q#:P#q#r#/}#r~#:PHX#<Y]Q1s%q7[OY#:PYZ<[Z]#:P]^<[^r#:Prs# ws#O#:P#O#P#=R#P#o#:P#o#p#/}#p#q#:P#q#r#/}#r~#:PHX#=YXQ1s%q7[OY#:PYZ<[Z]#:P]^<[^#o#:P#o#p#/}#p#q#:P#q#r#/}#r~#:PJP#=|XQ1s%q7[OY!FkYZ'PZ]!Fk]^'P^#o!Fk#o#p#>i#p#q!Fk#q#r#>i#r~!Fk3s#>v]Q1s%hS%kW%n`%w!bOY#>iYZ?[Z]#>i]^?[^r#>irs#?osw#>iwx#-}x#O#>i#O#P#DT#P#o#>i#o#p#Di#p~#>i3s#?z]Q1s%hS%n`%w!bOY#>iYZ?[Z]#>i]^?[^r#>irs#@ssw#>iwx#-}x#O#>i#O#P#DT#P#o#>i#o#p#Di#p~#>i3s#AO]Q1s%hS%n`%w!bOY#>iYZ?[Z]#>i]^?[^r#>irs#Awsw#>iwx#-}x#O#>i#O#P#DT#P#o#>i#o#p#Di#p~#>i3k#BSZQ1s%hS%n`%w!bOY#AwYZAnZ]#Aw]^An^w#Awwx#$ix#O#Aw#O#P#Bu#P#o#Aw#o#p#CZ#p~#Aw3k#BzTQ1sOY#AwYZAnZ]#Aw]^An^~#Aw3k#CbZQ1s%hSOY#'gYZ0xZ]#'g]^0x^w#'gwx#(Zx#O#'g#O#P#)m#P#o#'g#o#p#Aw#p~#'g3s#DYTQ1sOY#>iYZ?[Z]#>i]^?[^~#>i3s#Dr]Q1s%hS%kWOY#4PYZ8bZ]#4P]^8b^r#4Prs#4{sw#4Pwx#6ox#O#4P#O#P#8c#P#o#4P#o#p#>i#p~#4PJP#Ex_Q1s%q7[%hS%n`%w!bOY!FkYZ'PZ]!Fk]^'P^r!Fkrs#Fwsw!Fkwx!Gyx#O!Fk#O#P#=u#P#o!Fk#o#p#Di#p#q!Fk#q#r#>i#r~!FkIw#GU]Q1s%q7[%hS%n`%w!bOY#FwYZDvZ]#Fw]^Dv^w#Fwwx!Mwx#O#Fw#O#P#G}#P#o#Fw#o#p#CZ#p#q#Fw#q#r#Aw#r~#FwIw#HUXQ1s%q7[OY#FwYZDvZ]#Fw]^Dv^#o#Fw#o#p#Aw#p#q#Fw#q#r#Aw#r~#FwMV#IO_Q1s%q7[%kW%tp%y#tOY#I}YZGQZ]#I}]^GQ^r#I}rs!J_sw#I}wx$%]x#O#I}#O#P#K_#P#o#I}#o#p$$Z#p#q#I}#q#r#LR#r~#I}MV#J`_Q1s%q7[%hS%kW%tp%w!b%y#tOY#I}YZGQZ]#I}]^GQ^r#I}rs!J_sw#I}wx#Hqx#O#I}#O#P#K_#P#o#I}#o#p$$Z#p#q#I}#q#r#LR#r~#I}MV#KfXQ1s%q7[OY#I}YZGQZ]#I}]^GQ^#o#I}#o#p#LR#p#q#I}#q#r#LR#r~#I}6y#Lb]Q1s%hS%kW%tp%w!b%y#tOY#LRYZHhZ]#LR]^Hh^r#LRrs#+ysw#LRwx#MZx#O#LR#O#P$#u#P#o#LR#o#p$$Z#p~#LR6y#Mf]Q1s%kW%tp%y#tOY#LRYZHhZ]#LR]^Hh^r#LRrs#+ysw#LRwx#N_x#O#LR#O#P$#u#P#o#LR#o#p$$Z#p~#LR6y#Nj]Q1s%kW%tp%y#tOY#LRYZHhZ]#LR]^Hh^r#LRrs#+ysw#LRwx$ cx#O#LR#O#P$#u#P#o#LR#o#p$$Z#p~#LR5c$ n]Q1s%kW%tp%y#tOY$ cYZJ|Z]$ c]^J|^r$ crs#0qsw$ cwx$ cx#O$ c#O#P$!g#P#o$ c#o#p$!{#p~$ c5c$!lTQ1sOY$ cYZJ|Z]$ c]^J|^~$ c5c$#SZQ1s%kWOY#/}YZ6ZZ]#/}]^6Z^r#/}rs#0qs#O#/}#O#P#2T#P#o#/}#o#p$ c#p~#/}6y$#zTQ1sOY#LRYZHhZ]#LR]^Hh^~#LR6y$$d]Q1s%hS%kWOY#4PYZ8bZ]#4P]^8b^r#4Prs#4{sw#4Pwx#6ox#O#4P#O#P#8c#P#o#4P#o#p#LR#p~#4PMV$%j_Q1s%q7[%kW%tp%y#tOY#I}YZGQZ]#I}]^GQ^r#I}rs!J_sw#I}wx$&ix#O#I}#O#P#K_#P#o#I}#o#p$$Z#p#q#I}#q#r#LR#r~#I}Ko$&v_Q1s%q7[%kW%tp%y#tOY$&iYZN[Z]$&i]^N[^r$&irs#;Rsw$&iwx$&ix#O$&i#O#P$'u#P#o$&i#o#p$!{#p#q$&i#q#r$ c#r~$&iKo$'|XQ1s%q7[OY$&iYZN[Z]$&i]^N[^#o$&i#o#p$ c#p#q$&i#q#r$ c#r~$&iMg$(pXQ1s%q7[OY!C{YZ$}Z]!C{]^$}^#o!C{#o#p$)]#p#q!C{#q#r$)]#r~!C{7Z$)n]Q1s%hS%kW%n`%tp%w!b%y#tOY$)]YZ!!SZ]$)]]^!!S^r$)]rs#?osw$)]wx#MZx#O$)]#O#P$*g#P#o$)]#o#p$*{#p~$)]7Z$*lTQ1sOY$)]YZ!!SZ]$)]]^!!S^~$)]7Z$+U]Q1s%hS%kWOY#4PYZ8bZ]#4P]^8b^r#4Prs#4{sw#4Pwx#6ox#O#4P#O#P#8c#P#o#4P#o#p$)]#p~#4PGz$,b]$}Q%q7[%hS%kW%n`%tp%w!b%y#tOr$}rs&Rsw$}wxFSx!_$}!_!`$-Z!`#O$}#O#P! n#P#o$}#o#p!#U#p#q$}#q#r!!S#r~$}Gz$-nZ!s,W%q7[%hS%kW%n`%tp%w!b%y#tOr$}rs&Rsw$}wxFSx#O$}#O#P! n#P#o$}#o#p!#U#p#q$}#q#r!!S#r~$}Gz$.t]$wQ%q7[%hS%kW%n`%tp%w!b%y#tOr$}rs&Rsw$}wxFSx!_$}!_!`$-Z!`#O$}#O#P! n#P#o$}#o#p!#U#p#q$}#q#r!!S#r~$}G{$/|_%r`%q7[%kW%f,X%tp%y#tOY$0{YZGQZ]$0{]^GQ^r$0{rs$2]sw$0{wx$Jex#O$0{#O#P$Fw#P#o$0{#o#p$Ic#p#q$0{#q#r$G]#r~$0{Gk$1^_%q7[%hS%kW%f,X%tp%w!b%y#tOY$0{YZGQZ]$0{]^GQ^r$0{rs$2]sw$0{wx$Ewx#O$0{#O#P$Fw#P#o$0{#o#p$Ic#p#q$0{#q#r$G]#r~$0{DT$2h_%q7[%hS%f,X%w!bOY$3gYZ(yZ]$3g]^(y^r$3grs$Basw$3gwx$4sx#O$3g#O#P$5o#P#o$3g#o#p$={#p#q$3g#q#r$6T#r~$3gDT$3t_%q7[%hS%kW%f,X%w!bOY$3gYZ(yZ]$3g]^(y^r$3grs$2]sw$3gwx$4sx#O$3g#O#P$5o#P#o$3g#o#p$={#p#q$3g#q#r$6T#r~$3gDT$4|Z%q7[%kW%f,XOr(yrs)wsw(ywx;bx#O(y#O#P2V#P#o(y#o#p7n#p#q(y#q#r2k#r~(yDT$5tT%q7[O#o$3g#o#p$6T#p#q$3g#q#r$6T#r~$3g-w$6`]%hS%kW%f,X%w!bOY$6TYZ2kZ]$6T]^2k^r$6Trs$7Xsw$6Twx$=Rx#O$6T#O#P$=u#P#o$6T#o#p$={#p~$6T-w$7b]%hS%f,X%w!bOY$6TYZ2kZ]$6T]^2k^r$6Trs$8Zsw$6Twx$=Rx#O$6T#O#P$=u#P#o$6T#o#p$={#p~$6T-w$8d]%hS%f,X%w!bOY$6TYZ2kZ]$6T]^2k^r$6Trs$9]sw$6Twx$=Rx#O$6T#O#P$=u#P#o$6T#o#p$={#p~$6T-o$9fZ%hS%f,X%w!bOY$9]YZ.kZ]$9]]^.k^w$9]wx$:Xx#O$9]#O#P$:s#P#o$9]#o#p$:y#p~$9]-o$:^V%f,XOw.kwx/qx#O.k#O#P0W#P#o.k#o#p0^#p~.k-o$:vPO~$9]-o$;QZ%hS%f,XOY$;sYZ0xZ]$;s]^0x^w$;swx$<gx#O$;s#O#P$<{#P#o$;s#o#p$9]#p~$;s,]$;zX%hS%f,XOY$;sYZ0xZ]$;s]^0x^w$;swx$<gx#O$;s#O#P$<{#P~$;s,]$<lT%f,XOw0xwx1px#O0x#O#P2P#P~0x,]$=OPO~$;s-w$=YX%kW%f,XOr2krs3asw2kwx5ix#O2k#O#P7h#P#o2k#o#p7n#p~2k-w$=xPO~$6T-w$>U]%hS%kW%f,XOY$>}YZ8bZ]$>}]^8b^r$>}rs$?ysw$>}wx$Amx#O$>}#O#P$BZ#P#o$>}#o#p$6T#p~$>},e$?WZ%hS%kW%f,XOY$>}YZ8bZ]$>}]^8b^r$>}rs$?ysw$>}wx$Amx#O$>}#O#P$BZ#P~$>},e$@QZ%hS%f,XOY$>}YZ8bZ]$>}]^8b^r$>}rs$@ssw$>}wx$Amx#O$>}#O#P$BZ#P~$>},e$@zZ%hS%f,XOY$>}YZ8bZ]$>}]^8b^r$>}rs$;ssw$>}wx$Amx#O$>}#O#P$BZ#P~$>},e$AtV%kW%f,XOr8brs9Osw8bwx:px#O8b#O#P;[#P~8b,e$B^PO~$>}DT$Bl_%q7[%hS%f,X%w!bOY$3gYZ(yZ]$3g]^(y^r$3grs$Cksw$3gwx$4sx#O$3g#O#P$5o#P#o$3g#o#p$={#p#q$3g#q#r$6T#r~$3gC{$Cv]%q7[%hS%f,X%w!bOY$CkYZ+oZ]$Ck]^+o^w$Ckwx$Dox#O$Ck#O#P$Ec#P#o$Ck#o#p$:y#p#q$Ck#q#r$9]#r~$CkC{$DvX%q7[%f,XOw+owx-Vx#O+o#O#P.V#P#o+o#o#p0^#p#q+o#q#r.k#r~+oC{$EhT%q7[O#o$Ck#o#p$9]#p#q$Ck#q#r$9]#r~$CkGk$FUZ%q7[%kW%f,X%tp%y#tOrGQrs)wswGQwxM^x#OGQ#O#PHS#P#oGQ#o#pLj#p#qGQ#q#rHh#r~GQGk$F|T%q7[O#o$0{#o#p$G]#p#q$0{#q#r$G]#r~$0{1_$Gl]%hS%kW%f,X%tp%w!b%y#tOY$G]YZHhZ]$G]]^Hh^r$G]rs$7Xsw$G]wx$Hex#O$G]#O#P$I]#P#o$G]#o#p$Ic#p~$G]1_$HpX%kW%f,X%tp%y#tOrHhrs3aswHhwxJWx#OHh#O#PLd#P#oHh#o#pLj#p~Hh1_$I`PO~$G]1_$Il]%hS%kW%f,XOY$>}YZ8bZ]$>}]^8b^r$>}rs$?ysw$>}wx$Amx#O$>}#O#P$BZ#P#o$>}#o#p$G]#p~$>}Gk$JrZ%q7[%kW%f,X%tp%y#tOrGQrs)wswGQwx$Kex#OGQ#O#PHS#P#oGQ#o#pLj#p#qGQ#q#rHh#r~GQGk$KtZ%i!f%q7[%kW%g,X%tp%y#tOrN[rs=OswN[wxN[x#ON[#O#P! Y#P#oN[#o#pKx#p#qN[#q#rJ|#r~N[G{$LzZf,X%q7[%hS%kW%n`%tp%w!b%y#tOr$}rs&Rsw$}wxFSx#O$}#O#P! n#P#o$}#o#p!#U#p#q$}#q#r!!S#r~$}<u$NQZ!OR%q7[%hS%kW%n`%tp%w!b%y#tOr$}rs&Rsw$}wxFSx#O$}#O#P! n#P#o$}#o#p!#U#p#q$}#q#r!!S#r~$}G{% W_T,X%q7[%hS%kW%n`%tp%w!b%y#tOr$}rs&Rsw$}wxFSxz$}z{%!V{!_$}!_!`$-Z!`#O$}#O#P! n#P#o$}#o#p!#U#p#q$}#q#r!!S#r~$}G{%!j]_R%q7[%hS%kW%n`%tp%w!b%y#tOr$}rs&Rsw$}wxFSx!_$}!_!`$-Z!`#O$}#O#P! n#P#o$}#o#p!#U#p#q$}#q#r!!S#r~$}G{%#v]$z,X%q7[%hS%kW%n`%tp%w!b%y#tOr$}rs&Rsw$}wxFSx!_$}!_!`$-Z!`#O$}#O#P! n#P#o$}#o#p!#U#p#q$}#q#r!!S#r~$}<u%%SZwR%q7[%hS%kW%n`%tp%w!b%y#tOr$}rs&Rsw$}wxFSx#O$}#O#P! n#P#o$}#o#p!#U#p#q$}#q#r!!S#r~$}Mg%&Y^${,X%q7[%hS%kW%n`%tp%w!b%y#tOr$}rs&Rsw$}wxFSx!_$}!_!`$-Z!`!a%'U!a#O$}#O#P! n#P#o$}#o#p!#U#p#q$}#q#r!!S#r~$}B^%'iZ&U&j%q7[%hS%kW%n`%tp%w!b%y#tOr$}rs&Rsw$}wxFSx#O$}#O#P! n#P#o$}#o#p!#U#p#q$}#q#r!!S#r~$}G{%(o_!dQ%q7[%hS%kW%n`%tp%w!b%y#tOr$}rs&Rsw$}wxFSx!O$}!O!P%)n!P!Q$}!Q![%,O![#O$}#O#P! n#P#o$}#o#p!#U#p#q$}#q#r!!S#r~$}G{%*P]%q7[%hS%kW%n`%tp%w!b%y#tOr$}rs&Rsw$}wxFSx!O$}!O!P%*x!P#O$}#O#P! n#P#o$}#o#p!#U#p#q$}#q#r!!S#r~$}G{%+]Z!m,X%q7[%hS%kW%n`%tp%w!b%y#tOr$}rs&Rsw$}wxFSx#O$}#O#P! n#P#o$}#o#p!#U#p#q$}#q#r!!S#r~$}Gy%,cg!f,V%q7[%hS%kW%n`%tp%w!b%y#tOr$}rs&Rsw$}wxFSx!Q$}!Q![%,O![!g$}!g!h%-z!h!l$}!l!m%2[!m#O$}#O#P! n#P#R$}#R#S%,O#S#X$}#X#Y%-z#Y#^$}#^#_%2[#_#o$}#o#p!#U#p#q$}#q#r!!S#r~$}Gy%.]a%q7[%hS%kW%n`%tp%w!b%y#tOr$}rs&Rsw$}wxFSx{$}{|%/b|}$}}!O%/b!O!Q$}!Q![%0l![#O$}#O#P! n#P#o$}#o#p!#U#p#q$}#q#r!!S#r~$}Gy%/s]%q7[%hS%kW%n`%tp%w!b%y#tOr$}rs&Rsw$}wxFSx!Q$}!Q![%0l![#O$}#O#P! n#P#o$}#o#p!#U#p#q$}#q#r!!S#r~$}Gy%1Pc!f,V%q7[%hS%kW%n`%tp%w!b%y#tOr$}rs&Rsw$}wxFSx!Q$}!Q![%0l![!l$}!l!m%2[!m#O$}#O#P! n#P#R$}#R#S%0l#S#^$}#^#_%2[#_#o$}#o#p!#U#p#q$}#q#r!!S#r~$}Gy%2oZ!f,V%q7[%hS%kW%n`%tp%w!b%y#tOr$}rs&Rsw$}wxFSx#O$}#O#P! n#P#o$}#o#p!#U#p#q$}#q#r!!S#r~$}G{%3u_$|R%q7[%hS%kW%n`%tp%w!b%y#tOr$}rs&Rsw$}wxFSx!P$}!P!Q%4t!Q!_$}!_!`$-Z!`#O$}#O#P! n#P#o$}#o#p!#U#p#q$}#q#r!!S#r~$}Gz%5X]%OQ%q7[%hS%kW%n`%tp%w!b%y#tOr$}rs&Rsw$}wxFSx!_$}!_!`$-Z!`#O$}#O#P! n#P#o$}#o#p!#U#p#q$}#q#r!!S#r~$}Gy%6eu!f,V%q7[%hS%kW%n`%tp%w!b%y#tOr$}rs&Rsw$}wxFSx!O$}!O!P%8x!P!Q$}!Q![%:S![!d$}!d!e%<U!e!g$}!g!h%-z!h!l$}!l!m%2[!m!q$}!q!r%?O!r!z$}!z!{%Ar!{#O$}#O#P! n#P#R$}#R#S%:S#S#U$}#U#V%<U#V#X$}#X#Y%-z#Y#^$}#^#_%2[#_#c$}#c#d%?O#d#l$}#l#m%Ar#m#o$}#o#p!#U#p#q$}#q#r!!S#r~$}Gy%9Z]%q7[%hS%kW%n`%tp%w!b%y#tOr$}rs&Rsw$}wxFSx!Q$}!Q![%,O![#O$}#O#P! n#P#o$}#o#p!#U#p#q$}#q#r!!S#r~$}Gy%:gi!f,V%q7[%hS%kW%n`%tp%w!b%y#tOr$}rs&Rsw$}wxFSx!O$}!O!P%8x!P!Q$}!Q![%:S![!g$}!g!h%-z!h!l$}!l!m%2[!m#O$}#O#P! n#P#R$}#R#S%:S#S#X$}#X#Y%-z#Y#^$}#^#_%2[#_#o$}#o#p!#U#p#q$}#q#r!!S#r~$}Gy%<g`%q7[%hS%kW%n`%tp%w!b%y#tOr$}rs&Rsw$}wxFSx!Q$}!Q!R%=i!R!S%=i!S#O$}#O#P! n#P#R$}#R#S%=i#S#o$}#o#p!#U#p#q$}#q#r!!S#r~$}Gy%=|`!f,V%q7[%hS%kW%n`%tp%w!b%y#tOr$}rs&Rsw$}wxFSx!Q$}!Q!R%=i!R!S%=i!S#O$}#O#P! n#P#R$}#R#S%=i#S#o$}#o#p!#U#p#q$}#q#r!!S#r~$}Gy%?a_%q7[%hS%kW%n`%tp%w!b%y#tOr$}rs&Rsw$}wxFSx!Q$}!Q!Y%@`!Y#O$}#O#P! n#P#R$}#R#S%@`#S#o$}#o#p!#U#p#q$}#q#r!!S#r~$}Gy%@s_!f,V%q7[%hS%kW%n`%tp%w!b%y#tOr$}rs&Rsw$}wxFSx!Q$}!Q!Y%@`!Y#O$}#O#P! n#P#R$}#R#S%@`#S#o$}#o#p!#U#p#q$}#q#r!!S#r~$}Gy%BTc%q7[%hS%kW%n`%tp%w!b%y#tOr$}rs&Rsw$}wxFSx!Q$}!Q![%C`![!c$}!c!i%C`!i#O$}#O#P! n#P#R$}#R#S%C`#S#T$}#T#Z%C`#Z#o$}#o#p!#U#p#q$}#q#r!!S#r~$}Gy%Csc!f,V%q7[%hS%kW%n`%tp%w!b%y#tOr$}rs&Rsw$}wxFSx!Q$}!Q![%C`![!c$}!c!i%C`!i#O$}#O#P! n#P#R$}#R#S%C`#S#T$}#T#Z%C`#Z#o$}#o#p!#U#p#q$}#q#r!!S#r~$}Mg%Ec]x1s%q7[%hS%kW%n`%tp%w!b%y#tOr$}rs&Rsw$}wxFSx!_$}!_!`%F[!`#O$}#O#P! n#P#o$}#o#p!#U#p#q$}#q#r!!S#r~$}<u%FoZ%WR%q7[%hS%kW%n`%tp%w!b%y#tOr$}rs&Rsw$}wxFSx#O$}#O#P! n#P#o$}#o#p!#U#p#q$}#q#r!!S#r~$}G{%GuZ#^,X%q7[%hS%kW%n`%tp%w!b%y#tOr$}rs&Rsw$}wxFSx#O$}#O#P! n#P#o$}#o#p!#U#p#q$}#q#r!!S#r~$}G{%H{_jR%q7[%hS%kW%n`%tp%w!b%y#tOr$}rs&Rsw$}wxFSx!^$}!^!_%Iz!_!`!'m!`!a!'m!a#O$}#O#P! n#P#o$}#o#p!#U#p#q$}#q#r!!S#r~$}Gz%J_]$xQ%q7[%hS%kW%n`%tp%w!b%y#tOr$}rs&Rsw$}wxFSx!_$}!_!`$-Z!`#O$}#O#P! n#P#o$}#o#p!#U#p#q$}#q#r!!S#r~$}G{%Kk]%V,X%q7[%hS%kW%n`%tp%w!b%y#tOr$}rs&Rsw$}wxFSx!_$}!_!`!'m!`#O$}#O#P! n#P#o$}#o#p!#U#p#q$}#q#r!!S#r~$}G{%Lw^jR%q7[%hS%kW%n`%tp%w!b%y#tOr$}rs&Rsw$}wxFSx!_$}!_!`!'m!`!a%Ms!a#O$}#O#P! n#P#o$}#o#p!#U#p#q$}#q#r!!S#r~$}Gz%NW]$yQ%q7[%hS%kW%n`%tp%w!b%y#tOr$}rs&Rsw$}wxFSx!_$}!_!`$-Z!`#O$}#O#P! n#P#o$}#o#p!#U#p#q$}#q#r!!S#r~$}G{& f]]Q#tP%q7[%hS%kW%n`%tp%w!b%y#tOr$}rs&Rsw$}wxFSx!_$}!_!`$-Z!`#O$}#O#P! n#P#o$}#o#p!#U#p#q$}#q#r!!S#r~$}Mg&!tc%q7[%hS%kW%e&j%n`%tp%w!b%y#t%Q,XOr$}rs&Rsw$}wxFSx!Q$}!Q![&!_![!c$}!c!}&!_!}#O$}#O#P! n#P#R$}#R#S&!_#S#T$}#T#o&!_#o#p!#U#p#q$}#q#r!!S#r$g$}$g~&!_Mg&$fg%q7[%hS%kW%e&j%n`%tp%w!b%y#t%Q,XOr$}rs&%}sw$}wx&)Tx!Q$}!Q![&!_![!c$}!c!t&!_!t!u&,a!u!}&!_!}#O$}#O#P! n#P#R$}#R#S&!_#S#T$}#T#f&!_#f#g&,a#g#o&!_#o#p!#U#p#q$}#q#r!!S#r$g$}$g~&!_De&&[_%q7[%hS%f,X%n`%w!bOY!+XYZ'PZ]!+X]^'P^r!+Xrs&'Zsw!+Xwx!-gx#O!+X#O#P!>e#P#o!+X#o#p!@}#p#q!+X#q#r!>y#r~!+XDe&'hZ%q7[%hS%f,X%n`%w!bOr'Prs&(Zsw'Pwx(Px#O'P#O#P>v#P#o'P#o#pCU#p#q'P#q#r?[#r~'PD]&(hX%q7[%hS%j,X%n`%w!bOwDvwx,ex#ODv#O#PEn#P#oDv#o#pBd#p#qDv#q#rAn#r~DvGk&)b_%q7[%kW%f,X%tp%y#tOY$0{YZGQZ]$0{]^GQ^r$0{rs$2]sw$0{wx&*ax#O$0{#O#P$Fw#P#o$0{#o#p$Ic#p#q$0{#q#r$G]#r~$0{Gk&*nZ%q7[%kW%f,X%tp%y#tOrGQrs)wswGQwx&+ax#OGQ#O#PHS#P#oGQ#o#pLj#p#qGQ#q#rHh#r~GQFT&+nZ%q7[%kW%g,X%tp%y#tOrN[rs=OswN[wxN[x#ON[#O#P! Y#P#oN[#o#pKx#p#qN[#q#rJ|#r~N[Mg&,vc%q7[%hS%kW%e&j%n`%tp%w!b%y#t%Q,XOr$}rs&%}sw$}wx&)Tx!Q$}!Q![&!_![!c$}!c!}&!_!}#O$}#O#P! n#P#R$}#R#S&!_#S#T$}#T#o&!_#o#p!#U#p#q$}#q#r!!S#r$g$}$g~&!_Mg&.hg%q7[%hS%kW%e&j%n`%tp%w!b%y#t%Q,XOr$}rs&0Psw$}wx&2wx!Q$}!Q![&!_![!c$}!c!t&!_!t!u&5u!u!}&!_!}#O$}#O#P! n#P#R$}#R#S&!_#S#T$}#T#f&!_#f#g&5u#g#o&!_#o#p!#U#p#q$}#q#r!!S#r$g$}$g~&!_De&0^Z%q7[%hS%n`%w!b%s,XOr'Prs&1Psw'Pwx(Px#O'P#O#P>v#P#o'P#o#pCU#p#q'P#q#r?[#r~'PDe&1[Z%q7[%hS%n`%w!bOr'Prs&1}sw'Pwx(Px#O'P#O#P>v#P#o'P#o#pCU#p#q'P#q#r?[#r~'PD]&2[X%q7[%hS%x,X%n`%w!bOwDvwx,ex#ODv#O#PEn#P#oDv#o#pBd#p#qDv#q#rAn#r~DvGk&3UZ%q7[%kW%tp%y#t%m,XOrGQrs)wswGQwx&3wx#OGQ#O#PHS#P#oGQ#o#pLj#p#qGQ#q#rHh#r~GQGk&4SZ%q7[%kW%tp%y#tOrGQrs)wswGQwx&4ux#OGQ#O#PHS#P#oGQ#o#pLj#p#qGQ#q#rHh#r~GQFT&5SZ%q7[%kW%v,X%tp%y#tOrN[rs=OswN[wxN[x#ON[#O#P! Y#P#oN[#o#pKx#p#qN[#q#rJ|#r~N[Mg&6[c%q7[%hS%kW%e&j%n`%tp%w!b%y#t%Q,XOr$}rs&0Psw$}wx&2wx!Q$}!Q![&!_![!c$}!c!}&!_!}#O$}#O#P! n#P#R$}#R#S&!_#S#T$}#T#o&!_#o#p!#U#p#q$}#q#r!!S#r$g$}$g~&!_Mg&7|k%q7[%hS%kW%e&j%n`%tp%w!b%y#t%Q,XOr$}rs&%}sw$}wx&)Tx!Q$}!Q![&!_![!c$}!c!h&!_!h!i&5u!i!t&!_!t!u&,a!u!}&!_!}#O$}#O#P! n#P#R$}#R#S&!_#S#T$}#T#U&!_#U#V&,a#V#Y&!_#Y#Z&5u#Z#o&!_#o#p!#U#p#q$}#q#r!!S#r$g$}$g~&!_G{&:UZ!V,X%q7[%hS%kW%n`%tp%w!b%y#tOr$}rs&Rsw$}wxFSx#O$}#O#P! n#P#o$}#o#p!#U#p#q$}#q#r!!S#r~$}<u&;[Z!WR%q7[%hS%kW%n`%tp%w!b%y#tOr$}rs&Rsw$}wxFSx#O$}#O#P! n#P#o$}#o#p!#U#p#q$}#q#r!!S#r~$}Gz&<b]$vQ%q7[%hS%kW%n`%tp%w!b%y#tOr$}rs&Rsw$}wxFSx!_$}!_!`$-Z!`#O$}#O#P! n#P#o$}#o#p!#U#p#q$}#q#r!!S#r~$}Gy&=dX%hS%kW!ZGmOr8brs9Osw8bwx:Ux#O8b#O#P;[#P#o8b#o#p!!S#p~8bGz&>d]$uQ%q7[%hS%kW%n`%tp%w!b%y#tOr$}rs&Rsw$}wxFSx!_$}!_!`$-Z!`#O$}#O#P! n#P#o$}#o#p!#U#p#q$}#q#r!!S#r~$}<u&?nX![7_%hS%kW%n`%tp%w!b%y#tOr!!Srs@Ssw!!SwxIbx#O!!S#O#P!#O#P#o!!S#o#p!#U#p~!!SGy&@nZ%P,V%q7[%hS%kW%n`%tp%w!b%y#tOr$}rs&Rsw$}wxFSx#O$}#O#P! n#P#o$}#o#p!#U#p#q$}#q#r!!S#r~$}", - tokenizers: [legacyPrint, indentation, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, newlines], - topRules: {"Script":[0,3]}, - specialized: [{term: 186, get: value => spec_identifier[value] || -1}], - tokenPrec: 6584 - }); - - function indentBody(context, node) { - let base = context.lineIndent(node.from); - let line = context.lineAt(context.pos, -1), to = line.from + line.text.length; - // Don't consider blank, deindented lines at the end of the - // block part of the block - if (!/\S/.test(line.text) && - context.node.to < to + 100 && - !/\S/.test(context.state.sliceDoc(to, context.node.to)) && - context.lineIndent(context.pos, -1) <= base) - return null; - // A normally deindenting keyword that appears at a higher - // indentation than the block should probably be handled by the next - // level - if (/^\s*(else:|elif |except |finally:)/.test(context.textAfter) && context.lineIndent(context.pos, -1) > base) - return null; - return base + context.unit; - } - /** - A language provider based on the [Lezer Python - parser](https://github.com/lezer-parser/python), extended with - highlighting and indentation information. - */ - const pythonLanguage = /*@__PURE__*/LRLanguage.define({ - parser: /*@__PURE__*/parser.configure({ - props: [ - /*@__PURE__*/indentNodeProp.add({ - Body: context => { var _a; return (_a = indentBody(context, context.node)) !== null && _a !== void 0 ? _a : context.continue(); }, - IfStatement: cx => /^\s*(else:|elif )/.test(cx.textAfter) ? cx.baseIndent : cx.continue(), - TryStatement: cx => /^\s*(except |finally:)/.test(cx.textAfter) ? cx.baseIndent : cx.continue(), - "TupleExpression ComprehensionExpression ParamList ArgList ParenthesizedExpression": /*@__PURE__*/delimitedIndent({ closing: ")" }), - "DictionaryExpression DictionaryComprehensionExpression SetExpression SetComprehensionExpression": /*@__PURE__*/delimitedIndent({ closing: "}" }), - "ArrayExpression ArrayComprehensionExpression": /*@__PURE__*/delimitedIndent({ closing: "]" }), - Script: context => { - if (context.pos + /\s*/.exec(context.textAfter)[0].length >= context.node.to) { - let endBody = null; - for (let cur = context.node, to = cur.to;;) { - cur = cur.lastChild; - if (!cur || cur.to != to) - break; - if (cur.type.name == "Body") - endBody = cur; - } - if (endBody) { - let bodyIndent = indentBody(context, endBody); - if (bodyIndent != null) - return bodyIndent; - } - } - return context.continue(); - } - }), - /*@__PURE__*/foldNodeProp.add({ - "ArrayExpression DictionaryExpression": foldInside$1, - Body: (node, state) => ({ from: node.from + 1, to: node.to - (node.to == state.doc.length ? 0 : 1) }) - }), - /*@__PURE__*/styleTags({ - "async \"*\" \"**\" FormatConversion FormatSpec": tags.modifier, - "for while if elif else try except finally return raise break continue with pass assert await yield": tags.controlKeyword, - "in not and or is del": tags.operatorKeyword, - "from def class global nonlocal lambda": tags.definitionKeyword, - import: tags.moduleKeyword, - "with as print": tags.keyword, - Boolean: tags.bool, - None: tags.null, - VariableName: tags.variableName, - "CallExpression/VariableName": /*@__PURE__*/tags.function(tags.variableName), - "FunctionDefinition/VariableName": /*@__PURE__*/tags.function(/*@__PURE__*/tags.definition(tags.variableName)), - "ClassDefinition/VariableName": /*@__PURE__*/tags.definition(tags.className), - PropertyName: tags.propertyName, - "CallExpression/MemberExpression/PropertyName": /*@__PURE__*/tags.function(tags.propertyName), - Comment: tags.lineComment, - Number: tags.number, - String: tags.string, - FormatString: /*@__PURE__*/tags.special(tags.string), - UpdateOp: tags.updateOperator, - ArithOp: tags.arithmeticOperator, - BitOp: tags.bitwiseOperator, - CompareOp: tags.compareOperator, - AssignOp: tags.definitionOperator, - Ellipsis: tags.punctuation, - At: tags.meta, - "( )": tags.paren, - "[ ]": tags.squareBracket, - "{ }": tags.brace, - ".": tags.derefOperator, - ", ;": tags.separator - }) - ], - }), - languageData: { - closeBrackets: { brackets: ["(", "[", "{", "'", '"', "'''", '"""'] }, - commentTokens: { line: "#" }, - indentOnInput: /^\s*([\}\]\)]|else:|elif |except |finally:)$/ - } - }); - /** - Python language support. - */ - function python() { - return new LanguageSupport(pythonLanguage); - } - - // Using https://github.com/one-dark/vscode-one-dark-theme/ as reference for the colors - const chalky = "#e5c07b", coral = "#e06c75", cyan = "#56b6c2", invalid = "#ffffff", ivory = "#abb2bf", stone = "#7d8799", // Brightened compared to original to increase contrast - malibu = "#61afef", sage = "#98c379", whiskey = "#d19a66", violet = "#c678dd", darkBackground = "#21252b", highlightBackground = "#2c313a", background = "#282c34", tooltipBackground = "#353a42", selection = "#3E4451", cursor = "#528bff"; - /** - The editor theme styles for One Dark. - */ - const oneDarkTheme = /*@__PURE__*/EditorView.theme({ - "&": { - color: ivory, - backgroundColor: background - }, - ".cm-content": { - caretColor: cursor - }, - "&.cm-focused .cm-cursor": { borderLeftColor: cursor }, - "&.cm-focused .cm-selectionBackground, .cm-selectionBackground, .cm-content ::selection": { backgroundColor: selection }, - ".cm-panels": { backgroundColor: darkBackground, color: ivory }, - ".cm-panels.cm-panels-top": { borderBottom: "2px solid black" }, - ".cm-panels.cm-panels-bottom": { borderTop: "2px solid black" }, - ".cm-searchMatch": { - backgroundColor: "#72a1ff59", - outline: "1px solid #457dff" - }, - ".cm-searchMatch.cm-searchMatch-selected": { - backgroundColor: "#6199ff2f" - }, - ".cm-activeLine": { backgroundColor: highlightBackground }, - ".cm-selectionMatch": { backgroundColor: "#aafe661a" }, - "&.cm-focused .cm-matchingBracket, &.cm-focused .cm-nonmatchingBracket": { - backgroundColor: "#bad0f847", - outline: "1px solid #515a6b" - }, - ".cm-gutters": { - backgroundColor: background, - color: stone, - border: "none" - }, - ".cm-activeLineGutter": { - backgroundColor: highlightBackground - }, - ".cm-foldPlaceholder": { - backgroundColor: "transparent", - border: "none", - color: "#ddd" - }, - ".cm-tooltip": { - border: "none", - backgroundColor: tooltipBackground - }, - ".cm-tooltip .cm-tooltip-arrow:before": { - borderTopColor: "transparent", - borderBottomColor: "transparent" - }, - ".cm-tooltip .cm-tooltip-arrow:after": { - borderTopColor: tooltipBackground, - borderBottomColor: tooltipBackground - }, - ".cm-tooltip-autocomplete": { - "& > ul > li[aria-selected]": { - backgroundColor: highlightBackground, - color: ivory - } - } - }, { dark: true }); - /** - The highlighting style for code in the One Dark theme. - */ - /*@__PURE__*/HighlightStyle.define([ - { tag: tags.keyword, - color: violet }, - { tag: [tags.name, tags.deleted, tags.character, tags.propertyName, tags.macroName], - color: coral }, - { tag: [/*@__PURE__*/tags.function(tags.variableName), tags.labelName], - color: malibu }, - { tag: [tags.color, /*@__PURE__*/tags.constant(tags.name), /*@__PURE__*/tags.standard(tags.name)], - color: whiskey }, - { tag: [/*@__PURE__*/tags.definition(tags.name), tags.separator], - color: ivory }, - { tag: [tags.typeName, tags.className, tags.number, tags.changed, tags.annotation, tags.modifier, tags.self, tags.namespace], - color: chalky }, - { tag: [tags.operator, tags.operatorKeyword, tags.url, tags.escape, tags.regexp, tags.link, /*@__PURE__*/tags.special(tags.string)], - color: cyan }, - { tag: [tags.meta, tags.comment], - color: stone }, - { tag: tags.strong, - fontWeight: "bold" }, - { tag: tags.emphasis, - fontStyle: "italic" }, - { tag: tags.strikethrough, - textDecoration: "line-through" }, - { tag: tags.link, - color: stone, - textDecoration: "underline" }, - { tag: tags.heading, - fontWeight: "bold", - color: coral }, - { tag: [tags.atom, tags.bool, /*@__PURE__*/tags.special(tags.variableName)], - color: whiskey }, - { tag: [tags.processingInstruction, tags.string, tags.inserted], - color: sage }, - { tag: tags.invalid, - color: invalid }, - ]); - - const logger$7 = getLogger('py-repl'); - function createCmdHandler(el) { - // Creates a codemirror cmd handler that calls the el.evaluate when an event - // triggers that specific cmd - return () => { - void el.evaluate(); - return true; - }; - } - let initialTheme; - function getEditorTheme(el) { - return initialTheme || (initialTheme = el.getAttribute('theme')); - } - class PyRepl extends BaseEvalElement { - editor; - editorNode; - constructor() { - super(); - // add an extra div where we can attach the codemirror editor - this.editorNode = document.createElement('div'); - addClasses(this.editorNode, ['editor-box']); - this.shadow.appendChild(this.wrapper); - } - connectedCallback() { - this.checkId(); - this.code = htmlDecode(this.innerHTML); - this.innerHTML = ''; - const languageConf = new Compartment(); - const extensions = [ - basicSetup, - languageConf.of(python()), - keymap.of([ - ...defaultKeymap, - { key: 'Ctrl-Enter', run: createCmdHandler(this) }, - { key: 'Shift-Enter', run: createCmdHandler(this) }, - ]), - ]; - if (getEditorTheme(this) === 'dark') { - extensions.push(oneDarkTheme); - } - this.editor = new EditorView({ - state: EditorState.create({ - doc: this.code.trim(), - extensions, - }), - parent: this.editorNode, - }); - const mainDiv = document.createElement('div'); - addClasses(mainDiv, ['py-repl-box']); - // Styles that we use to hide the labels whilst also keeping it accessible for screen readers - const labelStyle = 'overflow:hidden; display:block; width:1px; height:1px'; - // Code editor Label - this.editorNode.id = 'code-editor'; - const editorLabel = document.createElement('label'); - editorLabel.innerHTML = 'Python Script Area'; - editorLabel.setAttribute('style', labelStyle); - editorLabel.htmlFor = 'code-editor'; - mainDiv.append(editorLabel); - // add Editor to main PyScript div - mainDiv.appendChild(this.editorNode); - // Play Button - this.btnRun = document.createElement('button'); - this.btnRun.id = 'btnRun'; - this.btnRun.innerHTML = - '<svg id="" class="svelte-fa svelte-ps5qeg" style="height:20px;width:20px;vertical-align:-.125em;transform-origin:center;overflow:visible;color:green" viewBox="0 0 384 512" aria-hidden="true" role="img" xmlns="http://www.w3.org/2000/svg"><g transform="translate(192 256)" transform-origin="96 0"><g transform="translate(0,0) scale(1,1)"><path d="M361 215C375.3 223.8 384 239.3 384 256C384 272.7 375.3 288.2 361 296.1L73.03 472.1C58.21 482 39.66 482.4 24.52 473.9C9.377 465.4 0 449.4 0 432V80C0 62.64 9.377 46.63 24.52 38.13C39.66 29.64 58.21 29.99 73.03 39.04L361 215z" fill="currentColor" transform="translate(-192 -256)"></path></g></g></svg>'; - addClasses(this.btnRun, ['absolute', 'repl-play-button']); - // Play Button Label - const btnLabel = document.createElement('label'); - btnLabel.innerHTML = 'Python Script Run Button'; - btnLabel.setAttribute('style', labelStyle); - btnLabel.htmlFor = 'btnRun'; - this.editorNode.appendChild(btnLabel); - this.editorNode.appendChild(this.btnRun); - this.btnRun.addEventListener('click', () => { - void this.evaluate(); - }); - if (!this.id) { - logger$7.warn("WARNING: <py-repl> defined without an id. <py-repl> should always have an id, otherwise multiple <py-repl> in the same page will not work!"); - } - if (!this.hasAttribute('exec-id')) { - this.setAttribute('exec-id', '1'); - } - if (!this.hasAttribute('root')) { - this.setAttribute('root', this.id); - } - if (this.hasAttribute('output')) { - this.errorElement = this.outputElement = document.getElementById(this.getAttribute('output')); - } - else { - if (this.hasAttribute('std-out')) { - this.outputElement = document.getElementById(this.getAttribute('std-out')); - } - else { - // In this case neither output or std-out have been provided so we need - // to create a new output div to output to - this.outputElement = document.createElement('div'); - this.outputElement.classList.add('output'); - this.outputElement.hidden = true; - this.outputElement.id = this.id + '-' + this.getAttribute('exec-id'); - // add the output div id if there's not output pre-defined - mainDiv.appendChild(this.outputElement); - } - this.errorElement = this.hasAttribute('std-err') - ? document.getElementById(this.getAttribute('std-err')) - : this.outputElement; - } - this.appendChild(mainDiv); - this.editor.focus(); - logger$7.debug(`element ${this.id} successfully connected`); - } - addToOutput(s) { - this.outputElement.innerHTML += '<div>' + s + '</div>'; - this.outputElement.hidden = false; - } - preEvaluate() { - this.setOutputMode("replace"); - if (!this.appendOutput) { - this.outputElement.innerHTML = ''; - } - } - postEvaluate() { - this.outputElement.hidden = false; - this.outputElement.style.display = 'block'; - if (this.hasAttribute('auto-generate')) { - const allPyRepls = document.querySelectorAll(`py-repl[root='${this.getAttribute('root')}'][exec-id]`); - const lastRepl = allPyRepls[allPyRepls.length - 1]; - const lastExecId = lastRepl.getAttribute('exec-id'); - const nextExecId = parseInt(lastExecId) + 1; - const newPyRepl = document.createElement('py-repl'); - newPyRepl.setAttribute('root', this.getAttribute('root')); - newPyRepl.id = this.getAttribute('root') + '-' + nextExecId.toString(); - if (this.hasAttribute('auto-generate')) { - newPyRepl.setAttribute('auto-generate', ''); - this.removeAttribute('auto-generate'); - } - if (this.hasAttribute('output-mode')) { - newPyRepl.setAttribute('output-mode', this.getAttribute('output-mode')); - } - const addReplAttribute = (attribute) => { - if (this.hasAttribute(attribute)) { - newPyRepl.setAttribute(attribute, this.getAttribute(attribute)); - } - }; - addReplAttribute('output'); - addReplAttribute('std-out'); - addReplAttribute('std-err'); - newPyRepl.setAttribute('exec-id', nextExecId.toString()); - this.parentElement.appendChild(newPyRepl); - } - } - getSourceFromElement() { - return this.editor.state.doc.toString(); - } - } - - const logger$6 = getLogger('py-box'); - class PyBox extends HTMLElement { - shadow; - wrapper; - theme; - widths; - constructor() { - super(); - // attach shadow so we can preserve the element original innerHtml content - this.shadow = this.attachShadow({ mode: 'open' }); - this.wrapper = document.createElement('slot'); - this.shadow.appendChild(this.wrapper); - } - connectedCallback() { - const mainDiv = document.createElement('div'); - addClasses(mainDiv, ['py-box']); - // Hack: for some reason when moving children, the editor box duplicates children - // meaning that we end up with 2 editors, if there's a <py-repl> inside the <py-box> - // so, if we have more than 2 children with the cm-editor class, we remove one of them - while (this.childNodes.length > 0) { - if (this.firstChild.nodeName == 'PY-REPL') { - // in this case we need to remove the child and create a new one from scratch - const replDiv = document.createElement('div'); - // we need to put the new repl inside a div so that if the repl has auto-generate true - // it can replicate itself inside that constrained div - replDiv.appendChild(this.firstChild.cloneNode()); - mainDiv.appendChild(replDiv); - this.firstChild.remove(); - } - else { - if (this.firstChild.nodeName != '#text') { - mainDiv.appendChild(this.firstChild); - } - else { - this.firstChild.remove(); - } - } - } - // now we need to set widths - this.widths = []; - if (this.hasAttribute('widths')) { - for (const w of this.getAttribute('widths').split(';')) { - if (w.includes('/')) - this.widths.push(w.split('/')[0]); - else - this.widths.push(w); - } - } - else { - this.widths = Array(mainDiv.children.length).fill('1 1 0'); - } - this.widths.forEach((width, index) => { - const node = mainDiv.childNodes[index]; - node.style.flex = width; - addClasses(node, ['py-box-child']); - }); - this.appendChild(mainDiv); - logger$6.info('py-box connected'); - } - } - - const logger$5 = getLogger('py-button'); - class PyButton extends BaseEvalElement { - widths; - label; - class; - defaultClass; - mount_name; - constructor() { - super(); - this.defaultClass = ['py-button']; - if (this.hasAttribute('label')) { - this.label = this.getAttribute('label'); - } - // Styling does the same thing as class in normal HTML. Using the name "class" makes the style to malfunction - if (this.hasAttribute('styling')) { - const klass = this.getAttribute('styling').trim(); - if (klass === '') { - this.class = this.defaultClass; - } - else { - // trim each element to remove unnecessary spaces which makes the button style to malfunction - this.class = klass - .split(' ') - .map(x => x.trim()) - .filter(x => x !== ''); - } - } - else { - this.class = this.defaultClass; - } - } - connectedCallback() { - this.checkId(); - this.code = htmlDecode(this.innerHTML); - this.mount_name = this.id.split('-').join('_'); - this.innerHTML = ''; - const mainDiv = document.createElement('button'); - mainDiv.innerHTML = this.label; - addClasses(mainDiv, this.class); - mainDiv.id = this.id; - this.id = `${this.id}-container`; - this.appendChild(mainDiv); - this.code = this.code.split('self').join(this.mount_name); - let registrationCode = `from pyodide.ffi import create_proxy`; - registrationCode += `\n${this.mount_name} = Element("${mainDiv.id}")`; - if (this.code.includes('def on_focus')) { - this.code = this.code.replace('def on_focus', `def on_focus_${this.mount_name}`); - registrationCode += `\n${this.mount_name}.element.addEventListener('focus', create_proxy(on_focus_${this.mount_name}))`; - } - if (this.code.includes('def on_click')) { - this.code = this.code.replace('def on_click', `def on_click_${this.mount_name}`); - registrationCode += `\n${this.mount_name}.element.addEventListener('click', create_proxy(on_click_${this.mount_name}))`; - } - // now that we appended and the element is attached, lets connect with the event handlers - // defined for this widget - this.runAfterRuntimeInitialized(async () => { - await this.eval(this.code); - await this.eval(registrationCode); - logger$5.debug('registered handlers'); - }); - logger$5.debug('py-button connected'); - } - } - - class PyTitle extends BaseEvalElement { - widths; - label; - mount_name; - constructor() { - super(); - } - connectedCallback() { - this.label = htmlDecode(this.innerHTML); - this.mount_name = this.id.split('-').join('_'); - this.innerHTML = ''; - const mainDiv = document.createElement('div'); - const divContent = document.createElement('h1'); - addClasses(mainDiv, ['py-title']); - divContent.innerHTML = this.label; - mainDiv.id = this.id; - this.id = `${this.id}-container`; - mainDiv.appendChild(divContent); - this.appendChild(mainDiv); - } - } - - const logger$4 = getLogger('py-inputbox'); - class PyInputBox extends BaseEvalElement { - widths; - label; - mount_name; - constructor() { - super(); - if (this.hasAttribute('label')) { - this.label = this.getAttribute('label'); - } - } - connectedCallback() { - this.checkId(); - this.code = htmlDecode(this.innerHTML); - this.mount_name = this.id.split('-').join('_'); - this.innerHTML = ''; - const mainDiv = document.createElement('input'); - mainDiv.type = 'text'; - addClasses(mainDiv, ['py-input']); - mainDiv.id = this.id; - this.id = `${this.id}-container`; - this.appendChild(mainDiv); - // now that we appended and the element is attached, lets connect with the event handlers - // defined for this widget - this.appendChild(mainDiv); - this.code = this.code.split('self').join(this.mount_name); - let registrationCode = `from pyodide.ffi import create_proxy`; - registrationCode += `\n${this.mount_name} = Element("${mainDiv.id}")`; - if (this.code.includes('def on_keypress')) { - this.code = this.code.replace('def on_keypress', `def on_keypress_${this.mount_name}`); - registrationCode += `\n${this.mount_name}.element.addEventListener('keypress', create_proxy(on_keypress_${this.mount_name}))`; - } - // TODO: For now we delay execution to allow pyodide to load but in the future this - // should really wait for it to load.. - this.runAfterRuntimeInitialized(async () => { - await this.eval(this.code); - await this.eval(registrationCode); - logger$4.debug('registered handlers'); - }); - } - } - - /* - These were taken from main.js because some of our components call - runAfterRuntimeInitialized immediately when we are creating the custom - element, this was causing tests to fail since runAfterRuntimeInitialized - expects the runtime to have been loaded before being called. - - This function is now called from within the `runtime.initialize`. Once - the runtime finished initializing, then we will create the custom elements - so they are rendered in the page and we will always have a runtime available. - - Ideally, this would live under utils.js, but importing all the components in - the utils.js file was causing jest to fail with weird errors such as: - "ReferenceError: Cannot access 'BaseEvalElement' before initialization" coming - from the PyScript class. - - */ - function createCustomElements() { - /* eslint-disable @typescript-eslint/no-unused-vars */ - customElements.define('py-repl', PyRepl); - customElements.define('py-box', PyBox); - customElements.define('py-title', PyTitle); - customElements.define('py-register-widget', PyWidget); - customElements.define('py-inputbox', PyInputBox); - customElements.define('py-button', PyButton); - /* eslint-enable @typescript-eslint/no-unused-vars */ - } - - const logger$3 = getLogger('pyscript/runtime'); - const version = "<<VERSION>>"; - let loader$1; - globalLoader.subscribe(value => { - loader$1 = value; - }); - let initializers_; - initializers.subscribe((value) => { - initializers_ = value; - }); - let postInitializers_; - postInitializers.subscribe((value) => { - postInitializers_ = value; - }); - let scriptsQueue_; - scriptsQueue.subscribe((value) => { - scriptsQueue_ = value; - }); - let appConfig_$1 = { - autoclose_loader: true - }; - appConfig.subscribe((value) => { - if (value) { - appConfig_$1 = value; - } - }); - /* - Runtime class is a super class that all different runtimes must respect - and adhere to. - - Currently, the only runtime available is Pyodide as indicated by the - `RuntimeInterpreter` type above. This serves as a Union of types of - different runtimes/interpreters which will be added in near future. - - The class has abstract methods available which each runtime is supposed - to implement. - - Methods available handle loading of the interpreter, initialization, - running code, loading and installation of packages, loading from files etc. - - For an example implementation, refer to the `PyodideRuntime` class - in `pyodide.ts` - */ - class Runtime extends Object { - /** - * initializes the page which involves loading of runtime, - * as well as evaluating all the code inside <py-script> tags - * along with initializers and postInitializers - * */ - async initialize() { - loader$1?.log('Loading runtime...'); - await this.loadInterpreter(); - const newEnv = { - id: 'default', - runtime: this, - state: 'loading', - }; - runtimeLoaded.set(this); - // Inject the loader into the runtime namespace - // eslint-disable-next-line - this.globals.set('pyscript_loader', loader$1); - loader$1?.log('Runtime created...'); - loadedEnvironments.update(environments => ({ - ...environments, - [newEnv['id']]: newEnv, - })); - // now we call all initializers before we actually executed all page scripts - loader$1?.log('Initializing components...'); - for (const initializer of initializers_) { - await initializer(); - } - loader$1?.log('Initializing scripts...'); - for (const script of scriptsQueue_) { - void script.evaluate(); - } - scriptsQueue.set([]); - // now we call all post initializers AFTER we actually executed all page scripts - loader$1?.log('Running post initializers...'); - // Finally create the custom elements for pyscript such as pybutton - createCustomElements(); - if (appConfig_$1 && appConfig_$1.autoclose_loader) { - loader$1?.close(); - } - for (const initializer of postInitializers_) { - await initializer(); - } - // NOTE: this message is used by integration tests to know that - // pyscript initialization has complete. If you change it, you need to - // change it also in tests/integration/support.py - logger$3.info('PyScript page fully initialized'); - } - } - - var pyscript = "import asyncio\nimport base64\nimport io\nimport sys\nimport time\nfrom textwrap import dedent\n\nimport micropip # noqa: F401\nfrom js import console, document\n\nloop = asyncio.get_event_loop()\n\nMIME_METHODS = {\n \"__repr__\": \"text/plain\",\n \"_repr_html_\": \"text/html\",\n \"_repr_markdown_\": \"text/markdown\",\n \"_repr_svg_\": \"image/svg+xml\",\n \"_repr_png_\": \"image/png\",\n \"_repr_pdf_\": \"application/pdf\",\n \"_repr_jpeg_\": \"image/jpeg\",\n \"_repr_latex\": \"text/latex\",\n \"_repr_json_\": \"application/json\",\n \"_repr_javascript_\": \"application/javascript\",\n \"savefig\": \"image/png\",\n}\n\n\ndef render_image(mime, value, meta):\n data = f\"data:{mime};charset=utf-8;base64,{value}\"\n attrs = \" \".join(['{k}=\"{v}\"' for k, v in meta.items()])\n return f'<img src=\"{data}\" {attrs}</img>'\n\n\ndef identity(value, meta):\n return value\n\n\nMIME_RENDERERS = {\n \"text/plain\": identity,\n \"text/html\": identity,\n \"image/png\": lambda value, meta: render_image(\"image/png\", value, meta),\n \"image/jpeg\": lambda value, meta: render_image(\"image/jpeg\", value, meta),\n \"image/svg+xml\": identity,\n \"application/json\": identity,\n \"application/javascript\": lambda value, meta: f\"<script>{value}</script>\",\n}\n\n\ndef eval_formatter(obj, print_method):\n \"\"\"\n Evaluates a formatter method.\n \"\"\"\n if print_method == \"__repr__\":\n return repr(obj)\n elif hasattr(obj, print_method):\n if print_method == \"savefig\":\n buf = io.BytesIO()\n obj.savefig(buf, format=\"png\")\n buf.seek(0)\n return base64.b64encode(buf.read()).decode(\"utf-8\")\n return getattr(obj, print_method)()\n elif print_method == \"_repr_mimebundle_\":\n return {}, {}\n return None\n\n\ndef format_mime(obj):\n \"\"\"\n Formats object using _repr_x_ methods.\n \"\"\"\n if isinstance(obj, str):\n return obj, \"text/plain\"\n\n mimebundle = eval_formatter(obj, \"_repr_mimebundle_\")\n if isinstance(mimebundle, tuple):\n format_dict, _ = mimebundle\n else:\n format_dict = mimebundle\n\n output, not_available = None, []\n for method, mime_type in reversed(MIME_METHODS.items()):\n if mime_type in format_dict:\n output = format_dict[mime_type]\n else:\n output = eval_formatter(obj, method)\n\n if output is None:\n continue\n elif mime_type not in MIME_RENDERERS:\n not_available.append(mime_type)\n continue\n break\n if output is None:\n if not_available:\n console.warn(\n f\"Rendered object requested unavailable MIME renderers: {not_available}\"\n )\n output = repr(output)\n mime_type = \"text/plain\"\n elif isinstance(output, tuple):\n output, meta = output\n else:\n meta = {}\n return MIME_RENDERERS[mime_type](output, meta), mime_type\n\n\nclass PyScript:\n loop = loop\n\n @staticmethod\n def run_until_complete(f):\n _ = loop.run_until_complete(f)\n\n @staticmethod\n def write(element_id, value, append=False, exec_id=0):\n \"\"\"Writes value to the element with id \"element_id\"\"\"\n Element(element_id).write(value=value, append=append)\n console.warn(\n dedent(\n \"\"\"PyScript Deprecation Warning: PyScript.write is\n marked as deprecated and will be removed sometime soon. Please, use\n Element(<id>).write instead.\"\"\"\n )\n )\n\n\nclass Element:\n def __init__(self, element_id, element=None):\n self._id = element_id\n self._element = element\n\n @property\n def id(self):\n return self._id\n\n @property\n def element(self):\n \"\"\"Return the dom element\"\"\"\n if not self._element:\n self._element = document.querySelector(f\"#{self._id}\")\n return self._element\n\n @property\n def value(self):\n return self.element.value\n\n @property\n def innerHtml(self):\n return self.element.innerHtml\n\n def write(self, value, append=False):\n out_element_id = self.id\n\n html, mime_type = format_mime(value)\n if html == \"\\n\":\n return\n\n if append:\n child = document.createElement(\"div\")\n exec_id = self.element.childElementCount + 1\n out_element_id = child.id = f\"{self.id}-{exec_id}\"\n self.element.appendChild(child)\n\n out_element = document.querySelector(f\"#{out_element_id}\")\n\n if mime_type in (\"application/javascript\", \"text/html\"):\n script_element = document.createRange().createContextualFragment(html)\n out_element.appendChild(script_element)\n else:\n out_element.innerHTML = html\n\n def clear(self):\n if hasattr(self.element, \"value\"):\n self.element.value = \"\"\n else:\n self.write(\"\", append=False)\n\n def select(self, query, from_content=False):\n el = self.element\n if from_content:\n el = el.content\n\n _el = el.querySelector(query)\n if _el:\n return Element(_el.id, _el)\n else:\n console.warn(f\"WARNING: can't find element matching query {query}\")\n\n def clone(self, new_id=None, to=None):\n if new_id is None:\n new_id = self.element.id\n\n clone = self.element.cloneNode(True)\n clone.id = new_id\n\n if to:\n to.element.appendChild(clone)\n\n # Inject it into the DOM\n self.element.after(clone)\n\n return Element(clone.id, clone)\n\n def remove_class(self, classname):\n if isinstance(classname, list):\n for cl in classname:\n self.remove_class(cl)\n else:\n self.element.classList.remove(classname)\n\n def add_class(self, classname):\n self.element.classList.add(classname)\n\n\ndef add_classes(element, class_list):\n for klass in class_list.split(\" \"):\n element.classList.add(klass)\n\n\ndef create(what, id_=None, classes=\"\"):\n element = document.createElement(what)\n if id_:\n element.id = id_\n add_classes(element, classes)\n return Element(id_, element)\n\n\nclass PyWidgetTheme:\n def __init__(self, main_style_classes):\n self.main_style_classes = main_style_classes\n\n def theme_it(self, widget):\n for klass in self.main_style_classes.split(\" \"):\n widget.classList.add(klass)\n\n\nclass PyItemTemplate(Element):\n label_fields = None\n\n def __init__(self, data, labels=None, state_key=None, parent=None):\n self.data = data\n\n self.register_parent(parent)\n\n if not labels:\n labels = list(self.data.keys())\n self.labels = labels\n\n self.state_key = state_key\n\n super().__init__(self._id)\n\n def register_parent(self, parent):\n self._parent = parent\n if parent:\n self._id = f\"{self._parent._id}-c-{len(self._parent._children)}\"\n self.data[\"id\"] = self._id\n else:\n self._id = None\n\n def create(self):\n new_child = create(\"div\", self._id, \"py-li-element\")\n new_child._element.innerHTML = dedent(\n f\"\"\"\n <label id=\"{self._id}\" for=\"flex items-center p-2 \">\n <input class=\"mr-2\" type=\"checkbox\" class=\"task-check\">\n <p>{self.render_content()}</p>\n </label>\n \"\"\"\n )\n return new_child\n\n def on_click(self, evt):\n pass\n\n def pre_append(self):\n pass\n\n def post_append(self):\n self.element.click = self.on_click\n self.element.onclick = self.on_click\n\n self._post_append()\n\n def _post_append(self):\n pass\n\n def strike(self, value, extra=None):\n if value:\n self.add_class(\"line-through\")\n else:\n self.remove_class(\"line-through\")\n\n def render_content(self):\n return \" - \".join([self.data[f] for f in self.labels])\n\n\nclass PyListTemplate:\n theme = PyWidgetTheme(\"py-li-element\")\n item_class = PyItemTemplate\n\n def __init__(self, parent):\n self.parent = parent\n self._children = []\n self._id = self.parent.id\n\n @property\n def children(self):\n return self._children\n\n @property\n def data(self):\n return [c.data for c in self._children]\n\n def render_children(self):\n binds = {}\n for i, c in enumerate(self._children):\n txt = c.element.innerHTML\n rnd = str(time.time()).replace(\".\", \"\")[-5:]\n new_id = f\"{c.element.id}-{i}-{rnd}\"\n binds[new_id] = c.element.id\n txt = txt.replace(\">\", f\" id='{new_id}'>\")\n print(txt)\n\n def foo(evt):\n evtEl = evt.srcElement\n srcEl = Element(binds[evtEl.id])\n srcEl.element.onclick()\n evtEl.classList = srcEl.element.classList\n\n for new_id in binds:\n Element(new_id).element.onclick = foo\n\n def connect(self):\n self.md = main_div = document.createElement(\"div\")\n main_div.id = self._id + \"-list-tasks-container\"\n\n if self.theme:\n self.theme.theme_it(main_div)\n\n self.parent.appendChild(main_div)\n\n def add(self, *args, **kws):\n if not isinstance(args[0], self.item_class):\n child = self.item_class(*args, **kws)\n else:\n child = args[0]\n child.register_parent(self)\n return self._add(child)\n\n def _add(self, child_elem):\n self.pre_child_append(child_elem)\n child_elem.pre_append()\n self._children.append(child_elem)\n self.md.appendChild(child_elem.create().element)\n child_elem.post_append()\n self.child_appended(child_elem)\n return child_elem\n\n def pre_child_append(self, child):\n pass\n\n def child_appended(self, child):\n \"\"\"Overwrite me to define logic\"\"\"\n pass\n\n\nclass OutputCtxManager:\n def __init__(self, out=None, output_to_console=True, append=True):\n self._out = out\n self._prev = out\n self.output_to_console = output_to_console\n self._append = append\n\n def change(self, out=None, output_to_console=True, append=True):\n self._prev = self._out\n self._out = out\n self.output_to_console = output_to_console\n self._append = append\n\n def revert(self):\n self._out = self._prev\n\n def write(self, value):\n if self._out:\n Element(self._out).write(value, self._append)\n\n if self.output_to_console:\n console.info(value)\n\n\nclass OutputManager:\n def __init__(self, out=None, err=None, output_to_console=True, append=True):\n sys.stdout = self._out_manager = OutputCtxManager(\n out=out, output_to_console=output_to_console, append=append\n )\n sys.stderr = self._err_manager = OutputCtxManager(\n out=err, output_to_console=output_to_console, append=append\n )\n self.output_to_console = output_to_console\n self._append = append\n\n def change(self, out=None, err=None, output_to_console=True, append=True):\n self._out_manager.change(\n out=out, output_to_console=output_to_console, append=append\n )\n sys.stdout = self._out_manager\n self._err_manager.change(\n out=err, output_to_console=output_to_console, append=append\n )\n sys.stderr = self._err_manager\n self.output_to_console = output_to_console\n self._append = append\n\n def revert(self):\n self._out_manager.revert()\n self._err_manager.revert()\n sys.stdout = self._out_manager\n sys.stderr = self._err_manager\n\n\npyscript = PyScript()\noutput_manager = OutputManager()\n"; - - const logger$2 = getLogger('pyscript/pyodide'); - class PyodideRuntime extends Runtime { - src; - name; - lang; - interpreter; - globals; - constructor(src = 'https://cdn.jsdelivr.net/pyodide/v0.21.2/full/pyodide.js', name = 'pyodide-default', lang = 'python') { - logger$2.info('Runtime config:', { name, lang, src }); - super(); - this.src = src; - this.name = name; - this.lang = lang; - } - /** - * Although `loadPyodide` is used below, - * notice that it is not imported i.e. - * import { loadPyodide } from 'pyodide'; - * is not used at the top of this file. - * - * This is because, if it's used, loadPyodide - * behaves mischievously i.e. it tries to load - * `pyodide.asm.js` and `pyodide_py.tar` but - * with paths that are wrong such as: - * - * http://127.0.0.1:8080/build/pyodide_py.tar - * which results in a 404 since `build` doesn't - * contain these files and is clearly the wrong - * path. - */ - async loadInterpreter() { - logger$2.info('Loading pyodide'); - // eslint-disable-next-line - // @ts-ignore - this.interpreter = await loadPyodide({ - stdout: console.log, - stderr: console.log, - fullStdLib: false, - }); - this.globals = this.interpreter.globals; - // XXX: ideally, we should load micropip only if we actually need it - await this.loadPackage('micropip'); - logger$2.info('importing pyscript.py'); - await this.run(pyscript); - logger$2.info('pyodide loaded and initialized'); - } - async run(code) { - return await this.interpreter.runPythonAsync(code); - } - registerJsModule(name, module) { - this.interpreter.registerJsModule(name, module); - } - async loadPackage(names) { - logger$2.info(`pyodide.loadPackage: ${names.toString()}`); - await this.interpreter.loadPackage(names, logger$2.info.bind(logger$2), logger$2.info.bind(logger$2)); - } - async installPackage(package_name) { - if (package_name.length > 0) { - logger$2.info(`micropip install ${package_name.toString()}`); - const micropip = this.globals.get('micropip'); - await micropip.install(package_name); - micropip.destroy(); - } - } - async loadFromFile(path) { - const filename = getLastPath(path); - await this.run(` - from pyodide.http import pyfetch - from js import console - - try: - response = await pyfetch("${path}") - except Exception as err: - console.warn("PyScript: Access to local files (using 'paths:' in py-env) is not available when directly opening a HTML file; you must use a webserver to serve the additional files. See https://github.com/pyscript/pyscript/issues/257#issuecomment-1119595062 on starting a simple webserver with Python.") - raise(err) - content = await response.bytes() - with open("${filename}", "wb") as f: - f.write(content) - `); - } - } - - // Subscriber used to connect to the first available runtime (can be pyodide or others) - let runtimeSpec; - runtimeLoaded.subscribe(value => { - runtimeSpec = value; - }); - let appConfig_; - appConfig.subscribe(value => { - appConfig_ = value; - }); - const logger$1 = getLogger('py-config'); - /** - * Configures general metadata about the PyScript application such - * as a list of runtimes, name, version, closing the loader - * automatically, etc. - * - * Also initializes the different runtimes passed. If no runtime is passed, - * the default runtime based on Pyodide is used. - */ - class PyConfig extends BaseEvalElement { - widths; - label; - mount_name; - details; - operation; - values; - constructor() { - super(); - } - extractFromSrc(configType) { - if (this.hasAttribute('src')) { - logger$1.info('config set from src attribute'); - return validateConfig(readTextFromPath(this.getAttribute('src')), configType); - } - return {}; - } - extractFromInline(configType) { - if (this.innerHTML !== '') { - this.code = this.innerHTML; - this.innerHTML = ''; - logger$1.info('config set from inline'); - return validateConfig(this.code, configType); - } - return {}; - } - injectMetadata() { - this.values.pyscript = { - "version": version, - "time": new Date().toISOString() - }; - } - connectedCallback() { - const configType = this.hasAttribute("type") ? this.getAttribute("type") : "toml"; - let srcConfig = this.extractFromSrc(configType); - const inlineConfig = this.extractFromInline(configType); - // first make config from src whole if it is partial - srcConfig = mergeConfig(srcConfig, defaultConfig$1); - // then merge inline config and config from src - this.values = mergeConfig(inlineConfig, srcConfig); - this.injectMetadata(); - appConfig.set(this.values); - logger$1.info('config set:', this.values); - addInitializer(this.loadPackages); - addInitializer(this.loadPaths); - this.loadRuntimes(); - } - log(msg) { - const newLog = document.createElement('p'); - newLog.innerText = msg; - this.details.appendChild(newLog); - } - close() { - this.remove(); - } - loadPackages = async () => { - const env = appConfig_.packages; - logger$1.info("Loading env: ", env); - await runtimeSpec.installPackage(env); - }; - loadPaths = async () => { - const paths = appConfig_.paths; - logger$1.info("Paths to load: ", paths); - for (const singleFile of paths) { - logger$1.info(` loading path: ${singleFile}`); - try { - await runtimeSpec.loadFromFile(singleFile); - } - catch (e) { - //Should we still export full error contents to console? - handleFetchError(e, singleFile); - } - } - logger$1.info("All paths loaded"); - }; - loadRuntimes() { - logger$1.info('Initializing runtimes'); - for (const runtime of this.values.runtimes) { - const runtimeObj = new PyodideRuntime(runtime.src, runtime.name, runtime.lang); - const script = document.createElement('script'); // create a script DOM node - script.src = runtimeObj.src; // set its src to the provided URL - script.addEventListener('load', () => { - void runtimeObj.initialize(); - }); - document.head.appendChild(script); - } - } - } - - const logger = getLogger('pyscript/main'); - /* eslint-disable @typescript-eslint/no-unused-vars */ - customElements.define('py-script', PyScript); - customElements.define('py-loader', PyLoader); - customElements.define('py-config', PyConfig); - customElements.define('py-env', PyEnv); - /* eslint-disable @typescript-eslint/no-unused-vars */ - // As first thing, loop for application configs - logger.info('checking for py-config'); - const config = document.querySelector('py-config'); - if (!config) { - const loader = document.createElement('py-config'); - document.body.append(loader); - } - // add loader to the page body - logger.info('add py-loader'); - const loader = document.createElement('py-loader'); - document.body.append(loader); - globalLoader.set(loader); - -})(); +})({}); //# sourceMappingURL=pyscript.js.map diff --git a/examples/03_numpy_grid_demo/resources/pyscript_bootstrap_templates-0.1.0-py3-none-any.whl b/examples/03_numpy_grid_demo/resources/pyscript_bootstrap_templates-0.1.0-py3-none-any.whl index 7d580e9..19acf2b 100644 Binary files a/examples/03_numpy_grid_demo/resources/pyscript_bootstrap_templates-0.1.0-py3-none-any.whl and b/examples/03_numpy_grid_demo/resources/pyscript_bootstrap_templates-0.1.0-py3-none-any.whl differ diff --git a/examples/03_numpy_grid_demo/resources/pyscript_bootstrap_templates-0.2.0-py3-none-any.whl b/examples/03_numpy_grid_demo/resources/pyscript_bootstrap_templates-0.2.0-py3-none-any.whl new file mode 100644 index 0000000..e1a2da0 Binary files /dev/null and b/examples/03_numpy_grid_demo/resources/pyscript_bootstrap_templates-0.2.0-py3-none-any.whl differ diff --git a/examples/03_numpy_grid_demo/serviceWorker.js b/examples/03_numpy_grid_demo/serviceWorker.js index d31ae9d..b2960e0 100644 --- a/examples/03_numpy_grid_demo/serviceWorker.js +++ b/examples/03_numpy_grid_demo/serviceWorker.js @@ -1,5 +1,5 @@ -const pwa_version = "03_numpy_grid_demo_202210161638" +const pwa_version = "03_numpy_grid_demo_202306031006" const assets = ["./index.html", "./main.py", "./resources/bootstrap.css", @@ -7,7 +7,7 @@ const assets = ["./index.html", "./resources/pyscript.css", "./resources/pyscript.js", "./resources/pyscript.py", - "./resources/pyscript_bootstrap_templates-0.1.0-py3-none-any.whl", + "./resources/pyscript_bootstrap_templates-0.2.0-py3-none-any.whl", "./resources/pwa.js", "./site.js", ] diff --git a/examples/04_cell_detector/config.json b/examples/04_cell_detector/config.json new file mode 100644 index 0000000..2961d5c --- /dev/null +++ b/examples/04_cell_detector/config.json @@ -0,0 +1,18 @@ +{ + "root_folder": "04_cell_detector", + "title": "04_cell_detector", + "packages": [ + "numpy", + "Pillow", + "opencv-python" + ], + "paths": [], + "pyscript_css_url": "https://pyscript.net/latest/pyscript.css", + "pyscript_js_url": "https://pyscript.net/latest/pyscript.js", + "pyscript_py_url": "https://pyscript.net/latest/pyscript.py", + "bootstrap_css_url": "https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css", + "bootstrap_js_url": "https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js", + "pyscript_bootstrap_templates_wheel_url": "../dist/pyscript_bootstrap_templates-0.2.0-py3-none-any.whl", + "pwa_bg_color": "#000000", + "pwa_theme_color": "#ffffff" +} \ No newline at end of file diff --git a/examples/04_cell_detector/index.html b/examples/04_cell_detector/index.html new file mode 100644 index 0000000..9203368 --- /dev/null +++ b/examples/04_cell_detector/index.html @@ -0,0 +1,40 @@ + +<!DOCTYPE html> +<html lang="en" style="width: 100%;height: 100%"> + <head id="head"> + <meta charset="UTF-8"> + <meta name="viewport" content="width=device-width, initial-scale=1.0"> + + <link rel="manifest" href="manifest.json" /> + + <script src="./resources/pwa.js"></script> + + <link rel="stylesheet" href="./resources/pyscript.css" /> + <script defer src="./resources/pyscript.js"></script> + <!-- Bootstrap CSS --> + <link href="./resources/bootstrap.css" rel="stylesheet"> + + <title>04_cell_detector + + + + { + "splashscreen": { + "autoclose": true + }, + "packages": [ + "./resources/pyscript_bootstrap_templates-0.2.0-py3-none-any.whl", + "numpy", + "Pillow", + "opencv-python" + ], + "paths": [] +} + +
+ + + + + + \ No newline at end of file diff --git a/examples/04_cell_detector/main.py b/examples/04_cell_detector/main.py new file mode 100644 index 0000000..774ac2f --- /dev/null +++ b/examples/04_cell_detector/main.py @@ -0,0 +1,214 @@ + +from pyscript_bootstrap_templates import bootstrap_templates +from pyscript_bootstrap_templates import bootstrap_HTML as bHTML +from pyscript_bootstrap_templates import bootstrap_inputs as bInputs +from pyscript_bootstrap_templates import HTML as HTML + + +import numpy as np +from PIL import Image +import cv2 + +loaded_img = None + +app = bootstrap_templates.PyScriptBootstrapDashboard(parent_element="pyscript_app", brand_name="Pyscript Cell Detector") + +main_div = bHTML.BootstrapContainer(parent=app.main) +main_div.w = 100 +result_div = bHTML.BootstrapContainer(parent=main_div) + + +def process_image(image, + hough_min_dist = 500, + hough_param1 = 80, + hough_param2 = 500, + minRadius = 100, + maxRadius=500, + inner_hough_circles=True): + + for child in result_div.children: + child.destroy() + #image = cv2.imread(str(test_img_path), cv2.IMREAD_COLOR) + # Convert the image to grayscale + gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) + + # Use median blur to reduce noise + gray = cv2.medianBlur(gray, 5) + + # Apply Hough transform on the image to find circles + circles = cv2.HoughCircles(gray, + cv2.HOUGH_GRADIENT, + 2, + minDist=hough_min_dist, + param1=hough_param1, + param2=hough_param2, + minRadius=minRadius, + maxRadius=maxRadius) + + if circles is None: + bHTML.AlertDanger("No cell areas detected in image", parent=app.main) + return False + + # Convert to integers + circles = np.uint16(np.around(circles)) + + # Loop over all detected circles and add them to the image + #for i in circles[0,:]: + # # Draw outer circle + # cv2.circle(image,(i[0],i[1]),i[2],(0,255,0),2) + # # Draw center of circle + # cv2.circle(image,(i[0],i[1]),2,(0,0,255),3) + + first_wells = [] + first_wells_gray = [] + + + for i in circles[0,:]: + + center = (i[0], i[1]) + radius = i[2] + + + # Cut out the well + well = image[center[1]-radius:center[1]+radius, center[0]-radius:center[0]+radius] + well_gray = gray[center[1]-radius:center[1]+radius, center[0]-radius:center[0]+radius] + + + first_wells.append(well) + first_wells_gray.append(well_gray) + + if inner_hough_circles: + + second_wells = [] + second_wells_gray = [] + + for well, well_gray in zip(first_wells, first_wells_gray): + + circles = cv2.HoughCircles(well_gray, cv2.HOUGH_GRADIENT, 1, minDist=hough_min_dist, param1=50, param2=50, minRadius=(well.shape[0] // 2) - 50, maxRadius=(well.shape[0] // 2) - 10) + if circles is not None: + circles = np.uint16(np.around(circles)) + i = circles[0,:][0] + center = (i[0], i[1]) + radius = i[2] - 1 + + min_y = max(center[1]-radius, 0) + max_y = center[1]+radius + + min_x = max(center[0]-radius, 0) + max_x = center[0]+radius + + + + second_wells.append(well[min_y:max_y, min_x:max_x]) + second_wells_gray.append(well_gray[min_y:max_y, min_x:max_x]) + else: + second_wells.append(well) + second_wells_gray.append(well_gray) + + else: + second_wells = first_wells + second_wells_gray = first_wells_gray + + + for well, well_gray in zip(second_wells, second_wells_gray): + + _, binary = cv2.threshold(255 - well_gray, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU) + + + # Perform some morphological operations to remove small noise - you can change the kernel size + kernel = np.ones((3,3),np.uint8) + cleaned = cv2.morphologyEx(binary, cv2.MORPH_OPEN, kernel) + + + radius = well.shape[0] // 2 -1 + # Now clear all pixels outside the circular well. + # We do this by creating a mask for the well and applying it to the image. + well_mask = np.zeros_like(cleaned, dtype=np.uint8) + cv2.circle(well_mask, (radius, radius), radius, 1, thickness=-1) + cleaned = cleaned * well_mask + + circle = well_mask > 0 + + # now create an image overlay to display + ratio = np.sum((cleaned > 0).astype(int)) / np.sum(circle.astype(int)) + div_result = bHTML.BootstrapContainer(f"ratio: {ratio * 100}%", parent=result_div) + div_result.shadow = bHTML.Shadow.LARGE + div_result.rounded = True + div_result.w = 50 + + well[cleaned > 0,0] = 255 + final_img = bHTML.Image.from_numpy_array(well, parent=div_result) + final_img.rounded = True + final_img.rounded_size = 10 + final_img.shadow = bHTML.Shadow.LARGE + final_img.w = 100 + + + +div = bHTML.BootstrapContainer("Controls", parent=app.sidebar) +div.font_size = 4 + +image_input = bInputs.InputFile(label_text="choose image file", parent=app.sidebar) + +i_hough_min_dist = bInputs.InputInt("hough min distance [px]", parent=app.sidebar) +i_hough_min_dist.value = 500 + +i_hough_param1 = bInputs.InputInt("hough param1", parent=app.sidebar) +i_hough_param1.value = 80 + +i_hough_param2 = bInputs.InputInt("hough param2", parent=app.sidebar) +i_hough_param2.value = 500 + +i_hough_min_radius = bInputs.InputInt("hough min radius [px]", parent=app.sidebar) +i_hough_min_radius.value = 100 + +i_hough_max_radius = bInputs.InputInt("hough max radius [px]", parent=app.sidebar) +i_hough_max_radius.value = 500 + + + +btn = bHTML.ButtonPrimary("Process", parent=app.sidebar) +btn.w = 100 + + + +def on_image_change(f, *args): + global loaded_img + f.seek(0) + img = np.array(Image.open(f)) + for child in result_div.children: + child.destroy() + + output = bHTML.Image.from_numpy_array(img, parent=result_div) + output.rounded = True + output.rounded_size = 10 + output.shadow = bHTML.Shadow.LARGE + output.w=50 + + loaded_img = img + +image_input.onchange = on_image_change + +def on_click(*args, **kwargs): + if loaded_img is None: + bHTML.AlertDanger("No image loaded", parent=app.main) + return + + h_min_dist = int(i_hough_min_dist.value) + h_param1 = int(i_hough_param1.value) + h_param2 = int(i_hough_param2.value) + h_min_radius = int(i_hough_min_radius.value) + h_max_radius = int(i_hough_max_radius.value) + + + process_image(loaded_img, + hough_min_dist=h_min_dist, + hough_param1=h_param1, + hough_param2=h_param2, + minRadius=h_min_radius, + maxRadius=h_max_radius, + inner_hough_circles=True) + +btn.onclick = on_click + + \ No newline at end of file diff --git a/examples/04_cell_detector/manifest.json b/examples/04_cell_detector/manifest.json new file mode 100644 index 0000000..f5f6487 --- /dev/null +++ b/examples/04_cell_detector/manifest.json @@ -0,0 +1 @@ +{"name": "04_cell_detector", "short_name": "04_cell_detector", "start_url": "./index.html", "scope": ".", "display": "standalone", "background_color": "#000000", "theme_color": "#ffffff", "icons": [{"src": "resources/icon-512x512.png", "type": "image/png", "sizes": "512x512"}]} \ No newline at end of file diff --git a/examples/04_cell_detector/resources/bootstrap.css b/examples/04_cell_detector/resources/bootstrap.css new file mode 100644 index 0000000..edfbbb0 --- /dev/null +++ b/examples/04_cell_detector/resources/bootstrap.css @@ -0,0 +1,7 @@ +@charset "UTF-8";/*! + * Bootstrap v5.0.2 (https://getbootstrap.com/) + * Copyright 2011-2021 The Bootstrap Authors + * Copyright 2011-2021 Twitter, Inc. + * Licensed under MIT (https://github.com/twbs/bootstrap/blob/main/LICENSE) + */:root{--bs-blue:#0d6efd;--bs-indigo:#6610f2;--bs-purple:#6f42c1;--bs-pink:#d63384;--bs-red:#dc3545;--bs-orange:#fd7e14;--bs-yellow:#ffc107;--bs-green:#198754;--bs-teal:#20c997;--bs-cyan:#0dcaf0;--bs-white:#fff;--bs-gray:#6c757d;--bs-gray-dark:#343a40;--bs-primary:#0d6efd;--bs-secondary:#6c757d;--bs-success:#198754;--bs-info:#0dcaf0;--bs-warning:#ffc107;--bs-danger:#dc3545;--bs-light:#f8f9fa;--bs-dark:#212529;--bs-font-sans-serif:system-ui,-apple-system,"Segoe UI",Roboto,"Helvetica Neue",Arial,"Noto Sans","Liberation Sans",sans-serif,"Apple Color Emoji","Segoe UI Emoji","Segoe UI Symbol","Noto Color Emoji";--bs-font-monospace:SFMono-Regular,Menlo,Monaco,Consolas,"Liberation Mono","Courier New",monospace;--bs-gradient:linear-gradient(180deg, rgba(255, 255, 255, 0.15), rgba(255, 255, 255, 0))}*,::after,::before{box-sizing:border-box}@media (prefers-reduced-motion:no-preference){:root{scroll-behavior:smooth}}body{margin:0;font-family:var(--bs-font-sans-serif);font-size:1rem;font-weight:400;line-height:1.5;color:#212529;background-color:#fff;-webkit-text-size-adjust:100%;-webkit-tap-highlight-color:transparent}hr{margin:1rem 0;color:inherit;background-color:currentColor;border:0;opacity:.25}hr:not([size]){height:1px}.h1,.h2,.h3,.h4,.h5,.h6,h1,h2,h3,h4,h5,h6{margin-top:0;margin-bottom:.5rem;font-weight:500;line-height:1.2}.h1,h1{font-size:calc(1.375rem + 1.5vw)}@media (min-width:1200px){.h1,h1{font-size:2.5rem}}.h2,h2{font-size:calc(1.325rem + .9vw)}@media (min-width:1200px){.h2,h2{font-size:2rem}}.h3,h3{font-size:calc(1.3rem + .6vw)}@media (min-width:1200px){.h3,h3{font-size:1.75rem}}.h4,h4{font-size:calc(1.275rem + .3vw)}@media (min-width:1200px){.h4,h4{font-size:1.5rem}}.h5,h5{font-size:1.25rem}.h6,h6{font-size:1rem}p{margin-top:0;margin-bottom:1rem}abbr[data-bs-original-title],abbr[title]{-webkit-text-decoration:underline dotted;text-decoration:underline dotted;cursor:help;-webkit-text-decoration-skip-ink:none;text-decoration-skip-ink:none}address{margin-bottom:1rem;font-style:normal;line-height:inherit}ol,ul{padding-left:2rem}dl,ol,ul{margin-top:0;margin-bottom:1rem}ol ol,ol ul,ul ol,ul ul{margin-bottom:0}dt{font-weight:700}dd{margin-bottom:.5rem;margin-left:0}blockquote{margin:0 0 1rem}b,strong{font-weight:bolder}.small,small{font-size:.875em}.mark,mark{padding:.2em;background-color:#fcf8e3}sub,sup{position:relative;font-size:.75em;line-height:0;vertical-align:baseline}sub{bottom:-.25em}sup{top:-.5em}a{color:#0d6efd;text-decoration:underline}a:hover{color:#0a58ca}a:not([href]):not([class]),a:not([href]):not([class]):hover{color:inherit;text-decoration:none}code,kbd,pre,samp{font-family:var(--bs-font-monospace);font-size:1em;direction:ltr;unicode-bidi:bidi-override}pre{display:block;margin-top:0;margin-bottom:1rem;overflow:auto;font-size:.875em}pre code{font-size:inherit;color:inherit;word-break:normal}code{font-size:.875em;color:#d63384;word-wrap:break-word}a>code{color:inherit}kbd{padding:.2rem .4rem;font-size:.875em;color:#fff;background-color:#212529;border-radius:.2rem}kbd kbd{padding:0;font-size:1em;font-weight:700}figure{margin:0 0 1rem}img,svg{vertical-align:middle}table{caption-side:bottom;border-collapse:collapse}caption{padding-top:.5rem;padding-bottom:.5rem;color:#6c757d;text-align:left}th{text-align:inherit;text-align:-webkit-match-parent}tbody,td,tfoot,th,thead,tr{border-color:inherit;border-style:solid;border-width:0}label{display:inline-block}button{border-radius:0}button:focus:not(:focus-visible){outline:0}button,input,optgroup,select,textarea{margin:0;font-family:inherit;font-size:inherit;line-height:inherit}button,select{text-transform:none}[role=button]{cursor:pointer}select{word-wrap:normal}select:disabled{opacity:1}[list]::-webkit-calendar-picker-indicator{display:none}[type=button],[type=reset],[type=submit],button{-webkit-appearance:button}[type=button]:not(:disabled),[type=reset]:not(:disabled),[type=submit]:not(:disabled),button:not(:disabled){cursor:pointer}::-moz-focus-inner{padding:0;border-style:none}textarea{resize:vertical}fieldset{min-width:0;padding:0;margin:0;border:0}legend{float:left;width:100%;padding:0;margin-bottom:.5rem;font-size:calc(1.275rem + .3vw);line-height:inherit}@media (min-width:1200px){legend{font-size:1.5rem}}legend+*{clear:left}::-webkit-datetime-edit-day-field,::-webkit-datetime-edit-fields-wrapper,::-webkit-datetime-edit-hour-field,::-webkit-datetime-edit-minute,::-webkit-datetime-edit-month-field,::-webkit-datetime-edit-text,::-webkit-datetime-edit-year-field{padding:0}::-webkit-inner-spin-button{height:auto}[type=search]{outline-offset:-2px;-webkit-appearance:textfield}::-webkit-search-decoration{-webkit-appearance:none}::-webkit-color-swatch-wrapper{padding:0}::file-selector-button{font:inherit}::-webkit-file-upload-button{font:inherit;-webkit-appearance:button}output{display:inline-block}iframe{border:0}summary{display:list-item;cursor:pointer}progress{vertical-align:baseline}[hidden]{display:none!important}.lead{font-size:1.25rem;font-weight:300}.display-1{font-size:calc(1.625rem + 4.5vw);font-weight:300;line-height:1.2}@media (min-width:1200px){.display-1{font-size:5rem}}.display-2{font-size:calc(1.575rem + 3.9vw);font-weight:300;line-height:1.2}@media (min-width:1200px){.display-2{font-size:4.5rem}}.display-3{font-size:calc(1.525rem + 3.3vw);font-weight:300;line-height:1.2}@media (min-width:1200px){.display-3{font-size:4rem}}.display-4{font-size:calc(1.475rem + 2.7vw);font-weight:300;line-height:1.2}@media (min-width:1200px){.display-4{font-size:3.5rem}}.display-5{font-size:calc(1.425rem + 2.1vw);font-weight:300;line-height:1.2}@media (min-width:1200px){.display-5{font-size:3rem}}.display-6{font-size:calc(1.375rem + 1.5vw);font-weight:300;line-height:1.2}@media (min-width:1200px){.display-6{font-size:2.5rem}}.list-unstyled{padding-left:0;list-style:none}.list-inline{padding-left:0;list-style:none}.list-inline-item{display:inline-block}.list-inline-item:not(:last-child){margin-right:.5rem}.initialism{font-size:.875em;text-transform:uppercase}.blockquote{margin-bottom:1rem;font-size:1.25rem}.blockquote>:last-child{margin-bottom:0}.blockquote-footer{margin-top:-1rem;margin-bottom:1rem;font-size:.875em;color:#6c757d}.blockquote-footer::before{content:"— "}.img-fluid{max-width:100%;height:auto}.img-thumbnail{padding:.25rem;background-color:#fff;border:1px solid #dee2e6;border-radius:.25rem;max-width:100%;height:auto}.figure{display:inline-block}.figure-img{margin-bottom:.5rem;line-height:1}.figure-caption{font-size:.875em;color:#6c757d}.container,.container-fluid,.container-lg,.container-md,.container-sm,.container-xl,.container-xxl{width:100%;padding-right:var(--bs-gutter-x,.75rem);padding-left:var(--bs-gutter-x,.75rem);margin-right:auto;margin-left:auto}@media (min-width:576px){.container,.container-sm{max-width:540px}}@media (min-width:768px){.container,.container-md,.container-sm{max-width:720px}}@media (min-width:992px){.container,.container-lg,.container-md,.container-sm{max-width:960px}}@media (min-width:1200px){.container,.container-lg,.container-md,.container-sm,.container-xl{max-width:1140px}}@media (min-width:1400px){.container,.container-lg,.container-md,.container-sm,.container-xl,.container-xxl{max-width:1320px}}.row{--bs-gutter-x:1.5rem;--bs-gutter-y:0;display:flex;flex-wrap:wrap;margin-top:calc(var(--bs-gutter-y) * -1);margin-right:calc(var(--bs-gutter-x) * -.5);margin-left:calc(var(--bs-gutter-x) * -.5)}.row>*{flex-shrink:0;width:100%;max-width:100%;padding-right:calc(var(--bs-gutter-x) * .5);padding-left:calc(var(--bs-gutter-x) * .5);margin-top:var(--bs-gutter-y)}.col{flex:1 0 0%}.row-cols-auto>*{flex:0 0 auto;width:auto}.row-cols-1>*{flex:0 0 auto;width:100%}.row-cols-2>*{flex:0 0 auto;width:50%}.row-cols-3>*{flex:0 0 auto;width:33.3333333333%}.row-cols-4>*{flex:0 0 auto;width:25%}.row-cols-5>*{flex:0 0 auto;width:20%}.row-cols-6>*{flex:0 0 auto;width:16.6666666667%}@media (min-width:576px){.col-sm{flex:1 0 0%}.row-cols-sm-auto>*{flex:0 0 auto;width:auto}.row-cols-sm-1>*{flex:0 0 auto;width:100%}.row-cols-sm-2>*{flex:0 0 auto;width:50%}.row-cols-sm-3>*{flex:0 0 auto;width:33.3333333333%}.row-cols-sm-4>*{flex:0 0 auto;width:25%}.row-cols-sm-5>*{flex:0 0 auto;width:20%}.row-cols-sm-6>*{flex:0 0 auto;width:16.6666666667%}}@media (min-width:768px){.col-md{flex:1 0 0%}.row-cols-md-auto>*{flex:0 0 auto;width:auto}.row-cols-md-1>*{flex:0 0 auto;width:100%}.row-cols-md-2>*{flex:0 0 auto;width:50%}.row-cols-md-3>*{flex:0 0 auto;width:33.3333333333%}.row-cols-md-4>*{flex:0 0 auto;width:25%}.row-cols-md-5>*{flex:0 0 auto;width:20%}.row-cols-md-6>*{flex:0 0 auto;width:16.6666666667%}}@media (min-width:992px){.col-lg{flex:1 0 0%}.row-cols-lg-auto>*{flex:0 0 auto;width:auto}.row-cols-lg-1>*{flex:0 0 auto;width:100%}.row-cols-lg-2>*{flex:0 0 auto;width:50%}.row-cols-lg-3>*{flex:0 0 auto;width:33.3333333333%}.row-cols-lg-4>*{flex:0 0 auto;width:25%}.row-cols-lg-5>*{flex:0 0 auto;width:20%}.row-cols-lg-6>*{flex:0 0 auto;width:16.6666666667%}}@media (min-width:1200px){.col-xl{flex:1 0 0%}.row-cols-xl-auto>*{flex:0 0 auto;width:auto}.row-cols-xl-1>*{flex:0 0 auto;width:100%}.row-cols-xl-2>*{flex:0 0 auto;width:50%}.row-cols-xl-3>*{flex:0 0 auto;width:33.3333333333%}.row-cols-xl-4>*{flex:0 0 auto;width:25%}.row-cols-xl-5>*{flex:0 0 auto;width:20%}.row-cols-xl-6>*{flex:0 0 auto;width:16.6666666667%}}@media (min-width:1400px){.col-xxl{flex:1 0 0%}.row-cols-xxl-auto>*{flex:0 0 auto;width:auto}.row-cols-xxl-1>*{flex:0 0 auto;width:100%}.row-cols-xxl-2>*{flex:0 0 auto;width:50%}.row-cols-xxl-3>*{flex:0 0 auto;width:33.3333333333%}.row-cols-xxl-4>*{flex:0 0 auto;width:25%}.row-cols-xxl-5>*{flex:0 0 auto;width:20%}.row-cols-xxl-6>*{flex:0 0 auto;width:16.6666666667%}}.col-auto{flex:0 0 auto;width:auto}.col-1{flex:0 0 auto;width:8.33333333%}.col-2{flex:0 0 auto;width:16.66666667%}.col-3{flex:0 0 auto;width:25%}.col-4{flex:0 0 auto;width:33.33333333%}.col-5{flex:0 0 auto;width:41.66666667%}.col-6{flex:0 0 auto;width:50%}.col-7{flex:0 0 auto;width:58.33333333%}.col-8{flex:0 0 auto;width:66.66666667%}.col-9{flex:0 0 auto;width:75%}.col-10{flex:0 0 auto;width:83.33333333%}.col-11{flex:0 0 auto;width:91.66666667%}.col-12{flex:0 0 auto;width:100%}.offset-1{margin-left:8.33333333%}.offset-2{margin-left:16.66666667%}.offset-3{margin-left:25%}.offset-4{margin-left:33.33333333%}.offset-5{margin-left:41.66666667%}.offset-6{margin-left:50%}.offset-7{margin-left:58.33333333%}.offset-8{margin-left:66.66666667%}.offset-9{margin-left:75%}.offset-10{margin-left:83.33333333%}.offset-11{margin-left:91.66666667%}.g-0,.gx-0{--bs-gutter-x:0}.g-0,.gy-0{--bs-gutter-y:0}.g-1,.gx-1{--bs-gutter-x:0.25rem}.g-1,.gy-1{--bs-gutter-y:0.25rem}.g-2,.gx-2{--bs-gutter-x:0.5rem}.g-2,.gy-2{--bs-gutter-y:0.5rem}.g-3,.gx-3{--bs-gutter-x:1rem}.g-3,.gy-3{--bs-gutter-y:1rem}.g-4,.gx-4{--bs-gutter-x:1.5rem}.g-4,.gy-4{--bs-gutter-y:1.5rem}.g-5,.gx-5{--bs-gutter-x:3rem}.g-5,.gy-5{--bs-gutter-y:3rem}@media (min-width:576px){.col-sm-auto{flex:0 0 auto;width:auto}.col-sm-1{flex:0 0 auto;width:8.33333333%}.col-sm-2{flex:0 0 auto;width:16.66666667%}.col-sm-3{flex:0 0 auto;width:25%}.col-sm-4{flex:0 0 auto;width:33.33333333%}.col-sm-5{flex:0 0 auto;width:41.66666667%}.col-sm-6{flex:0 0 auto;width:50%}.col-sm-7{flex:0 0 auto;width:58.33333333%}.col-sm-8{flex:0 0 auto;width:66.66666667%}.col-sm-9{flex:0 0 auto;width:75%}.col-sm-10{flex:0 0 auto;width:83.33333333%}.col-sm-11{flex:0 0 auto;width:91.66666667%}.col-sm-12{flex:0 0 auto;width:100%}.offset-sm-0{margin-left:0}.offset-sm-1{margin-left:8.33333333%}.offset-sm-2{margin-left:16.66666667%}.offset-sm-3{margin-left:25%}.offset-sm-4{margin-left:33.33333333%}.offset-sm-5{margin-left:41.66666667%}.offset-sm-6{margin-left:50%}.offset-sm-7{margin-left:58.33333333%}.offset-sm-8{margin-left:66.66666667%}.offset-sm-9{margin-left:75%}.offset-sm-10{margin-left:83.33333333%}.offset-sm-11{margin-left:91.66666667%}.g-sm-0,.gx-sm-0{--bs-gutter-x:0}.g-sm-0,.gy-sm-0{--bs-gutter-y:0}.g-sm-1,.gx-sm-1{--bs-gutter-x:0.25rem}.g-sm-1,.gy-sm-1{--bs-gutter-y:0.25rem}.g-sm-2,.gx-sm-2{--bs-gutter-x:0.5rem}.g-sm-2,.gy-sm-2{--bs-gutter-y:0.5rem}.g-sm-3,.gx-sm-3{--bs-gutter-x:1rem}.g-sm-3,.gy-sm-3{--bs-gutter-y:1rem}.g-sm-4,.gx-sm-4{--bs-gutter-x:1.5rem}.g-sm-4,.gy-sm-4{--bs-gutter-y:1.5rem}.g-sm-5,.gx-sm-5{--bs-gutter-x:3rem}.g-sm-5,.gy-sm-5{--bs-gutter-y:3rem}}@media (min-width:768px){.col-md-auto{flex:0 0 auto;width:auto}.col-md-1{flex:0 0 auto;width:8.33333333%}.col-md-2{flex:0 0 auto;width:16.66666667%}.col-md-3{flex:0 0 auto;width:25%}.col-md-4{flex:0 0 auto;width:33.33333333%}.col-md-5{flex:0 0 auto;width:41.66666667%}.col-md-6{flex:0 0 auto;width:50%}.col-md-7{flex:0 0 auto;width:58.33333333%}.col-md-8{flex:0 0 auto;width:66.66666667%}.col-md-9{flex:0 0 auto;width:75%}.col-md-10{flex:0 0 auto;width:83.33333333%}.col-md-11{flex:0 0 auto;width:91.66666667%}.col-md-12{flex:0 0 auto;width:100%}.offset-md-0{margin-left:0}.offset-md-1{margin-left:8.33333333%}.offset-md-2{margin-left:16.66666667%}.offset-md-3{margin-left:25%}.offset-md-4{margin-left:33.33333333%}.offset-md-5{margin-left:41.66666667%}.offset-md-6{margin-left:50%}.offset-md-7{margin-left:58.33333333%}.offset-md-8{margin-left:66.66666667%}.offset-md-9{margin-left:75%}.offset-md-10{margin-left:83.33333333%}.offset-md-11{margin-left:91.66666667%}.g-md-0,.gx-md-0{--bs-gutter-x:0}.g-md-0,.gy-md-0{--bs-gutter-y:0}.g-md-1,.gx-md-1{--bs-gutter-x:0.25rem}.g-md-1,.gy-md-1{--bs-gutter-y:0.25rem}.g-md-2,.gx-md-2{--bs-gutter-x:0.5rem}.g-md-2,.gy-md-2{--bs-gutter-y:0.5rem}.g-md-3,.gx-md-3{--bs-gutter-x:1rem}.g-md-3,.gy-md-3{--bs-gutter-y:1rem}.g-md-4,.gx-md-4{--bs-gutter-x:1.5rem}.g-md-4,.gy-md-4{--bs-gutter-y:1.5rem}.g-md-5,.gx-md-5{--bs-gutter-x:3rem}.g-md-5,.gy-md-5{--bs-gutter-y:3rem}}@media (min-width:992px){.col-lg-auto{flex:0 0 auto;width:auto}.col-lg-1{flex:0 0 auto;width:8.33333333%}.col-lg-2{flex:0 0 auto;width:16.66666667%}.col-lg-3{flex:0 0 auto;width:25%}.col-lg-4{flex:0 0 auto;width:33.33333333%}.col-lg-5{flex:0 0 auto;width:41.66666667%}.col-lg-6{flex:0 0 auto;width:50%}.col-lg-7{flex:0 0 auto;width:58.33333333%}.col-lg-8{flex:0 0 auto;width:66.66666667%}.col-lg-9{flex:0 0 auto;width:75%}.col-lg-10{flex:0 0 auto;width:83.33333333%}.col-lg-11{flex:0 0 auto;width:91.66666667%}.col-lg-12{flex:0 0 auto;width:100%}.offset-lg-0{margin-left:0}.offset-lg-1{margin-left:8.33333333%}.offset-lg-2{margin-left:16.66666667%}.offset-lg-3{margin-left:25%}.offset-lg-4{margin-left:33.33333333%}.offset-lg-5{margin-left:41.66666667%}.offset-lg-6{margin-left:50%}.offset-lg-7{margin-left:58.33333333%}.offset-lg-8{margin-left:66.66666667%}.offset-lg-9{margin-left:75%}.offset-lg-10{margin-left:83.33333333%}.offset-lg-11{margin-left:91.66666667%}.g-lg-0,.gx-lg-0{--bs-gutter-x:0}.g-lg-0,.gy-lg-0{--bs-gutter-y:0}.g-lg-1,.gx-lg-1{--bs-gutter-x:0.25rem}.g-lg-1,.gy-lg-1{--bs-gutter-y:0.25rem}.g-lg-2,.gx-lg-2{--bs-gutter-x:0.5rem}.g-lg-2,.gy-lg-2{--bs-gutter-y:0.5rem}.g-lg-3,.gx-lg-3{--bs-gutter-x:1rem}.g-lg-3,.gy-lg-3{--bs-gutter-y:1rem}.g-lg-4,.gx-lg-4{--bs-gutter-x:1.5rem}.g-lg-4,.gy-lg-4{--bs-gutter-y:1.5rem}.g-lg-5,.gx-lg-5{--bs-gutter-x:3rem}.g-lg-5,.gy-lg-5{--bs-gutter-y:3rem}}@media (min-width:1200px){.col-xl-auto{flex:0 0 auto;width:auto}.col-xl-1{flex:0 0 auto;width:8.33333333%}.col-xl-2{flex:0 0 auto;width:16.66666667%}.col-xl-3{flex:0 0 auto;width:25%}.col-xl-4{flex:0 0 auto;width:33.33333333%}.col-xl-5{flex:0 0 auto;width:41.66666667%}.col-xl-6{flex:0 0 auto;width:50%}.col-xl-7{flex:0 0 auto;width:58.33333333%}.col-xl-8{flex:0 0 auto;width:66.66666667%}.col-xl-9{flex:0 0 auto;width:75%}.col-xl-10{flex:0 0 auto;width:83.33333333%}.col-xl-11{flex:0 0 auto;width:91.66666667%}.col-xl-12{flex:0 0 auto;width:100%}.offset-xl-0{margin-left:0}.offset-xl-1{margin-left:8.33333333%}.offset-xl-2{margin-left:16.66666667%}.offset-xl-3{margin-left:25%}.offset-xl-4{margin-left:33.33333333%}.offset-xl-5{margin-left:41.66666667%}.offset-xl-6{margin-left:50%}.offset-xl-7{margin-left:58.33333333%}.offset-xl-8{margin-left:66.66666667%}.offset-xl-9{margin-left:75%}.offset-xl-10{margin-left:83.33333333%}.offset-xl-11{margin-left:91.66666667%}.g-xl-0,.gx-xl-0{--bs-gutter-x:0}.g-xl-0,.gy-xl-0{--bs-gutter-y:0}.g-xl-1,.gx-xl-1{--bs-gutter-x:0.25rem}.g-xl-1,.gy-xl-1{--bs-gutter-y:0.25rem}.g-xl-2,.gx-xl-2{--bs-gutter-x:0.5rem}.g-xl-2,.gy-xl-2{--bs-gutter-y:0.5rem}.g-xl-3,.gx-xl-3{--bs-gutter-x:1rem}.g-xl-3,.gy-xl-3{--bs-gutter-y:1rem}.g-xl-4,.gx-xl-4{--bs-gutter-x:1.5rem}.g-xl-4,.gy-xl-4{--bs-gutter-y:1.5rem}.g-xl-5,.gx-xl-5{--bs-gutter-x:3rem}.g-xl-5,.gy-xl-5{--bs-gutter-y:3rem}}@media (min-width:1400px){.col-xxl-auto{flex:0 0 auto;width:auto}.col-xxl-1{flex:0 0 auto;width:8.33333333%}.col-xxl-2{flex:0 0 auto;width:16.66666667%}.col-xxl-3{flex:0 0 auto;width:25%}.col-xxl-4{flex:0 0 auto;width:33.33333333%}.col-xxl-5{flex:0 0 auto;width:41.66666667%}.col-xxl-6{flex:0 0 auto;width:50%}.col-xxl-7{flex:0 0 auto;width:58.33333333%}.col-xxl-8{flex:0 0 auto;width:66.66666667%}.col-xxl-9{flex:0 0 auto;width:75%}.col-xxl-10{flex:0 0 auto;width:83.33333333%}.col-xxl-11{flex:0 0 auto;width:91.66666667%}.col-xxl-12{flex:0 0 auto;width:100%}.offset-xxl-0{margin-left:0}.offset-xxl-1{margin-left:8.33333333%}.offset-xxl-2{margin-left:16.66666667%}.offset-xxl-3{margin-left:25%}.offset-xxl-4{margin-left:33.33333333%}.offset-xxl-5{margin-left:41.66666667%}.offset-xxl-6{margin-left:50%}.offset-xxl-7{margin-left:58.33333333%}.offset-xxl-8{margin-left:66.66666667%}.offset-xxl-9{margin-left:75%}.offset-xxl-10{margin-left:83.33333333%}.offset-xxl-11{margin-left:91.66666667%}.g-xxl-0,.gx-xxl-0{--bs-gutter-x:0}.g-xxl-0,.gy-xxl-0{--bs-gutter-y:0}.g-xxl-1,.gx-xxl-1{--bs-gutter-x:0.25rem}.g-xxl-1,.gy-xxl-1{--bs-gutter-y:0.25rem}.g-xxl-2,.gx-xxl-2{--bs-gutter-x:0.5rem}.g-xxl-2,.gy-xxl-2{--bs-gutter-y:0.5rem}.g-xxl-3,.gx-xxl-3{--bs-gutter-x:1rem}.g-xxl-3,.gy-xxl-3{--bs-gutter-y:1rem}.g-xxl-4,.gx-xxl-4{--bs-gutter-x:1.5rem}.g-xxl-4,.gy-xxl-4{--bs-gutter-y:1.5rem}.g-xxl-5,.gx-xxl-5{--bs-gutter-x:3rem}.g-xxl-5,.gy-xxl-5{--bs-gutter-y:3rem}}.table{--bs-table-bg:transparent;--bs-table-accent-bg:transparent;--bs-table-striped-color:#212529;--bs-table-striped-bg:rgba(0, 0, 0, 0.05);--bs-table-active-color:#212529;--bs-table-active-bg:rgba(0, 0, 0, 0.1);--bs-table-hover-color:#212529;--bs-table-hover-bg:rgba(0, 0, 0, 0.075);width:100%;margin-bottom:1rem;color:#212529;vertical-align:top;border-color:#dee2e6}.table>:not(caption)>*>*{padding:.5rem .5rem;background-color:var(--bs-table-bg);border-bottom-width:1px;box-shadow:inset 0 0 0 9999px var(--bs-table-accent-bg)}.table>tbody{vertical-align:inherit}.table>thead{vertical-align:bottom}.table>:not(:last-child)>:last-child>*{border-bottom-color:currentColor}.caption-top{caption-side:top}.table-sm>:not(caption)>*>*{padding:.25rem .25rem}.table-bordered>:not(caption)>*{border-width:1px 0}.table-bordered>:not(caption)>*>*{border-width:0 1px}.table-borderless>:not(caption)>*>*{border-bottom-width:0}.table-striped>tbody>tr:nth-of-type(odd){--bs-table-accent-bg:var(--bs-table-striped-bg);color:var(--bs-table-striped-color)}.table-active{--bs-table-accent-bg:var(--bs-table-active-bg);color:var(--bs-table-active-color)}.table-hover>tbody>tr:hover{--bs-table-accent-bg:var(--bs-table-hover-bg);color:var(--bs-table-hover-color)}.table-primary{--bs-table-bg:#cfe2ff;--bs-table-striped-bg:#c5d7f2;--bs-table-striped-color:#000;--bs-table-active-bg:#bacbe6;--bs-table-active-color:#000;--bs-table-hover-bg:#bfd1ec;--bs-table-hover-color:#000;color:#000;border-color:#bacbe6}.table-secondary{--bs-table-bg:#e2e3e5;--bs-table-striped-bg:#d7d8da;--bs-table-striped-color:#000;--bs-table-active-bg:#cbccce;--bs-table-active-color:#000;--bs-table-hover-bg:#d1d2d4;--bs-table-hover-color:#000;color:#000;border-color:#cbccce}.table-success{--bs-table-bg:#d1e7dd;--bs-table-striped-bg:#c7dbd2;--bs-table-striped-color:#000;--bs-table-active-bg:#bcd0c7;--bs-table-active-color:#000;--bs-table-hover-bg:#c1d6cc;--bs-table-hover-color:#000;color:#000;border-color:#bcd0c7}.table-info{--bs-table-bg:#cff4fc;--bs-table-striped-bg:#c5e8ef;--bs-table-striped-color:#000;--bs-table-active-bg:#badce3;--bs-table-active-color:#000;--bs-table-hover-bg:#bfe2e9;--bs-table-hover-color:#000;color:#000;border-color:#badce3}.table-warning{--bs-table-bg:#fff3cd;--bs-table-striped-bg:#f2e7c3;--bs-table-striped-color:#000;--bs-table-active-bg:#e6dbb9;--bs-table-active-color:#000;--bs-table-hover-bg:#ece1be;--bs-table-hover-color:#000;color:#000;border-color:#e6dbb9}.table-danger{--bs-table-bg:#f8d7da;--bs-table-striped-bg:#eccccf;--bs-table-striped-color:#000;--bs-table-active-bg:#dfc2c4;--bs-table-active-color:#000;--bs-table-hover-bg:#e5c7ca;--bs-table-hover-color:#000;color:#000;border-color:#dfc2c4}.table-light{--bs-table-bg:#f8f9fa;--bs-table-striped-bg:#ecedee;--bs-table-striped-color:#000;--bs-table-active-bg:#dfe0e1;--bs-table-active-color:#000;--bs-table-hover-bg:#e5e6e7;--bs-table-hover-color:#000;color:#000;border-color:#dfe0e1}.table-dark{--bs-table-bg:#212529;--bs-table-striped-bg:#2c3034;--bs-table-striped-color:#fff;--bs-table-active-bg:#373b3e;--bs-table-active-color:#fff;--bs-table-hover-bg:#323539;--bs-table-hover-color:#fff;color:#fff;border-color:#373b3e}.table-responsive{overflow-x:auto;-webkit-overflow-scrolling:touch}@media (max-width:575.98px){.table-responsive-sm{overflow-x:auto;-webkit-overflow-scrolling:touch}}@media (max-width:767.98px){.table-responsive-md{overflow-x:auto;-webkit-overflow-scrolling:touch}}@media (max-width:991.98px){.table-responsive-lg{overflow-x:auto;-webkit-overflow-scrolling:touch}}@media (max-width:1199.98px){.table-responsive-xl{overflow-x:auto;-webkit-overflow-scrolling:touch}}@media (max-width:1399.98px){.table-responsive-xxl{overflow-x:auto;-webkit-overflow-scrolling:touch}}.form-label{margin-bottom:.5rem}.col-form-label{padding-top:calc(.375rem + 1px);padding-bottom:calc(.375rem + 1px);margin-bottom:0;font-size:inherit;line-height:1.5}.col-form-label-lg{padding-top:calc(.5rem + 1px);padding-bottom:calc(.5rem + 1px);font-size:1.25rem}.col-form-label-sm{padding-top:calc(.25rem + 1px);padding-bottom:calc(.25rem + 1px);font-size:.875rem}.form-text{margin-top:.25rem;font-size:.875em;color:#6c757d}.form-control{display:block;width:100%;padding:.375rem .75rem;font-size:1rem;font-weight:400;line-height:1.5;color:#212529;background-color:#fff;background-clip:padding-box;border:1px solid #ced4da;-webkit-appearance:none;-moz-appearance:none;appearance:none;border-radius:.25rem;transition:border-color .15s ease-in-out,box-shadow .15s ease-in-out}@media (prefers-reduced-motion:reduce){.form-control{transition:none}}.form-control[type=file]{overflow:hidden}.form-control[type=file]:not(:disabled):not([readonly]){cursor:pointer}.form-control:focus{color:#212529;background-color:#fff;border-color:#86b7fe;outline:0;box-shadow:0 0 0 .25rem rgba(13,110,253,.25)}.form-control::-webkit-date-and-time-value{height:1.5em}.form-control::-moz-placeholder{color:#6c757d;opacity:1}.form-control::placeholder{color:#6c757d;opacity:1}.form-control:disabled,.form-control[readonly]{background-color:#e9ecef;opacity:1}.form-control::file-selector-button{padding:.375rem .75rem;margin:-.375rem -.75rem;-webkit-margin-end:.75rem;margin-inline-end:.75rem;color:#212529;background-color:#e9ecef;pointer-events:none;border-color:inherit;border-style:solid;border-width:0;border-inline-end-width:1px;border-radius:0;transition:color .15s ease-in-out,background-color .15s ease-in-out,border-color .15s ease-in-out,box-shadow .15s ease-in-out}@media (prefers-reduced-motion:reduce){.form-control::file-selector-button{transition:none}}.form-control:hover:not(:disabled):not([readonly])::file-selector-button{background-color:#dde0e3}.form-control::-webkit-file-upload-button{padding:.375rem .75rem;margin:-.375rem -.75rem;-webkit-margin-end:.75rem;margin-inline-end:.75rem;color:#212529;background-color:#e9ecef;pointer-events:none;border-color:inherit;border-style:solid;border-width:0;border-inline-end-width:1px;border-radius:0;-webkit-transition:color .15s ease-in-out,background-color .15s ease-in-out,border-color .15s ease-in-out,box-shadow .15s ease-in-out;transition:color .15s ease-in-out,background-color .15s ease-in-out,border-color .15s ease-in-out,box-shadow .15s ease-in-out}@media (prefers-reduced-motion:reduce){.form-control::-webkit-file-upload-button{-webkit-transition:none;transition:none}}.form-control:hover:not(:disabled):not([readonly])::-webkit-file-upload-button{background-color:#dde0e3}.form-control-plaintext{display:block;width:100%;padding:.375rem 0;margin-bottom:0;line-height:1.5;color:#212529;background-color:transparent;border:solid transparent;border-width:1px 0}.form-control-plaintext.form-control-lg,.form-control-plaintext.form-control-sm{padding-right:0;padding-left:0}.form-control-sm{min-height:calc(1.5em + (.5rem + 2px));padding:.25rem .5rem;font-size:.875rem;border-radius:.2rem}.form-control-sm::file-selector-button{padding:.25rem .5rem;margin:-.25rem -.5rem;-webkit-margin-end:.5rem;margin-inline-end:.5rem}.form-control-sm::-webkit-file-upload-button{padding:.25rem .5rem;margin:-.25rem -.5rem;-webkit-margin-end:.5rem;margin-inline-end:.5rem}.form-control-lg{min-height:calc(1.5em + (1rem + 2px));padding:.5rem 1rem;font-size:1.25rem;border-radius:.3rem}.form-control-lg::file-selector-button{padding:.5rem 1rem;margin:-.5rem -1rem;-webkit-margin-end:1rem;margin-inline-end:1rem}.form-control-lg::-webkit-file-upload-button{padding:.5rem 1rem;margin:-.5rem -1rem;-webkit-margin-end:1rem;margin-inline-end:1rem}textarea.form-control{min-height:calc(1.5em + (.75rem + 2px))}textarea.form-control-sm{min-height:calc(1.5em + (.5rem + 2px))}textarea.form-control-lg{min-height:calc(1.5em + (1rem + 2px))}.form-control-color{max-width:3rem;height:auto;padding:.375rem}.form-control-color:not(:disabled):not([readonly]){cursor:pointer}.form-control-color::-moz-color-swatch{height:1.5em;border-radius:.25rem}.form-control-color::-webkit-color-swatch{height:1.5em;border-radius:.25rem}.form-select{display:block;width:100%;padding:.375rem 2.25rem .375rem .75rem;-moz-padding-start:calc(0.75rem - 3px);font-size:1rem;font-weight:400;line-height:1.5;color:#212529;background-color:#fff;background-image:url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 16 16'%3e%3cpath fill='none' stroke='%23343a40' stroke-linecap='round' stroke-linejoin='round' stroke-width='2' d='M2 5l6 6 6-6'/%3e%3c/svg%3e");background-repeat:no-repeat;background-position:right .75rem center;background-size:16px 12px;border:1px solid #ced4da;border-radius:.25rem;transition:border-color .15s ease-in-out,box-shadow .15s ease-in-out;-webkit-appearance:none;-moz-appearance:none;appearance:none}@media (prefers-reduced-motion:reduce){.form-select{transition:none}}.form-select:focus{border-color:#86b7fe;outline:0;box-shadow:0 0 0 .25rem rgba(13,110,253,.25)}.form-select[multiple],.form-select[size]:not([size="1"]){padding-right:.75rem;background-image:none}.form-select:disabled{background-color:#e9ecef}.form-select:-moz-focusring{color:transparent;text-shadow:0 0 0 #212529}.form-select-sm{padding-top:.25rem;padding-bottom:.25rem;padding-left:.5rem;font-size:.875rem}.form-select-lg{padding-top:.5rem;padding-bottom:.5rem;padding-left:1rem;font-size:1.25rem}.form-check{display:block;min-height:1.5rem;padding-left:1.5em;margin-bottom:.125rem}.form-check .form-check-input{float:left;margin-left:-1.5em}.form-check-input{width:1em;height:1em;margin-top:.25em;vertical-align:top;background-color:#fff;background-repeat:no-repeat;background-position:center;background-size:contain;border:1px solid rgba(0,0,0,.25);-webkit-appearance:none;-moz-appearance:none;appearance:none;-webkit-print-color-adjust:exact;color-adjust:exact}.form-check-input[type=checkbox]{border-radius:.25em}.form-check-input[type=radio]{border-radius:50%}.form-check-input:active{filter:brightness(90%)}.form-check-input:focus{border-color:#86b7fe;outline:0;box-shadow:0 0 0 .25rem rgba(13,110,253,.25)}.form-check-input:checked{background-color:#0d6efd;border-color:#0d6efd}.form-check-input:checked[type=checkbox]{background-image:url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 20 20'%3e%3cpath fill='none' stroke='%23fff' stroke-linecap='round' stroke-linejoin='round' stroke-width='3' d='M6 10l3 3l6-6'/%3e%3c/svg%3e")}.form-check-input:checked[type=radio]{background-image:url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' viewBox='-4 -4 8 8'%3e%3ccircle r='2' fill='%23fff'/%3e%3c/svg%3e")}.form-check-input[type=checkbox]:indeterminate{background-color:#0d6efd;border-color:#0d6efd;background-image:url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 20 20'%3e%3cpath fill='none' stroke='%23fff' stroke-linecap='round' stroke-linejoin='round' stroke-width='3' d='M6 10h8'/%3e%3c/svg%3e")}.form-check-input:disabled{pointer-events:none;filter:none;opacity:.5}.form-check-input:disabled~.form-check-label,.form-check-input[disabled]~.form-check-label{opacity:.5}.form-switch{padding-left:2.5em}.form-switch .form-check-input{width:2em;margin-left:-2.5em;background-image:url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' viewBox='-4 -4 8 8'%3e%3ccircle r='3' fill='rgba%280, 0, 0, 0.25%29'/%3e%3c/svg%3e");background-position:left center;border-radius:2em;transition:background-position .15s ease-in-out}@media (prefers-reduced-motion:reduce){.form-switch .form-check-input{transition:none}}.form-switch .form-check-input:focus{background-image:url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' viewBox='-4 -4 8 8'%3e%3ccircle r='3' fill='%2386b7fe'/%3e%3c/svg%3e")}.form-switch .form-check-input:checked{background-position:right center;background-image:url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' viewBox='-4 -4 8 8'%3e%3ccircle r='3' fill='%23fff'/%3e%3c/svg%3e")}.form-check-inline{display:inline-block;margin-right:1rem}.btn-check{position:absolute;clip:rect(0,0,0,0);pointer-events:none}.btn-check:disabled+.btn,.btn-check[disabled]+.btn{pointer-events:none;filter:none;opacity:.65}.form-range{width:100%;height:1.5rem;padding:0;background-color:transparent;-webkit-appearance:none;-moz-appearance:none;appearance:none}.form-range:focus{outline:0}.form-range:focus::-webkit-slider-thumb{box-shadow:0 0 0 1px #fff,0 0 0 .25rem rgba(13,110,253,.25)}.form-range:focus::-moz-range-thumb{box-shadow:0 0 0 1px #fff,0 0 0 .25rem rgba(13,110,253,.25)}.form-range::-moz-focus-outer{border:0}.form-range::-webkit-slider-thumb{width:1rem;height:1rem;margin-top:-.25rem;background-color:#0d6efd;border:0;border-radius:1rem;-webkit-transition:background-color .15s ease-in-out,border-color .15s ease-in-out,box-shadow .15s ease-in-out;transition:background-color .15s ease-in-out,border-color .15s ease-in-out,box-shadow .15s ease-in-out;-webkit-appearance:none;appearance:none}@media (prefers-reduced-motion:reduce){.form-range::-webkit-slider-thumb{-webkit-transition:none;transition:none}}.form-range::-webkit-slider-thumb:active{background-color:#b6d4fe}.form-range::-webkit-slider-runnable-track{width:100%;height:.5rem;color:transparent;cursor:pointer;background-color:#dee2e6;border-color:transparent;border-radius:1rem}.form-range::-moz-range-thumb{width:1rem;height:1rem;background-color:#0d6efd;border:0;border-radius:1rem;-moz-transition:background-color .15s ease-in-out,border-color .15s ease-in-out,box-shadow .15s ease-in-out;transition:background-color .15s ease-in-out,border-color .15s ease-in-out,box-shadow .15s ease-in-out;-moz-appearance:none;appearance:none}@media (prefers-reduced-motion:reduce){.form-range::-moz-range-thumb{-moz-transition:none;transition:none}}.form-range::-moz-range-thumb:active{background-color:#b6d4fe}.form-range::-moz-range-track{width:100%;height:.5rem;color:transparent;cursor:pointer;background-color:#dee2e6;border-color:transparent;border-radius:1rem}.form-range:disabled{pointer-events:none}.form-range:disabled::-webkit-slider-thumb{background-color:#adb5bd}.form-range:disabled::-moz-range-thumb{background-color:#adb5bd}.form-floating{position:relative}.form-floating>.form-control,.form-floating>.form-select{height:calc(3.5rem + 2px);line-height:1.25}.form-floating>label{position:absolute;top:0;left:0;height:100%;padding:1rem .75rem;pointer-events:none;border:1px solid transparent;transform-origin:0 0;transition:opacity .1s ease-in-out,transform .1s ease-in-out}@media (prefers-reduced-motion:reduce){.form-floating>label{transition:none}}.form-floating>.form-control{padding:1rem .75rem}.form-floating>.form-control::-moz-placeholder{color:transparent}.form-floating>.form-control::placeholder{color:transparent}.form-floating>.form-control:not(:-moz-placeholder-shown){padding-top:1.625rem;padding-bottom:.625rem}.form-floating>.form-control:focus,.form-floating>.form-control:not(:placeholder-shown){padding-top:1.625rem;padding-bottom:.625rem}.form-floating>.form-control:-webkit-autofill{padding-top:1.625rem;padding-bottom:.625rem}.form-floating>.form-select{padding-top:1.625rem;padding-bottom:.625rem}.form-floating>.form-control:not(:-moz-placeholder-shown)~label{opacity:.65;transform:scale(.85) translateY(-.5rem) translateX(.15rem)}.form-floating>.form-control:focus~label,.form-floating>.form-control:not(:placeholder-shown)~label,.form-floating>.form-select~label{opacity:.65;transform:scale(.85) translateY(-.5rem) translateX(.15rem)}.form-floating>.form-control:-webkit-autofill~label{opacity:.65;transform:scale(.85) translateY(-.5rem) translateX(.15rem)}.input-group{position:relative;display:flex;flex-wrap:wrap;align-items:stretch;width:100%}.input-group>.form-control,.input-group>.form-select{position:relative;flex:1 1 auto;width:1%;min-width:0}.input-group>.form-control:focus,.input-group>.form-select:focus{z-index:3}.input-group .btn{position:relative;z-index:2}.input-group .btn:focus{z-index:3}.input-group-text{display:flex;align-items:center;padding:.375rem .75rem;font-size:1rem;font-weight:400;line-height:1.5;color:#212529;text-align:center;white-space:nowrap;background-color:#e9ecef;border:1px solid #ced4da;border-radius:.25rem}.input-group-lg>.btn,.input-group-lg>.form-control,.input-group-lg>.form-select,.input-group-lg>.input-group-text{padding:.5rem 1rem;font-size:1.25rem;border-radius:.3rem}.input-group-sm>.btn,.input-group-sm>.form-control,.input-group-sm>.form-select,.input-group-sm>.input-group-text{padding:.25rem .5rem;font-size:.875rem;border-radius:.2rem}.input-group-lg>.form-select,.input-group-sm>.form-select{padding-right:3rem}.input-group:not(.has-validation)>.dropdown-toggle:nth-last-child(n+3),.input-group:not(.has-validation)>:not(:last-child):not(.dropdown-toggle):not(.dropdown-menu){border-top-right-radius:0;border-bottom-right-radius:0}.input-group.has-validation>.dropdown-toggle:nth-last-child(n+4),.input-group.has-validation>:nth-last-child(n+3):not(.dropdown-toggle):not(.dropdown-menu){border-top-right-radius:0;border-bottom-right-radius:0}.input-group>:not(:first-child):not(.dropdown-menu):not(.valid-tooltip):not(.valid-feedback):not(.invalid-tooltip):not(.invalid-feedback){margin-left:-1px;border-top-left-radius:0;border-bottom-left-radius:0}.valid-feedback{display:none;width:100%;margin-top:.25rem;font-size:.875em;color:#198754}.valid-tooltip{position:absolute;top:100%;z-index:5;display:none;max-width:100%;padding:.25rem .5rem;margin-top:.1rem;font-size:.875rem;color:#fff;background-color:rgba(25,135,84,.9);border-radius:.25rem}.is-valid~.valid-feedback,.is-valid~.valid-tooltip,.was-validated :valid~.valid-feedback,.was-validated :valid~.valid-tooltip{display:block}.form-control.is-valid,.was-validated .form-control:valid{border-color:#198754;padding-right:calc(1.5em + .75rem);background-image:url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 8 8'%3e%3cpath fill='%23198754' d='M2.3 6.73L.6 4.53c-.4-1.04.46-1.4 1.1-.8l1.1 1.4 3.4-3.8c.6-.63 1.6-.27 1.2.7l-4 4.6c-.43.5-.8.4-1.1.1z'/%3e%3c/svg%3e");background-repeat:no-repeat;background-position:right calc(.375em + .1875rem) center;background-size:calc(.75em + .375rem) calc(.75em + .375rem)}.form-control.is-valid:focus,.was-validated .form-control:valid:focus{border-color:#198754;box-shadow:0 0 0 .25rem rgba(25,135,84,.25)}.was-validated textarea.form-control:valid,textarea.form-control.is-valid{padding-right:calc(1.5em + .75rem);background-position:top calc(.375em + .1875rem) right calc(.375em + .1875rem)}.form-select.is-valid,.was-validated .form-select:valid{border-color:#198754}.form-select.is-valid:not([multiple]):not([size]),.form-select.is-valid:not([multiple])[size="1"],.was-validated .form-select:valid:not([multiple]):not([size]),.was-validated .form-select:valid:not([multiple])[size="1"]{padding-right:4.125rem;background-image:url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 16 16'%3e%3cpath fill='none' stroke='%23343a40' stroke-linecap='round' stroke-linejoin='round' stroke-width='2' d='M2 5l6 6 6-6'/%3e%3c/svg%3e"),url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 8 8'%3e%3cpath fill='%23198754' d='M2.3 6.73L.6 4.53c-.4-1.04.46-1.4 1.1-.8l1.1 1.4 3.4-3.8c.6-.63 1.6-.27 1.2.7l-4 4.6c-.43.5-.8.4-1.1.1z'/%3e%3c/svg%3e");background-position:right .75rem center,center right 2.25rem;background-size:16px 12px,calc(.75em + .375rem) calc(.75em + .375rem)}.form-select.is-valid:focus,.was-validated .form-select:valid:focus{border-color:#198754;box-shadow:0 0 0 .25rem rgba(25,135,84,.25)}.form-check-input.is-valid,.was-validated .form-check-input:valid{border-color:#198754}.form-check-input.is-valid:checked,.was-validated .form-check-input:valid:checked{background-color:#198754}.form-check-input.is-valid:focus,.was-validated .form-check-input:valid:focus{box-shadow:0 0 0 .25rem rgba(25,135,84,.25)}.form-check-input.is-valid~.form-check-label,.was-validated .form-check-input:valid~.form-check-label{color:#198754}.form-check-inline .form-check-input~.valid-feedback{margin-left:.5em}.input-group .form-control.is-valid,.input-group .form-select.is-valid,.was-validated .input-group .form-control:valid,.was-validated .input-group .form-select:valid{z-index:1}.input-group .form-control.is-valid:focus,.input-group .form-select.is-valid:focus,.was-validated .input-group .form-control:valid:focus,.was-validated .input-group .form-select:valid:focus{z-index:3}.invalid-feedback{display:none;width:100%;margin-top:.25rem;font-size:.875em;color:#dc3545}.invalid-tooltip{position:absolute;top:100%;z-index:5;display:none;max-width:100%;padding:.25rem .5rem;margin-top:.1rem;font-size:.875rem;color:#fff;background-color:rgba(220,53,69,.9);border-radius:.25rem}.is-invalid~.invalid-feedback,.is-invalid~.invalid-tooltip,.was-validated :invalid~.invalid-feedback,.was-validated :invalid~.invalid-tooltip{display:block}.form-control.is-invalid,.was-validated .form-control:invalid{border-color:#dc3545;padding-right:calc(1.5em + .75rem);background-image:url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 12 12' width='12' height='12' fill='none' stroke='%23dc3545'%3e%3ccircle cx='6' cy='6' r='4.5'/%3e%3cpath stroke-linejoin='round' d='M5.8 3.6h.4L6 6.5z'/%3e%3ccircle cx='6' cy='8.2' r='.6' fill='%23dc3545' stroke='none'/%3e%3c/svg%3e");background-repeat:no-repeat;background-position:right calc(.375em + .1875rem) center;background-size:calc(.75em + .375rem) calc(.75em + .375rem)}.form-control.is-invalid:focus,.was-validated .form-control:invalid:focus{border-color:#dc3545;box-shadow:0 0 0 .25rem rgba(220,53,69,.25)}.was-validated textarea.form-control:invalid,textarea.form-control.is-invalid{padding-right:calc(1.5em + .75rem);background-position:top calc(.375em + .1875rem) right calc(.375em + .1875rem)}.form-select.is-invalid,.was-validated .form-select:invalid{border-color:#dc3545}.form-select.is-invalid:not([multiple]):not([size]),.form-select.is-invalid:not([multiple])[size="1"],.was-validated .form-select:invalid:not([multiple]):not([size]),.was-validated .form-select:invalid:not([multiple])[size="1"]{padding-right:4.125rem;background-image:url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 16 16'%3e%3cpath fill='none' stroke='%23343a40' stroke-linecap='round' stroke-linejoin='round' stroke-width='2' d='M2 5l6 6 6-6'/%3e%3c/svg%3e"),url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 12 12' width='12' height='12' fill='none' stroke='%23dc3545'%3e%3ccircle cx='6' cy='6' r='4.5'/%3e%3cpath stroke-linejoin='round' d='M5.8 3.6h.4L6 6.5z'/%3e%3ccircle cx='6' cy='8.2' r='.6' fill='%23dc3545' stroke='none'/%3e%3c/svg%3e");background-position:right .75rem center,center right 2.25rem;background-size:16px 12px,calc(.75em + .375rem) calc(.75em + .375rem)}.form-select.is-invalid:focus,.was-validated .form-select:invalid:focus{border-color:#dc3545;box-shadow:0 0 0 .25rem rgba(220,53,69,.25)}.form-check-input.is-invalid,.was-validated .form-check-input:invalid{border-color:#dc3545}.form-check-input.is-invalid:checked,.was-validated .form-check-input:invalid:checked{background-color:#dc3545}.form-check-input.is-invalid:focus,.was-validated .form-check-input:invalid:focus{box-shadow:0 0 0 .25rem rgba(220,53,69,.25)}.form-check-input.is-invalid~.form-check-label,.was-validated .form-check-input:invalid~.form-check-label{color:#dc3545}.form-check-inline .form-check-input~.invalid-feedback{margin-left:.5em}.input-group .form-control.is-invalid,.input-group .form-select.is-invalid,.was-validated .input-group .form-control:invalid,.was-validated .input-group .form-select:invalid{z-index:2}.input-group .form-control.is-invalid:focus,.input-group .form-select.is-invalid:focus,.was-validated .input-group .form-control:invalid:focus,.was-validated .input-group .form-select:invalid:focus{z-index:3}.btn{display:inline-block;font-weight:400;line-height:1.5;color:#212529;text-align:center;text-decoration:none;vertical-align:middle;cursor:pointer;-webkit-user-select:none;-moz-user-select:none;user-select:none;background-color:transparent;border:1px solid transparent;padding:.375rem .75rem;font-size:1rem;border-radius:.25rem;transition:color .15s ease-in-out,background-color .15s ease-in-out,border-color .15s ease-in-out,box-shadow .15s ease-in-out}@media (prefers-reduced-motion:reduce){.btn{transition:none}}.btn:hover{color:#212529}.btn-check:focus+.btn,.btn:focus{outline:0;box-shadow:0 0 0 .25rem rgba(13,110,253,.25)}.btn.disabled,.btn:disabled,fieldset:disabled .btn{pointer-events:none;opacity:.65}.btn-primary{color:#fff;background-color:#0d6efd;border-color:#0d6efd}.btn-primary:hover{color:#fff;background-color:#0b5ed7;border-color:#0a58ca}.btn-check:focus+.btn-primary,.btn-primary:focus{color:#fff;background-color:#0b5ed7;border-color:#0a58ca;box-shadow:0 0 0 .25rem rgba(49,132,253,.5)}.btn-check:active+.btn-primary,.btn-check:checked+.btn-primary,.btn-primary.active,.btn-primary:active,.show>.btn-primary.dropdown-toggle{color:#fff;background-color:#0a58ca;border-color:#0a53be}.btn-check:active+.btn-primary:focus,.btn-check:checked+.btn-primary:focus,.btn-primary.active:focus,.btn-primary:active:focus,.show>.btn-primary.dropdown-toggle:focus{box-shadow:0 0 0 .25rem rgba(49,132,253,.5)}.btn-primary.disabled,.btn-primary:disabled{color:#fff;background-color:#0d6efd;border-color:#0d6efd}.btn-secondary{color:#fff;background-color:#6c757d;border-color:#6c757d}.btn-secondary:hover{color:#fff;background-color:#5c636a;border-color:#565e64}.btn-check:focus+.btn-secondary,.btn-secondary:focus{color:#fff;background-color:#5c636a;border-color:#565e64;box-shadow:0 0 0 .25rem rgba(130,138,145,.5)}.btn-check:active+.btn-secondary,.btn-check:checked+.btn-secondary,.btn-secondary.active,.btn-secondary:active,.show>.btn-secondary.dropdown-toggle{color:#fff;background-color:#565e64;border-color:#51585e}.btn-check:active+.btn-secondary:focus,.btn-check:checked+.btn-secondary:focus,.btn-secondary.active:focus,.btn-secondary:active:focus,.show>.btn-secondary.dropdown-toggle:focus{box-shadow:0 0 0 .25rem rgba(130,138,145,.5)}.btn-secondary.disabled,.btn-secondary:disabled{color:#fff;background-color:#6c757d;border-color:#6c757d}.btn-success{color:#fff;background-color:#198754;border-color:#198754}.btn-success:hover{color:#fff;background-color:#157347;border-color:#146c43}.btn-check:focus+.btn-success,.btn-success:focus{color:#fff;background-color:#157347;border-color:#146c43;box-shadow:0 0 0 .25rem rgba(60,153,110,.5)}.btn-check:active+.btn-success,.btn-check:checked+.btn-success,.btn-success.active,.btn-success:active,.show>.btn-success.dropdown-toggle{color:#fff;background-color:#146c43;border-color:#13653f}.btn-check:active+.btn-success:focus,.btn-check:checked+.btn-success:focus,.btn-success.active:focus,.btn-success:active:focus,.show>.btn-success.dropdown-toggle:focus{box-shadow:0 0 0 .25rem rgba(60,153,110,.5)}.btn-success.disabled,.btn-success:disabled{color:#fff;background-color:#198754;border-color:#198754}.btn-info{color:#000;background-color:#0dcaf0;border-color:#0dcaf0}.btn-info:hover{color:#000;background-color:#31d2f2;border-color:#25cff2}.btn-check:focus+.btn-info,.btn-info:focus{color:#000;background-color:#31d2f2;border-color:#25cff2;box-shadow:0 0 0 .25rem rgba(11,172,204,.5)}.btn-check:active+.btn-info,.btn-check:checked+.btn-info,.btn-info.active,.btn-info:active,.show>.btn-info.dropdown-toggle{color:#000;background-color:#3dd5f3;border-color:#25cff2}.btn-check:active+.btn-info:focus,.btn-check:checked+.btn-info:focus,.btn-info.active:focus,.btn-info:active:focus,.show>.btn-info.dropdown-toggle:focus{box-shadow:0 0 0 .25rem rgba(11,172,204,.5)}.btn-info.disabled,.btn-info:disabled{color:#000;background-color:#0dcaf0;border-color:#0dcaf0}.btn-warning{color:#000;background-color:#ffc107;border-color:#ffc107}.btn-warning:hover{color:#000;background-color:#ffca2c;border-color:#ffc720}.btn-check:focus+.btn-warning,.btn-warning:focus{color:#000;background-color:#ffca2c;border-color:#ffc720;box-shadow:0 0 0 .25rem rgba(217,164,6,.5)}.btn-check:active+.btn-warning,.btn-check:checked+.btn-warning,.btn-warning.active,.btn-warning:active,.show>.btn-warning.dropdown-toggle{color:#000;background-color:#ffcd39;border-color:#ffc720}.btn-check:active+.btn-warning:focus,.btn-check:checked+.btn-warning:focus,.btn-warning.active:focus,.btn-warning:active:focus,.show>.btn-warning.dropdown-toggle:focus{box-shadow:0 0 0 .25rem rgba(217,164,6,.5)}.btn-warning.disabled,.btn-warning:disabled{color:#000;background-color:#ffc107;border-color:#ffc107}.btn-danger{color:#fff;background-color:#dc3545;border-color:#dc3545}.btn-danger:hover{color:#fff;background-color:#bb2d3b;border-color:#b02a37}.btn-check:focus+.btn-danger,.btn-danger:focus{color:#fff;background-color:#bb2d3b;border-color:#b02a37;box-shadow:0 0 0 .25rem rgba(225,83,97,.5)}.btn-check:active+.btn-danger,.btn-check:checked+.btn-danger,.btn-danger.active,.btn-danger:active,.show>.btn-danger.dropdown-toggle{color:#fff;background-color:#b02a37;border-color:#a52834}.btn-check:active+.btn-danger:focus,.btn-check:checked+.btn-danger:focus,.btn-danger.active:focus,.btn-danger:active:focus,.show>.btn-danger.dropdown-toggle:focus{box-shadow:0 0 0 .25rem rgba(225,83,97,.5)}.btn-danger.disabled,.btn-danger:disabled{color:#fff;background-color:#dc3545;border-color:#dc3545}.btn-light{color:#000;background-color:#f8f9fa;border-color:#f8f9fa}.btn-light:hover{color:#000;background-color:#f9fafb;border-color:#f9fafb}.btn-check:focus+.btn-light,.btn-light:focus{color:#000;background-color:#f9fafb;border-color:#f9fafb;box-shadow:0 0 0 .25rem rgba(211,212,213,.5)}.btn-check:active+.btn-light,.btn-check:checked+.btn-light,.btn-light.active,.btn-light:active,.show>.btn-light.dropdown-toggle{color:#000;background-color:#f9fafb;border-color:#f9fafb}.btn-check:active+.btn-light:focus,.btn-check:checked+.btn-light:focus,.btn-light.active:focus,.btn-light:active:focus,.show>.btn-light.dropdown-toggle:focus{box-shadow:0 0 0 .25rem rgba(211,212,213,.5)}.btn-light.disabled,.btn-light:disabled{color:#000;background-color:#f8f9fa;border-color:#f8f9fa}.btn-dark{color:#fff;background-color:#212529;border-color:#212529}.btn-dark:hover{color:#fff;background-color:#1c1f23;border-color:#1a1e21}.btn-check:focus+.btn-dark,.btn-dark:focus{color:#fff;background-color:#1c1f23;border-color:#1a1e21;box-shadow:0 0 0 .25rem rgba(66,70,73,.5)}.btn-check:active+.btn-dark,.btn-check:checked+.btn-dark,.btn-dark.active,.btn-dark:active,.show>.btn-dark.dropdown-toggle{color:#fff;background-color:#1a1e21;border-color:#191c1f}.btn-check:active+.btn-dark:focus,.btn-check:checked+.btn-dark:focus,.btn-dark.active:focus,.btn-dark:active:focus,.show>.btn-dark.dropdown-toggle:focus{box-shadow:0 0 0 .25rem rgba(66,70,73,.5)}.btn-dark.disabled,.btn-dark:disabled{color:#fff;background-color:#212529;border-color:#212529}.btn-outline-primary{color:#0d6efd;border-color:#0d6efd}.btn-outline-primary:hover{color:#fff;background-color:#0d6efd;border-color:#0d6efd}.btn-check:focus+.btn-outline-primary,.btn-outline-primary:focus{box-shadow:0 0 0 .25rem rgba(13,110,253,.5)}.btn-check:active+.btn-outline-primary,.btn-check:checked+.btn-outline-primary,.btn-outline-primary.active,.btn-outline-primary.dropdown-toggle.show,.btn-outline-primary:active{color:#fff;background-color:#0d6efd;border-color:#0d6efd}.btn-check:active+.btn-outline-primary:focus,.btn-check:checked+.btn-outline-primary:focus,.btn-outline-primary.active:focus,.btn-outline-primary.dropdown-toggle.show:focus,.btn-outline-primary:active:focus{box-shadow:0 0 0 .25rem rgba(13,110,253,.5)}.btn-outline-primary.disabled,.btn-outline-primary:disabled{color:#0d6efd;background-color:transparent}.btn-outline-secondary{color:#6c757d;border-color:#6c757d}.btn-outline-secondary:hover{color:#fff;background-color:#6c757d;border-color:#6c757d}.btn-check:focus+.btn-outline-secondary,.btn-outline-secondary:focus{box-shadow:0 0 0 .25rem rgba(108,117,125,.5)}.btn-check:active+.btn-outline-secondary,.btn-check:checked+.btn-outline-secondary,.btn-outline-secondary.active,.btn-outline-secondary.dropdown-toggle.show,.btn-outline-secondary:active{color:#fff;background-color:#6c757d;border-color:#6c757d}.btn-check:active+.btn-outline-secondary:focus,.btn-check:checked+.btn-outline-secondary:focus,.btn-outline-secondary.active:focus,.btn-outline-secondary.dropdown-toggle.show:focus,.btn-outline-secondary:active:focus{box-shadow:0 0 0 .25rem rgba(108,117,125,.5)}.btn-outline-secondary.disabled,.btn-outline-secondary:disabled{color:#6c757d;background-color:transparent}.btn-outline-success{color:#198754;border-color:#198754}.btn-outline-success:hover{color:#fff;background-color:#198754;border-color:#198754}.btn-check:focus+.btn-outline-success,.btn-outline-success:focus{box-shadow:0 0 0 .25rem rgba(25,135,84,.5)}.btn-check:active+.btn-outline-success,.btn-check:checked+.btn-outline-success,.btn-outline-success.active,.btn-outline-success.dropdown-toggle.show,.btn-outline-success:active{color:#fff;background-color:#198754;border-color:#198754}.btn-check:active+.btn-outline-success:focus,.btn-check:checked+.btn-outline-success:focus,.btn-outline-success.active:focus,.btn-outline-success.dropdown-toggle.show:focus,.btn-outline-success:active:focus{box-shadow:0 0 0 .25rem rgba(25,135,84,.5)}.btn-outline-success.disabled,.btn-outline-success:disabled{color:#198754;background-color:transparent}.btn-outline-info{color:#0dcaf0;border-color:#0dcaf0}.btn-outline-info:hover{color:#000;background-color:#0dcaf0;border-color:#0dcaf0}.btn-check:focus+.btn-outline-info,.btn-outline-info:focus{box-shadow:0 0 0 .25rem rgba(13,202,240,.5)}.btn-check:active+.btn-outline-info,.btn-check:checked+.btn-outline-info,.btn-outline-info.active,.btn-outline-info.dropdown-toggle.show,.btn-outline-info:active{color:#000;background-color:#0dcaf0;border-color:#0dcaf0}.btn-check:active+.btn-outline-info:focus,.btn-check:checked+.btn-outline-info:focus,.btn-outline-info.active:focus,.btn-outline-info.dropdown-toggle.show:focus,.btn-outline-info:active:focus{box-shadow:0 0 0 .25rem rgba(13,202,240,.5)}.btn-outline-info.disabled,.btn-outline-info:disabled{color:#0dcaf0;background-color:transparent}.btn-outline-warning{color:#ffc107;border-color:#ffc107}.btn-outline-warning:hover{color:#000;background-color:#ffc107;border-color:#ffc107}.btn-check:focus+.btn-outline-warning,.btn-outline-warning:focus{box-shadow:0 0 0 .25rem rgba(255,193,7,.5)}.btn-check:active+.btn-outline-warning,.btn-check:checked+.btn-outline-warning,.btn-outline-warning.active,.btn-outline-warning.dropdown-toggle.show,.btn-outline-warning:active{color:#000;background-color:#ffc107;border-color:#ffc107}.btn-check:active+.btn-outline-warning:focus,.btn-check:checked+.btn-outline-warning:focus,.btn-outline-warning.active:focus,.btn-outline-warning.dropdown-toggle.show:focus,.btn-outline-warning:active:focus{box-shadow:0 0 0 .25rem rgba(255,193,7,.5)}.btn-outline-warning.disabled,.btn-outline-warning:disabled{color:#ffc107;background-color:transparent}.btn-outline-danger{color:#dc3545;border-color:#dc3545}.btn-outline-danger:hover{color:#fff;background-color:#dc3545;border-color:#dc3545}.btn-check:focus+.btn-outline-danger,.btn-outline-danger:focus{box-shadow:0 0 0 .25rem rgba(220,53,69,.5)}.btn-check:active+.btn-outline-danger,.btn-check:checked+.btn-outline-danger,.btn-outline-danger.active,.btn-outline-danger.dropdown-toggle.show,.btn-outline-danger:active{color:#fff;background-color:#dc3545;border-color:#dc3545}.btn-check:active+.btn-outline-danger:focus,.btn-check:checked+.btn-outline-danger:focus,.btn-outline-danger.active:focus,.btn-outline-danger.dropdown-toggle.show:focus,.btn-outline-danger:active:focus{box-shadow:0 0 0 .25rem rgba(220,53,69,.5)}.btn-outline-danger.disabled,.btn-outline-danger:disabled{color:#dc3545;background-color:transparent}.btn-outline-light{color:#f8f9fa;border-color:#f8f9fa}.btn-outline-light:hover{color:#000;background-color:#f8f9fa;border-color:#f8f9fa}.btn-check:focus+.btn-outline-light,.btn-outline-light:focus{box-shadow:0 0 0 .25rem rgba(248,249,250,.5)}.btn-check:active+.btn-outline-light,.btn-check:checked+.btn-outline-light,.btn-outline-light.active,.btn-outline-light.dropdown-toggle.show,.btn-outline-light:active{color:#000;background-color:#f8f9fa;border-color:#f8f9fa}.btn-check:active+.btn-outline-light:focus,.btn-check:checked+.btn-outline-light:focus,.btn-outline-light.active:focus,.btn-outline-light.dropdown-toggle.show:focus,.btn-outline-light:active:focus{box-shadow:0 0 0 .25rem rgba(248,249,250,.5)}.btn-outline-light.disabled,.btn-outline-light:disabled{color:#f8f9fa;background-color:transparent}.btn-outline-dark{color:#212529;border-color:#212529}.btn-outline-dark:hover{color:#fff;background-color:#212529;border-color:#212529}.btn-check:focus+.btn-outline-dark,.btn-outline-dark:focus{box-shadow:0 0 0 .25rem rgba(33,37,41,.5)}.btn-check:active+.btn-outline-dark,.btn-check:checked+.btn-outline-dark,.btn-outline-dark.active,.btn-outline-dark.dropdown-toggle.show,.btn-outline-dark:active{color:#fff;background-color:#212529;border-color:#212529}.btn-check:active+.btn-outline-dark:focus,.btn-check:checked+.btn-outline-dark:focus,.btn-outline-dark.active:focus,.btn-outline-dark.dropdown-toggle.show:focus,.btn-outline-dark:active:focus{box-shadow:0 0 0 .25rem rgba(33,37,41,.5)}.btn-outline-dark.disabled,.btn-outline-dark:disabled{color:#212529;background-color:transparent}.btn-link{font-weight:400;color:#0d6efd;text-decoration:underline}.btn-link:hover{color:#0a58ca}.btn-link.disabled,.btn-link:disabled{color:#6c757d}.btn-group-lg>.btn,.btn-lg{padding:.5rem 1rem;font-size:1.25rem;border-radius:.3rem}.btn-group-sm>.btn,.btn-sm{padding:.25rem .5rem;font-size:.875rem;border-radius:.2rem}.fade{transition:opacity .15s linear}@media (prefers-reduced-motion:reduce){.fade{transition:none}}.fade:not(.show){opacity:0}.collapse:not(.show){display:none}.collapsing{height:0;overflow:hidden;transition:height .35s ease}@media (prefers-reduced-motion:reduce){.collapsing{transition:none}}.dropdown,.dropend,.dropstart,.dropup{position:relative}.dropdown-toggle{white-space:nowrap}.dropdown-toggle::after{display:inline-block;margin-left:.255em;vertical-align:.255em;content:"";border-top:.3em solid;border-right:.3em solid transparent;border-bottom:0;border-left:.3em solid transparent}.dropdown-toggle:empty::after{margin-left:0}.dropdown-menu{position:absolute;z-index:1000;display:none;min-width:10rem;padding:.5rem 0;margin:0;font-size:1rem;color:#212529;text-align:left;list-style:none;background-color:#fff;background-clip:padding-box;border:1px solid rgba(0,0,0,.15);border-radius:.25rem}.dropdown-menu[data-bs-popper]{top:100%;left:0;margin-top:.125rem}.dropdown-menu-start{--bs-position:start}.dropdown-menu-start[data-bs-popper]{right:auto;left:0}.dropdown-menu-end{--bs-position:end}.dropdown-menu-end[data-bs-popper]{right:0;left:auto}@media (min-width:576px){.dropdown-menu-sm-start{--bs-position:start}.dropdown-menu-sm-start[data-bs-popper]{right:auto;left:0}.dropdown-menu-sm-end{--bs-position:end}.dropdown-menu-sm-end[data-bs-popper]{right:0;left:auto}}@media (min-width:768px){.dropdown-menu-md-start{--bs-position:start}.dropdown-menu-md-start[data-bs-popper]{right:auto;left:0}.dropdown-menu-md-end{--bs-position:end}.dropdown-menu-md-end[data-bs-popper]{right:0;left:auto}}@media (min-width:992px){.dropdown-menu-lg-start{--bs-position:start}.dropdown-menu-lg-start[data-bs-popper]{right:auto;left:0}.dropdown-menu-lg-end{--bs-position:end}.dropdown-menu-lg-end[data-bs-popper]{right:0;left:auto}}@media (min-width:1200px){.dropdown-menu-xl-start{--bs-position:start}.dropdown-menu-xl-start[data-bs-popper]{right:auto;left:0}.dropdown-menu-xl-end{--bs-position:end}.dropdown-menu-xl-end[data-bs-popper]{right:0;left:auto}}@media (min-width:1400px){.dropdown-menu-xxl-start{--bs-position:start}.dropdown-menu-xxl-start[data-bs-popper]{right:auto;left:0}.dropdown-menu-xxl-end{--bs-position:end}.dropdown-menu-xxl-end[data-bs-popper]{right:0;left:auto}}.dropup .dropdown-menu[data-bs-popper]{top:auto;bottom:100%;margin-top:0;margin-bottom:.125rem}.dropup .dropdown-toggle::after{display:inline-block;margin-left:.255em;vertical-align:.255em;content:"";border-top:0;border-right:.3em solid transparent;border-bottom:.3em solid;border-left:.3em solid transparent}.dropup .dropdown-toggle:empty::after{margin-left:0}.dropend .dropdown-menu[data-bs-popper]{top:0;right:auto;left:100%;margin-top:0;margin-left:.125rem}.dropend .dropdown-toggle::after{display:inline-block;margin-left:.255em;vertical-align:.255em;content:"";border-top:.3em solid transparent;border-right:0;border-bottom:.3em solid transparent;border-left:.3em solid}.dropend .dropdown-toggle:empty::after{margin-left:0}.dropend .dropdown-toggle::after{vertical-align:0}.dropstart .dropdown-menu[data-bs-popper]{top:0;right:100%;left:auto;margin-top:0;margin-right:.125rem}.dropstart .dropdown-toggle::after{display:inline-block;margin-left:.255em;vertical-align:.255em;content:""}.dropstart .dropdown-toggle::after{display:none}.dropstart .dropdown-toggle::before{display:inline-block;margin-right:.255em;vertical-align:.255em;content:"";border-top:.3em solid transparent;border-right:.3em solid;border-bottom:.3em solid transparent}.dropstart .dropdown-toggle:empty::after{margin-left:0}.dropstart .dropdown-toggle::before{vertical-align:0}.dropdown-divider{height:0;margin:.5rem 0;overflow:hidden;border-top:1px solid rgba(0,0,0,.15)}.dropdown-item{display:block;width:100%;padding:.25rem 1rem;clear:both;font-weight:400;color:#212529;text-align:inherit;text-decoration:none;white-space:nowrap;background-color:transparent;border:0}.dropdown-item:focus,.dropdown-item:hover{color:#1e2125;background-color:#e9ecef}.dropdown-item.active,.dropdown-item:active{color:#fff;text-decoration:none;background-color:#0d6efd}.dropdown-item.disabled,.dropdown-item:disabled{color:#adb5bd;pointer-events:none;background-color:transparent}.dropdown-menu.show{display:block}.dropdown-header{display:block;padding:.5rem 1rem;margin-bottom:0;font-size:.875rem;color:#6c757d;white-space:nowrap}.dropdown-item-text{display:block;padding:.25rem 1rem;color:#212529}.dropdown-menu-dark{color:#dee2e6;background-color:#343a40;border-color:rgba(0,0,0,.15)}.dropdown-menu-dark .dropdown-item{color:#dee2e6}.dropdown-menu-dark .dropdown-item:focus,.dropdown-menu-dark .dropdown-item:hover{color:#fff;background-color:rgba(255,255,255,.15)}.dropdown-menu-dark .dropdown-item.active,.dropdown-menu-dark .dropdown-item:active{color:#fff;background-color:#0d6efd}.dropdown-menu-dark .dropdown-item.disabled,.dropdown-menu-dark .dropdown-item:disabled{color:#adb5bd}.dropdown-menu-dark .dropdown-divider{border-color:rgba(0,0,0,.15)}.dropdown-menu-dark .dropdown-item-text{color:#dee2e6}.dropdown-menu-dark .dropdown-header{color:#adb5bd}.btn-group,.btn-group-vertical{position:relative;display:inline-flex;vertical-align:middle}.btn-group-vertical>.btn,.btn-group>.btn{position:relative;flex:1 1 auto}.btn-group-vertical>.btn-check:checked+.btn,.btn-group-vertical>.btn-check:focus+.btn,.btn-group-vertical>.btn.active,.btn-group-vertical>.btn:active,.btn-group-vertical>.btn:focus,.btn-group-vertical>.btn:hover,.btn-group>.btn-check:checked+.btn,.btn-group>.btn-check:focus+.btn,.btn-group>.btn.active,.btn-group>.btn:active,.btn-group>.btn:focus,.btn-group>.btn:hover{z-index:1}.btn-toolbar{display:flex;flex-wrap:wrap;justify-content:flex-start}.btn-toolbar .input-group{width:auto}.btn-group>.btn-group:not(:first-child),.btn-group>.btn:not(:first-child){margin-left:-1px}.btn-group>.btn-group:not(:last-child)>.btn,.btn-group>.btn:not(:last-child):not(.dropdown-toggle){border-top-right-radius:0;border-bottom-right-radius:0}.btn-group>.btn-group:not(:first-child)>.btn,.btn-group>.btn:nth-child(n+3),.btn-group>:not(.btn-check)+.btn{border-top-left-radius:0;border-bottom-left-radius:0}.dropdown-toggle-split{padding-right:.5625rem;padding-left:.5625rem}.dropdown-toggle-split::after,.dropend .dropdown-toggle-split::after,.dropup .dropdown-toggle-split::after{margin-left:0}.dropstart .dropdown-toggle-split::before{margin-right:0}.btn-group-sm>.btn+.dropdown-toggle-split,.btn-sm+.dropdown-toggle-split{padding-right:.375rem;padding-left:.375rem}.btn-group-lg>.btn+.dropdown-toggle-split,.btn-lg+.dropdown-toggle-split{padding-right:.75rem;padding-left:.75rem}.btn-group-vertical{flex-direction:column;align-items:flex-start;justify-content:center}.btn-group-vertical>.btn,.btn-group-vertical>.btn-group{width:100%}.btn-group-vertical>.btn-group:not(:first-child),.btn-group-vertical>.btn:not(:first-child){margin-top:-1px}.btn-group-vertical>.btn-group:not(:last-child)>.btn,.btn-group-vertical>.btn:not(:last-child):not(.dropdown-toggle){border-bottom-right-radius:0;border-bottom-left-radius:0}.btn-group-vertical>.btn-group:not(:first-child)>.btn,.btn-group-vertical>.btn~.btn{border-top-left-radius:0;border-top-right-radius:0}.nav{display:flex;flex-wrap:wrap;padding-left:0;margin-bottom:0;list-style:none}.nav-link{display:block;padding:.5rem 1rem;color:#0d6efd;text-decoration:none;transition:color .15s ease-in-out,background-color .15s ease-in-out,border-color .15s ease-in-out}@media (prefers-reduced-motion:reduce){.nav-link{transition:none}}.nav-link:focus,.nav-link:hover{color:#0a58ca}.nav-link.disabled{color:#6c757d;pointer-events:none;cursor:default}.nav-tabs{border-bottom:1px solid #dee2e6}.nav-tabs .nav-link{margin-bottom:-1px;background:0 0;border:1px solid transparent;border-top-left-radius:.25rem;border-top-right-radius:.25rem}.nav-tabs .nav-link:focus,.nav-tabs .nav-link:hover{border-color:#e9ecef #e9ecef #dee2e6;isolation:isolate}.nav-tabs .nav-link.disabled{color:#6c757d;background-color:transparent;border-color:transparent}.nav-tabs .nav-item.show .nav-link,.nav-tabs .nav-link.active{color:#495057;background-color:#fff;border-color:#dee2e6 #dee2e6 #fff}.nav-tabs .dropdown-menu{margin-top:-1px;border-top-left-radius:0;border-top-right-radius:0}.nav-pills .nav-link{background:0 0;border:0;border-radius:.25rem}.nav-pills .nav-link.active,.nav-pills .show>.nav-link{color:#fff;background-color:#0d6efd}.nav-fill .nav-item,.nav-fill>.nav-link{flex:1 1 auto;text-align:center}.nav-justified .nav-item,.nav-justified>.nav-link{flex-basis:0;flex-grow:1;text-align:center}.nav-fill .nav-item .nav-link,.nav-justified .nav-item .nav-link{width:100%}.tab-content>.tab-pane{display:none}.tab-content>.active{display:block}.navbar{position:relative;display:flex;flex-wrap:wrap;align-items:center;justify-content:space-between;padding-top:.5rem;padding-bottom:.5rem}.navbar>.container,.navbar>.container-fluid,.navbar>.container-lg,.navbar>.container-md,.navbar>.container-sm,.navbar>.container-xl,.navbar>.container-xxl{display:flex;flex-wrap:inherit;align-items:center;justify-content:space-between}.navbar-brand{padding-top:.3125rem;padding-bottom:.3125rem;margin-right:1rem;font-size:1.25rem;text-decoration:none;white-space:nowrap}.navbar-nav{display:flex;flex-direction:column;padding-left:0;margin-bottom:0;list-style:none}.navbar-nav .nav-link{padding-right:0;padding-left:0}.navbar-nav .dropdown-menu{position:static}.navbar-text{padding-top:.5rem;padding-bottom:.5rem}.navbar-collapse{flex-basis:100%;flex-grow:1;align-items:center}.navbar-toggler{padding:.25rem .75rem;font-size:1.25rem;line-height:1;background-color:transparent;border:1px solid transparent;border-radius:.25rem;transition:box-shadow .15s ease-in-out}@media (prefers-reduced-motion:reduce){.navbar-toggler{transition:none}}.navbar-toggler:hover{text-decoration:none}.navbar-toggler:focus{text-decoration:none;outline:0;box-shadow:0 0 0 .25rem}.navbar-toggler-icon{display:inline-block;width:1.5em;height:1.5em;vertical-align:middle;background-repeat:no-repeat;background-position:center;background-size:100%}.navbar-nav-scroll{max-height:var(--bs-scroll-height,75vh);overflow-y:auto}@media (min-width:576px){.navbar-expand-sm{flex-wrap:nowrap;justify-content:flex-start}.navbar-expand-sm .navbar-nav{flex-direction:row}.navbar-expand-sm .navbar-nav .dropdown-menu{position:absolute}.navbar-expand-sm .navbar-nav .nav-link{padding-right:.5rem;padding-left:.5rem}.navbar-expand-sm .navbar-nav-scroll{overflow:visible}.navbar-expand-sm .navbar-collapse{display:flex!important;flex-basis:auto}.navbar-expand-sm .navbar-toggler{display:none}}@media (min-width:768px){.navbar-expand-md{flex-wrap:nowrap;justify-content:flex-start}.navbar-expand-md .navbar-nav{flex-direction:row}.navbar-expand-md .navbar-nav .dropdown-menu{position:absolute}.navbar-expand-md .navbar-nav .nav-link{padding-right:.5rem;padding-left:.5rem}.navbar-expand-md .navbar-nav-scroll{overflow:visible}.navbar-expand-md .navbar-collapse{display:flex!important;flex-basis:auto}.navbar-expand-md .navbar-toggler{display:none}}@media (min-width:992px){.navbar-expand-lg{flex-wrap:nowrap;justify-content:flex-start}.navbar-expand-lg .navbar-nav{flex-direction:row}.navbar-expand-lg .navbar-nav .dropdown-menu{position:absolute}.navbar-expand-lg .navbar-nav .nav-link{padding-right:.5rem;padding-left:.5rem}.navbar-expand-lg .navbar-nav-scroll{overflow:visible}.navbar-expand-lg .navbar-collapse{display:flex!important;flex-basis:auto}.navbar-expand-lg .navbar-toggler{display:none}}@media (min-width:1200px){.navbar-expand-xl{flex-wrap:nowrap;justify-content:flex-start}.navbar-expand-xl .navbar-nav{flex-direction:row}.navbar-expand-xl .navbar-nav .dropdown-menu{position:absolute}.navbar-expand-xl .navbar-nav .nav-link{padding-right:.5rem;padding-left:.5rem}.navbar-expand-xl .navbar-nav-scroll{overflow:visible}.navbar-expand-xl .navbar-collapse{display:flex!important;flex-basis:auto}.navbar-expand-xl .navbar-toggler{display:none}}@media (min-width:1400px){.navbar-expand-xxl{flex-wrap:nowrap;justify-content:flex-start}.navbar-expand-xxl .navbar-nav{flex-direction:row}.navbar-expand-xxl .navbar-nav .dropdown-menu{position:absolute}.navbar-expand-xxl .navbar-nav .nav-link{padding-right:.5rem;padding-left:.5rem}.navbar-expand-xxl .navbar-nav-scroll{overflow:visible}.navbar-expand-xxl .navbar-collapse{display:flex!important;flex-basis:auto}.navbar-expand-xxl .navbar-toggler{display:none}}.navbar-expand{flex-wrap:nowrap;justify-content:flex-start}.navbar-expand .navbar-nav{flex-direction:row}.navbar-expand .navbar-nav .dropdown-menu{position:absolute}.navbar-expand .navbar-nav .nav-link{padding-right:.5rem;padding-left:.5rem}.navbar-expand .navbar-nav-scroll{overflow:visible}.navbar-expand .navbar-collapse{display:flex!important;flex-basis:auto}.navbar-expand .navbar-toggler{display:none}.navbar-light .navbar-brand{color:rgba(0,0,0,.9)}.navbar-light .navbar-brand:focus,.navbar-light .navbar-brand:hover{color:rgba(0,0,0,.9)}.navbar-light .navbar-nav .nav-link{color:rgba(0,0,0,.55)}.navbar-light .navbar-nav .nav-link:focus,.navbar-light .navbar-nav .nav-link:hover{color:rgba(0,0,0,.7)}.navbar-light .navbar-nav .nav-link.disabled{color:rgba(0,0,0,.3)}.navbar-light .navbar-nav .nav-link.active,.navbar-light .navbar-nav .show>.nav-link{color:rgba(0,0,0,.9)}.navbar-light .navbar-toggler{color:rgba(0,0,0,.55);border-color:rgba(0,0,0,.1)}.navbar-light .navbar-toggler-icon{background-image:url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 30 30'%3e%3cpath stroke='rgba%280, 0, 0, 0.55%29' stroke-linecap='round' stroke-miterlimit='10' stroke-width='2' d='M4 7h22M4 15h22M4 23h22'/%3e%3c/svg%3e")}.navbar-light .navbar-text{color:rgba(0,0,0,.55)}.navbar-light .navbar-text a,.navbar-light .navbar-text a:focus,.navbar-light .navbar-text a:hover{color:rgba(0,0,0,.9)}.navbar-dark .navbar-brand{color:#fff}.navbar-dark .navbar-brand:focus,.navbar-dark .navbar-brand:hover{color:#fff}.navbar-dark .navbar-nav .nav-link{color:rgba(255,255,255,.55)}.navbar-dark .navbar-nav .nav-link:focus,.navbar-dark .navbar-nav .nav-link:hover{color:rgba(255,255,255,.75)}.navbar-dark .navbar-nav .nav-link.disabled{color:rgba(255,255,255,.25)}.navbar-dark .navbar-nav .nav-link.active,.navbar-dark .navbar-nav .show>.nav-link{color:#fff}.navbar-dark .navbar-toggler{color:rgba(255,255,255,.55);border-color:rgba(255,255,255,.1)}.navbar-dark .navbar-toggler-icon{background-image:url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 30 30'%3e%3cpath stroke='rgba%28255, 255, 255, 0.55%29' stroke-linecap='round' stroke-miterlimit='10' stroke-width='2' d='M4 7h22M4 15h22M4 23h22'/%3e%3c/svg%3e")}.navbar-dark .navbar-text{color:rgba(255,255,255,.55)}.navbar-dark .navbar-text a,.navbar-dark .navbar-text a:focus,.navbar-dark .navbar-text a:hover{color:#fff}.card{position:relative;display:flex;flex-direction:column;min-width:0;word-wrap:break-word;background-color:#fff;background-clip:border-box;border:1px solid rgba(0,0,0,.125);border-radius:.25rem}.card>hr{margin-right:0;margin-left:0}.card>.list-group{border-top:inherit;border-bottom:inherit}.card>.list-group:first-child{border-top-width:0;border-top-left-radius:calc(.25rem - 1px);border-top-right-radius:calc(.25rem - 1px)}.card>.list-group:last-child{border-bottom-width:0;border-bottom-right-radius:calc(.25rem - 1px);border-bottom-left-radius:calc(.25rem - 1px)}.card>.card-header+.list-group,.card>.list-group+.card-footer{border-top:0}.card-body{flex:1 1 auto;padding:1rem 1rem}.card-title{margin-bottom:.5rem}.card-subtitle{margin-top:-.25rem;margin-bottom:0}.card-text:last-child{margin-bottom:0}.card-link:hover{text-decoration:none}.card-link+.card-link{margin-left:1rem}.card-header{padding:.5rem 1rem;margin-bottom:0;background-color:rgba(0,0,0,.03);border-bottom:1px solid rgba(0,0,0,.125)}.card-header:first-child{border-radius:calc(.25rem - 1px) calc(.25rem - 1px) 0 0}.card-footer{padding:.5rem 1rem;background-color:rgba(0,0,0,.03);border-top:1px solid rgba(0,0,0,.125)}.card-footer:last-child{border-radius:0 0 calc(.25rem - 1px) calc(.25rem - 1px)}.card-header-tabs{margin-right:-.5rem;margin-bottom:-.5rem;margin-left:-.5rem;border-bottom:0}.card-header-pills{margin-right:-.5rem;margin-left:-.5rem}.card-img-overlay{position:absolute;top:0;right:0;bottom:0;left:0;padding:1rem;border-radius:calc(.25rem - 1px)}.card-img,.card-img-bottom,.card-img-top{width:100%}.card-img,.card-img-top{border-top-left-radius:calc(.25rem - 1px);border-top-right-radius:calc(.25rem - 1px)}.card-img,.card-img-bottom{border-bottom-right-radius:calc(.25rem - 1px);border-bottom-left-radius:calc(.25rem - 1px)}.card-group>.card{margin-bottom:.75rem}@media (min-width:576px){.card-group{display:flex;flex-flow:row wrap}.card-group>.card{flex:1 0 0%;margin-bottom:0}.card-group>.card+.card{margin-left:0;border-left:0}.card-group>.card:not(:last-child){border-top-right-radius:0;border-bottom-right-radius:0}.card-group>.card:not(:last-child) .card-header,.card-group>.card:not(:last-child) .card-img-top{border-top-right-radius:0}.card-group>.card:not(:last-child) .card-footer,.card-group>.card:not(:last-child) .card-img-bottom{border-bottom-right-radius:0}.card-group>.card:not(:first-child){border-top-left-radius:0;border-bottom-left-radius:0}.card-group>.card:not(:first-child) .card-header,.card-group>.card:not(:first-child) .card-img-top{border-top-left-radius:0}.card-group>.card:not(:first-child) .card-footer,.card-group>.card:not(:first-child) .card-img-bottom{border-bottom-left-radius:0}}.accordion-button{position:relative;display:flex;align-items:center;width:100%;padding:1rem 1.25rem;font-size:1rem;color:#212529;text-align:left;background-color:#fff;border:0;border-radius:0;overflow-anchor:none;transition:color .15s ease-in-out,background-color .15s ease-in-out,border-color .15s ease-in-out,box-shadow .15s ease-in-out,border-radius .15s ease}@media (prefers-reduced-motion:reduce){.accordion-button{transition:none}}.accordion-button:not(.collapsed){color:#0c63e4;background-color:#e7f1ff;box-shadow:inset 0 -1px 0 rgba(0,0,0,.125)}.accordion-button:not(.collapsed)::after{background-image:url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 16 16' fill='%230c63e4'%3e%3cpath fill-rule='evenodd' d='M1.646 4.646a.5.5 0 0 1 .708 0L8 10.293l5.646-5.647a.5.5 0 0 1 .708.708l-6 6a.5.5 0 0 1-.708 0l-6-6a.5.5 0 0 1 0-.708z'/%3e%3c/svg%3e");transform:rotate(-180deg)}.accordion-button::after{flex-shrink:0;width:1.25rem;height:1.25rem;margin-left:auto;content:"";background-image:url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 16 16' fill='%23212529'%3e%3cpath fill-rule='evenodd' d='M1.646 4.646a.5.5 0 0 1 .708 0L8 10.293l5.646-5.647a.5.5 0 0 1 .708.708l-6 6a.5.5 0 0 1-.708 0l-6-6a.5.5 0 0 1 0-.708z'/%3e%3c/svg%3e");background-repeat:no-repeat;background-size:1.25rem;transition:transform .2s ease-in-out}@media (prefers-reduced-motion:reduce){.accordion-button::after{transition:none}}.accordion-button:hover{z-index:2}.accordion-button:focus{z-index:3;border-color:#86b7fe;outline:0;box-shadow:0 0 0 .25rem rgba(13,110,253,.25)}.accordion-header{margin-bottom:0}.accordion-item{background-color:#fff;border:1px solid rgba(0,0,0,.125)}.accordion-item:first-of-type{border-top-left-radius:.25rem;border-top-right-radius:.25rem}.accordion-item:first-of-type .accordion-button{border-top-left-radius:calc(.25rem - 1px);border-top-right-radius:calc(.25rem - 1px)}.accordion-item:not(:first-of-type){border-top:0}.accordion-item:last-of-type{border-bottom-right-radius:.25rem;border-bottom-left-radius:.25rem}.accordion-item:last-of-type .accordion-button.collapsed{border-bottom-right-radius:calc(.25rem - 1px);border-bottom-left-radius:calc(.25rem - 1px)}.accordion-item:last-of-type .accordion-collapse{border-bottom-right-radius:.25rem;border-bottom-left-radius:.25rem}.accordion-body{padding:1rem 1.25rem}.accordion-flush .accordion-collapse{border-width:0}.accordion-flush .accordion-item{border-right:0;border-left:0;border-radius:0}.accordion-flush .accordion-item:first-child{border-top:0}.accordion-flush .accordion-item:last-child{border-bottom:0}.accordion-flush .accordion-item .accordion-button{border-radius:0}.breadcrumb{display:flex;flex-wrap:wrap;padding:0 0;margin-bottom:1rem;list-style:none}.breadcrumb-item+.breadcrumb-item{padding-left:.5rem}.breadcrumb-item+.breadcrumb-item::before{float:left;padding-right:.5rem;color:#6c757d;content:var(--bs-breadcrumb-divider, "/")}.breadcrumb-item.active{color:#6c757d}.pagination{display:flex;padding-left:0;list-style:none}.page-link{position:relative;display:block;color:#0d6efd;text-decoration:none;background-color:#fff;border:1px solid #dee2e6;transition:color .15s ease-in-out,background-color .15s ease-in-out,border-color .15s ease-in-out,box-shadow .15s ease-in-out}@media (prefers-reduced-motion:reduce){.page-link{transition:none}}.page-link:hover{z-index:2;color:#0a58ca;background-color:#e9ecef;border-color:#dee2e6}.page-link:focus{z-index:3;color:#0a58ca;background-color:#e9ecef;outline:0;box-shadow:0 0 0 .25rem rgba(13,110,253,.25)}.page-item:not(:first-child) .page-link{margin-left:-1px}.page-item.active .page-link{z-index:3;color:#fff;background-color:#0d6efd;border-color:#0d6efd}.page-item.disabled .page-link{color:#6c757d;pointer-events:none;background-color:#fff;border-color:#dee2e6}.page-link{padding:.375rem .75rem}.page-item:first-child .page-link{border-top-left-radius:.25rem;border-bottom-left-radius:.25rem}.page-item:last-child .page-link{border-top-right-radius:.25rem;border-bottom-right-radius:.25rem}.pagination-lg .page-link{padding:.75rem 1.5rem;font-size:1.25rem}.pagination-lg .page-item:first-child .page-link{border-top-left-radius:.3rem;border-bottom-left-radius:.3rem}.pagination-lg .page-item:last-child .page-link{border-top-right-radius:.3rem;border-bottom-right-radius:.3rem}.pagination-sm .page-link{padding:.25rem .5rem;font-size:.875rem}.pagination-sm .page-item:first-child .page-link{border-top-left-radius:.2rem;border-bottom-left-radius:.2rem}.pagination-sm .page-item:last-child .page-link{border-top-right-radius:.2rem;border-bottom-right-radius:.2rem}.badge{display:inline-block;padding:.35em .65em;font-size:.75em;font-weight:700;line-height:1;color:#fff;text-align:center;white-space:nowrap;vertical-align:baseline;border-radius:.25rem}.badge:empty{display:none}.btn .badge{position:relative;top:-1px}.alert{position:relative;padding:1rem 1rem;margin-bottom:1rem;border:1px solid transparent;border-radius:.25rem}.alert-heading{color:inherit}.alert-link{font-weight:700}.alert-dismissible{padding-right:3rem}.alert-dismissible .btn-close{position:absolute;top:0;right:0;z-index:2;padding:1.25rem 1rem}.alert-primary{color:#084298;background-color:#cfe2ff;border-color:#b6d4fe}.alert-primary .alert-link{color:#06357a}.alert-secondary{color:#41464b;background-color:#e2e3e5;border-color:#d3d6d8}.alert-secondary .alert-link{color:#34383c}.alert-success{color:#0f5132;background-color:#d1e7dd;border-color:#badbcc}.alert-success .alert-link{color:#0c4128}.alert-info{color:#055160;background-color:#cff4fc;border-color:#b6effb}.alert-info .alert-link{color:#04414d}.alert-warning{color:#664d03;background-color:#fff3cd;border-color:#ffecb5}.alert-warning .alert-link{color:#523e02}.alert-danger{color:#842029;background-color:#f8d7da;border-color:#f5c2c7}.alert-danger .alert-link{color:#6a1a21}.alert-light{color:#636464;background-color:#fefefe;border-color:#fdfdfe}.alert-light .alert-link{color:#4f5050}.alert-dark{color:#141619;background-color:#d3d3d4;border-color:#bcbebf}.alert-dark .alert-link{color:#101214}@-webkit-keyframes progress-bar-stripes{0%{background-position-x:1rem}}@keyframes progress-bar-stripes{0%{background-position-x:1rem}}.progress{display:flex;height:1rem;overflow:hidden;font-size:.75rem;background-color:#e9ecef;border-radius:.25rem}.progress-bar{display:flex;flex-direction:column;justify-content:center;overflow:hidden;color:#fff;text-align:center;white-space:nowrap;background-color:#0d6efd;transition:width .6s ease}@media (prefers-reduced-motion:reduce){.progress-bar{transition:none}}.progress-bar-striped{background-image:linear-gradient(45deg,rgba(255,255,255,.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,.15) 50%,rgba(255,255,255,.15) 75%,transparent 75%,transparent);background-size:1rem 1rem}.progress-bar-animated{-webkit-animation:1s linear infinite progress-bar-stripes;animation:1s linear infinite progress-bar-stripes}@media (prefers-reduced-motion:reduce){.progress-bar-animated{-webkit-animation:none;animation:none}}.list-group{display:flex;flex-direction:column;padding-left:0;margin-bottom:0;border-radius:.25rem}.list-group-numbered{list-style-type:none;counter-reset:section}.list-group-numbered>li::before{content:counters(section, ".") ". ";counter-increment:section}.list-group-item-action{width:100%;color:#495057;text-align:inherit}.list-group-item-action:focus,.list-group-item-action:hover{z-index:1;color:#495057;text-decoration:none;background-color:#f8f9fa}.list-group-item-action:active{color:#212529;background-color:#e9ecef}.list-group-item{position:relative;display:block;padding:.5rem 1rem;color:#212529;text-decoration:none;background-color:#fff;border:1px solid rgba(0,0,0,.125)}.list-group-item:first-child{border-top-left-radius:inherit;border-top-right-radius:inherit}.list-group-item:last-child{border-bottom-right-radius:inherit;border-bottom-left-radius:inherit}.list-group-item.disabled,.list-group-item:disabled{color:#6c757d;pointer-events:none;background-color:#fff}.list-group-item.active{z-index:2;color:#fff;background-color:#0d6efd;border-color:#0d6efd}.list-group-item+.list-group-item{border-top-width:0}.list-group-item+.list-group-item.active{margin-top:-1px;border-top-width:1px}.list-group-horizontal{flex-direction:row}.list-group-horizontal>.list-group-item:first-child{border-bottom-left-radius:.25rem;border-top-right-radius:0}.list-group-horizontal>.list-group-item:last-child{border-top-right-radius:.25rem;border-bottom-left-radius:0}.list-group-horizontal>.list-group-item.active{margin-top:0}.list-group-horizontal>.list-group-item+.list-group-item{border-top-width:1px;border-left-width:0}.list-group-horizontal>.list-group-item+.list-group-item.active{margin-left:-1px;border-left-width:1px}@media (min-width:576px){.list-group-horizontal-sm{flex-direction:row}.list-group-horizontal-sm>.list-group-item:first-child{border-bottom-left-radius:.25rem;border-top-right-radius:0}.list-group-horizontal-sm>.list-group-item:last-child{border-top-right-radius:.25rem;border-bottom-left-radius:0}.list-group-horizontal-sm>.list-group-item.active{margin-top:0}.list-group-horizontal-sm>.list-group-item+.list-group-item{border-top-width:1px;border-left-width:0}.list-group-horizontal-sm>.list-group-item+.list-group-item.active{margin-left:-1px;border-left-width:1px}}@media (min-width:768px){.list-group-horizontal-md{flex-direction:row}.list-group-horizontal-md>.list-group-item:first-child{border-bottom-left-radius:.25rem;border-top-right-radius:0}.list-group-horizontal-md>.list-group-item:last-child{border-top-right-radius:.25rem;border-bottom-left-radius:0}.list-group-horizontal-md>.list-group-item.active{margin-top:0}.list-group-horizontal-md>.list-group-item+.list-group-item{border-top-width:1px;border-left-width:0}.list-group-horizontal-md>.list-group-item+.list-group-item.active{margin-left:-1px;border-left-width:1px}}@media (min-width:992px){.list-group-horizontal-lg{flex-direction:row}.list-group-horizontal-lg>.list-group-item:first-child{border-bottom-left-radius:.25rem;border-top-right-radius:0}.list-group-horizontal-lg>.list-group-item:last-child{border-top-right-radius:.25rem;border-bottom-left-radius:0}.list-group-horizontal-lg>.list-group-item.active{margin-top:0}.list-group-horizontal-lg>.list-group-item+.list-group-item{border-top-width:1px;border-left-width:0}.list-group-horizontal-lg>.list-group-item+.list-group-item.active{margin-left:-1px;border-left-width:1px}}@media (min-width:1200px){.list-group-horizontal-xl{flex-direction:row}.list-group-horizontal-xl>.list-group-item:first-child{border-bottom-left-radius:.25rem;border-top-right-radius:0}.list-group-horizontal-xl>.list-group-item:last-child{border-top-right-radius:.25rem;border-bottom-left-radius:0}.list-group-horizontal-xl>.list-group-item.active{margin-top:0}.list-group-horizontal-xl>.list-group-item+.list-group-item{border-top-width:1px;border-left-width:0}.list-group-horizontal-xl>.list-group-item+.list-group-item.active{margin-left:-1px;border-left-width:1px}}@media (min-width:1400px){.list-group-horizontal-xxl{flex-direction:row}.list-group-horizontal-xxl>.list-group-item:first-child{border-bottom-left-radius:.25rem;border-top-right-radius:0}.list-group-horizontal-xxl>.list-group-item:last-child{border-top-right-radius:.25rem;border-bottom-left-radius:0}.list-group-horizontal-xxl>.list-group-item.active{margin-top:0}.list-group-horizontal-xxl>.list-group-item+.list-group-item{border-top-width:1px;border-left-width:0}.list-group-horizontal-xxl>.list-group-item+.list-group-item.active{margin-left:-1px;border-left-width:1px}}.list-group-flush{border-radius:0}.list-group-flush>.list-group-item{border-width:0 0 1px}.list-group-flush>.list-group-item:last-child{border-bottom-width:0}.list-group-item-primary{color:#084298;background-color:#cfe2ff}.list-group-item-primary.list-group-item-action:focus,.list-group-item-primary.list-group-item-action:hover{color:#084298;background-color:#bacbe6}.list-group-item-primary.list-group-item-action.active{color:#fff;background-color:#084298;border-color:#084298}.list-group-item-secondary{color:#41464b;background-color:#e2e3e5}.list-group-item-secondary.list-group-item-action:focus,.list-group-item-secondary.list-group-item-action:hover{color:#41464b;background-color:#cbccce}.list-group-item-secondary.list-group-item-action.active{color:#fff;background-color:#41464b;border-color:#41464b}.list-group-item-success{color:#0f5132;background-color:#d1e7dd}.list-group-item-success.list-group-item-action:focus,.list-group-item-success.list-group-item-action:hover{color:#0f5132;background-color:#bcd0c7}.list-group-item-success.list-group-item-action.active{color:#fff;background-color:#0f5132;border-color:#0f5132}.list-group-item-info{color:#055160;background-color:#cff4fc}.list-group-item-info.list-group-item-action:focus,.list-group-item-info.list-group-item-action:hover{color:#055160;background-color:#badce3}.list-group-item-info.list-group-item-action.active{color:#fff;background-color:#055160;border-color:#055160}.list-group-item-warning{color:#664d03;background-color:#fff3cd}.list-group-item-warning.list-group-item-action:focus,.list-group-item-warning.list-group-item-action:hover{color:#664d03;background-color:#e6dbb9}.list-group-item-warning.list-group-item-action.active{color:#fff;background-color:#664d03;border-color:#664d03}.list-group-item-danger{color:#842029;background-color:#f8d7da}.list-group-item-danger.list-group-item-action:focus,.list-group-item-danger.list-group-item-action:hover{color:#842029;background-color:#dfc2c4}.list-group-item-danger.list-group-item-action.active{color:#fff;background-color:#842029;border-color:#842029}.list-group-item-light{color:#636464;background-color:#fefefe}.list-group-item-light.list-group-item-action:focus,.list-group-item-light.list-group-item-action:hover{color:#636464;background-color:#e5e5e5}.list-group-item-light.list-group-item-action.active{color:#fff;background-color:#636464;border-color:#636464}.list-group-item-dark{color:#141619;background-color:#d3d3d4}.list-group-item-dark.list-group-item-action:focus,.list-group-item-dark.list-group-item-action:hover{color:#141619;background-color:#bebebf}.list-group-item-dark.list-group-item-action.active{color:#fff;background-color:#141619;border-color:#141619}.btn-close{box-sizing:content-box;width:1em;height:1em;padding:.25em .25em;color:#000;background:transparent url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 16 16' fill='%23000'%3e%3cpath d='M.293.293a1 1 0 011.414 0L8 6.586 14.293.293a1 1 0 111.414 1.414L9.414 8l6.293 6.293a1 1 0 01-1.414 1.414L8 9.414l-6.293 6.293a1 1 0 01-1.414-1.414L6.586 8 .293 1.707a1 1 0 010-1.414z'/%3e%3c/svg%3e") center/1em auto no-repeat;border:0;border-radius:.25rem;opacity:.5}.btn-close:hover{color:#000;text-decoration:none;opacity:.75}.btn-close:focus{outline:0;box-shadow:0 0 0 .25rem rgba(13,110,253,.25);opacity:1}.btn-close.disabled,.btn-close:disabled{pointer-events:none;-webkit-user-select:none;-moz-user-select:none;user-select:none;opacity:.25}.btn-close-white{filter:invert(1) grayscale(100%) brightness(200%)}.toast{width:350px;max-width:100%;font-size:.875rem;pointer-events:auto;background-color:rgba(255,255,255,.85);background-clip:padding-box;border:1px solid rgba(0,0,0,.1);box-shadow:0 .5rem 1rem rgba(0,0,0,.15);border-radius:.25rem}.toast:not(.showing):not(.show){opacity:0}.toast.hide{display:none}.toast-container{width:-webkit-max-content;width:-moz-max-content;width:max-content;max-width:100%;pointer-events:none}.toast-container>:not(:last-child){margin-bottom:.75rem}.toast-header{display:flex;align-items:center;padding:.5rem .75rem;color:#6c757d;background-color:rgba(255,255,255,.85);background-clip:padding-box;border-bottom:1px solid rgba(0,0,0,.05);border-top-left-radius:calc(.25rem - 1px);border-top-right-radius:calc(.25rem - 1px)}.toast-header .btn-close{margin-right:-.375rem;margin-left:.75rem}.toast-body{padding:.75rem;word-wrap:break-word}.modal{position:fixed;top:0;left:0;z-index:1060;display:none;width:100%;height:100%;overflow-x:hidden;overflow-y:auto;outline:0}.modal-dialog{position:relative;width:auto;margin:.5rem;pointer-events:none}.modal.fade .modal-dialog{transition:transform .3s ease-out;transform:translate(0,-50px)}@media (prefers-reduced-motion:reduce){.modal.fade .modal-dialog{transition:none}}.modal.show .modal-dialog{transform:none}.modal.modal-static .modal-dialog{transform:scale(1.02)}.modal-dialog-scrollable{height:calc(100% - 1rem)}.modal-dialog-scrollable .modal-content{max-height:100%;overflow:hidden}.modal-dialog-scrollable .modal-body{overflow-y:auto}.modal-dialog-centered{display:flex;align-items:center;min-height:calc(100% - 1rem)}.modal-content{position:relative;display:flex;flex-direction:column;width:100%;pointer-events:auto;background-color:#fff;background-clip:padding-box;border:1px solid rgba(0,0,0,.2);border-radius:.3rem;outline:0}.modal-backdrop{position:fixed;top:0;left:0;z-index:1040;width:100vw;height:100vh;background-color:#000}.modal-backdrop.fade{opacity:0}.modal-backdrop.show{opacity:.5}.modal-header{display:flex;flex-shrink:0;align-items:center;justify-content:space-between;padding:1rem 1rem;border-bottom:1px solid #dee2e6;border-top-left-radius:calc(.3rem - 1px);border-top-right-radius:calc(.3rem - 1px)}.modal-header .btn-close{padding:.5rem .5rem;margin:-.5rem -.5rem -.5rem auto}.modal-title{margin-bottom:0;line-height:1.5}.modal-body{position:relative;flex:1 1 auto;padding:1rem}.modal-footer{display:flex;flex-wrap:wrap;flex-shrink:0;align-items:center;justify-content:flex-end;padding:.75rem;border-top:1px solid #dee2e6;border-bottom-right-radius:calc(.3rem - 1px);border-bottom-left-radius:calc(.3rem - 1px)}.modal-footer>*{margin:.25rem}@media (min-width:576px){.modal-dialog{max-width:500px;margin:1.75rem auto}.modal-dialog-scrollable{height:calc(100% - 3.5rem)}.modal-dialog-centered{min-height:calc(100% - 3.5rem)}.modal-sm{max-width:300px}}@media (min-width:992px){.modal-lg,.modal-xl{max-width:800px}}@media (min-width:1200px){.modal-xl{max-width:1140px}}.modal-fullscreen{width:100vw;max-width:none;height:100%;margin:0}.modal-fullscreen .modal-content{height:100%;border:0;border-radius:0}.modal-fullscreen .modal-header{border-radius:0}.modal-fullscreen .modal-body{overflow-y:auto}.modal-fullscreen .modal-footer{border-radius:0}@media (max-width:575.98px){.modal-fullscreen-sm-down{width:100vw;max-width:none;height:100%;margin:0}.modal-fullscreen-sm-down .modal-content{height:100%;border:0;border-radius:0}.modal-fullscreen-sm-down .modal-header{border-radius:0}.modal-fullscreen-sm-down .modal-body{overflow-y:auto}.modal-fullscreen-sm-down .modal-footer{border-radius:0}}@media (max-width:767.98px){.modal-fullscreen-md-down{width:100vw;max-width:none;height:100%;margin:0}.modal-fullscreen-md-down .modal-content{height:100%;border:0;border-radius:0}.modal-fullscreen-md-down .modal-header{border-radius:0}.modal-fullscreen-md-down .modal-body{overflow-y:auto}.modal-fullscreen-md-down .modal-footer{border-radius:0}}@media (max-width:991.98px){.modal-fullscreen-lg-down{width:100vw;max-width:none;height:100%;margin:0}.modal-fullscreen-lg-down .modal-content{height:100%;border:0;border-radius:0}.modal-fullscreen-lg-down .modal-header{border-radius:0}.modal-fullscreen-lg-down .modal-body{overflow-y:auto}.modal-fullscreen-lg-down .modal-footer{border-radius:0}}@media (max-width:1199.98px){.modal-fullscreen-xl-down{width:100vw;max-width:none;height:100%;margin:0}.modal-fullscreen-xl-down .modal-content{height:100%;border:0;border-radius:0}.modal-fullscreen-xl-down .modal-header{border-radius:0}.modal-fullscreen-xl-down .modal-body{overflow-y:auto}.modal-fullscreen-xl-down .modal-footer{border-radius:0}}@media (max-width:1399.98px){.modal-fullscreen-xxl-down{width:100vw;max-width:none;height:100%;margin:0}.modal-fullscreen-xxl-down .modal-content{height:100%;border:0;border-radius:0}.modal-fullscreen-xxl-down .modal-header{border-radius:0}.modal-fullscreen-xxl-down .modal-body{overflow-y:auto}.modal-fullscreen-xxl-down .modal-footer{border-radius:0}}.tooltip{position:absolute;z-index:1080;display:block;margin:0;font-family:var(--bs-font-sans-serif);font-style:normal;font-weight:400;line-height:1.5;text-align:left;text-align:start;text-decoration:none;text-shadow:none;text-transform:none;letter-spacing:normal;word-break:normal;word-spacing:normal;white-space:normal;line-break:auto;font-size:.875rem;word-wrap:break-word;opacity:0}.tooltip.show{opacity:.9}.tooltip .tooltip-arrow{position:absolute;display:block;width:.8rem;height:.4rem}.tooltip .tooltip-arrow::before{position:absolute;content:"";border-color:transparent;border-style:solid}.bs-tooltip-auto[data-popper-placement^=top],.bs-tooltip-top{padding:.4rem 0}.bs-tooltip-auto[data-popper-placement^=top] .tooltip-arrow,.bs-tooltip-top .tooltip-arrow{bottom:0}.bs-tooltip-auto[data-popper-placement^=top] .tooltip-arrow::before,.bs-tooltip-top .tooltip-arrow::before{top:-1px;border-width:.4rem .4rem 0;border-top-color:#000}.bs-tooltip-auto[data-popper-placement^=right],.bs-tooltip-end{padding:0 .4rem}.bs-tooltip-auto[data-popper-placement^=right] .tooltip-arrow,.bs-tooltip-end .tooltip-arrow{left:0;width:.4rem;height:.8rem}.bs-tooltip-auto[data-popper-placement^=right] .tooltip-arrow::before,.bs-tooltip-end .tooltip-arrow::before{right:-1px;border-width:.4rem .4rem .4rem 0;border-right-color:#000}.bs-tooltip-auto[data-popper-placement^=bottom],.bs-tooltip-bottom{padding:.4rem 0}.bs-tooltip-auto[data-popper-placement^=bottom] .tooltip-arrow,.bs-tooltip-bottom .tooltip-arrow{top:0}.bs-tooltip-auto[data-popper-placement^=bottom] .tooltip-arrow::before,.bs-tooltip-bottom .tooltip-arrow::before{bottom:-1px;border-width:0 .4rem .4rem;border-bottom-color:#000}.bs-tooltip-auto[data-popper-placement^=left],.bs-tooltip-start{padding:0 .4rem}.bs-tooltip-auto[data-popper-placement^=left] .tooltip-arrow,.bs-tooltip-start .tooltip-arrow{right:0;width:.4rem;height:.8rem}.bs-tooltip-auto[data-popper-placement^=left] .tooltip-arrow::before,.bs-tooltip-start .tooltip-arrow::before{left:-1px;border-width:.4rem 0 .4rem .4rem;border-left-color:#000}.tooltip-inner{max-width:200px;padding:.25rem .5rem;color:#fff;text-align:center;background-color:#000;border-radius:.25rem}.popover{position:absolute;top:0;left:0;z-index:1070;display:block;max-width:276px;font-family:var(--bs-font-sans-serif);font-style:normal;font-weight:400;line-height:1.5;text-align:left;text-align:start;text-decoration:none;text-shadow:none;text-transform:none;letter-spacing:normal;word-break:normal;word-spacing:normal;white-space:normal;line-break:auto;font-size:.875rem;word-wrap:break-word;background-color:#fff;background-clip:padding-box;border:1px solid rgba(0,0,0,.2);border-radius:.3rem}.popover .popover-arrow{position:absolute;display:block;width:1rem;height:.5rem}.popover .popover-arrow::after,.popover .popover-arrow::before{position:absolute;display:block;content:"";border-color:transparent;border-style:solid}.bs-popover-auto[data-popper-placement^=top]>.popover-arrow,.bs-popover-top>.popover-arrow{bottom:calc(-.5rem - 1px)}.bs-popover-auto[data-popper-placement^=top]>.popover-arrow::before,.bs-popover-top>.popover-arrow::before{bottom:0;border-width:.5rem .5rem 0;border-top-color:rgba(0,0,0,.25)}.bs-popover-auto[data-popper-placement^=top]>.popover-arrow::after,.bs-popover-top>.popover-arrow::after{bottom:1px;border-width:.5rem .5rem 0;border-top-color:#fff}.bs-popover-auto[data-popper-placement^=right]>.popover-arrow,.bs-popover-end>.popover-arrow{left:calc(-.5rem - 1px);width:.5rem;height:1rem}.bs-popover-auto[data-popper-placement^=right]>.popover-arrow::before,.bs-popover-end>.popover-arrow::before{left:0;border-width:.5rem .5rem .5rem 0;border-right-color:rgba(0,0,0,.25)}.bs-popover-auto[data-popper-placement^=right]>.popover-arrow::after,.bs-popover-end>.popover-arrow::after{left:1px;border-width:.5rem .5rem .5rem 0;border-right-color:#fff}.bs-popover-auto[data-popper-placement^=bottom]>.popover-arrow,.bs-popover-bottom>.popover-arrow{top:calc(-.5rem - 1px)}.bs-popover-auto[data-popper-placement^=bottom]>.popover-arrow::before,.bs-popover-bottom>.popover-arrow::before{top:0;border-width:0 .5rem .5rem .5rem;border-bottom-color:rgba(0,0,0,.25)}.bs-popover-auto[data-popper-placement^=bottom]>.popover-arrow::after,.bs-popover-bottom>.popover-arrow::after{top:1px;border-width:0 .5rem .5rem .5rem;border-bottom-color:#fff}.bs-popover-auto[data-popper-placement^=bottom] .popover-header::before,.bs-popover-bottom .popover-header::before{position:absolute;top:0;left:50%;display:block;width:1rem;margin-left:-.5rem;content:"";border-bottom:1px solid #f0f0f0}.bs-popover-auto[data-popper-placement^=left]>.popover-arrow,.bs-popover-start>.popover-arrow{right:calc(-.5rem - 1px);width:.5rem;height:1rem}.bs-popover-auto[data-popper-placement^=left]>.popover-arrow::before,.bs-popover-start>.popover-arrow::before{right:0;border-width:.5rem 0 .5rem .5rem;border-left-color:rgba(0,0,0,.25)}.bs-popover-auto[data-popper-placement^=left]>.popover-arrow::after,.bs-popover-start>.popover-arrow::after{right:1px;border-width:.5rem 0 .5rem .5rem;border-left-color:#fff}.popover-header{padding:.5rem 1rem;margin-bottom:0;font-size:1rem;background-color:#f0f0f0;border-bottom:1px solid rgba(0,0,0,.2);border-top-left-radius:calc(.3rem - 1px);border-top-right-radius:calc(.3rem - 1px)}.popover-header:empty{display:none}.popover-body{padding:1rem 1rem;color:#212529}.carousel{position:relative}.carousel.pointer-event{touch-action:pan-y}.carousel-inner{position:relative;width:100%;overflow:hidden}.carousel-inner::after{display:block;clear:both;content:""}.carousel-item{position:relative;display:none;float:left;width:100%;margin-right:-100%;-webkit-backface-visibility:hidden;backface-visibility:hidden;transition:transform .6s ease-in-out}@media (prefers-reduced-motion:reduce){.carousel-item{transition:none}}.carousel-item-next,.carousel-item-prev,.carousel-item.active{display:block}.active.carousel-item-end,.carousel-item-next:not(.carousel-item-start){transform:translateX(100%)}.active.carousel-item-start,.carousel-item-prev:not(.carousel-item-end){transform:translateX(-100%)}.carousel-fade .carousel-item{opacity:0;transition-property:opacity;transform:none}.carousel-fade .carousel-item-next.carousel-item-start,.carousel-fade .carousel-item-prev.carousel-item-end,.carousel-fade .carousel-item.active{z-index:1;opacity:1}.carousel-fade .active.carousel-item-end,.carousel-fade .active.carousel-item-start{z-index:0;opacity:0;transition:opacity 0s .6s}@media (prefers-reduced-motion:reduce){.carousel-fade .active.carousel-item-end,.carousel-fade .active.carousel-item-start{transition:none}}.carousel-control-next,.carousel-control-prev{position:absolute;top:0;bottom:0;z-index:1;display:flex;align-items:center;justify-content:center;width:15%;padding:0;color:#fff;text-align:center;background:0 0;border:0;opacity:.5;transition:opacity .15s ease}@media (prefers-reduced-motion:reduce){.carousel-control-next,.carousel-control-prev{transition:none}}.carousel-control-next:focus,.carousel-control-next:hover,.carousel-control-prev:focus,.carousel-control-prev:hover{color:#fff;text-decoration:none;outline:0;opacity:.9}.carousel-control-prev{left:0}.carousel-control-next{right:0}.carousel-control-next-icon,.carousel-control-prev-icon{display:inline-block;width:2rem;height:2rem;background-repeat:no-repeat;background-position:50%;background-size:100% 100%}.carousel-control-prev-icon{background-image:url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 16 16' fill='%23fff'%3e%3cpath d='M11.354 1.646a.5.5 0 0 1 0 .708L5.707 8l5.647 5.646a.5.5 0 0 1-.708.708l-6-6a.5.5 0 0 1 0-.708l6-6a.5.5 0 0 1 .708 0z'/%3e%3c/svg%3e")}.carousel-control-next-icon{background-image:url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 16 16' fill='%23fff'%3e%3cpath d='M4.646 1.646a.5.5 0 0 1 .708 0l6 6a.5.5 0 0 1 0 .708l-6 6a.5.5 0 0 1-.708-.708L10.293 8 4.646 2.354a.5.5 0 0 1 0-.708z'/%3e%3c/svg%3e")}.carousel-indicators{position:absolute;right:0;bottom:0;left:0;z-index:2;display:flex;justify-content:center;padding:0;margin-right:15%;margin-bottom:1rem;margin-left:15%;list-style:none}.carousel-indicators [data-bs-target]{box-sizing:content-box;flex:0 1 auto;width:30px;height:3px;padding:0;margin-right:3px;margin-left:3px;text-indent:-999px;cursor:pointer;background-color:#fff;background-clip:padding-box;border:0;border-top:10px solid transparent;border-bottom:10px solid transparent;opacity:.5;transition:opacity .6s ease}@media (prefers-reduced-motion:reduce){.carousel-indicators [data-bs-target]{transition:none}}.carousel-indicators .active{opacity:1}.carousel-caption{position:absolute;right:15%;bottom:1.25rem;left:15%;padding-top:1.25rem;padding-bottom:1.25rem;color:#fff;text-align:center}.carousel-dark .carousel-control-next-icon,.carousel-dark .carousel-control-prev-icon{filter:invert(1) grayscale(100)}.carousel-dark .carousel-indicators [data-bs-target]{background-color:#000}.carousel-dark .carousel-caption{color:#000}@-webkit-keyframes spinner-border{to{transform:rotate(360deg)}}@keyframes spinner-border{to{transform:rotate(360deg)}}.spinner-border{display:inline-block;width:2rem;height:2rem;vertical-align:-.125em;border:.25em solid currentColor;border-right-color:transparent;border-radius:50%;-webkit-animation:.75s linear infinite spinner-border;animation:.75s linear infinite spinner-border}.spinner-border-sm{width:1rem;height:1rem;border-width:.2em}@-webkit-keyframes spinner-grow{0%{transform:scale(0)}50%{opacity:1;transform:none}}@keyframes spinner-grow{0%{transform:scale(0)}50%{opacity:1;transform:none}}.spinner-grow{display:inline-block;width:2rem;height:2rem;vertical-align:-.125em;background-color:currentColor;border-radius:50%;opacity:0;-webkit-animation:.75s linear infinite spinner-grow;animation:.75s linear infinite spinner-grow}.spinner-grow-sm{width:1rem;height:1rem}@media (prefers-reduced-motion:reduce){.spinner-border,.spinner-grow{-webkit-animation-duration:1.5s;animation-duration:1.5s}}.offcanvas{position:fixed;bottom:0;z-index:1050;display:flex;flex-direction:column;max-width:100%;visibility:hidden;background-color:#fff;background-clip:padding-box;outline:0;transition:transform .3s ease-in-out}@media (prefers-reduced-motion:reduce){.offcanvas{transition:none}}.offcanvas-header{display:flex;align-items:center;justify-content:space-between;padding:1rem 1rem}.offcanvas-header .btn-close{padding:.5rem .5rem;margin-top:-.5rem;margin-right:-.5rem;margin-bottom:-.5rem}.offcanvas-title{margin-bottom:0;line-height:1.5}.offcanvas-body{flex-grow:1;padding:1rem 1rem;overflow-y:auto}.offcanvas-start{top:0;left:0;width:400px;border-right:1px solid rgba(0,0,0,.2);transform:translateX(-100%)}.offcanvas-end{top:0;right:0;width:400px;border-left:1px solid rgba(0,0,0,.2);transform:translateX(100%)}.offcanvas-top{top:0;right:0;left:0;height:30vh;max-height:100%;border-bottom:1px solid rgba(0,0,0,.2);transform:translateY(-100%)}.offcanvas-bottom{right:0;left:0;height:30vh;max-height:100%;border-top:1px solid rgba(0,0,0,.2);transform:translateY(100%)}.offcanvas.show{transform:none}.clearfix::after{display:block;clear:both;content:""}.link-primary{color:#0d6efd}.link-primary:focus,.link-primary:hover{color:#0a58ca}.link-secondary{color:#6c757d}.link-secondary:focus,.link-secondary:hover{color:#565e64}.link-success{color:#198754}.link-success:focus,.link-success:hover{color:#146c43}.link-info{color:#0dcaf0}.link-info:focus,.link-info:hover{color:#3dd5f3}.link-warning{color:#ffc107}.link-warning:focus,.link-warning:hover{color:#ffcd39}.link-danger{color:#dc3545}.link-danger:focus,.link-danger:hover{color:#b02a37}.link-light{color:#f8f9fa}.link-light:focus,.link-light:hover{color:#f9fafb}.link-dark{color:#212529}.link-dark:focus,.link-dark:hover{color:#1a1e21}.ratio{position:relative;width:100%}.ratio::before{display:block;padding-top:var(--bs-aspect-ratio);content:""}.ratio>*{position:absolute;top:0;left:0;width:100%;height:100%}.ratio-1x1{--bs-aspect-ratio:100%}.ratio-4x3{--bs-aspect-ratio:calc(3 / 4 * 100%)}.ratio-16x9{--bs-aspect-ratio:calc(9 / 16 * 100%)}.ratio-21x9{--bs-aspect-ratio:calc(9 / 21 * 100%)}.fixed-top{position:fixed;top:0;right:0;left:0;z-index:1030}.fixed-bottom{position:fixed;right:0;bottom:0;left:0;z-index:1030}.sticky-top{position:-webkit-sticky;position:sticky;top:0;z-index:1020}@media (min-width:576px){.sticky-sm-top{position:-webkit-sticky;position:sticky;top:0;z-index:1020}}@media (min-width:768px){.sticky-md-top{position:-webkit-sticky;position:sticky;top:0;z-index:1020}}@media (min-width:992px){.sticky-lg-top{position:-webkit-sticky;position:sticky;top:0;z-index:1020}}@media (min-width:1200px){.sticky-xl-top{position:-webkit-sticky;position:sticky;top:0;z-index:1020}}@media (min-width:1400px){.sticky-xxl-top{position:-webkit-sticky;position:sticky;top:0;z-index:1020}}.visually-hidden,.visually-hidden-focusable:not(:focus):not(:focus-within){position:absolute!important;width:1px!important;height:1px!important;padding:0!important;margin:-1px!important;overflow:hidden!important;clip:rect(0,0,0,0)!important;white-space:nowrap!important;border:0!important}.stretched-link::after{position:absolute;top:0;right:0;bottom:0;left:0;z-index:1;content:""}.text-truncate{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.align-baseline{vertical-align:baseline!important}.align-top{vertical-align:top!important}.align-middle{vertical-align:middle!important}.align-bottom{vertical-align:bottom!important}.align-text-bottom{vertical-align:text-bottom!important}.align-text-top{vertical-align:text-top!important}.float-start{float:left!important}.float-end{float:right!important}.float-none{float:none!important}.overflow-auto{overflow:auto!important}.overflow-hidden{overflow:hidden!important}.overflow-visible{overflow:visible!important}.overflow-scroll{overflow:scroll!important}.d-inline{display:inline!important}.d-inline-block{display:inline-block!important}.d-block{display:block!important}.d-grid{display:grid!important}.d-table{display:table!important}.d-table-row{display:table-row!important}.d-table-cell{display:table-cell!important}.d-flex{display:flex!important}.d-inline-flex{display:inline-flex!important}.d-none{display:none!important}.shadow{box-shadow:0 .5rem 1rem rgba(0,0,0,.15)!important}.shadow-sm{box-shadow:0 .125rem .25rem rgba(0,0,0,.075)!important}.shadow-lg{box-shadow:0 1rem 3rem rgba(0,0,0,.175)!important}.shadow-none{box-shadow:none!important}.position-static{position:static!important}.position-relative{position:relative!important}.position-absolute{position:absolute!important}.position-fixed{position:fixed!important}.position-sticky{position:-webkit-sticky!important;position:sticky!important}.top-0{top:0!important}.top-50{top:50%!important}.top-100{top:100%!important}.bottom-0{bottom:0!important}.bottom-50{bottom:50%!important}.bottom-100{bottom:100%!important}.start-0{left:0!important}.start-50{left:50%!important}.start-100{left:100%!important}.end-0{right:0!important}.end-50{right:50%!important}.end-100{right:100%!important}.translate-middle{transform:translate(-50%,-50%)!important}.translate-middle-x{transform:translateX(-50%)!important}.translate-middle-y{transform:translateY(-50%)!important}.border{border:1px solid #dee2e6!important}.border-0{border:0!important}.border-top{border-top:1px solid #dee2e6!important}.border-top-0{border-top:0!important}.border-end{border-right:1px solid #dee2e6!important}.border-end-0{border-right:0!important}.border-bottom{border-bottom:1px solid #dee2e6!important}.border-bottom-0{border-bottom:0!important}.border-start{border-left:1px solid #dee2e6!important}.border-start-0{border-left:0!important}.border-primary{border-color:#0d6efd!important}.border-secondary{border-color:#6c757d!important}.border-success{border-color:#198754!important}.border-info{border-color:#0dcaf0!important}.border-warning{border-color:#ffc107!important}.border-danger{border-color:#dc3545!important}.border-light{border-color:#f8f9fa!important}.border-dark{border-color:#212529!important}.border-white{border-color:#fff!important}.border-1{border-width:1px!important}.border-2{border-width:2px!important}.border-3{border-width:3px!important}.border-4{border-width:4px!important}.border-5{border-width:5px!important}.w-25{width:25%!important}.w-50{width:50%!important}.w-75{width:75%!important}.w-100{width:100%!important}.w-auto{width:auto!important}.mw-100{max-width:100%!important}.vw-100{width:100vw!important}.min-vw-100{min-width:100vw!important}.h-25{height:25%!important}.h-50{height:50%!important}.h-75{height:75%!important}.h-100{height:100%!important}.h-auto{height:auto!important}.mh-100{max-height:100%!important}.vh-100{height:100vh!important}.min-vh-100{min-height:100vh!important}.flex-fill{flex:1 1 auto!important}.flex-row{flex-direction:row!important}.flex-column{flex-direction:column!important}.flex-row-reverse{flex-direction:row-reverse!important}.flex-column-reverse{flex-direction:column-reverse!important}.flex-grow-0{flex-grow:0!important}.flex-grow-1{flex-grow:1!important}.flex-shrink-0{flex-shrink:0!important}.flex-shrink-1{flex-shrink:1!important}.flex-wrap{flex-wrap:wrap!important}.flex-nowrap{flex-wrap:nowrap!important}.flex-wrap-reverse{flex-wrap:wrap-reverse!important}.gap-0{gap:0!important}.gap-1{gap:.25rem!important}.gap-2{gap:.5rem!important}.gap-3{gap:1rem!important}.gap-4{gap:1.5rem!important}.gap-5{gap:3rem!important}.justify-content-start{justify-content:flex-start!important}.justify-content-end{justify-content:flex-end!important}.justify-content-center{justify-content:center!important}.justify-content-between{justify-content:space-between!important}.justify-content-around{justify-content:space-around!important}.justify-content-evenly{justify-content:space-evenly!important}.align-items-start{align-items:flex-start!important}.align-items-end{align-items:flex-end!important}.align-items-center{align-items:center!important}.align-items-baseline{align-items:baseline!important}.align-items-stretch{align-items:stretch!important}.align-content-start{align-content:flex-start!important}.align-content-end{align-content:flex-end!important}.align-content-center{align-content:center!important}.align-content-between{align-content:space-between!important}.align-content-around{align-content:space-around!important}.align-content-stretch{align-content:stretch!important}.align-self-auto{align-self:auto!important}.align-self-start{align-self:flex-start!important}.align-self-end{align-self:flex-end!important}.align-self-center{align-self:center!important}.align-self-baseline{align-self:baseline!important}.align-self-stretch{align-self:stretch!important}.order-first{order:-1!important}.order-0{order:0!important}.order-1{order:1!important}.order-2{order:2!important}.order-3{order:3!important}.order-4{order:4!important}.order-5{order:5!important}.order-last{order:6!important}.m-0{margin:0!important}.m-1{margin:.25rem!important}.m-2{margin:.5rem!important}.m-3{margin:1rem!important}.m-4{margin:1.5rem!important}.m-5{margin:3rem!important}.m-auto{margin:auto!important}.mx-0{margin-right:0!important;margin-left:0!important}.mx-1{margin-right:.25rem!important;margin-left:.25rem!important}.mx-2{margin-right:.5rem!important;margin-left:.5rem!important}.mx-3{margin-right:1rem!important;margin-left:1rem!important}.mx-4{margin-right:1.5rem!important;margin-left:1.5rem!important}.mx-5{margin-right:3rem!important;margin-left:3rem!important}.mx-auto{margin-right:auto!important;margin-left:auto!important}.my-0{margin-top:0!important;margin-bottom:0!important}.my-1{margin-top:.25rem!important;margin-bottom:.25rem!important}.my-2{margin-top:.5rem!important;margin-bottom:.5rem!important}.my-3{margin-top:1rem!important;margin-bottom:1rem!important}.my-4{margin-top:1.5rem!important;margin-bottom:1.5rem!important}.my-5{margin-top:3rem!important;margin-bottom:3rem!important}.my-auto{margin-top:auto!important;margin-bottom:auto!important}.mt-0{margin-top:0!important}.mt-1{margin-top:.25rem!important}.mt-2{margin-top:.5rem!important}.mt-3{margin-top:1rem!important}.mt-4{margin-top:1.5rem!important}.mt-5{margin-top:3rem!important}.mt-auto{margin-top:auto!important}.me-0{margin-right:0!important}.me-1{margin-right:.25rem!important}.me-2{margin-right:.5rem!important}.me-3{margin-right:1rem!important}.me-4{margin-right:1.5rem!important}.me-5{margin-right:3rem!important}.me-auto{margin-right:auto!important}.mb-0{margin-bottom:0!important}.mb-1{margin-bottom:.25rem!important}.mb-2{margin-bottom:.5rem!important}.mb-3{margin-bottom:1rem!important}.mb-4{margin-bottom:1.5rem!important}.mb-5{margin-bottom:3rem!important}.mb-auto{margin-bottom:auto!important}.ms-0{margin-left:0!important}.ms-1{margin-left:.25rem!important}.ms-2{margin-left:.5rem!important}.ms-3{margin-left:1rem!important}.ms-4{margin-left:1.5rem!important}.ms-5{margin-left:3rem!important}.ms-auto{margin-left:auto!important}.p-0{padding:0!important}.p-1{padding:.25rem!important}.p-2{padding:.5rem!important}.p-3{padding:1rem!important}.p-4{padding:1.5rem!important}.p-5{padding:3rem!important}.px-0{padding-right:0!important;padding-left:0!important}.px-1{padding-right:.25rem!important;padding-left:.25rem!important}.px-2{padding-right:.5rem!important;padding-left:.5rem!important}.px-3{padding-right:1rem!important;padding-left:1rem!important}.px-4{padding-right:1.5rem!important;padding-left:1.5rem!important}.px-5{padding-right:3rem!important;padding-left:3rem!important}.py-0{padding-top:0!important;padding-bottom:0!important}.py-1{padding-top:.25rem!important;padding-bottom:.25rem!important}.py-2{padding-top:.5rem!important;padding-bottom:.5rem!important}.py-3{padding-top:1rem!important;padding-bottom:1rem!important}.py-4{padding-top:1.5rem!important;padding-bottom:1.5rem!important}.py-5{padding-top:3rem!important;padding-bottom:3rem!important}.pt-0{padding-top:0!important}.pt-1{padding-top:.25rem!important}.pt-2{padding-top:.5rem!important}.pt-3{padding-top:1rem!important}.pt-4{padding-top:1.5rem!important}.pt-5{padding-top:3rem!important}.pe-0{padding-right:0!important}.pe-1{padding-right:.25rem!important}.pe-2{padding-right:.5rem!important}.pe-3{padding-right:1rem!important}.pe-4{padding-right:1.5rem!important}.pe-5{padding-right:3rem!important}.pb-0{padding-bottom:0!important}.pb-1{padding-bottom:.25rem!important}.pb-2{padding-bottom:.5rem!important}.pb-3{padding-bottom:1rem!important}.pb-4{padding-bottom:1.5rem!important}.pb-5{padding-bottom:3rem!important}.ps-0{padding-left:0!important}.ps-1{padding-left:.25rem!important}.ps-2{padding-left:.5rem!important}.ps-3{padding-left:1rem!important}.ps-4{padding-left:1.5rem!important}.ps-5{padding-left:3rem!important}.font-monospace{font-family:var(--bs-font-monospace)!important}.fs-1{font-size:calc(1.375rem + 1.5vw)!important}.fs-2{font-size:calc(1.325rem + .9vw)!important}.fs-3{font-size:calc(1.3rem + .6vw)!important}.fs-4{font-size:calc(1.275rem + .3vw)!important}.fs-5{font-size:1.25rem!important}.fs-6{font-size:1rem!important}.fst-italic{font-style:italic!important}.fst-normal{font-style:normal!important}.fw-light{font-weight:300!important}.fw-lighter{font-weight:lighter!important}.fw-normal{font-weight:400!important}.fw-bold{font-weight:700!important}.fw-bolder{font-weight:bolder!important}.lh-1{line-height:1!important}.lh-sm{line-height:1.25!important}.lh-base{line-height:1.5!important}.lh-lg{line-height:2!important}.text-start{text-align:left!important}.text-end{text-align:right!important}.text-center{text-align:center!important}.text-decoration-none{text-decoration:none!important}.text-decoration-underline{text-decoration:underline!important}.text-decoration-line-through{text-decoration:line-through!important}.text-lowercase{text-transform:lowercase!important}.text-uppercase{text-transform:uppercase!important}.text-capitalize{text-transform:capitalize!important}.text-wrap{white-space:normal!important}.text-nowrap{white-space:nowrap!important}.text-break{word-wrap:break-word!important;word-break:break-word!important}.text-primary{color:#0d6efd!important}.text-secondary{color:#6c757d!important}.text-success{color:#198754!important}.text-info{color:#0dcaf0!important}.text-warning{color:#ffc107!important}.text-danger{color:#dc3545!important}.text-light{color:#f8f9fa!important}.text-dark{color:#212529!important}.text-white{color:#fff!important}.text-body{color:#212529!important}.text-muted{color:#6c757d!important}.text-black-50{color:rgba(0,0,0,.5)!important}.text-white-50{color:rgba(255,255,255,.5)!important}.text-reset{color:inherit!important}.bg-primary{background-color:#0d6efd!important}.bg-secondary{background-color:#6c757d!important}.bg-success{background-color:#198754!important}.bg-info{background-color:#0dcaf0!important}.bg-warning{background-color:#ffc107!important}.bg-danger{background-color:#dc3545!important}.bg-light{background-color:#f8f9fa!important}.bg-dark{background-color:#212529!important}.bg-body{background-color:#fff!important}.bg-white{background-color:#fff!important}.bg-transparent{background-color:transparent!important}.bg-gradient{background-image:var(--bs-gradient)!important}.user-select-all{-webkit-user-select:all!important;-moz-user-select:all!important;user-select:all!important}.user-select-auto{-webkit-user-select:auto!important;-moz-user-select:auto!important;user-select:auto!important}.user-select-none{-webkit-user-select:none!important;-moz-user-select:none!important;user-select:none!important}.pe-none{pointer-events:none!important}.pe-auto{pointer-events:auto!important}.rounded{border-radius:.25rem!important}.rounded-0{border-radius:0!important}.rounded-1{border-radius:.2rem!important}.rounded-2{border-radius:.25rem!important}.rounded-3{border-radius:.3rem!important}.rounded-circle{border-radius:50%!important}.rounded-pill{border-radius:50rem!important}.rounded-top{border-top-left-radius:.25rem!important;border-top-right-radius:.25rem!important}.rounded-end{border-top-right-radius:.25rem!important;border-bottom-right-radius:.25rem!important}.rounded-bottom{border-bottom-right-radius:.25rem!important;border-bottom-left-radius:.25rem!important}.rounded-start{border-bottom-left-radius:.25rem!important;border-top-left-radius:.25rem!important}.visible{visibility:visible!important}.invisible{visibility:hidden!important}@media (min-width:576px){.float-sm-start{float:left!important}.float-sm-end{float:right!important}.float-sm-none{float:none!important}.d-sm-inline{display:inline!important}.d-sm-inline-block{display:inline-block!important}.d-sm-block{display:block!important}.d-sm-grid{display:grid!important}.d-sm-table{display:table!important}.d-sm-table-row{display:table-row!important}.d-sm-table-cell{display:table-cell!important}.d-sm-flex{display:flex!important}.d-sm-inline-flex{display:inline-flex!important}.d-sm-none{display:none!important}.flex-sm-fill{flex:1 1 auto!important}.flex-sm-row{flex-direction:row!important}.flex-sm-column{flex-direction:column!important}.flex-sm-row-reverse{flex-direction:row-reverse!important}.flex-sm-column-reverse{flex-direction:column-reverse!important}.flex-sm-grow-0{flex-grow:0!important}.flex-sm-grow-1{flex-grow:1!important}.flex-sm-shrink-0{flex-shrink:0!important}.flex-sm-shrink-1{flex-shrink:1!important}.flex-sm-wrap{flex-wrap:wrap!important}.flex-sm-nowrap{flex-wrap:nowrap!important}.flex-sm-wrap-reverse{flex-wrap:wrap-reverse!important}.gap-sm-0{gap:0!important}.gap-sm-1{gap:.25rem!important}.gap-sm-2{gap:.5rem!important}.gap-sm-3{gap:1rem!important}.gap-sm-4{gap:1.5rem!important}.gap-sm-5{gap:3rem!important}.justify-content-sm-start{justify-content:flex-start!important}.justify-content-sm-end{justify-content:flex-end!important}.justify-content-sm-center{justify-content:center!important}.justify-content-sm-between{justify-content:space-between!important}.justify-content-sm-around{justify-content:space-around!important}.justify-content-sm-evenly{justify-content:space-evenly!important}.align-items-sm-start{align-items:flex-start!important}.align-items-sm-end{align-items:flex-end!important}.align-items-sm-center{align-items:center!important}.align-items-sm-baseline{align-items:baseline!important}.align-items-sm-stretch{align-items:stretch!important}.align-content-sm-start{align-content:flex-start!important}.align-content-sm-end{align-content:flex-end!important}.align-content-sm-center{align-content:center!important}.align-content-sm-between{align-content:space-between!important}.align-content-sm-around{align-content:space-around!important}.align-content-sm-stretch{align-content:stretch!important}.align-self-sm-auto{align-self:auto!important}.align-self-sm-start{align-self:flex-start!important}.align-self-sm-end{align-self:flex-end!important}.align-self-sm-center{align-self:center!important}.align-self-sm-baseline{align-self:baseline!important}.align-self-sm-stretch{align-self:stretch!important}.order-sm-first{order:-1!important}.order-sm-0{order:0!important}.order-sm-1{order:1!important}.order-sm-2{order:2!important}.order-sm-3{order:3!important}.order-sm-4{order:4!important}.order-sm-5{order:5!important}.order-sm-last{order:6!important}.m-sm-0{margin:0!important}.m-sm-1{margin:.25rem!important}.m-sm-2{margin:.5rem!important}.m-sm-3{margin:1rem!important}.m-sm-4{margin:1.5rem!important}.m-sm-5{margin:3rem!important}.m-sm-auto{margin:auto!important}.mx-sm-0{margin-right:0!important;margin-left:0!important}.mx-sm-1{margin-right:.25rem!important;margin-left:.25rem!important}.mx-sm-2{margin-right:.5rem!important;margin-left:.5rem!important}.mx-sm-3{margin-right:1rem!important;margin-left:1rem!important}.mx-sm-4{margin-right:1.5rem!important;margin-left:1.5rem!important}.mx-sm-5{margin-right:3rem!important;margin-left:3rem!important}.mx-sm-auto{margin-right:auto!important;margin-left:auto!important}.my-sm-0{margin-top:0!important;margin-bottom:0!important}.my-sm-1{margin-top:.25rem!important;margin-bottom:.25rem!important}.my-sm-2{margin-top:.5rem!important;margin-bottom:.5rem!important}.my-sm-3{margin-top:1rem!important;margin-bottom:1rem!important}.my-sm-4{margin-top:1.5rem!important;margin-bottom:1.5rem!important}.my-sm-5{margin-top:3rem!important;margin-bottom:3rem!important}.my-sm-auto{margin-top:auto!important;margin-bottom:auto!important}.mt-sm-0{margin-top:0!important}.mt-sm-1{margin-top:.25rem!important}.mt-sm-2{margin-top:.5rem!important}.mt-sm-3{margin-top:1rem!important}.mt-sm-4{margin-top:1.5rem!important}.mt-sm-5{margin-top:3rem!important}.mt-sm-auto{margin-top:auto!important}.me-sm-0{margin-right:0!important}.me-sm-1{margin-right:.25rem!important}.me-sm-2{margin-right:.5rem!important}.me-sm-3{margin-right:1rem!important}.me-sm-4{margin-right:1.5rem!important}.me-sm-5{margin-right:3rem!important}.me-sm-auto{margin-right:auto!important}.mb-sm-0{margin-bottom:0!important}.mb-sm-1{margin-bottom:.25rem!important}.mb-sm-2{margin-bottom:.5rem!important}.mb-sm-3{margin-bottom:1rem!important}.mb-sm-4{margin-bottom:1.5rem!important}.mb-sm-5{margin-bottom:3rem!important}.mb-sm-auto{margin-bottom:auto!important}.ms-sm-0{margin-left:0!important}.ms-sm-1{margin-left:.25rem!important}.ms-sm-2{margin-left:.5rem!important}.ms-sm-3{margin-left:1rem!important}.ms-sm-4{margin-left:1.5rem!important}.ms-sm-5{margin-left:3rem!important}.ms-sm-auto{margin-left:auto!important}.p-sm-0{padding:0!important}.p-sm-1{padding:.25rem!important}.p-sm-2{padding:.5rem!important}.p-sm-3{padding:1rem!important}.p-sm-4{padding:1.5rem!important}.p-sm-5{padding:3rem!important}.px-sm-0{padding-right:0!important;padding-left:0!important}.px-sm-1{padding-right:.25rem!important;padding-left:.25rem!important}.px-sm-2{padding-right:.5rem!important;padding-left:.5rem!important}.px-sm-3{padding-right:1rem!important;padding-left:1rem!important}.px-sm-4{padding-right:1.5rem!important;padding-left:1.5rem!important}.px-sm-5{padding-right:3rem!important;padding-left:3rem!important}.py-sm-0{padding-top:0!important;padding-bottom:0!important}.py-sm-1{padding-top:.25rem!important;padding-bottom:.25rem!important}.py-sm-2{padding-top:.5rem!important;padding-bottom:.5rem!important}.py-sm-3{padding-top:1rem!important;padding-bottom:1rem!important}.py-sm-4{padding-top:1.5rem!important;padding-bottom:1.5rem!important}.py-sm-5{padding-top:3rem!important;padding-bottom:3rem!important}.pt-sm-0{padding-top:0!important}.pt-sm-1{padding-top:.25rem!important}.pt-sm-2{padding-top:.5rem!important}.pt-sm-3{padding-top:1rem!important}.pt-sm-4{padding-top:1.5rem!important}.pt-sm-5{padding-top:3rem!important}.pe-sm-0{padding-right:0!important}.pe-sm-1{padding-right:.25rem!important}.pe-sm-2{padding-right:.5rem!important}.pe-sm-3{padding-right:1rem!important}.pe-sm-4{padding-right:1.5rem!important}.pe-sm-5{padding-right:3rem!important}.pb-sm-0{padding-bottom:0!important}.pb-sm-1{padding-bottom:.25rem!important}.pb-sm-2{padding-bottom:.5rem!important}.pb-sm-3{padding-bottom:1rem!important}.pb-sm-4{padding-bottom:1.5rem!important}.pb-sm-5{padding-bottom:3rem!important}.ps-sm-0{padding-left:0!important}.ps-sm-1{padding-left:.25rem!important}.ps-sm-2{padding-left:.5rem!important}.ps-sm-3{padding-left:1rem!important}.ps-sm-4{padding-left:1.5rem!important}.ps-sm-5{padding-left:3rem!important}.text-sm-start{text-align:left!important}.text-sm-end{text-align:right!important}.text-sm-center{text-align:center!important}}@media (min-width:768px){.float-md-start{float:left!important}.float-md-end{float:right!important}.float-md-none{float:none!important}.d-md-inline{display:inline!important}.d-md-inline-block{display:inline-block!important}.d-md-block{display:block!important}.d-md-grid{display:grid!important}.d-md-table{display:table!important}.d-md-table-row{display:table-row!important}.d-md-table-cell{display:table-cell!important}.d-md-flex{display:flex!important}.d-md-inline-flex{display:inline-flex!important}.d-md-none{display:none!important}.flex-md-fill{flex:1 1 auto!important}.flex-md-row{flex-direction:row!important}.flex-md-column{flex-direction:column!important}.flex-md-row-reverse{flex-direction:row-reverse!important}.flex-md-column-reverse{flex-direction:column-reverse!important}.flex-md-grow-0{flex-grow:0!important}.flex-md-grow-1{flex-grow:1!important}.flex-md-shrink-0{flex-shrink:0!important}.flex-md-shrink-1{flex-shrink:1!important}.flex-md-wrap{flex-wrap:wrap!important}.flex-md-nowrap{flex-wrap:nowrap!important}.flex-md-wrap-reverse{flex-wrap:wrap-reverse!important}.gap-md-0{gap:0!important}.gap-md-1{gap:.25rem!important}.gap-md-2{gap:.5rem!important}.gap-md-3{gap:1rem!important}.gap-md-4{gap:1.5rem!important}.gap-md-5{gap:3rem!important}.justify-content-md-start{justify-content:flex-start!important}.justify-content-md-end{justify-content:flex-end!important}.justify-content-md-center{justify-content:center!important}.justify-content-md-between{justify-content:space-between!important}.justify-content-md-around{justify-content:space-around!important}.justify-content-md-evenly{justify-content:space-evenly!important}.align-items-md-start{align-items:flex-start!important}.align-items-md-end{align-items:flex-end!important}.align-items-md-center{align-items:center!important}.align-items-md-baseline{align-items:baseline!important}.align-items-md-stretch{align-items:stretch!important}.align-content-md-start{align-content:flex-start!important}.align-content-md-end{align-content:flex-end!important}.align-content-md-center{align-content:center!important}.align-content-md-between{align-content:space-between!important}.align-content-md-around{align-content:space-around!important}.align-content-md-stretch{align-content:stretch!important}.align-self-md-auto{align-self:auto!important}.align-self-md-start{align-self:flex-start!important}.align-self-md-end{align-self:flex-end!important}.align-self-md-center{align-self:center!important}.align-self-md-baseline{align-self:baseline!important}.align-self-md-stretch{align-self:stretch!important}.order-md-first{order:-1!important}.order-md-0{order:0!important}.order-md-1{order:1!important}.order-md-2{order:2!important}.order-md-3{order:3!important}.order-md-4{order:4!important}.order-md-5{order:5!important}.order-md-last{order:6!important}.m-md-0{margin:0!important}.m-md-1{margin:.25rem!important}.m-md-2{margin:.5rem!important}.m-md-3{margin:1rem!important}.m-md-4{margin:1.5rem!important}.m-md-5{margin:3rem!important}.m-md-auto{margin:auto!important}.mx-md-0{margin-right:0!important;margin-left:0!important}.mx-md-1{margin-right:.25rem!important;margin-left:.25rem!important}.mx-md-2{margin-right:.5rem!important;margin-left:.5rem!important}.mx-md-3{margin-right:1rem!important;margin-left:1rem!important}.mx-md-4{margin-right:1.5rem!important;margin-left:1.5rem!important}.mx-md-5{margin-right:3rem!important;margin-left:3rem!important}.mx-md-auto{margin-right:auto!important;margin-left:auto!important}.my-md-0{margin-top:0!important;margin-bottom:0!important}.my-md-1{margin-top:.25rem!important;margin-bottom:.25rem!important}.my-md-2{margin-top:.5rem!important;margin-bottom:.5rem!important}.my-md-3{margin-top:1rem!important;margin-bottom:1rem!important}.my-md-4{margin-top:1.5rem!important;margin-bottom:1.5rem!important}.my-md-5{margin-top:3rem!important;margin-bottom:3rem!important}.my-md-auto{margin-top:auto!important;margin-bottom:auto!important}.mt-md-0{margin-top:0!important}.mt-md-1{margin-top:.25rem!important}.mt-md-2{margin-top:.5rem!important}.mt-md-3{margin-top:1rem!important}.mt-md-4{margin-top:1.5rem!important}.mt-md-5{margin-top:3rem!important}.mt-md-auto{margin-top:auto!important}.me-md-0{margin-right:0!important}.me-md-1{margin-right:.25rem!important}.me-md-2{margin-right:.5rem!important}.me-md-3{margin-right:1rem!important}.me-md-4{margin-right:1.5rem!important}.me-md-5{margin-right:3rem!important}.me-md-auto{margin-right:auto!important}.mb-md-0{margin-bottom:0!important}.mb-md-1{margin-bottom:.25rem!important}.mb-md-2{margin-bottom:.5rem!important}.mb-md-3{margin-bottom:1rem!important}.mb-md-4{margin-bottom:1.5rem!important}.mb-md-5{margin-bottom:3rem!important}.mb-md-auto{margin-bottom:auto!important}.ms-md-0{margin-left:0!important}.ms-md-1{margin-left:.25rem!important}.ms-md-2{margin-left:.5rem!important}.ms-md-3{margin-left:1rem!important}.ms-md-4{margin-left:1.5rem!important}.ms-md-5{margin-left:3rem!important}.ms-md-auto{margin-left:auto!important}.p-md-0{padding:0!important}.p-md-1{padding:.25rem!important}.p-md-2{padding:.5rem!important}.p-md-3{padding:1rem!important}.p-md-4{padding:1.5rem!important}.p-md-5{padding:3rem!important}.px-md-0{padding-right:0!important;padding-left:0!important}.px-md-1{padding-right:.25rem!important;padding-left:.25rem!important}.px-md-2{padding-right:.5rem!important;padding-left:.5rem!important}.px-md-3{padding-right:1rem!important;padding-left:1rem!important}.px-md-4{padding-right:1.5rem!important;padding-left:1.5rem!important}.px-md-5{padding-right:3rem!important;padding-left:3rem!important}.py-md-0{padding-top:0!important;padding-bottom:0!important}.py-md-1{padding-top:.25rem!important;padding-bottom:.25rem!important}.py-md-2{padding-top:.5rem!important;padding-bottom:.5rem!important}.py-md-3{padding-top:1rem!important;padding-bottom:1rem!important}.py-md-4{padding-top:1.5rem!important;padding-bottom:1.5rem!important}.py-md-5{padding-top:3rem!important;padding-bottom:3rem!important}.pt-md-0{padding-top:0!important}.pt-md-1{padding-top:.25rem!important}.pt-md-2{padding-top:.5rem!important}.pt-md-3{padding-top:1rem!important}.pt-md-4{padding-top:1.5rem!important}.pt-md-5{padding-top:3rem!important}.pe-md-0{padding-right:0!important}.pe-md-1{padding-right:.25rem!important}.pe-md-2{padding-right:.5rem!important}.pe-md-3{padding-right:1rem!important}.pe-md-4{padding-right:1.5rem!important}.pe-md-5{padding-right:3rem!important}.pb-md-0{padding-bottom:0!important}.pb-md-1{padding-bottom:.25rem!important}.pb-md-2{padding-bottom:.5rem!important}.pb-md-3{padding-bottom:1rem!important}.pb-md-4{padding-bottom:1.5rem!important}.pb-md-5{padding-bottom:3rem!important}.ps-md-0{padding-left:0!important}.ps-md-1{padding-left:.25rem!important}.ps-md-2{padding-left:.5rem!important}.ps-md-3{padding-left:1rem!important}.ps-md-4{padding-left:1.5rem!important}.ps-md-5{padding-left:3rem!important}.text-md-start{text-align:left!important}.text-md-end{text-align:right!important}.text-md-center{text-align:center!important}}@media (min-width:992px){.float-lg-start{float:left!important}.float-lg-end{float:right!important}.float-lg-none{float:none!important}.d-lg-inline{display:inline!important}.d-lg-inline-block{display:inline-block!important}.d-lg-block{display:block!important}.d-lg-grid{display:grid!important}.d-lg-table{display:table!important}.d-lg-table-row{display:table-row!important}.d-lg-table-cell{display:table-cell!important}.d-lg-flex{display:flex!important}.d-lg-inline-flex{display:inline-flex!important}.d-lg-none{display:none!important}.flex-lg-fill{flex:1 1 auto!important}.flex-lg-row{flex-direction:row!important}.flex-lg-column{flex-direction:column!important}.flex-lg-row-reverse{flex-direction:row-reverse!important}.flex-lg-column-reverse{flex-direction:column-reverse!important}.flex-lg-grow-0{flex-grow:0!important}.flex-lg-grow-1{flex-grow:1!important}.flex-lg-shrink-0{flex-shrink:0!important}.flex-lg-shrink-1{flex-shrink:1!important}.flex-lg-wrap{flex-wrap:wrap!important}.flex-lg-nowrap{flex-wrap:nowrap!important}.flex-lg-wrap-reverse{flex-wrap:wrap-reverse!important}.gap-lg-0{gap:0!important}.gap-lg-1{gap:.25rem!important}.gap-lg-2{gap:.5rem!important}.gap-lg-3{gap:1rem!important}.gap-lg-4{gap:1.5rem!important}.gap-lg-5{gap:3rem!important}.justify-content-lg-start{justify-content:flex-start!important}.justify-content-lg-end{justify-content:flex-end!important}.justify-content-lg-center{justify-content:center!important}.justify-content-lg-between{justify-content:space-between!important}.justify-content-lg-around{justify-content:space-around!important}.justify-content-lg-evenly{justify-content:space-evenly!important}.align-items-lg-start{align-items:flex-start!important}.align-items-lg-end{align-items:flex-end!important}.align-items-lg-center{align-items:center!important}.align-items-lg-baseline{align-items:baseline!important}.align-items-lg-stretch{align-items:stretch!important}.align-content-lg-start{align-content:flex-start!important}.align-content-lg-end{align-content:flex-end!important}.align-content-lg-center{align-content:center!important}.align-content-lg-between{align-content:space-between!important}.align-content-lg-around{align-content:space-around!important}.align-content-lg-stretch{align-content:stretch!important}.align-self-lg-auto{align-self:auto!important}.align-self-lg-start{align-self:flex-start!important}.align-self-lg-end{align-self:flex-end!important}.align-self-lg-center{align-self:center!important}.align-self-lg-baseline{align-self:baseline!important}.align-self-lg-stretch{align-self:stretch!important}.order-lg-first{order:-1!important}.order-lg-0{order:0!important}.order-lg-1{order:1!important}.order-lg-2{order:2!important}.order-lg-3{order:3!important}.order-lg-4{order:4!important}.order-lg-5{order:5!important}.order-lg-last{order:6!important}.m-lg-0{margin:0!important}.m-lg-1{margin:.25rem!important}.m-lg-2{margin:.5rem!important}.m-lg-3{margin:1rem!important}.m-lg-4{margin:1.5rem!important}.m-lg-5{margin:3rem!important}.m-lg-auto{margin:auto!important}.mx-lg-0{margin-right:0!important;margin-left:0!important}.mx-lg-1{margin-right:.25rem!important;margin-left:.25rem!important}.mx-lg-2{margin-right:.5rem!important;margin-left:.5rem!important}.mx-lg-3{margin-right:1rem!important;margin-left:1rem!important}.mx-lg-4{margin-right:1.5rem!important;margin-left:1.5rem!important}.mx-lg-5{margin-right:3rem!important;margin-left:3rem!important}.mx-lg-auto{margin-right:auto!important;margin-left:auto!important}.my-lg-0{margin-top:0!important;margin-bottom:0!important}.my-lg-1{margin-top:.25rem!important;margin-bottom:.25rem!important}.my-lg-2{margin-top:.5rem!important;margin-bottom:.5rem!important}.my-lg-3{margin-top:1rem!important;margin-bottom:1rem!important}.my-lg-4{margin-top:1.5rem!important;margin-bottom:1.5rem!important}.my-lg-5{margin-top:3rem!important;margin-bottom:3rem!important}.my-lg-auto{margin-top:auto!important;margin-bottom:auto!important}.mt-lg-0{margin-top:0!important}.mt-lg-1{margin-top:.25rem!important}.mt-lg-2{margin-top:.5rem!important}.mt-lg-3{margin-top:1rem!important}.mt-lg-4{margin-top:1.5rem!important}.mt-lg-5{margin-top:3rem!important}.mt-lg-auto{margin-top:auto!important}.me-lg-0{margin-right:0!important}.me-lg-1{margin-right:.25rem!important}.me-lg-2{margin-right:.5rem!important}.me-lg-3{margin-right:1rem!important}.me-lg-4{margin-right:1.5rem!important}.me-lg-5{margin-right:3rem!important}.me-lg-auto{margin-right:auto!important}.mb-lg-0{margin-bottom:0!important}.mb-lg-1{margin-bottom:.25rem!important}.mb-lg-2{margin-bottom:.5rem!important}.mb-lg-3{margin-bottom:1rem!important}.mb-lg-4{margin-bottom:1.5rem!important}.mb-lg-5{margin-bottom:3rem!important}.mb-lg-auto{margin-bottom:auto!important}.ms-lg-0{margin-left:0!important}.ms-lg-1{margin-left:.25rem!important}.ms-lg-2{margin-left:.5rem!important}.ms-lg-3{margin-left:1rem!important}.ms-lg-4{margin-left:1.5rem!important}.ms-lg-5{margin-left:3rem!important}.ms-lg-auto{margin-left:auto!important}.p-lg-0{padding:0!important}.p-lg-1{padding:.25rem!important}.p-lg-2{padding:.5rem!important}.p-lg-3{padding:1rem!important}.p-lg-4{padding:1.5rem!important}.p-lg-5{padding:3rem!important}.px-lg-0{padding-right:0!important;padding-left:0!important}.px-lg-1{padding-right:.25rem!important;padding-left:.25rem!important}.px-lg-2{padding-right:.5rem!important;padding-left:.5rem!important}.px-lg-3{padding-right:1rem!important;padding-left:1rem!important}.px-lg-4{padding-right:1.5rem!important;padding-left:1.5rem!important}.px-lg-5{padding-right:3rem!important;padding-left:3rem!important}.py-lg-0{padding-top:0!important;padding-bottom:0!important}.py-lg-1{padding-top:.25rem!important;padding-bottom:.25rem!important}.py-lg-2{padding-top:.5rem!important;padding-bottom:.5rem!important}.py-lg-3{padding-top:1rem!important;padding-bottom:1rem!important}.py-lg-4{padding-top:1.5rem!important;padding-bottom:1.5rem!important}.py-lg-5{padding-top:3rem!important;padding-bottom:3rem!important}.pt-lg-0{padding-top:0!important}.pt-lg-1{padding-top:.25rem!important}.pt-lg-2{padding-top:.5rem!important}.pt-lg-3{padding-top:1rem!important}.pt-lg-4{padding-top:1.5rem!important}.pt-lg-5{padding-top:3rem!important}.pe-lg-0{padding-right:0!important}.pe-lg-1{padding-right:.25rem!important}.pe-lg-2{padding-right:.5rem!important}.pe-lg-3{padding-right:1rem!important}.pe-lg-4{padding-right:1.5rem!important}.pe-lg-5{padding-right:3rem!important}.pb-lg-0{padding-bottom:0!important}.pb-lg-1{padding-bottom:.25rem!important}.pb-lg-2{padding-bottom:.5rem!important}.pb-lg-3{padding-bottom:1rem!important}.pb-lg-4{padding-bottom:1.5rem!important}.pb-lg-5{padding-bottom:3rem!important}.ps-lg-0{padding-left:0!important}.ps-lg-1{padding-left:.25rem!important}.ps-lg-2{padding-left:.5rem!important}.ps-lg-3{padding-left:1rem!important}.ps-lg-4{padding-left:1.5rem!important}.ps-lg-5{padding-left:3rem!important}.text-lg-start{text-align:left!important}.text-lg-end{text-align:right!important}.text-lg-center{text-align:center!important}}@media (min-width:1200px){.float-xl-start{float:left!important}.float-xl-end{float:right!important}.float-xl-none{float:none!important}.d-xl-inline{display:inline!important}.d-xl-inline-block{display:inline-block!important}.d-xl-block{display:block!important}.d-xl-grid{display:grid!important}.d-xl-table{display:table!important}.d-xl-table-row{display:table-row!important}.d-xl-table-cell{display:table-cell!important}.d-xl-flex{display:flex!important}.d-xl-inline-flex{display:inline-flex!important}.d-xl-none{display:none!important}.flex-xl-fill{flex:1 1 auto!important}.flex-xl-row{flex-direction:row!important}.flex-xl-column{flex-direction:column!important}.flex-xl-row-reverse{flex-direction:row-reverse!important}.flex-xl-column-reverse{flex-direction:column-reverse!important}.flex-xl-grow-0{flex-grow:0!important}.flex-xl-grow-1{flex-grow:1!important}.flex-xl-shrink-0{flex-shrink:0!important}.flex-xl-shrink-1{flex-shrink:1!important}.flex-xl-wrap{flex-wrap:wrap!important}.flex-xl-nowrap{flex-wrap:nowrap!important}.flex-xl-wrap-reverse{flex-wrap:wrap-reverse!important}.gap-xl-0{gap:0!important}.gap-xl-1{gap:.25rem!important}.gap-xl-2{gap:.5rem!important}.gap-xl-3{gap:1rem!important}.gap-xl-4{gap:1.5rem!important}.gap-xl-5{gap:3rem!important}.justify-content-xl-start{justify-content:flex-start!important}.justify-content-xl-end{justify-content:flex-end!important}.justify-content-xl-center{justify-content:center!important}.justify-content-xl-between{justify-content:space-between!important}.justify-content-xl-around{justify-content:space-around!important}.justify-content-xl-evenly{justify-content:space-evenly!important}.align-items-xl-start{align-items:flex-start!important}.align-items-xl-end{align-items:flex-end!important}.align-items-xl-center{align-items:center!important}.align-items-xl-baseline{align-items:baseline!important}.align-items-xl-stretch{align-items:stretch!important}.align-content-xl-start{align-content:flex-start!important}.align-content-xl-end{align-content:flex-end!important}.align-content-xl-center{align-content:center!important}.align-content-xl-between{align-content:space-between!important}.align-content-xl-around{align-content:space-around!important}.align-content-xl-stretch{align-content:stretch!important}.align-self-xl-auto{align-self:auto!important}.align-self-xl-start{align-self:flex-start!important}.align-self-xl-end{align-self:flex-end!important}.align-self-xl-center{align-self:center!important}.align-self-xl-baseline{align-self:baseline!important}.align-self-xl-stretch{align-self:stretch!important}.order-xl-first{order:-1!important}.order-xl-0{order:0!important}.order-xl-1{order:1!important}.order-xl-2{order:2!important}.order-xl-3{order:3!important}.order-xl-4{order:4!important}.order-xl-5{order:5!important}.order-xl-last{order:6!important}.m-xl-0{margin:0!important}.m-xl-1{margin:.25rem!important}.m-xl-2{margin:.5rem!important}.m-xl-3{margin:1rem!important}.m-xl-4{margin:1.5rem!important}.m-xl-5{margin:3rem!important}.m-xl-auto{margin:auto!important}.mx-xl-0{margin-right:0!important;margin-left:0!important}.mx-xl-1{margin-right:.25rem!important;margin-left:.25rem!important}.mx-xl-2{margin-right:.5rem!important;margin-left:.5rem!important}.mx-xl-3{margin-right:1rem!important;margin-left:1rem!important}.mx-xl-4{margin-right:1.5rem!important;margin-left:1.5rem!important}.mx-xl-5{margin-right:3rem!important;margin-left:3rem!important}.mx-xl-auto{margin-right:auto!important;margin-left:auto!important}.my-xl-0{margin-top:0!important;margin-bottom:0!important}.my-xl-1{margin-top:.25rem!important;margin-bottom:.25rem!important}.my-xl-2{margin-top:.5rem!important;margin-bottom:.5rem!important}.my-xl-3{margin-top:1rem!important;margin-bottom:1rem!important}.my-xl-4{margin-top:1.5rem!important;margin-bottom:1.5rem!important}.my-xl-5{margin-top:3rem!important;margin-bottom:3rem!important}.my-xl-auto{margin-top:auto!important;margin-bottom:auto!important}.mt-xl-0{margin-top:0!important}.mt-xl-1{margin-top:.25rem!important}.mt-xl-2{margin-top:.5rem!important}.mt-xl-3{margin-top:1rem!important}.mt-xl-4{margin-top:1.5rem!important}.mt-xl-5{margin-top:3rem!important}.mt-xl-auto{margin-top:auto!important}.me-xl-0{margin-right:0!important}.me-xl-1{margin-right:.25rem!important}.me-xl-2{margin-right:.5rem!important}.me-xl-3{margin-right:1rem!important}.me-xl-4{margin-right:1.5rem!important}.me-xl-5{margin-right:3rem!important}.me-xl-auto{margin-right:auto!important}.mb-xl-0{margin-bottom:0!important}.mb-xl-1{margin-bottom:.25rem!important}.mb-xl-2{margin-bottom:.5rem!important}.mb-xl-3{margin-bottom:1rem!important}.mb-xl-4{margin-bottom:1.5rem!important}.mb-xl-5{margin-bottom:3rem!important}.mb-xl-auto{margin-bottom:auto!important}.ms-xl-0{margin-left:0!important}.ms-xl-1{margin-left:.25rem!important}.ms-xl-2{margin-left:.5rem!important}.ms-xl-3{margin-left:1rem!important}.ms-xl-4{margin-left:1.5rem!important}.ms-xl-5{margin-left:3rem!important}.ms-xl-auto{margin-left:auto!important}.p-xl-0{padding:0!important}.p-xl-1{padding:.25rem!important}.p-xl-2{padding:.5rem!important}.p-xl-3{padding:1rem!important}.p-xl-4{padding:1.5rem!important}.p-xl-5{padding:3rem!important}.px-xl-0{padding-right:0!important;padding-left:0!important}.px-xl-1{padding-right:.25rem!important;padding-left:.25rem!important}.px-xl-2{padding-right:.5rem!important;padding-left:.5rem!important}.px-xl-3{padding-right:1rem!important;padding-left:1rem!important}.px-xl-4{padding-right:1.5rem!important;padding-left:1.5rem!important}.px-xl-5{padding-right:3rem!important;padding-left:3rem!important}.py-xl-0{padding-top:0!important;padding-bottom:0!important}.py-xl-1{padding-top:.25rem!important;padding-bottom:.25rem!important}.py-xl-2{padding-top:.5rem!important;padding-bottom:.5rem!important}.py-xl-3{padding-top:1rem!important;padding-bottom:1rem!important}.py-xl-4{padding-top:1.5rem!important;padding-bottom:1.5rem!important}.py-xl-5{padding-top:3rem!important;padding-bottom:3rem!important}.pt-xl-0{padding-top:0!important}.pt-xl-1{padding-top:.25rem!important}.pt-xl-2{padding-top:.5rem!important}.pt-xl-3{padding-top:1rem!important}.pt-xl-4{padding-top:1.5rem!important}.pt-xl-5{padding-top:3rem!important}.pe-xl-0{padding-right:0!important}.pe-xl-1{padding-right:.25rem!important}.pe-xl-2{padding-right:.5rem!important}.pe-xl-3{padding-right:1rem!important}.pe-xl-4{padding-right:1.5rem!important}.pe-xl-5{padding-right:3rem!important}.pb-xl-0{padding-bottom:0!important}.pb-xl-1{padding-bottom:.25rem!important}.pb-xl-2{padding-bottom:.5rem!important}.pb-xl-3{padding-bottom:1rem!important}.pb-xl-4{padding-bottom:1.5rem!important}.pb-xl-5{padding-bottom:3rem!important}.ps-xl-0{padding-left:0!important}.ps-xl-1{padding-left:.25rem!important}.ps-xl-2{padding-left:.5rem!important}.ps-xl-3{padding-left:1rem!important}.ps-xl-4{padding-left:1.5rem!important}.ps-xl-5{padding-left:3rem!important}.text-xl-start{text-align:left!important}.text-xl-end{text-align:right!important}.text-xl-center{text-align:center!important}}@media (min-width:1400px){.float-xxl-start{float:left!important}.float-xxl-end{float:right!important}.float-xxl-none{float:none!important}.d-xxl-inline{display:inline!important}.d-xxl-inline-block{display:inline-block!important}.d-xxl-block{display:block!important}.d-xxl-grid{display:grid!important}.d-xxl-table{display:table!important}.d-xxl-table-row{display:table-row!important}.d-xxl-table-cell{display:table-cell!important}.d-xxl-flex{display:flex!important}.d-xxl-inline-flex{display:inline-flex!important}.d-xxl-none{display:none!important}.flex-xxl-fill{flex:1 1 auto!important}.flex-xxl-row{flex-direction:row!important}.flex-xxl-column{flex-direction:column!important}.flex-xxl-row-reverse{flex-direction:row-reverse!important}.flex-xxl-column-reverse{flex-direction:column-reverse!important}.flex-xxl-grow-0{flex-grow:0!important}.flex-xxl-grow-1{flex-grow:1!important}.flex-xxl-shrink-0{flex-shrink:0!important}.flex-xxl-shrink-1{flex-shrink:1!important}.flex-xxl-wrap{flex-wrap:wrap!important}.flex-xxl-nowrap{flex-wrap:nowrap!important}.flex-xxl-wrap-reverse{flex-wrap:wrap-reverse!important}.gap-xxl-0{gap:0!important}.gap-xxl-1{gap:.25rem!important}.gap-xxl-2{gap:.5rem!important}.gap-xxl-3{gap:1rem!important}.gap-xxl-4{gap:1.5rem!important}.gap-xxl-5{gap:3rem!important}.justify-content-xxl-start{justify-content:flex-start!important}.justify-content-xxl-end{justify-content:flex-end!important}.justify-content-xxl-center{justify-content:center!important}.justify-content-xxl-between{justify-content:space-between!important}.justify-content-xxl-around{justify-content:space-around!important}.justify-content-xxl-evenly{justify-content:space-evenly!important}.align-items-xxl-start{align-items:flex-start!important}.align-items-xxl-end{align-items:flex-end!important}.align-items-xxl-center{align-items:center!important}.align-items-xxl-baseline{align-items:baseline!important}.align-items-xxl-stretch{align-items:stretch!important}.align-content-xxl-start{align-content:flex-start!important}.align-content-xxl-end{align-content:flex-end!important}.align-content-xxl-center{align-content:center!important}.align-content-xxl-between{align-content:space-between!important}.align-content-xxl-around{align-content:space-around!important}.align-content-xxl-stretch{align-content:stretch!important}.align-self-xxl-auto{align-self:auto!important}.align-self-xxl-start{align-self:flex-start!important}.align-self-xxl-end{align-self:flex-end!important}.align-self-xxl-center{align-self:center!important}.align-self-xxl-baseline{align-self:baseline!important}.align-self-xxl-stretch{align-self:stretch!important}.order-xxl-first{order:-1!important}.order-xxl-0{order:0!important}.order-xxl-1{order:1!important}.order-xxl-2{order:2!important}.order-xxl-3{order:3!important}.order-xxl-4{order:4!important}.order-xxl-5{order:5!important}.order-xxl-last{order:6!important}.m-xxl-0{margin:0!important}.m-xxl-1{margin:.25rem!important}.m-xxl-2{margin:.5rem!important}.m-xxl-3{margin:1rem!important}.m-xxl-4{margin:1.5rem!important}.m-xxl-5{margin:3rem!important}.m-xxl-auto{margin:auto!important}.mx-xxl-0{margin-right:0!important;margin-left:0!important}.mx-xxl-1{margin-right:.25rem!important;margin-left:.25rem!important}.mx-xxl-2{margin-right:.5rem!important;margin-left:.5rem!important}.mx-xxl-3{margin-right:1rem!important;margin-left:1rem!important}.mx-xxl-4{margin-right:1.5rem!important;margin-left:1.5rem!important}.mx-xxl-5{margin-right:3rem!important;margin-left:3rem!important}.mx-xxl-auto{margin-right:auto!important;margin-left:auto!important}.my-xxl-0{margin-top:0!important;margin-bottom:0!important}.my-xxl-1{margin-top:.25rem!important;margin-bottom:.25rem!important}.my-xxl-2{margin-top:.5rem!important;margin-bottom:.5rem!important}.my-xxl-3{margin-top:1rem!important;margin-bottom:1rem!important}.my-xxl-4{margin-top:1.5rem!important;margin-bottom:1.5rem!important}.my-xxl-5{margin-top:3rem!important;margin-bottom:3rem!important}.my-xxl-auto{margin-top:auto!important;margin-bottom:auto!important}.mt-xxl-0{margin-top:0!important}.mt-xxl-1{margin-top:.25rem!important}.mt-xxl-2{margin-top:.5rem!important}.mt-xxl-3{margin-top:1rem!important}.mt-xxl-4{margin-top:1.5rem!important}.mt-xxl-5{margin-top:3rem!important}.mt-xxl-auto{margin-top:auto!important}.me-xxl-0{margin-right:0!important}.me-xxl-1{margin-right:.25rem!important}.me-xxl-2{margin-right:.5rem!important}.me-xxl-3{margin-right:1rem!important}.me-xxl-4{margin-right:1.5rem!important}.me-xxl-5{margin-right:3rem!important}.me-xxl-auto{margin-right:auto!important}.mb-xxl-0{margin-bottom:0!important}.mb-xxl-1{margin-bottom:.25rem!important}.mb-xxl-2{margin-bottom:.5rem!important}.mb-xxl-3{margin-bottom:1rem!important}.mb-xxl-4{margin-bottom:1.5rem!important}.mb-xxl-5{margin-bottom:3rem!important}.mb-xxl-auto{margin-bottom:auto!important}.ms-xxl-0{margin-left:0!important}.ms-xxl-1{margin-left:.25rem!important}.ms-xxl-2{margin-left:.5rem!important}.ms-xxl-3{margin-left:1rem!important}.ms-xxl-4{margin-left:1.5rem!important}.ms-xxl-5{margin-left:3rem!important}.ms-xxl-auto{margin-left:auto!important}.p-xxl-0{padding:0!important}.p-xxl-1{padding:.25rem!important}.p-xxl-2{padding:.5rem!important}.p-xxl-3{padding:1rem!important}.p-xxl-4{padding:1.5rem!important}.p-xxl-5{padding:3rem!important}.px-xxl-0{padding-right:0!important;padding-left:0!important}.px-xxl-1{padding-right:.25rem!important;padding-left:.25rem!important}.px-xxl-2{padding-right:.5rem!important;padding-left:.5rem!important}.px-xxl-3{padding-right:1rem!important;padding-left:1rem!important}.px-xxl-4{padding-right:1.5rem!important;padding-left:1.5rem!important}.px-xxl-5{padding-right:3rem!important;padding-left:3rem!important}.py-xxl-0{padding-top:0!important;padding-bottom:0!important}.py-xxl-1{padding-top:.25rem!important;padding-bottom:.25rem!important}.py-xxl-2{padding-top:.5rem!important;padding-bottom:.5rem!important}.py-xxl-3{padding-top:1rem!important;padding-bottom:1rem!important}.py-xxl-4{padding-top:1.5rem!important;padding-bottom:1.5rem!important}.py-xxl-5{padding-top:3rem!important;padding-bottom:3rem!important}.pt-xxl-0{padding-top:0!important}.pt-xxl-1{padding-top:.25rem!important}.pt-xxl-2{padding-top:.5rem!important}.pt-xxl-3{padding-top:1rem!important}.pt-xxl-4{padding-top:1.5rem!important}.pt-xxl-5{padding-top:3rem!important}.pe-xxl-0{padding-right:0!important}.pe-xxl-1{padding-right:.25rem!important}.pe-xxl-2{padding-right:.5rem!important}.pe-xxl-3{padding-right:1rem!important}.pe-xxl-4{padding-right:1.5rem!important}.pe-xxl-5{padding-right:3rem!important}.pb-xxl-0{padding-bottom:0!important}.pb-xxl-1{padding-bottom:.25rem!important}.pb-xxl-2{padding-bottom:.5rem!important}.pb-xxl-3{padding-bottom:1rem!important}.pb-xxl-4{padding-bottom:1.5rem!important}.pb-xxl-5{padding-bottom:3rem!important}.ps-xxl-0{padding-left:0!important}.ps-xxl-1{padding-left:.25rem!important}.ps-xxl-2{padding-left:.5rem!important}.ps-xxl-3{padding-left:1rem!important}.ps-xxl-4{padding-left:1.5rem!important}.ps-xxl-5{padding-left:3rem!important}.text-xxl-start{text-align:left!important}.text-xxl-end{text-align:right!important}.text-xxl-center{text-align:center!important}}@media (min-width:1200px){.fs-1{font-size:2.5rem!important}.fs-2{font-size:2rem!important}.fs-3{font-size:1.75rem!important}.fs-4{font-size:1.5rem!important}}@media print{.d-print-inline{display:inline!important}.d-print-inline-block{display:inline-block!important}.d-print-block{display:block!important}.d-print-grid{display:grid!important}.d-print-table{display:table!important}.d-print-table-row{display:table-row!important}.d-print-table-cell{display:table-cell!important}.d-print-flex{display:flex!important}.d-print-inline-flex{display:inline-flex!important}.d-print-none{display:none!important}} +/*# sourceMappingURL=bootstrap.min.css.map */ \ No newline at end of file diff --git a/examples/04_cell_detector/resources/bootstrap.js b/examples/04_cell_detector/resources/bootstrap.js new file mode 100644 index 0000000..68acb7a --- /dev/null +++ b/examples/04_cell_detector/resources/bootstrap.js @@ -0,0 +1,7 @@ +/*! + * Bootstrap v5.0.2 (https://getbootstrap.com/) + * Copyright 2011-2021 The Bootstrap Authors (https://github.com/twbs/bootstrap/graphs/contributors) + * Licensed under MIT (https://github.com/twbs/bootstrap/blob/main/LICENSE) + */ +!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?module.exports=e():"function"==typeof define&&define.amd?define(e):(t="undefined"!=typeof globalThis?globalThis:t||self).bootstrap=e()}(this,(function(){"use strict";const t={find:(t,e=document.documentElement)=>[].concat(...Element.prototype.querySelectorAll.call(e,t)),findOne:(t,e=document.documentElement)=>Element.prototype.querySelector.call(e,t),children:(t,e)=>[].concat(...t.children).filter(t=>t.matches(e)),parents(t,e){const i=[];let n=t.parentNode;for(;n&&n.nodeType===Node.ELEMENT_NODE&&3!==n.nodeType;)n.matches(e)&&i.push(n),n=n.parentNode;return i},prev(t,e){let i=t.previousElementSibling;for(;i;){if(i.matches(e))return[i];i=i.previousElementSibling}return[]},next(t,e){let i=t.nextElementSibling;for(;i;){if(i.matches(e))return[i];i=i.nextElementSibling}return[]}},e=t=>{do{t+=Math.floor(1e6*Math.random())}while(document.getElementById(t));return t},i=t=>{let e=t.getAttribute("data-bs-target");if(!e||"#"===e){let i=t.getAttribute("href");if(!i||!i.includes("#")&&!i.startsWith("."))return null;i.includes("#")&&!i.startsWith("#")&&(i="#"+i.split("#")[1]),e=i&&"#"!==i?i.trim():null}return e},n=t=>{const e=i(t);return e&&document.querySelector(e)?e:null},s=t=>{const e=i(t);return e?document.querySelector(e):null},o=t=>{t.dispatchEvent(new Event("transitionend"))},r=t=>!(!t||"object"!=typeof t)&&(void 0!==t.jquery&&(t=t[0]),void 0!==t.nodeType),a=e=>r(e)?e.jquery?e[0]:e:"string"==typeof e&&e.length>0?t.findOne(e):null,l=(t,e,i)=>{Object.keys(i).forEach(n=>{const s=i[n],o=e[n],a=o&&r(o)?"element":null==(l=o)?""+l:{}.toString.call(l).match(/\s([a-z]+)/i)[1].toLowerCase();var l;if(!new RegExp(s).test(a))throw new TypeError(`${t.toUpperCase()}: Option "${n}" provided type "${a}" but expected type "${s}".`)})},c=t=>!(!r(t)||0===t.getClientRects().length)&&"visible"===getComputedStyle(t).getPropertyValue("visibility"),h=t=>!t||t.nodeType!==Node.ELEMENT_NODE||!!t.classList.contains("disabled")||(void 0!==t.disabled?t.disabled:t.hasAttribute("disabled")&&"false"!==t.getAttribute("disabled")),d=t=>{if(!document.documentElement.attachShadow)return null;if("function"==typeof t.getRootNode){const e=t.getRootNode();return e instanceof ShadowRoot?e:null}return t instanceof ShadowRoot?t:t.parentNode?d(t.parentNode):null},u=()=>{},f=t=>t.offsetHeight,p=()=>{const{jQuery:t}=window;return t&&!document.body.hasAttribute("data-bs-no-jquery")?t:null},m=[],g=()=>"rtl"===document.documentElement.dir,_=t=>{var e;e=()=>{const e=p();if(e){const i=t.NAME,n=e.fn[i];e.fn[i]=t.jQueryInterface,e.fn[i].Constructor=t,e.fn[i].noConflict=()=>(e.fn[i]=n,t.jQueryInterface)}},"loading"===document.readyState?(m.length||document.addEventListener("DOMContentLoaded",()=>{m.forEach(t=>t())}),m.push(e)):e()},b=t=>{"function"==typeof t&&t()},v=(t,e,i=!0)=>{if(!i)return void b(t);const n=(t=>{if(!t)return 0;let{transitionDuration:e,transitionDelay:i}=window.getComputedStyle(t);const n=Number.parseFloat(e),s=Number.parseFloat(i);return n||s?(e=e.split(",")[0],i=i.split(",")[0],1e3*(Number.parseFloat(e)+Number.parseFloat(i))):0})(e)+5;let s=!1;const r=({target:i})=>{i===e&&(s=!0,e.removeEventListener("transitionend",r),b(t))};e.addEventListener("transitionend",r),setTimeout(()=>{s||o(e)},n)},y=(t,e,i,n)=>{let s=t.indexOf(e);if(-1===s)return t[!i&&n?t.length-1:0];const o=t.length;return s+=i?1:-1,n&&(s=(s+o)%o),t[Math.max(0,Math.min(s,o-1))]},w=/[^.]*(?=\..*)\.|.*/,E=/\..*/,A=/::\d+$/,T={};let O=1;const C={mouseenter:"mouseover",mouseleave:"mouseout"},k=/^(mouseenter|mouseleave)/i,L=new Set(["click","dblclick","mouseup","mousedown","contextmenu","mousewheel","DOMMouseScroll","mouseover","mouseout","mousemove","selectstart","selectend","keydown","keypress","keyup","orientationchange","touchstart","touchmove","touchend","touchcancel","pointerdown","pointermove","pointerup","pointerleave","pointercancel","gesturestart","gesturechange","gestureend","focus","blur","change","reset","select","submit","focusin","focusout","load","unload","beforeunload","resize","move","DOMContentLoaded","readystatechange","error","abort","scroll"]);function x(t,e){return e&&`${e}::${O++}`||t.uidEvent||O++}function D(t){const e=x(t);return t.uidEvent=e,T[e]=T[e]||{},T[e]}function S(t,e,i=null){const n=Object.keys(t);for(let s=0,o=n.length;sfunction(e){if(!e.relatedTarget||e.relatedTarget!==e.delegateTarget&&!e.delegateTarget.contains(e.relatedTarget))return t.call(this,e)};n?n=t(n):i=t(i)}const[o,r,a]=I(e,i,n),l=D(t),c=l[a]||(l[a]={}),h=S(c,r,o?i:null);if(h)return void(h.oneOff=h.oneOff&&s);const d=x(r,e.replace(w,"")),u=o?function(t,e,i){return function n(s){const o=t.querySelectorAll(e);for(let{target:r}=s;r&&r!==this;r=r.parentNode)for(let a=o.length;a--;)if(o[a]===r)return s.delegateTarget=r,n.oneOff&&P.off(t,s.type,e,i),i.apply(r,[s]);return null}}(t,i,n):function(t,e){return function i(n){return n.delegateTarget=t,i.oneOff&&P.off(t,n.type,e),e.apply(t,[n])}}(t,i);u.delegationSelector=o?i:null,u.originalHandler=r,u.oneOff=s,u.uidEvent=d,c[d]=u,t.addEventListener(a,u,o)}function j(t,e,i,n,s){const o=S(e[i],n,s);o&&(t.removeEventListener(i,o,Boolean(s)),delete e[i][o.uidEvent])}function M(t){return t=t.replace(E,""),C[t]||t}const P={on(t,e,i,n){N(t,e,i,n,!1)},one(t,e,i,n){N(t,e,i,n,!0)},off(t,e,i,n){if("string"!=typeof e||!t)return;const[s,o,r]=I(e,i,n),a=r!==e,l=D(t),c=e.startsWith(".");if(void 0!==o){if(!l||!l[r])return;return void j(t,l,r,o,s?i:null)}c&&Object.keys(l).forEach(i=>{!function(t,e,i,n){const s=e[i]||{};Object.keys(s).forEach(o=>{if(o.includes(n)){const n=s[o];j(t,e,i,n.originalHandler,n.delegationSelector)}})}(t,l,i,e.slice(1))});const h=l[r]||{};Object.keys(h).forEach(i=>{const n=i.replace(A,"");if(!a||e.includes(n)){const e=h[i];j(t,l,r,e.originalHandler,e.delegationSelector)}})},trigger(t,e,i){if("string"!=typeof e||!t)return null;const n=p(),s=M(e),o=e!==s,r=L.has(s);let a,l=!0,c=!0,h=!1,d=null;return o&&n&&(a=n.Event(e,i),n(t).trigger(a),l=!a.isPropagationStopped(),c=!a.isImmediatePropagationStopped(),h=a.isDefaultPrevented()),r?(d=document.createEvent("HTMLEvents"),d.initEvent(s,l,!0)):d=new CustomEvent(e,{bubbles:l,cancelable:!0}),void 0!==i&&Object.keys(i).forEach(t=>{Object.defineProperty(d,t,{get:()=>i[t]})}),h&&d.preventDefault(),c&&t.dispatchEvent(d),d.defaultPrevented&&void 0!==a&&a.preventDefault(),d}},H=new Map;var R={set(t,e,i){H.has(t)||H.set(t,new Map);const n=H.get(t);n.has(e)||0===n.size?n.set(e,i):console.error(`Bootstrap doesn't allow more than one instance per element. Bound instance: ${Array.from(n.keys())[0]}.`)},get:(t,e)=>H.has(t)&&H.get(t).get(e)||null,remove(t,e){if(!H.has(t))return;const i=H.get(t);i.delete(e),0===i.size&&H.delete(t)}};class B{constructor(t){(t=a(t))&&(this._element=t,R.set(this._element,this.constructor.DATA_KEY,this))}dispose(){R.remove(this._element,this.constructor.DATA_KEY),P.off(this._element,this.constructor.EVENT_KEY),Object.getOwnPropertyNames(this).forEach(t=>{this[t]=null})}_queueCallback(t,e,i=!0){v(t,e,i)}static getInstance(t){return R.get(t,this.DATA_KEY)}static getOrCreateInstance(t,e={}){return this.getInstance(t)||new this(t,"object"==typeof e?e:null)}static get VERSION(){return"5.0.2"}static get NAME(){throw new Error('You have to implement the static method "NAME", for each component!')}static get DATA_KEY(){return"bs."+this.NAME}static get EVENT_KEY(){return"."+this.DATA_KEY}}class W extends B{static get NAME(){return"alert"}close(t){const e=t?this._getRootElement(t):this._element,i=this._triggerCloseEvent(e);null===i||i.defaultPrevented||this._removeElement(e)}_getRootElement(t){return s(t)||t.closest(".alert")}_triggerCloseEvent(t){return P.trigger(t,"close.bs.alert")}_removeElement(t){t.classList.remove("show");const e=t.classList.contains("fade");this._queueCallback(()=>this._destroyElement(t),t,e)}_destroyElement(t){t.remove(),P.trigger(t,"closed.bs.alert")}static jQueryInterface(t){return this.each((function(){const e=W.getOrCreateInstance(this);"close"===t&&e[t](this)}))}static handleDismiss(t){return function(e){e&&e.preventDefault(),t.close(this)}}}P.on(document,"click.bs.alert.data-api",'[data-bs-dismiss="alert"]',W.handleDismiss(new W)),_(W);class q extends B{static get NAME(){return"button"}toggle(){this._element.setAttribute("aria-pressed",this._element.classList.toggle("active"))}static jQueryInterface(t){return this.each((function(){const e=q.getOrCreateInstance(this);"toggle"===t&&e[t]()}))}}function z(t){return"true"===t||"false"!==t&&(t===Number(t).toString()?Number(t):""===t||"null"===t?null:t)}function $(t){return t.replace(/[A-Z]/g,t=>"-"+t.toLowerCase())}P.on(document,"click.bs.button.data-api",'[data-bs-toggle="button"]',t=>{t.preventDefault();const e=t.target.closest('[data-bs-toggle="button"]');q.getOrCreateInstance(e).toggle()}),_(q);const U={setDataAttribute(t,e,i){t.setAttribute("data-bs-"+$(e),i)},removeDataAttribute(t,e){t.removeAttribute("data-bs-"+$(e))},getDataAttributes(t){if(!t)return{};const e={};return Object.keys(t.dataset).filter(t=>t.startsWith("bs")).forEach(i=>{let n=i.replace(/^bs/,"");n=n.charAt(0).toLowerCase()+n.slice(1,n.length),e[n]=z(t.dataset[i])}),e},getDataAttribute:(t,e)=>z(t.getAttribute("data-bs-"+$(e))),offset(t){const e=t.getBoundingClientRect();return{top:e.top+document.body.scrollTop,left:e.left+document.body.scrollLeft}},position:t=>({top:t.offsetTop,left:t.offsetLeft})},F={interval:5e3,keyboard:!0,slide:!1,pause:"hover",wrap:!0,touch:!0},V={interval:"(number|boolean)",keyboard:"boolean",slide:"(boolean|string)",pause:"(string|boolean)",wrap:"boolean",touch:"boolean"},K="next",X="prev",Y="left",Q="right",G={ArrowLeft:Q,ArrowRight:Y};class Z extends B{constructor(e,i){super(e),this._items=null,this._interval=null,this._activeElement=null,this._isPaused=!1,this._isSliding=!1,this.touchTimeout=null,this.touchStartX=0,this.touchDeltaX=0,this._config=this._getConfig(i),this._indicatorsElement=t.findOne(".carousel-indicators",this._element),this._touchSupported="ontouchstart"in document.documentElement||navigator.maxTouchPoints>0,this._pointerEvent=Boolean(window.PointerEvent),this._addEventListeners()}static get Default(){return F}static get NAME(){return"carousel"}next(){this._slide(K)}nextWhenVisible(){!document.hidden&&c(this._element)&&this.next()}prev(){this._slide(X)}pause(e){e||(this._isPaused=!0),t.findOne(".carousel-item-next, .carousel-item-prev",this._element)&&(o(this._element),this.cycle(!0)),clearInterval(this._interval),this._interval=null}cycle(t){t||(this._isPaused=!1),this._interval&&(clearInterval(this._interval),this._interval=null),this._config&&this._config.interval&&!this._isPaused&&(this._updateInterval(),this._interval=setInterval((document.visibilityState?this.nextWhenVisible:this.next).bind(this),this._config.interval))}to(e){this._activeElement=t.findOne(".active.carousel-item",this._element);const i=this._getItemIndex(this._activeElement);if(e>this._items.length-1||e<0)return;if(this._isSliding)return void P.one(this._element,"slid.bs.carousel",()=>this.to(e));if(i===e)return this.pause(),void this.cycle();const n=e>i?K:X;this._slide(n,this._items[e])}_getConfig(t){return t={...F,...U.getDataAttributes(this._element),..."object"==typeof t?t:{}},l("carousel",t,V),t}_handleSwipe(){const t=Math.abs(this.touchDeltaX);if(t<=40)return;const e=t/this.touchDeltaX;this.touchDeltaX=0,e&&this._slide(e>0?Q:Y)}_addEventListeners(){this._config.keyboard&&P.on(this._element,"keydown.bs.carousel",t=>this._keydown(t)),"hover"===this._config.pause&&(P.on(this._element,"mouseenter.bs.carousel",t=>this.pause(t)),P.on(this._element,"mouseleave.bs.carousel",t=>this.cycle(t))),this._config.touch&&this._touchSupported&&this._addTouchEventListeners()}_addTouchEventListeners(){const e=t=>{!this._pointerEvent||"pen"!==t.pointerType&&"touch"!==t.pointerType?this._pointerEvent||(this.touchStartX=t.touches[0].clientX):this.touchStartX=t.clientX},i=t=>{this.touchDeltaX=t.touches&&t.touches.length>1?0:t.touches[0].clientX-this.touchStartX},n=t=>{!this._pointerEvent||"pen"!==t.pointerType&&"touch"!==t.pointerType||(this.touchDeltaX=t.clientX-this.touchStartX),this._handleSwipe(),"hover"===this._config.pause&&(this.pause(),this.touchTimeout&&clearTimeout(this.touchTimeout),this.touchTimeout=setTimeout(t=>this.cycle(t),500+this._config.interval))};t.find(".carousel-item img",this._element).forEach(t=>{P.on(t,"dragstart.bs.carousel",t=>t.preventDefault())}),this._pointerEvent?(P.on(this._element,"pointerdown.bs.carousel",t=>e(t)),P.on(this._element,"pointerup.bs.carousel",t=>n(t)),this._element.classList.add("pointer-event")):(P.on(this._element,"touchstart.bs.carousel",t=>e(t)),P.on(this._element,"touchmove.bs.carousel",t=>i(t)),P.on(this._element,"touchend.bs.carousel",t=>n(t)))}_keydown(t){if(/input|textarea/i.test(t.target.tagName))return;const e=G[t.key];e&&(t.preventDefault(),this._slide(e))}_getItemIndex(e){return this._items=e&&e.parentNode?t.find(".carousel-item",e.parentNode):[],this._items.indexOf(e)}_getItemByOrder(t,e){const i=t===K;return y(this._items,e,i,this._config.wrap)}_triggerSlideEvent(e,i){const n=this._getItemIndex(e),s=this._getItemIndex(t.findOne(".active.carousel-item",this._element));return P.trigger(this._element,"slide.bs.carousel",{relatedTarget:e,direction:i,from:s,to:n})}_setActiveIndicatorElement(e){if(this._indicatorsElement){const i=t.findOne(".active",this._indicatorsElement);i.classList.remove("active"),i.removeAttribute("aria-current");const n=t.find("[data-bs-target]",this._indicatorsElement);for(let t=0;t{P.trigger(this._element,"slid.bs.carousel",{relatedTarget:r,direction:u,from:o,to:a})};if(this._element.classList.contains("slide")){r.classList.add(d),f(r),s.classList.add(h),r.classList.add(h);const t=()=>{r.classList.remove(h,d),r.classList.add("active"),s.classList.remove("active",d,h),this._isSliding=!1,setTimeout(p,0)};this._queueCallback(t,s,!0)}else s.classList.remove("active"),r.classList.add("active"),this._isSliding=!1,p();l&&this.cycle()}_directionToOrder(t){return[Q,Y].includes(t)?g()?t===Y?X:K:t===Y?K:X:t}_orderToDirection(t){return[K,X].includes(t)?g()?t===X?Y:Q:t===X?Q:Y:t}static carouselInterface(t,e){const i=Z.getOrCreateInstance(t,e);let{_config:n}=i;"object"==typeof e&&(n={...n,...e});const s="string"==typeof e?e:n.slide;if("number"==typeof e)i.to(e);else if("string"==typeof s){if(void 0===i[s])throw new TypeError(`No method named "${s}"`);i[s]()}else n.interval&&n.ride&&(i.pause(),i.cycle())}static jQueryInterface(t){return this.each((function(){Z.carouselInterface(this,t)}))}static dataApiClickHandler(t){const e=s(this);if(!e||!e.classList.contains("carousel"))return;const i={...U.getDataAttributes(e),...U.getDataAttributes(this)},n=this.getAttribute("data-bs-slide-to");n&&(i.interval=!1),Z.carouselInterface(e,i),n&&Z.getInstance(e).to(n),t.preventDefault()}}P.on(document,"click.bs.carousel.data-api","[data-bs-slide], [data-bs-slide-to]",Z.dataApiClickHandler),P.on(window,"load.bs.carousel.data-api",()=>{const e=t.find('[data-bs-ride="carousel"]');for(let t=0,i=e.length;tt===this._element);null!==o&&r.length&&(this._selector=o,this._triggerArray.push(i))}this._parent=this._config.parent?this._getParent():null,this._config.parent||this._addAriaAndCollapsedClass(this._element,this._triggerArray),this._config.toggle&&this.toggle()}static get Default(){return J}static get NAME(){return"collapse"}toggle(){this._element.classList.contains("show")?this.hide():this.show()}show(){if(this._isTransitioning||this._element.classList.contains("show"))return;let e,i;this._parent&&(e=t.find(".show, .collapsing",this._parent).filter(t=>"string"==typeof this._config.parent?t.getAttribute("data-bs-parent")===this._config.parent:t.classList.contains("collapse")),0===e.length&&(e=null));const n=t.findOne(this._selector);if(e){const t=e.find(t=>n!==t);if(i=t?et.getInstance(t):null,i&&i._isTransitioning)return}if(P.trigger(this._element,"show.bs.collapse").defaultPrevented)return;e&&e.forEach(t=>{n!==t&&et.collapseInterface(t,"hide"),i||R.set(t,"bs.collapse",null)});const s=this._getDimension();this._element.classList.remove("collapse"),this._element.classList.add("collapsing"),this._element.style[s]=0,this._triggerArray.length&&this._triggerArray.forEach(t=>{t.classList.remove("collapsed"),t.setAttribute("aria-expanded",!0)}),this.setTransitioning(!0);const o="scroll"+(s[0].toUpperCase()+s.slice(1));this._queueCallback(()=>{this._element.classList.remove("collapsing"),this._element.classList.add("collapse","show"),this._element.style[s]="",this.setTransitioning(!1),P.trigger(this._element,"shown.bs.collapse")},this._element,!0),this._element.style[s]=this._element[o]+"px"}hide(){if(this._isTransitioning||!this._element.classList.contains("show"))return;if(P.trigger(this._element,"hide.bs.collapse").defaultPrevented)return;const t=this._getDimension();this._element.style[t]=this._element.getBoundingClientRect()[t]+"px",f(this._element),this._element.classList.add("collapsing"),this._element.classList.remove("collapse","show");const e=this._triggerArray.length;if(e>0)for(let t=0;t{this.setTransitioning(!1),this._element.classList.remove("collapsing"),this._element.classList.add("collapse"),P.trigger(this._element,"hidden.bs.collapse")},this._element,!0)}setTransitioning(t){this._isTransitioning=t}_getConfig(t){return(t={...J,...t}).toggle=Boolean(t.toggle),l("collapse",t,tt),t}_getDimension(){return this._element.classList.contains("width")?"width":"height"}_getParent(){let{parent:e}=this._config;e=a(e);const i=`[data-bs-toggle="collapse"][data-bs-parent="${e}"]`;return t.find(i,e).forEach(t=>{const e=s(t);this._addAriaAndCollapsedClass(e,[t])}),e}_addAriaAndCollapsedClass(t,e){if(!t||!e.length)return;const i=t.classList.contains("show");e.forEach(t=>{i?t.classList.remove("collapsed"):t.classList.add("collapsed"),t.setAttribute("aria-expanded",i)})}static collapseInterface(t,e){let i=et.getInstance(t);const n={...J,...U.getDataAttributes(t),..."object"==typeof e&&e?e:{}};if(!i&&n.toggle&&"string"==typeof e&&/show|hide/.test(e)&&(n.toggle=!1),i||(i=new et(t,n)),"string"==typeof e){if(void 0===i[e])throw new TypeError(`No method named "${e}"`);i[e]()}}static jQueryInterface(t){return this.each((function(){et.collapseInterface(this,t)}))}}P.on(document,"click.bs.collapse.data-api",'[data-bs-toggle="collapse"]',(function(e){("A"===e.target.tagName||e.delegateTarget&&"A"===e.delegateTarget.tagName)&&e.preventDefault();const i=U.getDataAttributes(this),s=n(this);t.find(s).forEach(t=>{const e=et.getInstance(t);let n;e?(null===e._parent&&"string"==typeof i.parent&&(e._config.parent=i.parent,e._parent=e._getParent()),n="toggle"):n=i,et.collapseInterface(t,n)})})),_(et);var it="top",nt="bottom",st="right",ot="left",rt=[it,nt,st,ot],at=rt.reduce((function(t,e){return t.concat([e+"-start",e+"-end"])}),[]),lt=[].concat(rt,["auto"]).reduce((function(t,e){return t.concat([e,e+"-start",e+"-end"])}),[]),ct=["beforeRead","read","afterRead","beforeMain","main","afterMain","beforeWrite","write","afterWrite"];function ht(t){return t?(t.nodeName||"").toLowerCase():null}function dt(t){if(null==t)return window;if("[object Window]"!==t.toString()){var e=t.ownerDocument;return e&&e.defaultView||window}return t}function ut(t){return t instanceof dt(t).Element||t instanceof Element}function ft(t){return t instanceof dt(t).HTMLElement||t instanceof HTMLElement}function pt(t){return"undefined"!=typeof ShadowRoot&&(t instanceof dt(t).ShadowRoot||t instanceof ShadowRoot)}var mt={name:"applyStyles",enabled:!0,phase:"write",fn:function(t){var e=t.state;Object.keys(e.elements).forEach((function(t){var i=e.styles[t]||{},n=e.attributes[t]||{},s=e.elements[t];ft(s)&&ht(s)&&(Object.assign(s.style,i),Object.keys(n).forEach((function(t){var e=n[t];!1===e?s.removeAttribute(t):s.setAttribute(t,!0===e?"":e)})))}))},effect:function(t){var e=t.state,i={popper:{position:e.options.strategy,left:"0",top:"0",margin:"0"},arrow:{position:"absolute"},reference:{}};return Object.assign(e.elements.popper.style,i.popper),e.styles=i,e.elements.arrow&&Object.assign(e.elements.arrow.style,i.arrow),function(){Object.keys(e.elements).forEach((function(t){var n=e.elements[t],s=e.attributes[t]||{},o=Object.keys(e.styles.hasOwnProperty(t)?e.styles[t]:i[t]).reduce((function(t,e){return t[e]="",t}),{});ft(n)&&ht(n)&&(Object.assign(n.style,o),Object.keys(s).forEach((function(t){n.removeAttribute(t)})))}))}},requires:["computeStyles"]};function gt(t){return t.split("-")[0]}function _t(t){var e=t.getBoundingClientRect();return{width:e.width,height:e.height,top:e.top,right:e.right,bottom:e.bottom,left:e.left,x:e.left,y:e.top}}function bt(t){var e=_t(t),i=t.offsetWidth,n=t.offsetHeight;return Math.abs(e.width-i)<=1&&(i=e.width),Math.abs(e.height-n)<=1&&(n=e.height),{x:t.offsetLeft,y:t.offsetTop,width:i,height:n}}function vt(t,e){var i=e.getRootNode&&e.getRootNode();if(t.contains(e))return!0;if(i&&pt(i)){var n=e;do{if(n&&t.isSameNode(n))return!0;n=n.parentNode||n.host}while(n)}return!1}function yt(t){return dt(t).getComputedStyle(t)}function wt(t){return["table","td","th"].indexOf(ht(t))>=0}function Et(t){return((ut(t)?t.ownerDocument:t.document)||window.document).documentElement}function At(t){return"html"===ht(t)?t:t.assignedSlot||t.parentNode||(pt(t)?t.host:null)||Et(t)}function Tt(t){return ft(t)&&"fixed"!==yt(t).position?t.offsetParent:null}function Ot(t){for(var e=dt(t),i=Tt(t);i&&wt(i)&&"static"===yt(i).position;)i=Tt(i);return i&&("html"===ht(i)||"body"===ht(i)&&"static"===yt(i).position)?e:i||function(t){var e=-1!==navigator.userAgent.toLowerCase().indexOf("firefox");if(-1!==navigator.userAgent.indexOf("Trident")&&ft(t)&&"fixed"===yt(t).position)return null;for(var i=At(t);ft(i)&&["html","body"].indexOf(ht(i))<0;){var n=yt(i);if("none"!==n.transform||"none"!==n.perspective||"paint"===n.contain||-1!==["transform","perspective"].indexOf(n.willChange)||e&&"filter"===n.willChange||e&&n.filter&&"none"!==n.filter)return i;i=i.parentNode}return null}(t)||e}function Ct(t){return["top","bottom"].indexOf(t)>=0?"x":"y"}var kt=Math.max,Lt=Math.min,xt=Math.round;function Dt(t,e,i){return kt(t,Lt(e,i))}function St(t){return Object.assign({},{top:0,right:0,bottom:0,left:0},t)}function It(t,e){return e.reduce((function(e,i){return e[i]=t,e}),{})}var Nt={name:"arrow",enabled:!0,phase:"main",fn:function(t){var e,i=t.state,n=t.name,s=t.options,o=i.elements.arrow,r=i.modifiersData.popperOffsets,a=gt(i.placement),l=Ct(a),c=[ot,st].indexOf(a)>=0?"height":"width";if(o&&r){var h=function(t,e){return St("number"!=typeof(t="function"==typeof t?t(Object.assign({},e.rects,{placement:e.placement})):t)?t:It(t,rt))}(s.padding,i),d=bt(o),u="y"===l?it:ot,f="y"===l?nt:st,p=i.rects.reference[c]+i.rects.reference[l]-r[l]-i.rects.popper[c],m=r[l]-i.rects.reference[l],g=Ot(o),_=g?"y"===l?g.clientHeight||0:g.clientWidth||0:0,b=p/2-m/2,v=h[u],y=_-d[c]-h[f],w=_/2-d[c]/2+b,E=Dt(v,w,y),A=l;i.modifiersData[n]=((e={})[A]=E,e.centerOffset=E-w,e)}},effect:function(t){var e=t.state,i=t.options.element,n=void 0===i?"[data-popper-arrow]":i;null!=n&&("string"!=typeof n||(n=e.elements.popper.querySelector(n)))&&vt(e.elements.popper,n)&&(e.elements.arrow=n)},requires:["popperOffsets"],requiresIfExists:["preventOverflow"]},jt={top:"auto",right:"auto",bottom:"auto",left:"auto"};function Mt(t){var e,i=t.popper,n=t.popperRect,s=t.placement,o=t.offsets,r=t.position,a=t.gpuAcceleration,l=t.adaptive,c=t.roundOffsets,h=!0===c?function(t){var e=t.x,i=t.y,n=window.devicePixelRatio||1;return{x:xt(xt(e*n)/n)||0,y:xt(xt(i*n)/n)||0}}(o):"function"==typeof c?c(o):o,d=h.x,u=void 0===d?0:d,f=h.y,p=void 0===f?0:f,m=o.hasOwnProperty("x"),g=o.hasOwnProperty("y"),_=ot,b=it,v=window;if(l){var y=Ot(i),w="clientHeight",E="clientWidth";y===dt(i)&&"static"!==yt(y=Et(i)).position&&(w="scrollHeight",E="scrollWidth"),y=y,s===it&&(b=nt,p-=y[w]-n.height,p*=a?1:-1),s===ot&&(_=st,u-=y[E]-n.width,u*=a?1:-1)}var A,T=Object.assign({position:r},l&&jt);return a?Object.assign({},T,((A={})[b]=g?"0":"",A[_]=m?"0":"",A.transform=(v.devicePixelRatio||1)<2?"translate("+u+"px, "+p+"px)":"translate3d("+u+"px, "+p+"px, 0)",A)):Object.assign({},T,((e={})[b]=g?p+"px":"",e[_]=m?u+"px":"",e.transform="",e))}var Pt={name:"computeStyles",enabled:!0,phase:"beforeWrite",fn:function(t){var e=t.state,i=t.options,n=i.gpuAcceleration,s=void 0===n||n,o=i.adaptive,r=void 0===o||o,a=i.roundOffsets,l=void 0===a||a,c={placement:gt(e.placement),popper:e.elements.popper,popperRect:e.rects.popper,gpuAcceleration:s};null!=e.modifiersData.popperOffsets&&(e.styles.popper=Object.assign({},e.styles.popper,Mt(Object.assign({},c,{offsets:e.modifiersData.popperOffsets,position:e.options.strategy,adaptive:r,roundOffsets:l})))),null!=e.modifiersData.arrow&&(e.styles.arrow=Object.assign({},e.styles.arrow,Mt(Object.assign({},c,{offsets:e.modifiersData.arrow,position:"absolute",adaptive:!1,roundOffsets:l})))),e.attributes.popper=Object.assign({},e.attributes.popper,{"data-popper-placement":e.placement})},data:{}},Ht={passive:!0},Rt={name:"eventListeners",enabled:!0,phase:"write",fn:function(){},effect:function(t){var e=t.state,i=t.instance,n=t.options,s=n.scroll,o=void 0===s||s,r=n.resize,a=void 0===r||r,l=dt(e.elements.popper),c=[].concat(e.scrollParents.reference,e.scrollParents.popper);return o&&c.forEach((function(t){t.addEventListener("scroll",i.update,Ht)})),a&&l.addEventListener("resize",i.update,Ht),function(){o&&c.forEach((function(t){t.removeEventListener("scroll",i.update,Ht)})),a&&l.removeEventListener("resize",i.update,Ht)}},data:{}},Bt={left:"right",right:"left",bottom:"top",top:"bottom"};function Wt(t){return t.replace(/left|right|bottom|top/g,(function(t){return Bt[t]}))}var qt={start:"end",end:"start"};function zt(t){return t.replace(/start|end/g,(function(t){return qt[t]}))}function $t(t){var e=dt(t);return{scrollLeft:e.pageXOffset,scrollTop:e.pageYOffset}}function Ut(t){return _t(Et(t)).left+$t(t).scrollLeft}function Ft(t){var e=yt(t),i=e.overflow,n=e.overflowX,s=e.overflowY;return/auto|scroll|overlay|hidden/.test(i+s+n)}function Vt(t,e){var i;void 0===e&&(e=[]);var n=function t(e){return["html","body","#document"].indexOf(ht(e))>=0?e.ownerDocument.body:ft(e)&&Ft(e)?e:t(At(e))}(t),s=n===(null==(i=t.ownerDocument)?void 0:i.body),o=dt(n),r=s?[o].concat(o.visualViewport||[],Ft(n)?n:[]):n,a=e.concat(r);return s?a:a.concat(Vt(At(r)))}function Kt(t){return Object.assign({},t,{left:t.x,top:t.y,right:t.x+t.width,bottom:t.y+t.height})}function Xt(t,e){return"viewport"===e?Kt(function(t){var e=dt(t),i=Et(t),n=e.visualViewport,s=i.clientWidth,o=i.clientHeight,r=0,a=0;return n&&(s=n.width,o=n.height,/^((?!chrome|android).)*safari/i.test(navigator.userAgent)||(r=n.offsetLeft,a=n.offsetTop)),{width:s,height:o,x:r+Ut(t),y:a}}(t)):ft(e)?function(t){var e=_t(t);return e.top=e.top+t.clientTop,e.left=e.left+t.clientLeft,e.bottom=e.top+t.clientHeight,e.right=e.left+t.clientWidth,e.width=t.clientWidth,e.height=t.clientHeight,e.x=e.left,e.y=e.top,e}(e):Kt(function(t){var e,i=Et(t),n=$t(t),s=null==(e=t.ownerDocument)?void 0:e.body,o=kt(i.scrollWidth,i.clientWidth,s?s.scrollWidth:0,s?s.clientWidth:0),r=kt(i.scrollHeight,i.clientHeight,s?s.scrollHeight:0,s?s.clientHeight:0),a=-n.scrollLeft+Ut(t),l=-n.scrollTop;return"rtl"===yt(s||i).direction&&(a+=kt(i.clientWidth,s?s.clientWidth:0)-o),{width:o,height:r,x:a,y:l}}(Et(t)))}function Yt(t){return t.split("-")[1]}function Qt(t){var e,i=t.reference,n=t.element,s=t.placement,o=s?gt(s):null,r=s?Yt(s):null,a=i.x+i.width/2-n.width/2,l=i.y+i.height/2-n.height/2;switch(o){case it:e={x:a,y:i.y-n.height};break;case nt:e={x:a,y:i.y+i.height};break;case st:e={x:i.x+i.width,y:l};break;case ot:e={x:i.x-n.width,y:l};break;default:e={x:i.x,y:i.y}}var c=o?Ct(o):null;if(null!=c){var h="y"===c?"height":"width";switch(r){case"start":e[c]=e[c]-(i[h]/2-n[h]/2);break;case"end":e[c]=e[c]+(i[h]/2-n[h]/2)}}return e}function Gt(t,e){void 0===e&&(e={});var i=e,n=i.placement,s=void 0===n?t.placement:n,o=i.boundary,r=void 0===o?"clippingParents":o,a=i.rootBoundary,l=void 0===a?"viewport":a,c=i.elementContext,h=void 0===c?"popper":c,d=i.altBoundary,u=void 0!==d&&d,f=i.padding,p=void 0===f?0:f,m=St("number"!=typeof p?p:It(p,rt)),g="popper"===h?"reference":"popper",_=t.elements.reference,b=t.rects.popper,v=t.elements[u?g:h],y=function(t,e,i){var n="clippingParents"===e?function(t){var e=Vt(At(t)),i=["absolute","fixed"].indexOf(yt(t).position)>=0&&ft(t)?Ot(t):t;return ut(i)?e.filter((function(t){return ut(t)&&vt(t,i)&&"body"!==ht(t)})):[]}(t):[].concat(e),s=[].concat(n,[i]),o=s[0],r=s.reduce((function(e,i){var n=Xt(t,i);return e.top=kt(n.top,e.top),e.right=Lt(n.right,e.right),e.bottom=Lt(n.bottom,e.bottom),e.left=kt(n.left,e.left),e}),Xt(t,o));return r.width=r.right-r.left,r.height=r.bottom-r.top,r.x=r.left,r.y=r.top,r}(ut(v)?v:v.contextElement||Et(t.elements.popper),r,l),w=_t(_),E=Qt({reference:w,element:b,strategy:"absolute",placement:s}),A=Kt(Object.assign({},b,E)),T="popper"===h?A:w,O={top:y.top-T.top+m.top,bottom:T.bottom-y.bottom+m.bottom,left:y.left-T.left+m.left,right:T.right-y.right+m.right},C=t.modifiersData.offset;if("popper"===h&&C){var k=C[s];Object.keys(O).forEach((function(t){var e=[st,nt].indexOf(t)>=0?1:-1,i=[it,nt].indexOf(t)>=0?"y":"x";O[t]+=k[i]*e}))}return O}function Zt(t,e){void 0===e&&(e={});var i=e,n=i.placement,s=i.boundary,o=i.rootBoundary,r=i.padding,a=i.flipVariations,l=i.allowedAutoPlacements,c=void 0===l?lt:l,h=Yt(n),d=h?a?at:at.filter((function(t){return Yt(t)===h})):rt,u=d.filter((function(t){return c.indexOf(t)>=0}));0===u.length&&(u=d);var f=u.reduce((function(e,i){return e[i]=Gt(t,{placement:i,boundary:s,rootBoundary:o,padding:r})[gt(i)],e}),{});return Object.keys(f).sort((function(t,e){return f[t]-f[e]}))}var Jt={name:"flip",enabled:!0,phase:"main",fn:function(t){var e=t.state,i=t.options,n=t.name;if(!e.modifiersData[n]._skip){for(var s=i.mainAxis,o=void 0===s||s,r=i.altAxis,a=void 0===r||r,l=i.fallbackPlacements,c=i.padding,h=i.boundary,d=i.rootBoundary,u=i.altBoundary,f=i.flipVariations,p=void 0===f||f,m=i.allowedAutoPlacements,g=e.options.placement,_=gt(g),b=l||(_!==g&&p?function(t){if("auto"===gt(t))return[];var e=Wt(t);return[zt(t),e,zt(e)]}(g):[Wt(g)]),v=[g].concat(b).reduce((function(t,i){return t.concat("auto"===gt(i)?Zt(e,{placement:i,boundary:h,rootBoundary:d,padding:c,flipVariations:p,allowedAutoPlacements:m}):i)}),[]),y=e.rects.reference,w=e.rects.popper,E=new Map,A=!0,T=v[0],O=0;O=0,D=x?"width":"height",S=Gt(e,{placement:C,boundary:h,rootBoundary:d,altBoundary:u,padding:c}),I=x?L?st:ot:L?nt:it;y[D]>w[D]&&(I=Wt(I));var N=Wt(I),j=[];if(o&&j.push(S[k]<=0),a&&j.push(S[I]<=0,S[N]<=0),j.every((function(t){return t}))){T=C,A=!1;break}E.set(C,j)}if(A)for(var M=function(t){var e=v.find((function(e){var i=E.get(e);if(i)return i.slice(0,t).every((function(t){return t}))}));if(e)return T=e,"break"},P=p?3:1;P>0&&"break"!==M(P);P--);e.placement!==T&&(e.modifiersData[n]._skip=!0,e.placement=T,e.reset=!0)}},requiresIfExists:["offset"],data:{_skip:!1}};function te(t,e,i){return void 0===i&&(i={x:0,y:0}),{top:t.top-e.height-i.y,right:t.right-e.width+i.x,bottom:t.bottom-e.height+i.y,left:t.left-e.width-i.x}}function ee(t){return[it,st,nt,ot].some((function(e){return t[e]>=0}))}var ie={name:"hide",enabled:!0,phase:"main",requiresIfExists:["preventOverflow"],fn:function(t){var e=t.state,i=t.name,n=e.rects.reference,s=e.rects.popper,o=e.modifiersData.preventOverflow,r=Gt(e,{elementContext:"reference"}),a=Gt(e,{altBoundary:!0}),l=te(r,n),c=te(a,s,o),h=ee(l),d=ee(c);e.modifiersData[i]={referenceClippingOffsets:l,popperEscapeOffsets:c,isReferenceHidden:h,hasPopperEscaped:d},e.attributes.popper=Object.assign({},e.attributes.popper,{"data-popper-reference-hidden":h,"data-popper-escaped":d})}},ne={name:"offset",enabled:!0,phase:"main",requires:["popperOffsets"],fn:function(t){var e=t.state,i=t.options,n=t.name,s=i.offset,o=void 0===s?[0,0]:s,r=lt.reduce((function(t,i){return t[i]=function(t,e,i){var n=gt(t),s=[ot,it].indexOf(n)>=0?-1:1,o="function"==typeof i?i(Object.assign({},e,{placement:t})):i,r=o[0],a=o[1];return r=r||0,a=(a||0)*s,[ot,st].indexOf(n)>=0?{x:a,y:r}:{x:r,y:a}}(i,e.rects,o),t}),{}),a=r[e.placement],l=a.x,c=a.y;null!=e.modifiersData.popperOffsets&&(e.modifiersData.popperOffsets.x+=l,e.modifiersData.popperOffsets.y+=c),e.modifiersData[n]=r}},se={name:"popperOffsets",enabled:!0,phase:"read",fn:function(t){var e=t.state,i=t.name;e.modifiersData[i]=Qt({reference:e.rects.reference,element:e.rects.popper,strategy:"absolute",placement:e.placement})},data:{}},oe={name:"preventOverflow",enabled:!0,phase:"main",fn:function(t){var e=t.state,i=t.options,n=t.name,s=i.mainAxis,o=void 0===s||s,r=i.altAxis,a=void 0!==r&&r,l=i.boundary,c=i.rootBoundary,h=i.altBoundary,d=i.padding,u=i.tether,f=void 0===u||u,p=i.tetherOffset,m=void 0===p?0:p,g=Gt(e,{boundary:l,rootBoundary:c,padding:d,altBoundary:h}),_=gt(e.placement),b=Yt(e.placement),v=!b,y=Ct(_),w="x"===y?"y":"x",E=e.modifiersData.popperOffsets,A=e.rects.reference,T=e.rects.popper,O="function"==typeof m?m(Object.assign({},e.rects,{placement:e.placement})):m,C={x:0,y:0};if(E){if(o||a){var k="y"===y?it:ot,L="y"===y?nt:st,x="y"===y?"height":"width",D=E[y],S=E[y]+g[k],I=E[y]-g[L],N=f?-T[x]/2:0,j="start"===b?A[x]:T[x],M="start"===b?-T[x]:-A[x],P=e.elements.arrow,H=f&&P?bt(P):{width:0,height:0},R=e.modifiersData["arrow#persistent"]?e.modifiersData["arrow#persistent"].padding:{top:0,right:0,bottom:0,left:0},B=R[k],W=R[L],q=Dt(0,A[x],H[x]),z=v?A[x]/2-N-q-B-O:j-q-B-O,$=v?-A[x]/2+N+q+W+O:M+q+W+O,U=e.elements.arrow&&Ot(e.elements.arrow),F=U?"y"===y?U.clientTop||0:U.clientLeft||0:0,V=e.modifiersData.offset?e.modifiersData.offset[e.placement][y]:0,K=E[y]+z-V-F,X=E[y]+$-V;if(o){var Y=Dt(f?Lt(S,K):S,D,f?kt(I,X):I);E[y]=Y,C[y]=Y-D}if(a){var Q="x"===y?it:ot,G="x"===y?nt:st,Z=E[w],J=Z+g[Q],tt=Z-g[G],et=Dt(f?Lt(J,K):J,Z,f?kt(tt,X):tt);E[w]=et,C[w]=et-Z}}e.modifiersData[n]=C}},requiresIfExists:["offset"]};function re(t,e,i){void 0===i&&(i=!1);var n,s,o=Et(e),r=_t(t),a=ft(e),l={scrollLeft:0,scrollTop:0},c={x:0,y:0};return(a||!a&&!i)&&(("body"!==ht(e)||Ft(o))&&(l=(n=e)!==dt(n)&&ft(n)?{scrollLeft:(s=n).scrollLeft,scrollTop:s.scrollTop}:$t(n)),ft(e)?((c=_t(e)).x+=e.clientLeft,c.y+=e.clientTop):o&&(c.x=Ut(o))),{x:r.left+l.scrollLeft-c.x,y:r.top+l.scrollTop-c.y,width:r.width,height:r.height}}var ae={placement:"bottom",modifiers:[],strategy:"absolute"};function le(){for(var t=arguments.length,e=new Array(t),i=0;i"applyStyles"===t.name&&!1===t.enabled);this._popper=ue(e,this._menu,i),n&&U.setDataAttribute(this._menu,"popper","static")}"ontouchstart"in document.documentElement&&!t.closest(".navbar-nav")&&[].concat(...document.body.children).forEach(t=>P.on(t,"mouseover",u)),this._element.focus(),this._element.setAttribute("aria-expanded",!0),this._menu.classList.toggle("show"),this._element.classList.toggle("show"),P.trigger(this._element,"shown.bs.dropdown",e)}}hide(){if(h(this._element)||!this._menu.classList.contains("show"))return;const t={relatedTarget:this._element};this._completeHide(t)}dispose(){this._popper&&this._popper.destroy(),super.dispose()}update(){this._inNavbar=this._detectNavbar(),this._popper&&this._popper.update()}_addEventListeners(){P.on(this._element,"click.bs.dropdown",t=>{t.preventDefault(),this.toggle()})}_completeHide(t){P.trigger(this._element,"hide.bs.dropdown",t).defaultPrevented||("ontouchstart"in document.documentElement&&[].concat(...document.body.children).forEach(t=>P.off(t,"mouseover",u)),this._popper&&this._popper.destroy(),this._menu.classList.remove("show"),this._element.classList.remove("show"),this._element.setAttribute("aria-expanded","false"),U.removeDataAttribute(this._menu,"popper"),P.trigger(this._element,"hidden.bs.dropdown",t))}_getConfig(t){if(t={...this.constructor.Default,...U.getDataAttributes(this._element),...t},l("dropdown",t,this.constructor.DefaultType),"object"==typeof t.reference&&!r(t.reference)&&"function"!=typeof t.reference.getBoundingClientRect)throw new TypeError("dropdown".toUpperCase()+': Option "reference" provided type "object" without a required "getBoundingClientRect" method.');return t}_getMenuElement(){return t.next(this._element,".dropdown-menu")[0]}_getPlacement(){const t=this._element.parentNode;if(t.classList.contains("dropend"))return ve;if(t.classList.contains("dropstart"))return ye;const e="end"===getComputedStyle(this._menu).getPropertyValue("--bs-position").trim();return t.classList.contains("dropup")?e?ge:me:e?be:_e}_detectNavbar(){return null!==this._element.closest(".navbar")}_getOffset(){const{offset:t}=this._config;return"string"==typeof t?t.split(",").map(t=>Number.parseInt(t,10)):"function"==typeof t?e=>t(e,this._element):t}_getPopperConfig(){const t={placement:this._getPlacement(),modifiers:[{name:"preventOverflow",options:{boundary:this._config.boundary}},{name:"offset",options:{offset:this._getOffset()}}]};return"static"===this._config.display&&(t.modifiers=[{name:"applyStyles",enabled:!1}]),{...t,..."function"==typeof this._config.popperConfig?this._config.popperConfig(t):this._config.popperConfig}}_selectMenuItem({key:e,target:i}){const n=t.find(".dropdown-menu .dropdown-item:not(.disabled):not(:disabled)",this._menu).filter(c);n.length&&y(n,i,"ArrowDown"===e,!n.includes(i)).focus()}static dropdownInterface(t,e){const i=Ae.getOrCreateInstance(t,e);if("string"==typeof e){if(void 0===i[e])throw new TypeError(`No method named "${e}"`);i[e]()}}static jQueryInterface(t){return this.each((function(){Ae.dropdownInterface(this,t)}))}static clearMenus(e){if(e&&(2===e.button||"keyup"===e.type&&"Tab"!==e.key))return;const i=t.find('[data-bs-toggle="dropdown"]');for(let t=0,n=i.length;tthis.matches('[data-bs-toggle="dropdown"]')?this:t.prev(this,'[data-bs-toggle="dropdown"]')[0];return"Escape"===e.key?(n().focus(),void Ae.clearMenus()):"ArrowUp"===e.key||"ArrowDown"===e.key?(i||n().click(),void Ae.getInstance(n())._selectMenuItem(e)):void(i&&"Space"!==e.key||Ae.clearMenus())}}P.on(document,"keydown.bs.dropdown.data-api",'[data-bs-toggle="dropdown"]',Ae.dataApiKeydownHandler),P.on(document,"keydown.bs.dropdown.data-api",".dropdown-menu",Ae.dataApiKeydownHandler),P.on(document,"click.bs.dropdown.data-api",Ae.clearMenus),P.on(document,"keyup.bs.dropdown.data-api",Ae.clearMenus),P.on(document,"click.bs.dropdown.data-api",'[data-bs-toggle="dropdown"]',(function(t){t.preventDefault(),Ae.dropdownInterface(this)})),_(Ae);class Te{constructor(){this._element=document.body}getWidth(){const t=document.documentElement.clientWidth;return Math.abs(window.innerWidth-t)}hide(){const t=this.getWidth();this._disableOverFlow(),this._setElementAttributes(this._element,"paddingRight",e=>e+t),this._setElementAttributes(".fixed-top, .fixed-bottom, .is-fixed, .sticky-top","paddingRight",e=>e+t),this._setElementAttributes(".sticky-top","marginRight",e=>e-t)}_disableOverFlow(){this._saveInitialAttribute(this._element,"overflow"),this._element.style.overflow="hidden"}_setElementAttributes(t,e,i){const n=this.getWidth();this._applyManipulationCallback(t,t=>{if(t!==this._element&&window.innerWidth>t.clientWidth+n)return;this._saveInitialAttribute(t,e);const s=window.getComputedStyle(t)[e];t.style[e]=i(Number.parseFloat(s))+"px"})}reset(){this._resetElementAttributes(this._element,"overflow"),this._resetElementAttributes(this._element,"paddingRight"),this._resetElementAttributes(".fixed-top, .fixed-bottom, .is-fixed, .sticky-top","paddingRight"),this._resetElementAttributes(".sticky-top","marginRight")}_saveInitialAttribute(t,e){const i=t.style[e];i&&U.setDataAttribute(t,e,i)}_resetElementAttributes(t,e){this._applyManipulationCallback(t,t=>{const i=U.getDataAttribute(t,e);void 0===i?t.style.removeProperty(e):(U.removeDataAttribute(t,e),t.style[e]=i)})}_applyManipulationCallback(e,i){r(e)?i(e):t.find(e,this._element).forEach(i)}isOverflowing(){return this.getWidth()>0}}const Oe={isVisible:!0,isAnimated:!1,rootElement:"body",clickCallback:null},Ce={isVisible:"boolean",isAnimated:"boolean",rootElement:"(element|string)",clickCallback:"(function|null)"};class ke{constructor(t){this._config=this._getConfig(t),this._isAppended=!1,this._element=null}show(t){this._config.isVisible?(this._append(),this._config.isAnimated&&f(this._getElement()),this._getElement().classList.add("show"),this._emulateAnimation(()=>{b(t)})):b(t)}hide(t){this._config.isVisible?(this._getElement().classList.remove("show"),this._emulateAnimation(()=>{this.dispose(),b(t)})):b(t)}_getElement(){if(!this._element){const t=document.createElement("div");t.className="modal-backdrop",this._config.isAnimated&&t.classList.add("fade"),this._element=t}return this._element}_getConfig(t){return(t={...Oe,..."object"==typeof t?t:{}}).rootElement=a(t.rootElement),l("backdrop",t,Ce),t}_append(){this._isAppended||(this._config.rootElement.appendChild(this._getElement()),P.on(this._getElement(),"mousedown.bs.backdrop",()=>{b(this._config.clickCallback)}),this._isAppended=!0)}dispose(){this._isAppended&&(P.off(this._element,"mousedown.bs.backdrop"),this._element.remove(),this._isAppended=!1)}_emulateAnimation(t){v(t,this._getElement(),this._config.isAnimated)}}const Le={backdrop:!0,keyboard:!0,focus:!0},xe={backdrop:"(boolean|string)",keyboard:"boolean",focus:"boolean"};class De extends B{constructor(e,i){super(e),this._config=this._getConfig(i),this._dialog=t.findOne(".modal-dialog",this._element),this._backdrop=this._initializeBackDrop(),this._isShown=!1,this._ignoreBackdropClick=!1,this._isTransitioning=!1,this._scrollBar=new Te}static get Default(){return Le}static get NAME(){return"modal"}toggle(t){return this._isShown?this.hide():this.show(t)}show(t){this._isShown||this._isTransitioning||P.trigger(this._element,"show.bs.modal",{relatedTarget:t}).defaultPrevented||(this._isShown=!0,this._isAnimated()&&(this._isTransitioning=!0),this._scrollBar.hide(),document.body.classList.add("modal-open"),this._adjustDialog(),this._setEscapeEvent(),this._setResizeEvent(),P.on(this._element,"click.dismiss.bs.modal",'[data-bs-dismiss="modal"]',t=>this.hide(t)),P.on(this._dialog,"mousedown.dismiss.bs.modal",()=>{P.one(this._element,"mouseup.dismiss.bs.modal",t=>{t.target===this._element&&(this._ignoreBackdropClick=!0)})}),this._showBackdrop(()=>this._showElement(t)))}hide(t){if(t&&["A","AREA"].includes(t.target.tagName)&&t.preventDefault(),!this._isShown||this._isTransitioning)return;if(P.trigger(this._element,"hide.bs.modal").defaultPrevented)return;this._isShown=!1;const e=this._isAnimated();e&&(this._isTransitioning=!0),this._setEscapeEvent(),this._setResizeEvent(),P.off(document,"focusin.bs.modal"),this._element.classList.remove("show"),P.off(this._element,"click.dismiss.bs.modal"),P.off(this._dialog,"mousedown.dismiss.bs.modal"),this._queueCallback(()=>this._hideModal(),this._element,e)}dispose(){[window,this._dialog].forEach(t=>P.off(t,".bs.modal")),this._backdrop.dispose(),super.dispose(),P.off(document,"focusin.bs.modal")}handleUpdate(){this._adjustDialog()}_initializeBackDrop(){return new ke({isVisible:Boolean(this._config.backdrop),isAnimated:this._isAnimated()})}_getConfig(t){return t={...Le,...U.getDataAttributes(this._element),..."object"==typeof t?t:{}},l("modal",t,xe),t}_showElement(e){const i=this._isAnimated(),n=t.findOne(".modal-body",this._dialog);this._element.parentNode&&this._element.parentNode.nodeType===Node.ELEMENT_NODE||document.body.appendChild(this._element),this._element.style.display="block",this._element.removeAttribute("aria-hidden"),this._element.setAttribute("aria-modal",!0),this._element.setAttribute("role","dialog"),this._element.scrollTop=0,n&&(n.scrollTop=0),i&&f(this._element),this._element.classList.add("show"),this._config.focus&&this._enforceFocus(),this._queueCallback(()=>{this._config.focus&&this._element.focus(),this._isTransitioning=!1,P.trigger(this._element,"shown.bs.modal",{relatedTarget:e})},this._dialog,i)}_enforceFocus(){P.off(document,"focusin.bs.modal"),P.on(document,"focusin.bs.modal",t=>{document===t.target||this._element===t.target||this._element.contains(t.target)||this._element.focus()})}_setEscapeEvent(){this._isShown?P.on(this._element,"keydown.dismiss.bs.modal",t=>{this._config.keyboard&&"Escape"===t.key?(t.preventDefault(),this.hide()):this._config.keyboard||"Escape"!==t.key||this._triggerBackdropTransition()}):P.off(this._element,"keydown.dismiss.bs.modal")}_setResizeEvent(){this._isShown?P.on(window,"resize.bs.modal",()=>this._adjustDialog()):P.off(window,"resize.bs.modal")}_hideModal(){this._element.style.display="none",this._element.setAttribute("aria-hidden",!0),this._element.removeAttribute("aria-modal"),this._element.removeAttribute("role"),this._isTransitioning=!1,this._backdrop.hide(()=>{document.body.classList.remove("modal-open"),this._resetAdjustments(),this._scrollBar.reset(),P.trigger(this._element,"hidden.bs.modal")})}_showBackdrop(t){P.on(this._element,"click.dismiss.bs.modal",t=>{this._ignoreBackdropClick?this._ignoreBackdropClick=!1:t.target===t.currentTarget&&(!0===this._config.backdrop?this.hide():"static"===this._config.backdrop&&this._triggerBackdropTransition())}),this._backdrop.show(t)}_isAnimated(){return this._element.classList.contains("fade")}_triggerBackdropTransition(){if(P.trigger(this._element,"hidePrevented.bs.modal").defaultPrevented)return;const{classList:t,scrollHeight:e,style:i}=this._element,n=e>document.documentElement.clientHeight;!n&&"hidden"===i.overflowY||t.contains("modal-static")||(n||(i.overflowY="hidden"),t.add("modal-static"),this._queueCallback(()=>{t.remove("modal-static"),n||this._queueCallback(()=>{i.overflowY=""},this._dialog)},this._dialog),this._element.focus())}_adjustDialog(){const t=this._element.scrollHeight>document.documentElement.clientHeight,e=this._scrollBar.getWidth(),i=e>0;(!i&&t&&!g()||i&&!t&&g())&&(this._element.style.paddingLeft=e+"px"),(i&&!t&&!g()||!i&&t&&g())&&(this._element.style.paddingRight=e+"px")}_resetAdjustments(){this._element.style.paddingLeft="",this._element.style.paddingRight=""}static jQueryInterface(t,e){return this.each((function(){const i=De.getOrCreateInstance(this,t);if("string"==typeof t){if(void 0===i[t])throw new TypeError(`No method named "${t}"`);i[t](e)}}))}}P.on(document,"click.bs.modal.data-api",'[data-bs-toggle="modal"]',(function(t){const e=s(this);["A","AREA"].includes(this.tagName)&&t.preventDefault(),P.one(e,"show.bs.modal",t=>{t.defaultPrevented||P.one(e,"hidden.bs.modal",()=>{c(this)&&this.focus()})}),De.getOrCreateInstance(e).toggle(this)})),_(De);const Se={backdrop:!0,keyboard:!0,scroll:!1},Ie={backdrop:"boolean",keyboard:"boolean",scroll:"boolean"};class Ne extends B{constructor(t,e){super(t),this._config=this._getConfig(e),this._isShown=!1,this._backdrop=this._initializeBackDrop(),this._addEventListeners()}static get NAME(){return"offcanvas"}static get Default(){return Se}toggle(t){return this._isShown?this.hide():this.show(t)}show(t){this._isShown||P.trigger(this._element,"show.bs.offcanvas",{relatedTarget:t}).defaultPrevented||(this._isShown=!0,this._element.style.visibility="visible",this._backdrop.show(),this._config.scroll||((new Te).hide(),this._enforceFocusOnElement(this._element)),this._element.removeAttribute("aria-hidden"),this._element.setAttribute("aria-modal",!0),this._element.setAttribute("role","dialog"),this._element.classList.add("show"),this._queueCallback(()=>{P.trigger(this._element,"shown.bs.offcanvas",{relatedTarget:t})},this._element,!0))}hide(){this._isShown&&(P.trigger(this._element,"hide.bs.offcanvas").defaultPrevented||(P.off(document,"focusin.bs.offcanvas"),this._element.blur(),this._isShown=!1,this._element.classList.remove("show"),this._backdrop.hide(),this._queueCallback(()=>{this._element.setAttribute("aria-hidden",!0),this._element.removeAttribute("aria-modal"),this._element.removeAttribute("role"),this._element.style.visibility="hidden",this._config.scroll||(new Te).reset(),P.trigger(this._element,"hidden.bs.offcanvas")},this._element,!0)))}dispose(){this._backdrop.dispose(),super.dispose(),P.off(document,"focusin.bs.offcanvas")}_getConfig(t){return t={...Se,...U.getDataAttributes(this._element),..."object"==typeof t?t:{}},l("offcanvas",t,Ie),t}_initializeBackDrop(){return new ke({isVisible:this._config.backdrop,isAnimated:!0,rootElement:this._element.parentNode,clickCallback:()=>this.hide()})}_enforceFocusOnElement(t){P.off(document,"focusin.bs.offcanvas"),P.on(document,"focusin.bs.offcanvas",e=>{document===e.target||t===e.target||t.contains(e.target)||t.focus()}),t.focus()}_addEventListeners(){P.on(this._element,"click.dismiss.bs.offcanvas",'[data-bs-dismiss="offcanvas"]',()=>this.hide()),P.on(this._element,"keydown.dismiss.bs.offcanvas",t=>{this._config.keyboard&&"Escape"===t.key&&this.hide()})}static jQueryInterface(t){return this.each((function(){const e=Ne.getOrCreateInstance(this,t);if("string"==typeof t){if(void 0===e[t]||t.startsWith("_")||"constructor"===t)throw new TypeError(`No method named "${t}"`);e[t](this)}}))}}P.on(document,"click.bs.offcanvas.data-api",'[data-bs-toggle="offcanvas"]',(function(e){const i=s(this);if(["A","AREA"].includes(this.tagName)&&e.preventDefault(),h(this))return;P.one(i,"hidden.bs.offcanvas",()=>{c(this)&&this.focus()});const n=t.findOne(".offcanvas.show");n&&n!==i&&Ne.getInstance(n).hide(),Ne.getOrCreateInstance(i).toggle(this)})),P.on(window,"load.bs.offcanvas.data-api",()=>t.find(".offcanvas.show").forEach(t=>Ne.getOrCreateInstance(t).show())),_(Ne);const je=new Set(["background","cite","href","itemtype","longdesc","poster","src","xlink:href"]),Me=/^(?:(?:https?|mailto|ftp|tel|file):|[^#&/:?]*(?:[#/?]|$))/i,Pe=/^data:(?:image\/(?:bmp|gif|jpeg|jpg|png|tiff|webp)|video\/(?:mpeg|mp4|ogg|webm)|audio\/(?:mp3|oga|ogg|opus));base64,[\d+/a-z]+=*$/i,He=(t,e)=>{const i=t.nodeName.toLowerCase();if(e.includes(i))return!je.has(i)||Boolean(Me.test(t.nodeValue)||Pe.test(t.nodeValue));const n=e.filter(t=>t instanceof RegExp);for(let t=0,e=n.length;t{He(t,a)||i.removeAttribute(t.nodeName)})}return n.body.innerHTML}const Be=new RegExp("(^|\\s)bs-tooltip\\S+","g"),We=new Set(["sanitize","allowList","sanitizeFn"]),qe={animation:"boolean",template:"string",title:"(string|element|function)",trigger:"string",delay:"(number|object)",html:"boolean",selector:"(string|boolean)",placement:"(string|function)",offset:"(array|string|function)",container:"(string|element|boolean)",fallbackPlacements:"array",boundary:"(string|element)",customClass:"(string|function)",sanitize:"boolean",sanitizeFn:"(null|function)",allowList:"object",popperConfig:"(null|object|function)"},ze={AUTO:"auto",TOP:"top",RIGHT:g()?"left":"right",BOTTOM:"bottom",LEFT:g()?"right":"left"},$e={animation:!0,template:'',trigger:"hover focus",title:"",delay:0,html:!1,selector:!1,placement:"top",offset:[0,0],container:!1,fallbackPlacements:["top","right","bottom","left"],boundary:"clippingParents",customClass:"",sanitize:!0,sanitizeFn:null,allowList:{"*":["class","dir","id","lang","role",/^aria-[\w-]*$/i],a:["target","href","title","rel"],area:[],b:[],br:[],col:[],code:[],div:[],em:[],hr:[],h1:[],h2:[],h3:[],h4:[],h5:[],h6:[],i:[],img:["src","srcset","alt","title","width","height"],li:[],ol:[],p:[],pre:[],s:[],small:[],span:[],sub:[],sup:[],strong:[],u:[],ul:[]},popperConfig:null},Ue={HIDE:"hide.bs.tooltip",HIDDEN:"hidden.bs.tooltip",SHOW:"show.bs.tooltip",SHOWN:"shown.bs.tooltip",INSERTED:"inserted.bs.tooltip",CLICK:"click.bs.tooltip",FOCUSIN:"focusin.bs.tooltip",FOCUSOUT:"focusout.bs.tooltip",MOUSEENTER:"mouseenter.bs.tooltip",MOUSELEAVE:"mouseleave.bs.tooltip"};class Fe extends B{constructor(t,e){if(void 0===fe)throw new TypeError("Bootstrap's tooltips require Popper (https://popper.js.org)");super(t),this._isEnabled=!0,this._timeout=0,this._hoverState="",this._activeTrigger={},this._popper=null,this._config=this._getConfig(e),this.tip=null,this._setListeners()}static get Default(){return $e}static get NAME(){return"tooltip"}static get Event(){return Ue}static get DefaultType(){return qe}enable(){this._isEnabled=!0}disable(){this._isEnabled=!1}toggleEnabled(){this._isEnabled=!this._isEnabled}toggle(t){if(this._isEnabled)if(t){const e=this._initializeOnDelegatedTarget(t);e._activeTrigger.click=!e._activeTrigger.click,e._isWithActiveTrigger()?e._enter(null,e):e._leave(null,e)}else{if(this.getTipElement().classList.contains("show"))return void this._leave(null,this);this._enter(null,this)}}dispose(){clearTimeout(this._timeout),P.off(this._element.closest(".modal"),"hide.bs.modal",this._hideModalHandler),this.tip&&this.tip.remove(),this._popper&&this._popper.destroy(),super.dispose()}show(){if("none"===this._element.style.display)throw new Error("Please use show on visible elements");if(!this.isWithContent()||!this._isEnabled)return;const t=P.trigger(this._element,this.constructor.Event.SHOW),i=d(this._element),n=null===i?this._element.ownerDocument.documentElement.contains(this._element):i.contains(this._element);if(t.defaultPrevented||!n)return;const s=this.getTipElement(),o=e(this.constructor.NAME);s.setAttribute("id",o),this._element.setAttribute("aria-describedby",o),this.setContent(),this._config.animation&&s.classList.add("fade");const r="function"==typeof this._config.placement?this._config.placement.call(this,s,this._element):this._config.placement,a=this._getAttachment(r);this._addAttachmentClass(a);const{container:l}=this._config;R.set(s,this.constructor.DATA_KEY,this),this._element.ownerDocument.documentElement.contains(this.tip)||(l.appendChild(s),P.trigger(this._element,this.constructor.Event.INSERTED)),this._popper?this._popper.update():this._popper=ue(this._element,s,this._getPopperConfig(a)),s.classList.add("show");const c="function"==typeof this._config.customClass?this._config.customClass():this._config.customClass;c&&s.classList.add(...c.split(" ")),"ontouchstart"in document.documentElement&&[].concat(...document.body.children).forEach(t=>{P.on(t,"mouseover",u)});const h=this.tip.classList.contains("fade");this._queueCallback(()=>{const t=this._hoverState;this._hoverState=null,P.trigger(this._element,this.constructor.Event.SHOWN),"out"===t&&this._leave(null,this)},this.tip,h)}hide(){if(!this._popper)return;const t=this.getTipElement();if(P.trigger(this._element,this.constructor.Event.HIDE).defaultPrevented)return;t.classList.remove("show"),"ontouchstart"in document.documentElement&&[].concat(...document.body.children).forEach(t=>P.off(t,"mouseover",u)),this._activeTrigger.click=!1,this._activeTrigger.focus=!1,this._activeTrigger.hover=!1;const e=this.tip.classList.contains("fade");this._queueCallback(()=>{this._isWithActiveTrigger()||("show"!==this._hoverState&&t.remove(),this._cleanTipClass(),this._element.removeAttribute("aria-describedby"),P.trigger(this._element,this.constructor.Event.HIDDEN),this._popper&&(this._popper.destroy(),this._popper=null))},this.tip,e),this._hoverState=""}update(){null!==this._popper&&this._popper.update()}isWithContent(){return Boolean(this.getTitle())}getTipElement(){if(this.tip)return this.tip;const t=document.createElement("div");return t.innerHTML=this._config.template,this.tip=t.children[0],this.tip}setContent(){const e=this.getTipElement();this.setElementContent(t.findOne(".tooltip-inner",e),this.getTitle()),e.classList.remove("fade","show")}setElementContent(t,e){if(null!==t)return r(e)?(e=a(e),void(this._config.html?e.parentNode!==t&&(t.innerHTML="",t.appendChild(e)):t.textContent=e.textContent)):void(this._config.html?(this._config.sanitize&&(e=Re(e,this._config.allowList,this._config.sanitizeFn)),t.innerHTML=e):t.textContent=e)}getTitle(){let t=this._element.getAttribute("data-bs-original-title");return t||(t="function"==typeof this._config.title?this._config.title.call(this._element):this._config.title),t}updateAttachment(t){return"right"===t?"end":"left"===t?"start":t}_initializeOnDelegatedTarget(t,e){const i=this.constructor.DATA_KEY;return(e=e||R.get(t.delegateTarget,i))||(e=new this.constructor(t.delegateTarget,this._getDelegateConfig()),R.set(t.delegateTarget,i,e)),e}_getOffset(){const{offset:t}=this._config;return"string"==typeof t?t.split(",").map(t=>Number.parseInt(t,10)):"function"==typeof t?e=>t(e,this._element):t}_getPopperConfig(t){const e={placement:t,modifiers:[{name:"flip",options:{fallbackPlacements:this._config.fallbackPlacements}},{name:"offset",options:{offset:this._getOffset()}},{name:"preventOverflow",options:{boundary:this._config.boundary}},{name:"arrow",options:{element:`.${this.constructor.NAME}-arrow`}},{name:"onChange",enabled:!0,phase:"afterWrite",fn:t=>this._handlePopperPlacementChange(t)}],onFirstUpdate:t=>{t.options.placement!==t.placement&&this._handlePopperPlacementChange(t)}};return{...e,..."function"==typeof this._config.popperConfig?this._config.popperConfig(e):this._config.popperConfig}}_addAttachmentClass(t){this.getTipElement().classList.add("bs-tooltip-"+this.updateAttachment(t))}_getAttachment(t){return ze[t.toUpperCase()]}_setListeners(){this._config.trigger.split(" ").forEach(t=>{if("click"===t)P.on(this._element,this.constructor.Event.CLICK,this._config.selector,t=>this.toggle(t));else if("manual"!==t){const e="hover"===t?this.constructor.Event.MOUSEENTER:this.constructor.Event.FOCUSIN,i="hover"===t?this.constructor.Event.MOUSELEAVE:this.constructor.Event.FOCUSOUT;P.on(this._element,e,this._config.selector,t=>this._enter(t)),P.on(this._element,i,this._config.selector,t=>this._leave(t))}}),this._hideModalHandler=()=>{this._element&&this.hide()},P.on(this._element.closest(".modal"),"hide.bs.modal",this._hideModalHandler),this._config.selector?this._config={...this._config,trigger:"manual",selector:""}:this._fixTitle()}_fixTitle(){const t=this._element.getAttribute("title"),e=typeof this._element.getAttribute("data-bs-original-title");(t||"string"!==e)&&(this._element.setAttribute("data-bs-original-title",t||""),!t||this._element.getAttribute("aria-label")||this._element.textContent||this._element.setAttribute("aria-label",t),this._element.setAttribute("title",""))}_enter(t,e){e=this._initializeOnDelegatedTarget(t,e),t&&(e._activeTrigger["focusin"===t.type?"focus":"hover"]=!0),e.getTipElement().classList.contains("show")||"show"===e._hoverState?e._hoverState="show":(clearTimeout(e._timeout),e._hoverState="show",e._config.delay&&e._config.delay.show?e._timeout=setTimeout(()=>{"show"===e._hoverState&&e.show()},e._config.delay.show):e.show())}_leave(t,e){e=this._initializeOnDelegatedTarget(t,e),t&&(e._activeTrigger["focusout"===t.type?"focus":"hover"]=e._element.contains(t.relatedTarget)),e._isWithActiveTrigger()||(clearTimeout(e._timeout),e._hoverState="out",e._config.delay&&e._config.delay.hide?e._timeout=setTimeout(()=>{"out"===e._hoverState&&e.hide()},e._config.delay.hide):e.hide())}_isWithActiveTrigger(){for(const t in this._activeTrigger)if(this._activeTrigger[t])return!0;return!1}_getConfig(t){const e=U.getDataAttributes(this._element);return Object.keys(e).forEach(t=>{We.has(t)&&delete e[t]}),(t={...this.constructor.Default,...e,..."object"==typeof t&&t?t:{}}).container=!1===t.container?document.body:a(t.container),"number"==typeof t.delay&&(t.delay={show:t.delay,hide:t.delay}),"number"==typeof t.title&&(t.title=t.title.toString()),"number"==typeof t.content&&(t.content=t.content.toString()),l("tooltip",t,this.constructor.DefaultType),t.sanitize&&(t.template=Re(t.template,t.allowList,t.sanitizeFn)),t}_getDelegateConfig(){const t={};if(this._config)for(const e in this._config)this.constructor.Default[e]!==this._config[e]&&(t[e]=this._config[e]);return t}_cleanTipClass(){const t=this.getTipElement(),e=t.getAttribute("class").match(Be);null!==e&&e.length>0&&e.map(t=>t.trim()).forEach(e=>t.classList.remove(e))}_handlePopperPlacementChange(t){const{state:e}=t;e&&(this.tip=e.elements.popper,this._cleanTipClass(),this._addAttachmentClass(this._getAttachment(e.placement)))}static jQueryInterface(t){return this.each((function(){const e=Fe.getOrCreateInstance(this,t);if("string"==typeof t){if(void 0===e[t])throw new TypeError(`No method named "${t}"`);e[t]()}}))}}_(Fe);const Ve=new RegExp("(^|\\s)bs-popover\\S+","g"),Ke={...Fe.Default,placement:"right",offset:[0,8],trigger:"click",content:"",template:''},Xe={...Fe.DefaultType,content:"(string|element|function)"},Ye={HIDE:"hide.bs.popover",HIDDEN:"hidden.bs.popover",SHOW:"show.bs.popover",SHOWN:"shown.bs.popover",INSERTED:"inserted.bs.popover",CLICK:"click.bs.popover",FOCUSIN:"focusin.bs.popover",FOCUSOUT:"focusout.bs.popover",MOUSEENTER:"mouseenter.bs.popover",MOUSELEAVE:"mouseleave.bs.popover"};class Qe extends Fe{static get Default(){return Ke}static get NAME(){return"popover"}static get Event(){return Ye}static get DefaultType(){return Xe}isWithContent(){return this.getTitle()||this._getContent()}getTipElement(){return this.tip||(this.tip=super.getTipElement(),this.getTitle()||t.findOne(".popover-header",this.tip).remove(),this._getContent()||t.findOne(".popover-body",this.tip).remove()),this.tip}setContent(){const e=this.getTipElement();this.setElementContent(t.findOne(".popover-header",e),this.getTitle());let i=this._getContent();"function"==typeof i&&(i=i.call(this._element)),this.setElementContent(t.findOne(".popover-body",e),i),e.classList.remove("fade","show")}_addAttachmentClass(t){this.getTipElement().classList.add("bs-popover-"+this.updateAttachment(t))}_getContent(){return this._element.getAttribute("data-bs-content")||this._config.content}_cleanTipClass(){const t=this.getTipElement(),e=t.getAttribute("class").match(Ve);null!==e&&e.length>0&&e.map(t=>t.trim()).forEach(e=>t.classList.remove(e))}static jQueryInterface(t){return this.each((function(){const e=Qe.getOrCreateInstance(this,t);if("string"==typeof t){if(void 0===e[t])throw new TypeError(`No method named "${t}"`);e[t]()}}))}}_(Qe);const Ge={offset:10,method:"auto",target:""},Ze={offset:"number",method:"string",target:"(string|element)"};class Je extends B{constructor(t,e){super(t),this._scrollElement="BODY"===this._element.tagName?window:this._element,this._config=this._getConfig(e),this._selector=`${this._config.target} .nav-link, ${this._config.target} .list-group-item, ${this._config.target} .dropdown-item`,this._offsets=[],this._targets=[],this._activeTarget=null,this._scrollHeight=0,P.on(this._scrollElement,"scroll.bs.scrollspy",()=>this._process()),this.refresh(),this._process()}static get Default(){return Ge}static get NAME(){return"scrollspy"}refresh(){const e=this._scrollElement===this._scrollElement.window?"offset":"position",i="auto"===this._config.method?e:this._config.method,s="position"===i?this._getScrollTop():0;this._offsets=[],this._targets=[],this._scrollHeight=this._getScrollHeight(),t.find(this._selector).map(e=>{const o=n(e),r=o?t.findOne(o):null;if(r){const t=r.getBoundingClientRect();if(t.width||t.height)return[U[i](r).top+s,o]}return null}).filter(t=>t).sort((t,e)=>t[0]-e[0]).forEach(t=>{this._offsets.push(t[0]),this._targets.push(t[1])})}dispose(){P.off(this._scrollElement,".bs.scrollspy"),super.dispose()}_getConfig(t){if("string"!=typeof(t={...Ge,...U.getDataAttributes(this._element),..."object"==typeof t&&t?t:{}}).target&&r(t.target)){let{id:i}=t.target;i||(i=e("scrollspy"),t.target.id=i),t.target="#"+i}return l("scrollspy",t,Ze),t}_getScrollTop(){return this._scrollElement===window?this._scrollElement.pageYOffset:this._scrollElement.scrollTop}_getScrollHeight(){return this._scrollElement.scrollHeight||Math.max(document.body.scrollHeight,document.documentElement.scrollHeight)}_getOffsetHeight(){return this._scrollElement===window?window.innerHeight:this._scrollElement.getBoundingClientRect().height}_process(){const t=this._getScrollTop()+this._config.offset,e=this._getScrollHeight(),i=this._config.offset+e-this._getOffsetHeight();if(this._scrollHeight!==e&&this.refresh(),t>=i){const t=this._targets[this._targets.length-1];this._activeTarget!==t&&this._activate(t)}else{if(this._activeTarget&&t0)return this._activeTarget=null,void this._clear();for(let e=this._offsets.length;e--;)this._activeTarget!==this._targets[e]&&t>=this._offsets[e]&&(void 0===this._offsets[e+1]||t`${t}[data-bs-target="${e}"],${t}[href="${e}"]`),n=t.findOne(i.join(","));n.classList.contains("dropdown-item")?(t.findOne(".dropdown-toggle",n.closest(".dropdown")).classList.add("active"),n.classList.add("active")):(n.classList.add("active"),t.parents(n,".nav, .list-group").forEach(e=>{t.prev(e,".nav-link, .list-group-item").forEach(t=>t.classList.add("active")),t.prev(e,".nav-item").forEach(e=>{t.children(e,".nav-link").forEach(t=>t.classList.add("active"))})})),P.trigger(this._scrollElement,"activate.bs.scrollspy",{relatedTarget:e})}_clear(){t.find(this._selector).filter(t=>t.classList.contains("active")).forEach(t=>t.classList.remove("active"))}static jQueryInterface(t){return this.each((function(){const e=Je.getOrCreateInstance(this,t);if("string"==typeof t){if(void 0===e[t])throw new TypeError(`No method named "${t}"`);e[t]()}}))}}P.on(window,"load.bs.scrollspy.data-api",()=>{t.find('[data-bs-spy="scroll"]').forEach(t=>new Je(t))}),_(Je);class ti extends B{static get NAME(){return"tab"}show(){if(this._element.parentNode&&this._element.parentNode.nodeType===Node.ELEMENT_NODE&&this._element.classList.contains("active"))return;let e;const i=s(this._element),n=this._element.closest(".nav, .list-group");if(n){const i="UL"===n.nodeName||"OL"===n.nodeName?":scope > li > .active":".active";e=t.find(i,n),e=e[e.length-1]}const o=e?P.trigger(e,"hide.bs.tab",{relatedTarget:this._element}):null;if(P.trigger(this._element,"show.bs.tab",{relatedTarget:e}).defaultPrevented||null!==o&&o.defaultPrevented)return;this._activate(this._element,n);const r=()=>{P.trigger(e,"hidden.bs.tab",{relatedTarget:this._element}),P.trigger(this._element,"shown.bs.tab",{relatedTarget:e})};i?this._activate(i,i.parentNode,r):r()}_activate(e,i,n){const s=(!i||"UL"!==i.nodeName&&"OL"!==i.nodeName?t.children(i,".active"):t.find(":scope > li > .active",i))[0],o=n&&s&&s.classList.contains("fade"),r=()=>this._transitionComplete(e,s,n);s&&o?(s.classList.remove("show"),this._queueCallback(r,e,!0)):r()}_transitionComplete(e,i,n){if(i){i.classList.remove("active");const e=t.findOne(":scope > .dropdown-menu .active",i.parentNode);e&&e.classList.remove("active"),"tab"===i.getAttribute("role")&&i.setAttribute("aria-selected",!1)}e.classList.add("active"),"tab"===e.getAttribute("role")&&e.setAttribute("aria-selected",!0),f(e),e.classList.contains("fade")&&e.classList.add("show");let s=e.parentNode;if(s&&"LI"===s.nodeName&&(s=s.parentNode),s&&s.classList.contains("dropdown-menu")){const i=e.closest(".dropdown");i&&t.find(".dropdown-toggle",i).forEach(t=>t.classList.add("active")),e.setAttribute("aria-expanded",!0)}n&&n()}static jQueryInterface(t){return this.each((function(){const e=ti.getOrCreateInstance(this);if("string"==typeof t){if(void 0===e[t])throw new TypeError(`No method named "${t}"`);e[t]()}}))}}P.on(document,"click.bs.tab.data-api",'[data-bs-toggle="tab"], [data-bs-toggle="pill"], [data-bs-toggle="list"]',(function(t){["A","AREA"].includes(this.tagName)&&t.preventDefault(),h(this)||ti.getOrCreateInstance(this).show()})),_(ti);const ei={animation:"boolean",autohide:"boolean",delay:"number"},ii={animation:!0,autohide:!0,delay:5e3};class ni extends B{constructor(t,e){super(t),this._config=this._getConfig(e),this._timeout=null,this._hasMouseInteraction=!1,this._hasKeyboardInteraction=!1,this._setListeners()}static get DefaultType(){return ei}static get Default(){return ii}static get NAME(){return"toast"}show(){P.trigger(this._element,"show.bs.toast").defaultPrevented||(this._clearTimeout(),this._config.animation&&this._element.classList.add("fade"),this._element.classList.remove("hide"),f(this._element),this._element.classList.add("showing"),this._queueCallback(()=>{this._element.classList.remove("showing"),this._element.classList.add("show"),P.trigger(this._element,"shown.bs.toast"),this._maybeScheduleHide()},this._element,this._config.animation))}hide(){this._element.classList.contains("show")&&(P.trigger(this._element,"hide.bs.toast").defaultPrevented||(this._element.classList.remove("show"),this._queueCallback(()=>{this._element.classList.add("hide"),P.trigger(this._element,"hidden.bs.toast")},this._element,this._config.animation)))}dispose(){this._clearTimeout(),this._element.classList.contains("show")&&this._element.classList.remove("show"),super.dispose()}_getConfig(t){return t={...ii,...U.getDataAttributes(this._element),..."object"==typeof t&&t?t:{}},l("toast",t,this.constructor.DefaultType),t}_maybeScheduleHide(){this._config.autohide&&(this._hasMouseInteraction||this._hasKeyboardInteraction||(this._timeout=setTimeout(()=>{this.hide()},this._config.delay)))}_onInteraction(t,e){switch(t.type){case"mouseover":case"mouseout":this._hasMouseInteraction=e;break;case"focusin":case"focusout":this._hasKeyboardInteraction=e}if(e)return void this._clearTimeout();const i=t.relatedTarget;this._element===i||this._element.contains(i)||this._maybeScheduleHide()}_setListeners(){P.on(this._element,"click.dismiss.bs.toast",'[data-bs-dismiss="toast"]',()=>this.hide()),P.on(this._element,"mouseover.bs.toast",t=>this._onInteraction(t,!0)),P.on(this._element,"mouseout.bs.toast",t=>this._onInteraction(t,!1)),P.on(this._element,"focusin.bs.toast",t=>this._onInteraction(t,!0)),P.on(this._element,"focusout.bs.toast",t=>this._onInteraction(t,!1))}_clearTimeout(){clearTimeout(this._timeout),this._timeout=null}static jQueryInterface(t){return this.each((function(){const e=ni.getOrCreateInstance(this,t);if("string"==typeof t){if(void 0===e[t])throw new TypeError(`No method named "${t}"`);e[t](this)}}))}}return _(ni),{Alert:W,Button:q,Carousel:Z,Collapse:et,Dropdown:Ae,Modal:De,Offcanvas:Ne,Popover:Qe,ScrollSpy:Je,Tab:ti,Toast:ni,Tooltip:Fe}})); +//# sourceMappingURL=bootstrap.bundle.min.js.map \ No newline at end of file diff --git a/examples/04_cell_detector/resources/icon-512x512.png b/examples/04_cell_detector/resources/icon-512x512.png new file mode 100644 index 0000000..c450626 Binary files /dev/null and b/examples/04_cell_detector/resources/icon-512x512.png differ diff --git a/examples/04_cell_detector/resources/pwa.js b/examples/04_cell_detector/resources/pwa.js new file mode 100644 index 0000000..e8ec724 --- /dev/null +++ b/examples/04_cell_detector/resources/pwa.js @@ -0,0 +1,10 @@ + +if ("serviceWorker" in navigator) { + window.addEventListener("load", function () { + navigator.serviceWorker + .register("./serviceWorker.js") + .then(res => console.log("service worker registered", res)) + .catch(err => console.log("service worker not registered", err)) + }) +} + \ No newline at end of file diff --git a/examples/04_cell_detector/resources/pyscript.css b/examples/04_cell_detector/resources/pyscript.css new file mode 100644 index 0000000..10a1f1c --- /dev/null +++ b/examples/04_cell_detector/resources/pyscript.css @@ -0,0 +1,332 @@ +/* py-config - not a component */ +py-config { + display: none; +} +/* py-{el} - components not defined */ +py-script:not(:defined) { + display: none; +} + +py-repl:not(:defined) { + display: none; +} + +py-title:not(:defined) { + display: none; +} + +py-inputbox:not(:defined) { + display: none; +} + +py-button:not(:defined) { + display: none; +} + +py-box:not(:defined) { + display: none; +} + +html { + font-family: ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', + Arial, 'Noto Sans', sans-serif, 'Apple Color Emoji', 'Segoe UI Emoji', 'Segoe UI Symbol', 'Noto Color Emoji'; + line-height: 1.5; +} + +.spinner::after { + content: ''; + box-sizing: border-box; + width: 40px; + height: 40px; + position: absolute; + top: calc(40% - 20px); + left: calc(50% - 20px); + border-radius: 50%; +} + +.spinner.smooth::after { + border-top: 4px solid rgba(255, 255, 255, 1); + border-left: 4px solid rgba(255, 255, 255, 1); + border-right: 4px solid rgba(255, 255, 255, 0); + animation: spinner 0.6s linear infinite; +} + +@keyframes spinner { + to { + transform: rotate(360deg); + } +} + +.label { + text-align: center; + width: 100%; + display: block; + color: rgba(255, 255, 255, 0.8); + font-size: 0.8rem; + margin-top: 6rem; +} + +/* Pop-up second layer begin */ + +.py-overlay { + position: fixed; + display: flex; + justify-content: center; + align-items: center; + color: white; + top: 0; + bottom: 0; + left: 0; + right: 0; + background: rgba(0, 0, 0, 0.5); + transition: opacity 500ms; + visibility: hidden; + color: visible; + opacity: 1; +} + +.py-overlay { + visibility: visible; + opacity: 1; +} + +.py-pop-up { + text-align: center; + width: 600px; +} + +.py-pop-up p { + margin: 5px; +} + +.py-pop-up a { + position: absolute; + color: white; + text-decoration: none; + font-size: 200%; + top: 3.5%; + right: 5%; +} + +/* Pop-up second layer end */ +.alert-banner { + position: relative; + padding: 0.5rem 1.5rem 0.5rem 0.5rem; + margin: 5px 0; +} + +.alert-banner p { + margin: 0; +} + +.py-error { + background-color: #ffe9e8; + border: solid; + border-color: #f0625f; + color: #9d041c; +} + +.py-warning { + background-color: rgb(255, 244, 229); + border: solid; + border-color: #ffa016; + color: #794700; +} + +.alert-banner.py-error > #alert-close-button { + color: #9d041c; +} + +.alert-banner.py-warning > #alert-close-button { + color: #794700; +} + +#alert-close-button { + position: absolute; + right: 0.5rem; + top: 0.5rem; + cursor: pointer; + background: transparent; + border: none; +} + +.py-box { + display: flex; + flex-direction: row; + justify-content: flex-start; +} + +.py-box div.py-box-child * { + max-width: 100%; +} + +.py-repl-box { + flex-direction: column; +} + +.py-repl-editor { + --tw-border-opacity: 1; + border-color: rgba(209, 213, 219, var(--tw-border-opacity)); + border-width: 1px; + position: relative; + --tw-ring-inset: var(--tw-empty, /*!*/ /*!*/); + --tw-ring-offset-width: 0px; + --tw-ring-offset-color: #fff; + --tw-ring-color: rgba(59, 130, 246, 0.5); + --tw-ring-offset-shadow: 0 0 #0000; + --tw-ring-shadow: 0 0 #0000; + --tw-shadow: 0 0 #0000; + position: relative; + + box-sizing: border-box; + border-width: 1px; + border-style: solid; + border-color: rgb(209, 213, 219); +} + +.editor-box:hover button { + opacity: 1; +} + +.py-repl-run-button { + opacity: 0; + bottom: 0.25rem; + right: 0.25rem; + position: absolute; + padding: 0; + line-height: inherit; + color: inherit; + cursor: pointer; + background-color: transparent; + background-image: none; + -webkit-appearance: button; + text-transform: none; + font-family: inherit; + font-size: 100%; + margin: 0; + text-rendering: auto; + letter-spacing: normal; + word-spacing: normal; + line-height: normal; + text-transform: none; + text-indent: 0px; + text-shadow: none; + display: inline-block; + text-align: center; + align-items: flex-start; + cursor: default; + box-sizing: border-box; + background-color: -internal-light-dark(rgb(239, 239, 239), rgb(59, 59, 59)); + margin: 0em; + padding: 1px 6px; + border: 0; +} + +.py-repl-run-button:hover { + opacity: 1; +} + +.py-title { + text-transform: uppercase; + text-align: center; +} + +.py-title h1 { + font-weight: 700; + font-size: 1.875rem; +} + +.py-input { + padding: 0.5rem; + --tw-border-opacity: 1; + border-color: rgba(209, 213, 219, var(--tw-border-opacity)); + border-width: 1px; + border-radius: 0.25rem; + margin-right: 0.75rem; + border-style: solid; + width: auto; +} + +.py-box input.py-input { + width: -webkit-fill-available; +} + +.central-content { + max-width: 20rem; + margin-left: auto; + margin-right: auto; +} + +input { + text-rendering: auto; + color: -internal-light-dark(black, white); + letter-spacing: normal; + word-spacing: normal; + line-height: normal; + text-transform: none; + text-indent: 0px; + text-shadow: none; + display: inline-block; + text-align: start; + appearance: auto; + -webkit-rtl-ordering: logical; + background-color: -internal-light-dark(rgb(255, 255, 255), rgb(59, 59, 59)); + margin: 0em; + padding: 1px 2px; + border-width: 2px; + border-style: inset; + border-color: -internal-light-dark(rgb(118, 118, 118), rgb(133, 133, 133)); + border-image: initial; +} + +.py-button { + --tw-text-opacity: 1; + color: rgba(255, 255, 255, var(--tw-text-opacity)); + padding: 0.5rem; + --tw-bg-opacity: 1; + background-color: rgba(37, 99, 235, var(--tw-bg-opacity)); + --tw-border-opacity: 1; + border-color: rgba(37, 99, 235, var(--tw-border-opacity)); + border-width: 1px; + border-radius: 0.25rem; + cursor: pointer; +} + +.py-li-element p { + margin: 5px; +} + +.py-li-element p { + display: inline; +} + +button, +input, +optgroup, +select, +textarea { + font-family: inherit; + font-size: 100%; + line-height: 1.15; + margin: 0; +} + +.line-through { + text-decoration: line-through; +} + +/* ===== py-terminal plugin ===== */ +/* XXX: it would be nice if these rules were stored in e.g. pyterminal.css and + bundled together at build time (by rollup?) */ + +.py-terminal { + min-height: 10em; + background-color: black; + color: white; + padding: 0.5rem; + overflow: auto; +} + +.py-terminal-hidden { + display: none; +} diff --git a/examples/04_cell_detector/resources/pyscript.js b/examples/04_cell_detector/resources/pyscript.js new file mode 100644 index 0000000..4bc0b89 --- /dev/null +++ b/examples/04_cell_detector/resources/pyscript.js @@ -0,0 +1,28907 @@ +var pyscript = (function (exports) { + 'use strict'; + + var parser$2 = /* + * Generated by PEG.js 0.10.0. + * + * http://pegjs.org/ + */ + (function() { + + function peg$subclass(child, parent) { + function ctor() { this.constructor = child; } + ctor.prototype = parent.prototype; + child.prototype = new ctor(); + } + + function peg$SyntaxError(message, expected, found, location) { + this.message = message; + this.expected = expected; + this.found = found; + this.location = location; + this.name = "SyntaxError"; + + if (typeof Error.captureStackTrace === "function") { + Error.captureStackTrace(this, peg$SyntaxError); + } + } + + peg$subclass(peg$SyntaxError, Error); + + peg$SyntaxError.buildMessage = function(expected, found) { + var DESCRIBE_EXPECTATION_FNS = { + literal: function(expectation) { + return "\"" + literalEscape(expectation.text) + "\""; + }, + + "class": function(expectation) { + var escapedParts = "", + i; + + for (i = 0; i < expectation.parts.length; i++) { + escapedParts += expectation.parts[i] instanceof Array + ? classEscape(expectation.parts[i][0]) + "-" + classEscape(expectation.parts[i][1]) + : classEscape(expectation.parts[i]); + } + + return "[" + (expectation.inverted ? "^" : "") + escapedParts + "]"; + }, + + any: function(expectation) { + return "any character"; + }, + + end: function(expectation) { + return "end of input"; + }, + + other: function(expectation) { + return expectation.description; + } + }; + + function hex(ch) { + return ch.charCodeAt(0).toString(16).toUpperCase(); + } + + function literalEscape(s) { + return s + .replace(/\\/g, '\\\\') + .replace(/"/g, '\\"') + .replace(/\0/g, '\\0') + .replace(/\t/g, '\\t') + .replace(/\n/g, '\\n') + .replace(/\r/g, '\\r') + .replace(/[\x00-\x0F]/g, function(ch) { return '\\x0' + hex(ch); }) + .replace(/[\x10-\x1F\x7F-\x9F]/g, function(ch) { return '\\x' + hex(ch); }); + } + + function classEscape(s) { + return s + .replace(/\\/g, '\\\\') + .replace(/\]/g, '\\]') + .replace(/\^/g, '\\^') + .replace(/-/g, '\\-') + .replace(/\0/g, '\\0') + .replace(/\t/g, '\\t') + .replace(/\n/g, '\\n') + .replace(/\r/g, '\\r') + .replace(/[\x00-\x0F]/g, function(ch) { return '\\x0' + hex(ch); }) + .replace(/[\x10-\x1F\x7F-\x9F]/g, function(ch) { return '\\x' + hex(ch); }); + } + + function describeExpectation(expectation) { + return DESCRIBE_EXPECTATION_FNS[expectation.type](expectation); + } + + function describeExpected(expected) { + var descriptions = new Array(expected.length), + i, j; + + for (i = 0; i < expected.length; i++) { + descriptions[i] = describeExpectation(expected[i]); + } + + descriptions.sort(); + + if (descriptions.length > 0) { + for (i = 1, j = 1; i < descriptions.length; i++) { + if (descriptions[i - 1] !== descriptions[i]) { + descriptions[j] = descriptions[i]; + j++; + } + } + descriptions.length = j; + } + + switch (descriptions.length) { + case 1: + return descriptions[0]; + + case 2: + return descriptions[0] + " or " + descriptions[1]; + + default: + return descriptions.slice(0, -1).join(", ") + + ", or " + + descriptions[descriptions.length - 1]; + } + } + + function describeFound(found) { + return found ? "\"" + literalEscape(found) + "\"" : "end of input"; + } + + return "Expected " + describeExpected(expected) + " but " + describeFound(found) + " found."; + }; + + function peg$parse(input, options) { + options = options !== void 0 ? options : {}; + + var peg$FAILED = {}, + + peg$startRuleFunctions = { Expressions: peg$parseExpressions }, + peg$startRuleFunction = peg$parseExpressions, + + peg$c0 = function() { + return g_root; + }, + peg$c1 = function(path) { + g_context = findContext(g_root, true, path); + }, + peg$c2 = function(path) { + g_context = findContext(g_root, false, path); + }, + peg$c3 = function(keyValue) { + checkTableKey(g_context.table, keyValue[0]); + g_context.table[keyValue[0]] = keyValue[1]; + }, + peg$c4 = peg$otherExpectation("Newline"), + peg$c5 = "\n", + peg$c6 = peg$literalExpectation("\n", false), + peg$c7 = "\r\n", + peg$c8 = peg$literalExpectation("\r\n", false), + peg$c9 = peg$otherExpectation("Whitespace"), + peg$c10 = /^[ \t]/, + peg$c11 = peg$classExpectation([" ", "\t"], false, false), + peg$c12 = peg$otherExpectation("Comment"), + peg$c13 = "#", + peg$c14 = peg$literalExpectation("#", false), + peg$c15 = peg$anyExpectation(), + peg$c16 = "=", + peg$c17 = peg$literalExpectation("=", false), + peg$c18 = function(key, value) { + return [key, value.value]; + }, + peg$c19 = function() { + return text(); + }, + peg$c20 = peg$otherExpectation("[a-z], [A-Z], [0-9], \"-\", \"_\""), + peg$c21 = /^[a-zA-Z0-9\-_]/, + peg$c22 = peg$classExpectation([["a", "z"], ["A", "Z"], ["0", "9"], "-", "_"], false, false), + peg$c23 = function(chars) { + return chars.join(''); + }, + peg$c24 = peg$otherExpectation("DoubleQuote"), + peg$c25 = "\"", + peg$c26 = peg$literalExpectation("\"", false), + peg$c27 = peg$otherExpectation("SingleQuote"), + peg$c28 = "'", + peg$c29 = peg$literalExpectation("'", false), + peg$c30 = peg$otherExpectation("ThreeDoubleQuotes"), + peg$c31 = "\"\"\"", + peg$c32 = peg$literalExpectation("\"\"\"", false), + peg$c33 = peg$otherExpectation("ThreeSingleQuotes"), + peg$c34 = "'''", + peg$c35 = peg$literalExpectation("'''", false), + peg$c36 = function(chars) { + return { + type: 'String', + value: chars.join('') + }; + }, + peg$c37 = peg$otherExpectation("NormalCharacter"), + peg$c38 = /^[^\0-\x1F"\\]/, + peg$c39 = peg$classExpectation([["\0", "\x1F"], "\"", "\\"], true, false), + peg$c40 = "u", + peg$c41 = peg$literalExpectation("u", false), + peg$c42 = "U", + peg$c43 = peg$literalExpectation("U", false), + peg$c44 = function() { + var s = text(); + if (s.length <= 2) { + return unescape(s[1]); + } + return fromCodePoint(parseInt(s.substr(2), 16)); + }, + peg$c45 = peg$otherExpectation("\"b\", \"f\", \"n\", \"r\", \"t\""), + peg$c46 = /^[bfnrt]/, + peg$c47 = peg$classExpectation(["b", "f", "n", "r", "t"], false, false), + peg$c48 = peg$otherExpectation("Backslash"), + peg$c49 = "\\", + peg$c50 = peg$literalExpectation("\\", false), + peg$c51 = peg$otherExpectation("FourHexadecimalDigits"), + peg$c52 = peg$otherExpectation("EightHexadecimalDigits"), + peg$c53 = /^[0-9A-Fa-f]/, + peg$c54 = peg$classExpectation([["0", "9"], ["A", "F"], ["a", "f"]], false, false), + peg$c55 = function() { + var s = text(); + return { + type: 'String', + value: s.substr(1, s.length - 2) + }; + }, + peg$c56 = /^[^\0-\x08\n-\x1F']/, + peg$c57 = peg$classExpectation([["\0", "\b"], ["\n", "\x1F"], "'"], true, false), + peg$c58 = function(chars) { + return { + type: 'String', + value: chars.join('').replace(/\\\r?\n(?:\r?\n|[ \t])*/g, '') + }; + }, + peg$c59 = /^[^\0-\x1F\\]/, + peg$c60 = peg$classExpectation([["\0", "\x1F"], "\\"], true, false), + peg$c61 = peg$otherExpectation("AnyCharacter"), + peg$c62 = /^[^\0-\x08\n-\x1F]/, + peg$c63 = peg$classExpectation([["\0", "\b"], ["\n", "\x1F"]], true, false), + peg$c64 = "true", + peg$c65 = peg$literalExpectation("true", false), + peg$c66 = function() { + return { + type: 'Boolean', + value: true + }; + }, + peg$c67 = "false", + peg$c68 = peg$literalExpectation("false", false), + peg$c69 = function() { + return { + type: 'Boolean', + value: false + }; + }, + peg$c70 = function() { + // A double-precision 64-bit floating-point number in IEEE 754 standard. + var s = text(); + var number = parseFloat(s.replace(/_/g, '')); + if (!isFiniteNumber(number)) { + error(s + 'is not a 64-bit floating-point number.'); + } + return { + type: 'Float', + value: number + }; + }, + peg$c71 = ".", + peg$c72 = peg$literalExpectation(".", false), + peg$c73 = "_", + peg$c74 = peg$literalExpectation("_", false), + peg$c75 = "e", + peg$c76 = peg$literalExpectation("e", false), + peg$c77 = "E", + peg$c78 = peg$literalExpectation("E", false), + peg$c79 = function() { + // Be careful of JavaScript limits: + // 1) Number.MAX_SAFE_INTEGER = 9007199254740991 + // 2) Number.MIN_SAFE_INTEGER = -9007199254740991 + var s = text(); + var number = s.replace(/_/g, ''); + // Check if it is a 64-bit signed integer. + var invalid = false; + if (number[0] === '-') { + var minInt = '-9223372036854775808'; + if (number.length > minInt.length || + (number.length === minInt.length && number > minInt)) { + invalid = true; + } + } else { + if (number[0] === '+') { + number = number.substr(1); + } + var maxInt = '9223372036854775807'; + if (number.length > maxInt.length || + (number.length === maxInt.length && number > maxInt)) { + invalid = true; + } + } + if (invalid) { + error(s + ' is not a 64-bit signed integer.'); + } + number = parseInt(number, 10); + if (!isFiniteNumber(number)) { + error(s + ' is not a 64-bit signed integer.'); + } + return { + type: 'Integer', + value: number + }; + }, + peg$c80 = "+", + peg$c81 = peg$literalExpectation("+", false), + peg$c82 = "-", + peg$c83 = peg$literalExpectation("-", false), + peg$c84 = /^[1-9]/, + peg$c85 = peg$classExpectation([["1", "9"]], false, false), + peg$c86 = /^[0-9]/, + peg$c87 = peg$classExpectation([["0", "9"]], false, false), + peg$c88 = "T", + peg$c89 = peg$literalExpectation("T", false), + peg$c90 = function() { + var s = text(); + var date = new Date(s); + if (!isFiniteNumber(date.getTime())) { + error('Date-time ' + s + ' is invalid. It does not conform to RFC 3339 or this is a browser-specific problem.'); + } + return { + type: 'DateTime', + value: date + }; + }, + peg$c91 = peg$otherExpectation("FullDate (YYYY-mm-dd)"), + peg$c92 = ":", + peg$c93 = peg$literalExpectation(":", false), + peg$c94 = peg$otherExpectation("Hour (HH)"), + peg$c95 = peg$otherExpectation("Minute (MM)"), + peg$c96 = peg$otherExpectation("Second (SS)"), + peg$c97 = peg$otherExpectation("TimeOffset (Z or +/-HH:MM)"), + peg$c98 = "Z", + peg$c99 = peg$literalExpectation("Z", false), + peg$c100 = "[", + peg$c101 = peg$literalExpectation("[", false), + peg$c102 = ",", + peg$c103 = peg$literalExpectation(",", false), + peg$c104 = "]", + peg$c105 = peg$literalExpectation("]", false), + peg$c106 = function(values) { + var o = { + type: 'Array', + value: values ? values[0] : [] + }; + for (var i = 0, arr = o.value, l = arr.length; i < l; i++) { + arr[i] = arr[i].value; + } + return o; + }, + peg$c107 = function(value, opt) { + var array = [value]; + if (opt) { + var type = value.type; + for (var i = 0, arr = opt[3], l = arr.length; i < l; i++) { + if (type !== arr[i].type) { + error(stringify(arr[i].value) + ' should be of type "' + type + + '".'); + } + array.push(arr[i]); + } + } + return array; + }, + peg$c108 = "{", + peg$c109 = peg$literalExpectation("{", false), + peg$c110 = "}", + peg$c111 = peg$literalExpectation("}", false), + peg$c112 = function(opt) { + var table = {}; + if (opt) { + table[opt[0][0]] = opt[0][1]; + for (var i = 0, arr = opt[1], l = arr.length; i < l; i++) { + var kv = arr[i][3]; + checkTableKey(table, kv[0]); + table[kv[0]] = kv[1]; + } + } + return { + type: 'InlineTable', + value: table + }; + }, + peg$c113 = function(path) { + return path; + }, + peg$c114 = function(key, arr) { + var path = [key]; + for (var i = 0, l = arr.length; i < l; i++) { + path.push(arr[i][3]); + } + return path; + }, + + peg$currPos = 0, + peg$savedPos = 0, + peg$posDetailsCache = [{ line: 1, column: 1 }], + peg$maxFailPos = 0, + peg$maxFailExpected = [], + peg$silentFails = 0, + + peg$result; + + if ("startRule" in options) { + if (!(options.startRule in peg$startRuleFunctions)) { + throw new Error("Can't start parsing from rule \"" + options.startRule + "\"."); + } + + peg$startRuleFunction = peg$startRuleFunctions[options.startRule]; + } + + function text() { + return input.substring(peg$savedPos, peg$currPos); + } + + function error(message, location) { + location = location !== void 0 ? location : peg$computeLocation(peg$savedPos, peg$currPos); + + throw peg$buildSimpleError(message, location); + } + + function peg$literalExpectation(text, ignoreCase) { + return { type: "literal", text: text, ignoreCase: ignoreCase }; + } + + function peg$classExpectation(parts, inverted, ignoreCase) { + return { type: "class", parts: parts, inverted: inverted, ignoreCase: ignoreCase }; + } + + function peg$anyExpectation() { + return { type: "any" }; + } + + function peg$endExpectation() { + return { type: "end" }; + } + + function peg$otherExpectation(description) { + return { type: "other", description: description }; + } + + function peg$computePosDetails(pos) { + var details = peg$posDetailsCache[pos], p; + + if (details) { + return details; + } else { + p = pos - 1; + while (!peg$posDetailsCache[p]) { + p--; + } + + details = peg$posDetailsCache[p]; + details = { + line: details.line, + column: details.column + }; + + while (p < pos) { + if (input.charCodeAt(p) === 10) { + details.line++; + details.column = 1; + } else { + details.column++; + } + + p++; + } + + peg$posDetailsCache[pos] = details; + return details; + } + } + + function peg$computeLocation(startPos, endPos) { + var startPosDetails = peg$computePosDetails(startPos), + endPosDetails = peg$computePosDetails(endPos); + + return { + start: { + offset: startPos, + line: startPosDetails.line, + column: startPosDetails.column + }, + end: { + offset: endPos, + line: endPosDetails.line, + column: endPosDetails.column + } + }; + } + + function peg$fail(expected) { + if (peg$currPos < peg$maxFailPos) { return; } + + if (peg$currPos > peg$maxFailPos) { + peg$maxFailPos = peg$currPos; + peg$maxFailExpected = []; + } + + peg$maxFailExpected.push(expected); + } + + function peg$buildSimpleError(message, location) { + return new peg$SyntaxError(message, null, null, location); + } + + function peg$buildStructuredError(expected, found, location) { + return new peg$SyntaxError( + peg$SyntaxError.buildMessage(expected, found), + expected, + found, + location + ); + } + + function peg$parseExpressions() { + var s0, s1, s2, s3, s4, s5, s6, s7; + + s0 = peg$currPos; + s1 = []; + s2 = peg$parseWhitespace(); + if (s2 === peg$FAILED) { + s2 = peg$parseNewline(); + if (s2 === peg$FAILED) { + s2 = peg$parseComment(); + } + } + while (s2 !== peg$FAILED) { + s1.push(s2); + s2 = peg$parseWhitespace(); + if (s2 === peg$FAILED) { + s2 = peg$parseNewline(); + if (s2 === peg$FAILED) { + s2 = peg$parseComment(); + } + } + } + if (s1 !== peg$FAILED) { + s2 = peg$currPos; + s3 = peg$parseExpression(); + if (s3 !== peg$FAILED) { + s4 = []; + s5 = peg$parseWhitespace(); + if (s5 === peg$FAILED) { + s5 = peg$parseComment(); + } + while (s5 !== peg$FAILED) { + s4.push(s5); + s5 = peg$parseWhitespace(); + if (s5 === peg$FAILED) { + s5 = peg$parseComment(); + } + } + if (s4 !== peg$FAILED) { + s5 = peg$currPos; + s6 = peg$parseNewline(); + if (s6 !== peg$FAILED) { + s7 = peg$parseExpressions(); + if (s7 !== peg$FAILED) { + s6 = [s6, s7]; + s5 = s6; + } else { + peg$currPos = s5; + s5 = peg$FAILED; + } + } else { + peg$currPos = s5; + s5 = peg$FAILED; + } + if (s5 === peg$FAILED) { + s5 = null; + } + if (s5 !== peg$FAILED) { + s3 = [s3, s4, s5]; + s2 = s3; + } else { + peg$currPos = s2; + s2 = peg$FAILED; + } + } else { + peg$currPos = s2; + s2 = peg$FAILED; + } + } else { + peg$currPos = s2; + s2 = peg$FAILED; + } + if (s2 === peg$FAILED) { + s2 = null; + } + if (s2 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c0(); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + + return s0; + } + + function peg$parseExpression() { + var s0, s1; + + s0 = peg$currPos; + s1 = peg$parseTableArrayHeader(); + if (s1 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c1(s1); + } + s0 = s1; + if (s0 === peg$FAILED) { + s0 = peg$currPos; + s1 = peg$parseTableHeader(); + if (s1 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c2(s1); + } + s0 = s1; + if (s0 === peg$FAILED) { + s0 = peg$currPos; + s1 = peg$parseKeyValue(); + if (s1 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c3(s1); + } + s0 = s1; + } + } + + return s0; + } + + function peg$parseNewline() { + var s0; + + peg$silentFails++; + if (input.charCodeAt(peg$currPos) === 10) { + s0 = peg$c5; + peg$currPos++; + } else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c6); } + } + if (s0 === peg$FAILED) { + if (input.substr(peg$currPos, 2) === peg$c7) { + s0 = peg$c7; + peg$currPos += 2; + } else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c8); } + } + } + peg$silentFails--; + if (s0 === peg$FAILED) { + if (peg$silentFails === 0) { peg$fail(peg$c4); } + } + + return s0; + } + + function peg$parseWhitespace() { + var s0; + + peg$silentFails++; + if (peg$c10.test(input.charAt(peg$currPos))) { + s0 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c11); } + } + peg$silentFails--; + if (s0 === peg$FAILED) { + if (peg$silentFails === 0) { peg$fail(peg$c9); } + } + + return s0; + } + + function peg$parseComment() { + var s0, s1, s2, s3, s4, s5; + + peg$silentFails++; + s0 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 35) { + s1 = peg$c13; + peg$currPos++; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c14); } + } + if (s1 !== peg$FAILED) { + s2 = []; + s3 = peg$currPos; + s4 = peg$currPos; + peg$silentFails++; + s5 = peg$parseNewline(); + peg$silentFails--; + if (s5 === peg$FAILED) { + s4 = void 0; + } else { + peg$currPos = s4; + s4 = peg$FAILED; + } + if (s4 !== peg$FAILED) { + if (input.length > peg$currPos) { + s5 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s5 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c15); } + } + if (s5 !== peg$FAILED) { + s4 = [s4, s5]; + s3 = s4; + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + while (s3 !== peg$FAILED) { + s2.push(s3); + s3 = peg$currPos; + s4 = peg$currPos; + peg$silentFails++; + s5 = peg$parseNewline(); + peg$silentFails--; + if (s5 === peg$FAILED) { + s4 = void 0; + } else { + peg$currPos = s4; + s4 = peg$FAILED; + } + if (s4 !== peg$FAILED) { + if (input.length > peg$currPos) { + s5 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s5 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c15); } + } + if (s5 !== peg$FAILED) { + s4 = [s4, s5]; + s3 = s4; + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } + if (s2 !== peg$FAILED) { + s1 = [s1, s2]; + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + peg$silentFails--; + if (s0 === peg$FAILED) { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c12); } + } + + return s0; + } + + function peg$parseKeyValue() { + var s0, s1, s2, s3, s4, s5; + + s0 = peg$currPos; + s1 = peg$parseKey(); + if (s1 !== peg$FAILED) { + s2 = []; + s3 = peg$parseWhitespace(); + while (s3 !== peg$FAILED) { + s2.push(s3); + s3 = peg$parseWhitespace(); + } + if (s2 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 61) { + s3 = peg$c16; + peg$currPos++; + } else { + s3 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c17); } + } + if (s3 !== peg$FAILED) { + s4 = []; + s5 = peg$parseWhitespace(); + while (s5 !== peg$FAILED) { + s4.push(s5); + s5 = peg$parseWhitespace(); + } + if (s4 !== peg$FAILED) { + s5 = peg$parseValue(); + if (s5 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c18(s1, s5); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + + return s0; + } + + function peg$parseKey() { + var s0; + + s0 = peg$parseBareKey(); + if (s0 === peg$FAILED) { + s0 = peg$parseQuotedKey(); + } + + return s0; + } + + function peg$parseBareKey() { + var s0, s1, s2; + + s0 = peg$currPos; + s1 = []; + s2 = peg$parseBareKeyCharacter(); + if (s2 !== peg$FAILED) { + while (s2 !== peg$FAILED) { + s1.push(s2); + s2 = peg$parseBareKeyCharacter(); + } + } else { + s1 = peg$FAILED; + } + if (s1 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c19(); + } + s0 = s1; + + return s0; + } + + function peg$parseBareKeyCharacter() { + var s0; + + peg$silentFails++; + if (peg$c21.test(input.charAt(peg$currPos))) { + s0 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c22); } + } + peg$silentFails--; + if (s0 === peg$FAILED) { + if (peg$silentFails === 0) { peg$fail(peg$c20); } + } + + return s0; + } + + function peg$parseQuotedKey() { + var s0, s1, s2, s3; + + s0 = peg$currPos; + s1 = peg$parseDoubleQuote(); + if (s1 !== peg$FAILED) { + s2 = []; + s3 = peg$parseBasicCharacter(); + if (s3 !== peg$FAILED) { + while (s3 !== peg$FAILED) { + s2.push(s3); + s3 = peg$parseBasicCharacter(); + } + } else { + s2 = peg$FAILED; + } + if (s2 !== peg$FAILED) { + s3 = peg$parseDoubleQuote(); + if (s3 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c23(s2); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + + return s0; + } + + function peg$parseDoubleQuote() { + var s0; + + peg$silentFails++; + if (input.charCodeAt(peg$currPos) === 34) { + s0 = peg$c25; + peg$currPos++; + } else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c26); } + } + peg$silentFails--; + if (s0 === peg$FAILED) { + if (peg$silentFails === 0) { peg$fail(peg$c24); } + } + + return s0; + } + + function peg$parseSingleQuote() { + var s0; + + peg$silentFails++; + if (input.charCodeAt(peg$currPos) === 39) { + s0 = peg$c28; + peg$currPos++; + } else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c29); } + } + peg$silentFails--; + if (s0 === peg$FAILED) { + if (peg$silentFails === 0) { peg$fail(peg$c27); } + } + + return s0; + } + + function peg$parseThreeDoubleQuotes() { + var s0; + + peg$silentFails++; + if (input.substr(peg$currPos, 3) === peg$c31) { + s0 = peg$c31; + peg$currPos += 3; + } else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c32); } + } + peg$silentFails--; + if (s0 === peg$FAILED) { + if (peg$silentFails === 0) { peg$fail(peg$c30); } + } + + return s0; + } + + function peg$parseThreeSingleQuotes() { + var s0; + + peg$silentFails++; + if (input.substr(peg$currPos, 3) === peg$c34) { + s0 = peg$c34; + peg$currPos += 3; + } else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c35); } + } + peg$silentFails--; + if (s0 === peg$FAILED) { + if (peg$silentFails === 0) { peg$fail(peg$c33); } + } + + return s0; + } + + function peg$parseValue() { + var s0; + + s0 = peg$parseString(); + if (s0 === peg$FAILED) { + s0 = peg$parseBoolean(); + if (s0 === peg$FAILED) { + s0 = peg$parseDateTime(); + if (s0 === peg$FAILED) { + s0 = peg$parseFloat(); + if (s0 === peg$FAILED) { + s0 = peg$parseInteger(); + if (s0 === peg$FAILED) { + s0 = peg$parseArray(); + if (s0 === peg$FAILED) { + s0 = peg$parseInlineTable(); + } + } + } + } + } + } + + return s0; + } + + function peg$parseString() { + var s0; + + s0 = peg$parseMultilineBasicString(); + if (s0 === peg$FAILED) { + s0 = peg$parseBasicString(); + if (s0 === peg$FAILED) { + s0 = peg$parseMultilineLiteralString(); + if (s0 === peg$FAILED) { + s0 = peg$parseLiteralString(); + } + } + } + + return s0; + } + + function peg$parseBasicString() { + var s0, s1, s2, s3; + + s0 = peg$currPos; + s1 = peg$parseDoubleQuote(); + if (s1 !== peg$FAILED) { + s2 = []; + s3 = peg$parseBasicCharacter(); + while (s3 !== peg$FAILED) { + s2.push(s3); + s3 = peg$parseBasicCharacter(); + } + if (s2 !== peg$FAILED) { + s3 = peg$parseDoubleQuote(); + if (s3 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c36(s2); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + + return s0; + } + + function peg$parseBasicCharacter() { + var s0; + + s0 = peg$parseNormalCharacter(); + if (s0 === peg$FAILED) { + s0 = peg$parseEscapedCharacter(); + } + + return s0; + } + + function peg$parseNormalCharacter() { + var s0, s1, s2; + + peg$silentFails++; + s0 = peg$currPos; + s1 = peg$currPos; + peg$silentFails++; + s2 = peg$parseNewline(); + peg$silentFails--; + if (s2 === peg$FAILED) { + s1 = void 0; + } else { + peg$currPos = s1; + s1 = peg$FAILED; + } + if (s1 !== peg$FAILED) { + if (peg$c38.test(input.charAt(peg$currPos))) { + s2 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c39); } + } + if (s2 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c19(); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + peg$silentFails--; + if (s0 === peg$FAILED) { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c37); } + } + + return s0; + } + + function peg$parseEscapedCharacter() { + var s0, s1, s2, s3, s4; + + s0 = peg$currPos; + s1 = peg$parseBackslash(); + if (s1 !== peg$FAILED) { + s2 = peg$parseControlCharacter(); + if (s2 === peg$FAILED) { + s2 = peg$parseDoubleQuote(); + if (s2 === peg$FAILED) { + s2 = peg$parseBackslash(); + if (s2 === peg$FAILED) { + s2 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 117) { + s3 = peg$c40; + peg$currPos++; + } else { + s3 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c41); } + } + if (s3 !== peg$FAILED) { + s4 = peg$parseFourHexadecimalDigits(); + if (s4 !== peg$FAILED) { + s3 = [s3, s4]; + s2 = s3; + } else { + peg$currPos = s2; + s2 = peg$FAILED; + } + } else { + peg$currPos = s2; + s2 = peg$FAILED; + } + if (s2 === peg$FAILED) { + s2 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 85) { + s3 = peg$c42; + peg$currPos++; + } else { + s3 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c43); } + } + if (s3 !== peg$FAILED) { + s4 = peg$parseEightHexadecimalDigits(); + if (s4 !== peg$FAILED) { + s3 = [s3, s4]; + s2 = s3; + } else { + peg$currPos = s2; + s2 = peg$FAILED; + } + } else { + peg$currPos = s2; + s2 = peg$FAILED; + } + } + } + } + } + if (s2 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c44(); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + + return s0; + } + + function peg$parseControlCharacter() { + var s0; + + peg$silentFails++; + if (peg$c46.test(input.charAt(peg$currPos))) { + s0 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c47); } + } + peg$silentFails--; + if (s0 === peg$FAILED) { + if (peg$silentFails === 0) { peg$fail(peg$c45); } + } + + return s0; + } + + function peg$parseBackslash() { + var s0; + + peg$silentFails++; + if (input.charCodeAt(peg$currPos) === 92) { + s0 = peg$c49; + peg$currPos++; + } else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c50); } + } + peg$silentFails--; + if (s0 === peg$FAILED) { + if (peg$silentFails === 0) { peg$fail(peg$c48); } + } + + return s0; + } + + function peg$parseFourHexadecimalDigits() { + var s0, s1, s2, s3, s4; + + peg$silentFails++; + s0 = peg$currPos; + s1 = peg$parseHexDigit(); + if (s1 !== peg$FAILED) { + s2 = peg$parseHexDigit(); + if (s2 !== peg$FAILED) { + s3 = peg$parseHexDigit(); + if (s3 !== peg$FAILED) { + s4 = peg$parseHexDigit(); + if (s4 !== peg$FAILED) { + s1 = [s1, s2, s3, s4]; + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + peg$silentFails--; + if (s0 === peg$FAILED) { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c51); } + } + + return s0; + } + + function peg$parseEightHexadecimalDigits() { + var s0, s1, s2, s3, s4, s5, s6, s7, s8; + + peg$silentFails++; + s0 = peg$currPos; + s1 = peg$parseHexDigit(); + if (s1 !== peg$FAILED) { + s2 = peg$parseHexDigit(); + if (s2 !== peg$FAILED) { + s3 = peg$parseHexDigit(); + if (s3 !== peg$FAILED) { + s4 = peg$parseHexDigit(); + if (s4 !== peg$FAILED) { + s5 = peg$parseHexDigit(); + if (s5 !== peg$FAILED) { + s6 = peg$parseHexDigit(); + if (s6 !== peg$FAILED) { + s7 = peg$parseHexDigit(); + if (s7 !== peg$FAILED) { + s8 = peg$parseHexDigit(); + if (s8 !== peg$FAILED) { + s1 = [s1, s2, s3, s4, s5, s6, s7, s8]; + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + peg$silentFails--; + if (s0 === peg$FAILED) { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c52); } + } + + return s0; + } + + function peg$parseHexDigit() { + var s0; + + if (peg$c53.test(input.charAt(peg$currPos))) { + s0 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c54); } + } + + return s0; + } + + function peg$parseLiteralString() { + var s0, s1, s2, s3; + + s0 = peg$currPos; + s1 = peg$parseSingleQuote(); + if (s1 !== peg$FAILED) { + s2 = []; + s3 = peg$parseLiteralCharacter(); + while (s3 !== peg$FAILED) { + s2.push(s3); + s3 = peg$parseLiteralCharacter(); + } + if (s2 !== peg$FAILED) { + s3 = peg$parseSingleQuote(); + if (s3 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c55(); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + + return s0; + } + + function peg$parseLiteralCharacter() { + var s0, s1, s2; + + peg$silentFails++; + s0 = peg$currPos; + s1 = peg$currPos; + peg$silentFails++; + s2 = peg$parseNewline(); + peg$silentFails--; + if (s2 === peg$FAILED) { + s1 = void 0; + } else { + peg$currPos = s1; + s1 = peg$FAILED; + } + if (s1 !== peg$FAILED) { + if (peg$c56.test(input.charAt(peg$currPos))) { + s2 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c57); } + } + if (s2 !== peg$FAILED) { + s1 = [s1, s2]; + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + peg$silentFails--; + if (s0 === peg$FAILED) { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c37); } + } + + return s0; + } + + function peg$parseMultilineBasicString() { + var s0, s1, s2, s3, s4; + + s0 = peg$currPos; + s1 = peg$parseThreeDoubleQuotes(); + if (s1 !== peg$FAILED) { + s2 = peg$parseNewline(); + if (s2 === peg$FAILED) { + s2 = null; + } + if (s2 !== peg$FAILED) { + s3 = []; + s4 = peg$parseMultilineBasicText(); + while (s4 !== peg$FAILED) { + s3.push(s4); + s4 = peg$parseMultilineBasicText(); + } + if (s3 !== peg$FAILED) { + s4 = peg$parseThreeDoubleQuotes(); + if (s4 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c58(s3); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + + return s0; + } + + function peg$parseMultilineBasicText() { + var s0, s1, s2; + + s0 = peg$parseMultilineBasicCharacter(); + if (s0 === peg$FAILED) { + s0 = peg$currPos; + s1 = peg$parseBackslash(); + if (s1 !== peg$FAILED) { + s2 = peg$parseNewline(); + if (s2 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c19(); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + if (s0 === peg$FAILED) { + s0 = peg$parseNewline(); + } + } + + return s0; + } + + function peg$parseMultilineBasicCharacter() { + var s0, s1, s2; + + s0 = peg$currPos; + s1 = peg$currPos; + peg$silentFails++; + s2 = peg$parseThreeDoubleQuotes(); + peg$silentFails--; + if (s2 === peg$FAILED) { + s1 = void 0; + } else { + peg$currPos = s1; + s1 = peg$FAILED; + } + if (s1 !== peg$FAILED) { + s2 = peg$parseMultilineNormalCharacter(); + if (s2 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c19(); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + if (s0 === peg$FAILED) { + s0 = peg$parseEscapedCharacter(); + } + + return s0; + } + + function peg$parseMultilineNormalCharacter() { + var s0, s1, s2; + + peg$silentFails++; + s0 = peg$currPos; + s1 = peg$currPos; + peg$silentFails++; + s2 = peg$parseNewline(); + peg$silentFails--; + if (s2 === peg$FAILED) { + s1 = void 0; + } else { + peg$currPos = s1; + s1 = peg$FAILED; + } + if (s1 !== peg$FAILED) { + if (peg$c59.test(input.charAt(peg$currPos))) { + s2 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c60); } + } + if (s2 !== peg$FAILED) { + s1 = [s1, s2]; + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + peg$silentFails--; + if (s0 === peg$FAILED) { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c37); } + } + + return s0; + } + + function peg$parseMultilineLiteralString() { + var s0, s1, s2, s3, s4; + + s0 = peg$currPos; + s1 = peg$parseThreeSingleQuotes(); + if (s1 !== peg$FAILED) { + s2 = peg$parseNewline(); + if (s2 === peg$FAILED) { + s2 = null; + } + if (s2 !== peg$FAILED) { + s3 = []; + s4 = peg$parseMultilineLiteralText(); + while (s4 !== peg$FAILED) { + s3.push(s4); + s4 = peg$parseMultilineLiteralText(); + } + if (s3 !== peg$FAILED) { + s4 = peg$parseThreeSingleQuotes(); + if (s4 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c36(s3); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + + return s0; + } + + function peg$parseMultilineLiteralText() { + var s0, s1, s2; + + s0 = peg$currPos; + s1 = peg$currPos; + peg$silentFails++; + if (input.substr(peg$currPos, 3) === peg$c34) { + s2 = peg$c34; + peg$currPos += 3; + } else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c35); } + } + peg$silentFails--; + if (s2 === peg$FAILED) { + s1 = void 0; + } else { + peg$currPos = s1; + s1 = peg$FAILED; + } + if (s1 !== peg$FAILED) { + s2 = peg$parseMultilineLiteralCharacter(); + if (s2 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c19(); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + if (s0 === peg$FAILED) { + s0 = peg$parseNewline(); + } + + return s0; + } + + function peg$parseMultilineLiteralCharacter() { + var s0, s1, s2; + + peg$silentFails++; + s0 = peg$currPos; + s1 = peg$currPos; + peg$silentFails++; + s2 = peg$parseNewline(); + peg$silentFails--; + if (s2 === peg$FAILED) { + s1 = void 0; + } else { + peg$currPos = s1; + s1 = peg$FAILED; + } + if (s1 !== peg$FAILED) { + if (peg$c62.test(input.charAt(peg$currPos))) { + s2 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c63); } + } + if (s2 !== peg$FAILED) { + s1 = [s1, s2]; + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + peg$silentFails--; + if (s0 === peg$FAILED) { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c61); } + } + + return s0; + } + + function peg$parseBoolean() { + var s0, s1; + + s0 = peg$currPos; + if (input.substr(peg$currPos, 4) === peg$c64) { + s1 = peg$c64; + peg$currPos += 4; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c65); } + } + if (s1 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c66(); + } + s0 = s1; + if (s0 === peg$FAILED) { + s0 = peg$currPos; + if (input.substr(peg$currPos, 5) === peg$c67) { + s1 = peg$c67; + peg$currPos += 5; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c68); } + } + if (s1 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c69(); + } + s0 = s1; + } + + return s0; + } + + function peg$parseFloat() { + var s0, s1, s2, s3, s4; + + s0 = peg$currPos; + s1 = peg$parseInteger(); + if (s1 !== peg$FAILED) { + s2 = peg$currPos; + s3 = peg$parseFraction(); + if (s3 !== peg$FAILED) { + s4 = peg$parseExponent(); + if (s4 === peg$FAILED) { + s4 = null; + } + if (s4 !== peg$FAILED) { + s3 = [s3, s4]; + s2 = s3; + } else { + peg$currPos = s2; + s2 = peg$FAILED; + } + } else { + peg$currPos = s2; + s2 = peg$FAILED; + } + if (s2 === peg$FAILED) { + s2 = peg$parseExponent(); + } + if (s2 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c70(); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + + return s0; + } + + function peg$parseFraction() { + var s0, s1, s2, s3, s4, s5, s6; + + s0 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 46) { + s1 = peg$c71; + peg$currPos++; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c72); } + } + if (s1 !== peg$FAILED) { + s2 = peg$parseDigit(); + if (s2 !== peg$FAILED) { + s3 = []; + s4 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 95) { + s5 = peg$c73; + peg$currPos++; + } else { + s5 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c74); } + } + if (s5 === peg$FAILED) { + s5 = null; + } + if (s5 !== peg$FAILED) { + s6 = peg$parseDigit(); + if (s6 !== peg$FAILED) { + s5 = [s5, s6]; + s4 = s5; + } else { + peg$currPos = s4; + s4 = peg$FAILED; + } + } else { + peg$currPos = s4; + s4 = peg$FAILED; + } + while (s4 !== peg$FAILED) { + s3.push(s4); + s4 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 95) { + s5 = peg$c73; + peg$currPos++; + } else { + s5 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c74); } + } + if (s5 === peg$FAILED) { + s5 = null; + } + if (s5 !== peg$FAILED) { + s6 = peg$parseDigit(); + if (s6 !== peg$FAILED) { + s5 = [s5, s6]; + s4 = s5; + } else { + peg$currPos = s4; + s4 = peg$FAILED; + } + } else { + peg$currPos = s4; + s4 = peg$FAILED; + } + } + if (s3 !== peg$FAILED) { + s1 = [s1, s2, s3]; + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + + return s0; + } + + function peg$parseExponent() { + var s0, s1, s2; + + s0 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 101) { + s1 = peg$c75; + peg$currPos++; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c76); } + } + if (s1 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 69) { + s1 = peg$c77; + peg$currPos++; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c78); } + } + } + if (s1 !== peg$FAILED) { + s2 = peg$parseInteger(); + if (s2 !== peg$FAILED) { + s1 = [s1, s2]; + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + + return s0; + } + + function peg$parseInteger() { + var s0, s1, s2; + + s0 = peg$currPos; + s1 = peg$parseSign(); + if (s1 === peg$FAILED) { + s1 = null; + } + if (s1 !== peg$FAILED) { + s2 = peg$parseIntDigits(); + if (s2 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c79(); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + + return s0; + } + + function peg$parseSign() { + var s0; + + if (input.charCodeAt(peg$currPos) === 43) { + s0 = peg$c80; + peg$currPos++; + } else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c81); } + } + if (s0 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 45) { + s0 = peg$c82; + peg$currPos++; + } else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c83); } + } + } + + return s0; + } + + function peg$parseIntDigits() { + var s0, s1, s2, s3, s4, s5; + + s0 = peg$currPos; + s1 = peg$parseDigit_1to9(); + if (s1 !== peg$FAILED) { + s2 = []; + s3 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 95) { + s4 = peg$c73; + peg$currPos++; + } else { + s4 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c74); } + } + if (s4 === peg$FAILED) { + s4 = null; + } + if (s4 !== peg$FAILED) { + s5 = peg$parseDigit(); + if (s5 !== peg$FAILED) { + s4 = [s4, s5]; + s3 = s4; + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + if (s3 !== peg$FAILED) { + while (s3 !== peg$FAILED) { + s2.push(s3); + s3 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 95) { + s4 = peg$c73; + peg$currPos++; + } else { + s4 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c74); } + } + if (s4 === peg$FAILED) { + s4 = null; + } + if (s4 !== peg$FAILED) { + s5 = peg$parseDigit(); + if (s5 !== peg$FAILED) { + s4 = [s4, s5]; + s3 = s4; + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } + } else { + s2 = peg$FAILED; + } + if (s2 !== peg$FAILED) { + s1 = [s1, s2]; + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + if (s0 === peg$FAILED) { + s0 = peg$parseDigit(); + } + + return s0; + } + + function peg$parseDigit_1to9() { + var s0; + + if (peg$c84.test(input.charAt(peg$currPos))) { + s0 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c85); } + } + + return s0; + } + + function peg$parseDigit() { + var s0; + + if (peg$c86.test(input.charAt(peg$currPos))) { + s0 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c87); } + } + + return s0; + } + + function peg$parseDateTime() { + var s0, s1, s2, s3; + + s0 = peg$currPos; + s1 = peg$parseFullDate(); + if (s1 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 84) { + s2 = peg$c88; + peg$currPos++; + } else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c89); } + } + if (s2 !== peg$FAILED) { + s3 = peg$parseFullTime(); + if (s3 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c90(); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + + return s0; + } + + function peg$parseFullDate() { + var s0, s1, s2, s3, s4, s5; + + peg$silentFails++; + s0 = peg$currPos; + s1 = peg$parseYear(); + if (s1 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 45) { + s2 = peg$c82; + peg$currPos++; + } else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c83); } + } + if (s2 !== peg$FAILED) { + s3 = peg$parseMonth(); + if (s3 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 45) { + s4 = peg$c82; + peg$currPos++; + } else { + s4 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c83); } + } + if (s4 !== peg$FAILED) { + s5 = peg$parseMDay(); + if (s5 !== peg$FAILED) { + s1 = [s1, s2, s3, s4, s5]; + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + peg$silentFails--; + if (s0 === peg$FAILED) { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c91); } + } + + return s0; + } + + function peg$parseYear() { + var s0, s1, s2, s3, s4; + + s0 = peg$currPos; + s1 = peg$parseDigit(); + if (s1 !== peg$FAILED) { + s2 = peg$parseDigit(); + if (s2 !== peg$FAILED) { + s3 = peg$parseDigit(); + if (s3 !== peg$FAILED) { + s4 = peg$parseDigit(); + if (s4 !== peg$FAILED) { + s1 = [s1, s2, s3, s4]; + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + + return s0; + } + + function peg$parseMonth() { + var s0, s1, s2; + + s0 = peg$currPos; + s1 = peg$parseDigit(); + if (s1 !== peg$FAILED) { + s2 = peg$parseDigit(); + if (s2 !== peg$FAILED) { + s1 = [s1, s2]; + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + + return s0; + } + + function peg$parseMDay() { + var s0, s1, s2; + + s0 = peg$currPos; + s1 = peg$parseDigit(); + if (s1 !== peg$FAILED) { + s2 = peg$parseDigit(); + if (s2 !== peg$FAILED) { + s1 = [s1, s2]; + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + + return s0; + } + + function peg$parseFullTime() { + var s0, s1, s2; + + s0 = peg$currPos; + s1 = peg$parseTime(); + if (s1 !== peg$FAILED) { + s2 = peg$parseTimeOffset(); + if (s2 !== peg$FAILED) { + s1 = [s1, s2]; + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + + return s0; + } + + function peg$parseTime() { + var s0, s1, s2, s3, s4, s5, s6; + + s0 = peg$currPos; + s1 = peg$parseHour(); + if (s1 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 58) { + s2 = peg$c92; + peg$currPos++; + } else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c93); } + } + if (s2 !== peg$FAILED) { + s3 = peg$parseMinute(); + if (s3 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 58) { + s4 = peg$c92; + peg$currPos++; + } else { + s4 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c93); } + } + if (s4 !== peg$FAILED) { + s5 = peg$parseSecond(); + if (s5 !== peg$FAILED) { + s6 = peg$parseSecondFraction(); + if (s6 === peg$FAILED) { + s6 = null; + } + if (s6 !== peg$FAILED) { + s1 = [s1, s2, s3, s4, s5, s6]; + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + + return s0; + } + + function peg$parseHour() { + var s0, s1, s2; + + peg$silentFails++; + s0 = peg$currPos; + s1 = peg$parseDigit(); + if (s1 !== peg$FAILED) { + s2 = peg$parseDigit(); + if (s2 !== peg$FAILED) { + s1 = [s1, s2]; + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + peg$silentFails--; + if (s0 === peg$FAILED) { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c94); } + } + + return s0; + } + + function peg$parseMinute() { + var s0, s1, s2; + + peg$silentFails++; + s0 = peg$currPos; + s1 = peg$parseDigit(); + if (s1 !== peg$FAILED) { + s2 = peg$parseDigit(); + if (s2 !== peg$FAILED) { + s1 = [s1, s2]; + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + peg$silentFails--; + if (s0 === peg$FAILED) { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c95); } + } + + return s0; + } + + function peg$parseSecond() { + var s0, s1, s2; + + peg$silentFails++; + s0 = peg$currPos; + s1 = peg$parseDigit(); + if (s1 !== peg$FAILED) { + s2 = peg$parseDigit(); + if (s2 !== peg$FAILED) { + s1 = [s1, s2]; + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + peg$silentFails--; + if (s0 === peg$FAILED) { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c96); } + } + + return s0; + } + + function peg$parseSecondFraction() { + var s0, s1, s2, s3; + + s0 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 46) { + s1 = peg$c71; + peg$currPos++; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c72); } + } + if (s1 !== peg$FAILED) { + s2 = []; + s3 = peg$parseDigit(); + if (s3 !== peg$FAILED) { + while (s3 !== peg$FAILED) { + s2.push(s3); + s3 = peg$parseDigit(); + } + } else { + s2 = peg$FAILED; + } + if (s2 !== peg$FAILED) { + s1 = [s1, s2]; + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + + return s0; + } + + function peg$parseTimeOffset() { + var s0, s1, s2, s3, s4; + + peg$silentFails++; + if (input.charCodeAt(peg$currPos) === 90) { + s0 = peg$c98; + peg$currPos++; + } else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c99); } + } + if (s0 === peg$FAILED) { + s0 = peg$currPos; + s1 = peg$parseSign(); + if (s1 !== peg$FAILED) { + s2 = peg$parseHour(); + if (s2 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 58) { + s3 = peg$c92; + peg$currPos++; + } else { + s3 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c93); } + } + if (s3 !== peg$FAILED) { + s4 = peg$parseMinute(); + if (s4 !== peg$FAILED) { + s1 = [s1, s2, s3, s4]; + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + peg$silentFails--; + if (s0 === peg$FAILED) { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c97); } + } + + return s0; + } + + function peg$parseArray() { + var s0, s1, s2, s3, s4, s5, s6, s7, s8, s9; + + s0 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 91) { + s1 = peg$c100; + peg$currPos++; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c101); } + } + if (s1 !== peg$FAILED) { + s2 = []; + s3 = peg$parseArraySpace(); + while (s3 !== peg$FAILED) { + s2.push(s3); + s3 = peg$parseArraySpace(); + } + if (s2 !== peg$FAILED) { + s3 = peg$currPos; + s4 = peg$parseArrayValue(); + if (s4 !== peg$FAILED) { + s5 = []; + s6 = peg$parseArraySpace(); + while (s6 !== peg$FAILED) { + s5.push(s6); + s6 = peg$parseArraySpace(); + } + if (s5 !== peg$FAILED) { + s6 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 44) { + s7 = peg$c102; + peg$currPos++; + } else { + s7 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c103); } + } + if (s7 !== peg$FAILED) { + s8 = []; + s9 = peg$parseArraySpace(); + while (s9 !== peg$FAILED) { + s8.push(s9); + s9 = peg$parseArraySpace(); + } + if (s8 !== peg$FAILED) { + s7 = [s7, s8]; + s6 = s7; + } else { + peg$currPos = s6; + s6 = peg$FAILED; + } + } else { + peg$currPos = s6; + s6 = peg$FAILED; + } + if (s6 === peg$FAILED) { + s6 = null; + } + if (s6 !== peg$FAILED) { + s4 = [s4, s5, s6]; + s3 = s4; + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + if (s3 === peg$FAILED) { + s3 = null; + } + if (s3 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 93) { + s4 = peg$c104; + peg$currPos++; + } else { + s4 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c105); } + } + if (s4 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c106(s3); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + + return s0; + } + + function peg$parseArrayValue() { + var s0, s1, s2, s3, s4, s5, s6; + + s0 = peg$currPos; + s1 = peg$parseValue(); + if (s1 !== peg$FAILED) { + s2 = peg$currPos; + s3 = []; + s4 = peg$parseArraySpace(); + while (s4 !== peg$FAILED) { + s3.push(s4); + s4 = peg$parseArraySpace(); + } + if (s3 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 44) { + s4 = peg$c102; + peg$currPos++; + } else { + s4 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c103); } + } + if (s4 !== peg$FAILED) { + s5 = []; + s6 = peg$parseArraySpace(); + while (s6 !== peg$FAILED) { + s5.push(s6); + s6 = peg$parseArraySpace(); + } + if (s5 !== peg$FAILED) { + s6 = peg$parseArrayValue(); + if (s6 !== peg$FAILED) { + s3 = [s3, s4, s5, s6]; + s2 = s3; + } else { + peg$currPos = s2; + s2 = peg$FAILED; + } + } else { + peg$currPos = s2; + s2 = peg$FAILED; + } + } else { + peg$currPos = s2; + s2 = peg$FAILED; + } + } else { + peg$currPos = s2; + s2 = peg$FAILED; + } + if (s2 === peg$FAILED) { + s2 = null; + } + if (s2 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c107(s1, s2); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + + return s0; + } + + function peg$parseArraySpace() { + var s0; + + s0 = peg$parseWhitespace(); + if (s0 === peg$FAILED) { + s0 = peg$parseNewline(); + if (s0 === peg$FAILED) { + s0 = peg$parseComment(); + } + } + + return s0; + } + + function peg$parseInlineTable() { + var s0, s1, s2, s3, s4, s5, s6, s7, s8, s9, s10; + + s0 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 123) { + s1 = peg$c108; + peg$currPos++; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c109); } + } + if (s1 !== peg$FAILED) { + s2 = []; + s3 = peg$parseWhitespace(); + while (s3 !== peg$FAILED) { + s2.push(s3); + s3 = peg$parseWhitespace(); + } + if (s2 !== peg$FAILED) { + s3 = peg$currPos; + s4 = peg$parseKeyValue(); + if (s4 !== peg$FAILED) { + s5 = []; + s6 = peg$currPos; + s7 = []; + s8 = peg$parseWhitespace(); + while (s8 !== peg$FAILED) { + s7.push(s8); + s8 = peg$parseWhitespace(); + } + if (s7 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 44) { + s8 = peg$c102; + peg$currPos++; + } else { + s8 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c103); } + } + if (s8 !== peg$FAILED) { + s9 = []; + s10 = peg$parseWhitespace(); + while (s10 !== peg$FAILED) { + s9.push(s10); + s10 = peg$parseWhitespace(); + } + if (s9 !== peg$FAILED) { + s10 = peg$parseKeyValue(); + if (s10 !== peg$FAILED) { + s7 = [s7, s8, s9, s10]; + s6 = s7; + } else { + peg$currPos = s6; + s6 = peg$FAILED; + } + } else { + peg$currPos = s6; + s6 = peg$FAILED; + } + } else { + peg$currPos = s6; + s6 = peg$FAILED; + } + } else { + peg$currPos = s6; + s6 = peg$FAILED; + } + while (s6 !== peg$FAILED) { + s5.push(s6); + s6 = peg$currPos; + s7 = []; + s8 = peg$parseWhitespace(); + while (s8 !== peg$FAILED) { + s7.push(s8); + s8 = peg$parseWhitespace(); + } + if (s7 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 44) { + s8 = peg$c102; + peg$currPos++; + } else { + s8 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c103); } + } + if (s8 !== peg$FAILED) { + s9 = []; + s10 = peg$parseWhitespace(); + while (s10 !== peg$FAILED) { + s9.push(s10); + s10 = peg$parseWhitespace(); + } + if (s9 !== peg$FAILED) { + s10 = peg$parseKeyValue(); + if (s10 !== peg$FAILED) { + s7 = [s7, s8, s9, s10]; + s6 = s7; + } else { + peg$currPos = s6; + s6 = peg$FAILED; + } + } else { + peg$currPos = s6; + s6 = peg$FAILED; + } + } else { + peg$currPos = s6; + s6 = peg$FAILED; + } + } else { + peg$currPos = s6; + s6 = peg$FAILED; + } + } + if (s5 !== peg$FAILED) { + s6 = []; + s7 = peg$parseWhitespace(); + while (s7 !== peg$FAILED) { + s6.push(s7); + s7 = peg$parseWhitespace(); + } + if (s6 !== peg$FAILED) { + s4 = [s4, s5, s6]; + s3 = s4; + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + if (s3 === peg$FAILED) { + s3 = null; + } + if (s3 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 125) { + s4 = peg$c110; + peg$currPos++; + } else { + s4 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c111); } + } + if (s4 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c112(s3); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + + return s0; + } + + function peg$parseTableArrayHeader() { + var s0, s1, s2, s3; + + s0 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 91) { + s1 = peg$c100; + peg$currPos++; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c101); } + } + if (s1 !== peg$FAILED) { + s2 = peg$parseTableHeader(); + if (s2 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 93) { + s3 = peg$c104; + peg$currPos++; + } else { + s3 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c105); } + } + if (s3 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c113(s2); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + + return s0; + } + + function peg$parseTableHeader() { + var s0, s1, s2, s3, s4, s5, s6, s7, s8, s9; + + s0 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 91) { + s1 = peg$c100; + peg$currPos++; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c101); } + } + if (s1 !== peg$FAILED) { + s2 = []; + s3 = peg$parseWhitespace(); + while (s3 !== peg$FAILED) { + s2.push(s3); + s3 = peg$parseWhitespace(); + } + if (s2 !== peg$FAILED) { + s3 = peg$parseKey(); + if (s3 !== peg$FAILED) { + s4 = []; + s5 = peg$currPos; + s6 = []; + s7 = peg$parseWhitespace(); + while (s7 !== peg$FAILED) { + s6.push(s7); + s7 = peg$parseWhitespace(); + } + if (s6 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 46) { + s7 = peg$c71; + peg$currPos++; + } else { + s7 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c72); } + } + if (s7 !== peg$FAILED) { + s8 = []; + s9 = peg$parseWhitespace(); + while (s9 !== peg$FAILED) { + s8.push(s9); + s9 = peg$parseWhitespace(); + } + if (s8 !== peg$FAILED) { + s9 = peg$parseKey(); + if (s9 !== peg$FAILED) { + s6 = [s6, s7, s8, s9]; + s5 = s6; + } else { + peg$currPos = s5; + s5 = peg$FAILED; + } + } else { + peg$currPos = s5; + s5 = peg$FAILED; + } + } else { + peg$currPos = s5; + s5 = peg$FAILED; + } + } else { + peg$currPos = s5; + s5 = peg$FAILED; + } + while (s5 !== peg$FAILED) { + s4.push(s5); + s5 = peg$currPos; + s6 = []; + s7 = peg$parseWhitespace(); + while (s7 !== peg$FAILED) { + s6.push(s7); + s7 = peg$parseWhitespace(); + } + if (s6 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 46) { + s7 = peg$c71; + peg$currPos++; + } else { + s7 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c72); } + } + if (s7 !== peg$FAILED) { + s8 = []; + s9 = peg$parseWhitespace(); + while (s9 !== peg$FAILED) { + s8.push(s9); + s9 = peg$parseWhitespace(); + } + if (s8 !== peg$FAILED) { + s9 = peg$parseKey(); + if (s9 !== peg$FAILED) { + s6 = [s6, s7, s8, s9]; + s5 = s6; + } else { + peg$currPos = s5; + s5 = peg$FAILED; + } + } else { + peg$currPos = s5; + s5 = peg$FAILED; + } + } else { + peg$currPos = s5; + s5 = peg$FAILED; + } + } else { + peg$currPos = s5; + s5 = peg$FAILED; + } + } + if (s4 !== peg$FAILED) { + s5 = []; + s6 = peg$parseWhitespace(); + while (s6 !== peg$FAILED) { + s5.push(s6); + s6 = peg$parseWhitespace(); + } + if (s5 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 93) { + s6 = peg$c104; + peg$currPos++; + } else { + s6 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c105); } + } + if (s6 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c114(s3, s4); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + + return s0; + } + + + var genMsgRedefined, isFiniteNumber, isArray, hasOwnProperty, stringify, + unescape, fromCodePoint, checkTableKey, findContext; + + genMsgRedefined = function (key) { + return ('Value for ' + key + ' should not be redefined in the same table.'); + }; + + isFiniteNumber = Number.isFinite || function (n) { + return typeof n === 'number' && isFinite(n); + }; + + isArray = Array.isArray || function (obj) { + return Object.prototype.toString.call(obj) === '[object Array]'; + }; + + hasOwnProperty = function (obj, key) { + return Object.prototype.hasOwnProperty.call(obj, key); + }; + + stringify = typeof JSON === 'object' && JSON ? JSON.stringify : function (o) { + return '"' + String(o).replace(/[\x00-\x1F"\\]/g, function (c) { + switch (c) { + case '"': case '\\': return '\\' + c; + case '\t': return '\\t'; + case '\n': return '\\n'; + case '\r': return '\\r'; + case '\b': return '\\b'; + case '\f': return '\\f'; + default: + var hex = c.charCodeAt(0).toString(16); + return '\\u' + '0000'.substr(hex.length) + hex; + } + }) + '"'; + }; + + unescape = function (c) { + switch (c) { + case '"': case '\\': return c; + case 't': return '\t'; + case 'n': return '\n'; + case 'r': return '\r'; + case 'b': return '\b'; + case 'f': return '\f'; + default: error(stringify(c) + ' cannot be escaped.'); + } + }; + + fromCodePoint = function (codepoint) { + if (!isFiniteNumber(codepoint) || codepoint < 0 || codepoint > 0x10FFFF) { + error('U+' + codepoint.toString(16) + + ' is not a valid Unicode code point.'); + } + if (String.fromCodePoint) { + return String.fromCodePoint(codepoint); + } + // See: punnycode.ucs2.encode from https://github.com/bestiejs/punycode.js + var c = ''; + if (codepoint > 0xFFFF) { + codepoint -= 0x10000; + c += String.fromCharCode((codepoint >>> 10) & 0x3FF | 0xD800); + codepoint = 0xDC00 | codepoint & 0x3FF; + } + c += String.fromCharCode(codepoint); + return c; + }; + + checkTableKey = function (table, k) { + if (hasOwnProperty(table, k)) { + error(genMsgRedefined(stringify(k))); + } + }; + + findContext = function (table, isTableArray, path) { + var s = ''; + for (var i = 0, l = path.length; i < l; i++) { + var k = path[i]; + s += (s ? '.' : '') + stringify(k); + if (!hasOwnProperty(table, k)) { + if (isTableArray && i + 1 === l) { + var t = {}; + table[k] = [t]; + table = t; + g_table_arrays[s] = true; + } else { + table = table[k] = {}; + g_tables[s] = true; + } + } else { + if (isTableArray) { + if (isArray(table[k])) { + if (!g_table_arrays[s]) { + error(genMsgRedefined(s)); + } + if (i + 1 === l) { + var t = {}; + table[k].push(t); + table = t; + } else { + s += '.' + stringify(table[k].length - 1); + table = table[k][table[k].length-1]; + } + } else { + if (!g_tables[s]) { + error(genMsgRedefined(s)); + } + table = table[k]; + } + } else { + if (isArray(table[k])) { + if (!g_table_arrays[s] || i + 1 === l) { + error(genMsgRedefined(s)); + } + s += '.' + stringify(table[k].length - 1); + table = table[k][table[k].length-1]; + } else { + if (!g_tables[s]) { + error(genMsgRedefined(s)); + } + table = table[k]; + } + } + } + } + if (isTableArray) { + if (!g_table_arrays[s]) { + error(genMsgRedefined(s)); + } + } else { + if (g_defined_tables[s] || g_table_arrays[s]) { + error(genMsgRedefined(s)); + } + g_defined_tables[s] = true; + } + return { + table: table, + path: path + }; + }; + + var g_root = {}; // TOML table + var g_context = { // current context + table: g_root, + path: [] + }; + var g_tables = {}; // paths to tables + var g_defined_tables = {}; // paths to tables directly defined + var g_table_arrays = {}; // paths to table arrays + + + peg$result = peg$startRuleFunction(); + + if (peg$result !== peg$FAILED && peg$currPos === input.length) { + return peg$result; + } else { + if (peg$result !== peg$FAILED && peg$currPos < input.length) { + peg$fail(peg$endExpectation()); + } + + throw peg$buildStructuredError( + peg$maxFailExpected, + peg$maxFailPos < input.length ? input.charAt(peg$maxFailPos) : null, + peg$maxFailPos < input.length + ? peg$computeLocation(peg$maxFailPos, peg$maxFailPos + 1) + : peg$computeLocation(peg$maxFailPos, peg$maxFailPos) + ); + } + } + + return { + SyntaxError: peg$SyntaxError, + parse: peg$parse + }; + })(); + + function subclass(child, parent) { + function ctor() { + this.constructor = child; + } + ctor.prototype = parent.prototype; + child.prototype = new ctor(); + } + + function TomlSyntaxError(message, offset, line, column) { + this.message = message; + this.offset = offset; + this.line = line; + this.column = column; + } + + subclass(TomlSyntaxError, SyntaxError); + + var parser$1 = parser$2; + var toml = { + parse: function (src) { + try { + return parser$1.parse(src); + } catch (err) { + if (err instanceof parser$1.SyntaxError) { + err.line = err.location.start.line; + err.column = err.location.start.column; + err.offset = err.location.start.offset; + throw new TomlSyntaxError( + err.message, + err.location.start.offset, + err.location.start.line, + err.location.start.column); + } else { + throw err; + } + } + }, + SyntaxError: TomlSyntaxError + }; + + var toml_1 = toml; + + /* Very simple logger interface. + + Each module is expected to create its own logger by doing e.g.: + + const logger = getLogger('my-prefix'); + + and then use it instead of console: + + logger.info('hello', 'world'); + logger.warn('...'); + logger.error('...'); + + The logger automatically adds the prefix "[my-prefix]" to all logs. + E.g., the above call would print: + + [my-prefix] hello world + + logger.log is intentionally omitted. The idea is that PyScript should not + write anything to console.log, to leave it free for the user. + + Currently, the logger does not to anything more than that. In the future, + we might want to add additional features such as the ability to + enable/disable logs on a global or per-module basis. + */ + const _cache = new Map(); + function getLogger(prefix) { + let logger = _cache.get(prefix); + if (logger === undefined) { + logger = _makeLogger(prefix); + _cache.set(prefix, logger); + } + return logger; + } + function _makeLogger(prefix) { + prefix = `[${prefix}] `; + function make(level) { + const out_fn = console[level].bind(console); + function fn(fmt, ...args) { + out_fn(prefix + fmt, ...args); + } + return fn; + } + // 'log' is intentionally omitted + const debug = make('debug'); + const info = make('info'); + const warn = make('warn'); + const error = make('error'); + return { debug, info, warn, error }; + } + + /** + * @fileoverview Version of pyscript + * The version is based on calver which contains YEAR.MONTH.DAY.MODIFIER. + * The Modifier can be an optional text tag, such as "dev", "rc", etc. + * + * We are adding this file because we can't add version in main.js due to + * circular imports. + */ + const version = '2022.12.1.dev'; + + const CLOSEBUTTON = ``; + /* + These error codes are used to identify the type of error that occurred. + The convention is: + * PY0 - errors that occur when fetching + * PY1 - errors that occur in config + * Py2 - errors that occur in plugins + * PY9 - Deprecation errors + */ + var ErrorCode; + (function (ErrorCode) { + ErrorCode["GENERIC"] = "PY0000"; + ErrorCode["FETCH_ERROR"] = "PY0001"; + ErrorCode["FETCH_NAME_ERROR"] = "PY0002"; + // Currently these are created depending on error code received from fetching + ErrorCode["FETCH_UNAUTHORIZED_ERROR"] = "PY0401"; + ErrorCode["FETCH_FORBIDDEN_ERROR"] = "PY0403"; + ErrorCode["FETCH_NOT_FOUND_ERROR"] = "PY0404"; + ErrorCode["FETCH_SERVER_ERROR"] = "PY0500"; + ErrorCode["FETCH_UNAVAILABLE_ERROR"] = "PY0503"; + ErrorCode["BAD_CONFIG"] = "PY1000"; + ErrorCode["MICROPIP_INSTALL_ERROR"] = "PY1001"; + ErrorCode["BAD_PLUGIN_FILE_EXTENSION"] = "PY2000"; + ErrorCode["NO_DEFAULT_EXPORT"] = "PY2001"; + ErrorCode["TOP_LEVEL_AWAIT"] = "PY9000"; + })(ErrorCode || (ErrorCode = {})); + class UserError extends Error { + constructor(errorCode, message, t = 'text') { + super(message); + this.errorCode = errorCode; + this.name = 'UserError'; + this.messageType = t; + this.message = `(${errorCode}): ${message}`; + } + } + class FetchError extends UserError { + constructor(errorCode, message) { + super(errorCode, message); + this.name = 'FetchError'; + } + } + class InstallError extends UserError { + constructor(errorCode, message) { + super(errorCode, message); + this.name = 'InstallError'; + } + } + function _createAlertBanner(message, level = 'error', messageType = 'text', logMessage = true) { + // eslint-disable-next-line @typescript-eslint/restrict-template-expressions + switch (`log-${level}-${logMessage}`) { + case 'log-error-true': + console.error(message); + break; + case 'log-warning-true': + console.warn(message); + break; + } + const banner = document.createElement('div'); + banner.className = `alert-banner py-${level}`; + if (messageType === 'html') { + banner.innerHTML = message; + } + else { + banner.textContent = message; + } + if (level === 'warning') { + const closeButton = document.createElement('button'); + closeButton.id = 'alert-close-button'; + closeButton.addEventListener('click', () => { + banner.remove(); + }); + closeButton.innerHTML = CLOSEBUTTON; + banner.appendChild(closeButton); + } + document.body.prepend(banner); + } + + function escape(str) { + return str.replace(//g, '>'); + } + function htmlDecode(input) { + const doc = new DOMParser().parseFromString(ltrim(escape(input)), 'text/html'); + return doc.documentElement.textContent; + } + function ltrim(code) { + const lines = code.split('\n'); + if (lines.length == 0) + return code; + const lengths = lines + .filter(line => line.trim().length != 0) + .map(line => { + return line.match(/^\s*/)?.pop()?.length; + }); + const k = Math.min(...lengths); + return k != 0 ? lines.map(line => line.substring(k)).join('\n') : code; + } + let _uniqueIdCounter = 0; + function ensureUniqueId(el) { + if (el.id === '') + el.id = `py-internal-${_uniqueIdCounter++}`; + } + function showWarning(msg, messageType = 'text') { + _createAlertBanner(msg, 'warning', messageType); + } + function readTextFromPath(path) { + const request = new XMLHttpRequest(); + request.open('GET', path, false); + request.send(); + const returnValue = request.responseText; + return returnValue; + } + function globalExport(name, obj) { + // attach the given object to the global object, so that it is globally + // visible everywhere. Should be used very sparingly! + globalThis[name] = obj; + } + function getAttribute(el, attr) { + if (el.hasAttribute(attr)) { + const value = el.getAttribute(attr); + if (value) { + return value; + } + } + return null; + } + function joinPaths(parts, separator = '/') { + const res = parts + .map(function (part) { + return part.trim().replace(/(^[/]*|[/]*$)/g, ''); + }) + .filter(p => p !== '') + .join(separator || '/'); + if (parts[0].startsWith('/')) { + return '/' + res; + } + return res; + } + function createDeprecationWarning(msg, elementName) { + createSingularWarning(msg, elementName); + } + /** Adds a warning banner with content {msg} at the top of the page if + * and only if no banner containing the {sentinelText} already exists. + * If sentinelText is null, the full text of {msg} is used instead + * + * @param msg {string} The full text content of the warning banner to be displayed + * @param sentinelText {string} [null] The text to match against existing warning banners. + * If null, the full text of 'msg' is used instead. + */ + function createSingularWarning(msg, sentinelText = null) { + const banners = document.getElementsByClassName('alert-banner py-warning'); + let bannerCount = 0; + for (const banner of banners) { + if (banner.innerHTML.includes(sentinelText ? sentinelText : msg)) { + bannerCount++; + } + } + if (bannerCount == 0) { + _createAlertBanner(msg, 'warning'); + } + } + /** + * @returns A new asynchronous lock + * @private + */ + function createLock() { + // This is a promise that is resolved when the lock is open, not resolved when lock is held. + let _lock = Promise.resolve(); + /** + * Acquire the async lock + * @returns A zero argument function that releases the lock. + * @private + */ + async function acquireLock() { + const old_lock = _lock; + let releaseLock; + _lock = new Promise(resolve => (releaseLock = resolve)); + await old_lock; + return releaseLock; + } + return acquireLock; + } + + const logger$b = getLogger('py-config'); + const allKeys = { + string: ['name', 'description', 'version', 'type', 'author_name', 'author_email', 'license'], + number: ['schema_version'], + array: ['runtimes', 'interpreters', 'packages', 'fetch', 'plugins'], + }; + const defaultConfig$1 = { + schema_version: 1, + type: 'app', + interpreters: [ + { + src: 'https://cdn.jsdelivr.net/pyodide/v0.22.1/full/pyodide.js', + name: 'pyodide-0.22.1', + lang: 'python', + }, + ], + // This is for backward compatibility, we need to remove it in the future + runtimes: [], + packages: [], + fetch: [], + plugins: [], + }; + function loadConfigFromElement(el) { + let srcConfig; + let inlineConfig; + if (el === null) { + srcConfig = {}; + inlineConfig = {}; + } + else { + const configType = getAttribute(el, 'type') || 'toml'; + srcConfig = extractFromSrc(el, configType); + inlineConfig = extractFromInline(el, configType); + } + srcConfig = mergeConfig(srcConfig, defaultConfig$1); + const result = mergeConfig(inlineConfig, srcConfig); + result.pyscript = { + version, + time: new Date().toISOString(), + }; + return result; + } + function extractFromSrc(el, configType) { + const src = getAttribute(el, 'src'); + if (src) { + logger$b.info('loading ', src); + return validateConfig(readTextFromPath(src), configType); + } + return {}; + } + function extractFromInline(el, configType) { + if (el.innerHTML !== '') { + logger$b.info('loading content'); + return validateConfig(htmlDecode(el.innerHTML), configType); + } + return {}; + } + function fillUserData(inputConfig, resultConfig) { + for (const key in inputConfig) { + // fill in all extra keys ignored by the validator + if (!(key in defaultConfig$1)) { + resultConfig[key] = inputConfig[key]; + } + } + return resultConfig; + } + function mergeConfig(inlineConfig, externalConfig) { + if (Object.keys(inlineConfig).length === 0 && Object.keys(externalConfig).length === 0) { + return defaultConfig$1; + } + else if (Object.keys(inlineConfig).length === 0) { + return externalConfig; + } + else if (Object.keys(externalConfig).length === 0) { + return inlineConfig; + } + else { + let merged = {}; + for (const keyType in allKeys) { + const keys = allKeys[keyType]; + keys.forEach(function (item) { + if (keyType === 'boolean') { + merged[item] = + typeof inlineConfig[item] !== 'undefined' ? inlineConfig[item] : externalConfig[item]; + } + else { + merged[item] = inlineConfig[item] || externalConfig[item]; + } + }); + } + // fill extra keys from external first + // they will be overridden by inline if extra keys also clash + merged = fillUserData(externalConfig, merged); + merged = fillUserData(inlineConfig, merged); + return merged; + } + } + function parseConfig(configText, configType = 'toml') { + if (configType === 'toml') { + // TOML parser is soft and can parse even JSON strings, this additional check prevents it. + if (configText.trim()[0] === '{') { + throw new UserError(ErrorCode.BAD_CONFIG, `The config supplied: ${configText} is an invalid TOML and cannot be parsed`); + } + try { + return toml_1.parse(configText); + } + catch (err) { + const errMessage = err.toString(); + throw new UserError(ErrorCode.BAD_CONFIG, `The config supplied: ${configText} is an invalid TOML and cannot be parsed: ${errMessage}`); + } + } + else if (configType === 'json') { + try { + return JSON.parse(configText); + } + catch (err) { + const errMessage = err.toString(); + throw new UserError(ErrorCode.BAD_CONFIG, `The config supplied: ${configText} is an invalid JSON and cannot be parsed: ${errMessage}`); + } + } + else { + throw new UserError(ErrorCode.BAD_CONFIG, `The type of config supplied '${configType}' is not supported, supported values are ["toml", "json"]`); + } + } + function validateConfig(configText, configType = 'toml') { + const config = parseConfig(configText, configType); + const finalConfig = {}; + for (const keyType in allKeys) { + const keys = allKeys[keyType]; + keys.forEach(function (item) { + if (validateParamInConfig(item, keyType, config)) { + if (item === 'interpreters') { + finalConfig[item] = []; + const interpreters = config[item]; + interpreters.forEach(function (eachInterpreter) { + const interpreterConfig = {}; + for (const eachInterpreterParam in eachInterpreter) { + if (validateParamInConfig(eachInterpreterParam, 'string', eachInterpreter)) { + interpreterConfig[eachInterpreterParam] = eachInterpreter[eachInterpreterParam]; + } + } + finalConfig[item].push(interpreterConfig); + }); + } + else if (item === 'runtimes') { + // This code is a bit of a mess, but it's used for backwards + // compatibility with the old runtimes config. It should be + // removed when we remove support for the old config. + // We also need the warning here since we are pushing + // runtimes to `interpreter` and we can't show the warning + // in main.js + createDeprecationWarning('The configuration option `config.runtimes` is deprecated. ' + + 'Please use `config.interpreters` instead.', ''); + finalConfig['interpreters'] = []; + const interpreters = config[item]; + interpreters.forEach(function (eachInterpreter) { + const interpreterConfig = {}; + for (const eachInterpreterParam in eachInterpreter) { + if (validateParamInConfig(eachInterpreterParam, 'string', eachInterpreter)) { + interpreterConfig[eachInterpreterParam] = eachInterpreter[eachInterpreterParam]; + } + } + finalConfig['interpreters'].push(interpreterConfig); + }); + } + else if (item === 'fetch') { + finalConfig[item] = []; + const fetchList = config[item]; + fetchList.forEach(function (eachFetch) { + const eachFetchConfig = {}; + for (const eachFetchConfigParam in eachFetch) { + const targetType = eachFetchConfigParam === 'files' ? 'array' : 'string'; + if (validateParamInConfig(eachFetchConfigParam, targetType, eachFetch)) { + eachFetchConfig[eachFetchConfigParam] = eachFetch[eachFetchConfigParam]; + } + } + finalConfig[item].push(eachFetchConfig); + }); + } + else { + finalConfig[item] = config[item]; + } + } + }); + } + return fillUserData(config, finalConfig); + } + function validateParamInConfig(paramName, paramType, config) { + if (paramName in config) { + return paramType === 'array' ? Array.isArray(config[paramName]) : typeof config[paramName] === paramType; + } + return false; + } + + /** + * This is a fetch wrapper that handles any non 200 responses and throws a + * FetchError with the right ErrorCode. This is useful because our FetchError + * will automatically create an alert banner. + * + * @param url - URL to fetch + * @param options - options to pass to fetch + * @returns Response + */ + async function robustFetch(url, options) { + let response; + // Note: We need to wrap fetch into a try/catch block because fetch + // throws a TypeError if the URL is invalid such as http://blah.blah + try { + response = await fetch(url, options); + } + catch (err) { + const error = err; + let errMsg; + if (url.startsWith('http')) { + errMsg = + `Fetching from URL ${url} failed with error ` + + `'${error.message}'. Are your filename and path correct?`; + } + else { + errMsg = `PyScript: Access to local files + (using "Paths:" in <py-config>) + is not available when directly opening a HTML file; + you must use a webserver to serve the additional files. + See this reference + on starting a simple webserver with Python. + `; + } + throw new FetchError(ErrorCode.FETCH_ERROR, errMsg); + } + // Note that response.ok is true for 200-299 responses + if (!response.ok) { + const errorMsg = `Fetching from URL ${url} failed with error ${response.status} (${response.statusText}). Are your filename and path correct?`; + switch (response.status) { + case 404: + throw new FetchError(ErrorCode.FETCH_NOT_FOUND_ERROR, errorMsg); + case 401: + throw new FetchError(ErrorCode.FETCH_UNAUTHORIZED_ERROR, errorMsg); + case 403: + throw new FetchError(ErrorCode.FETCH_FORBIDDEN_ERROR, errorMsg); + case 500: + throw new FetchError(ErrorCode.FETCH_SERVER_ERROR, errorMsg); + case 503: + throw new FetchError(ErrorCode.FETCH_UNAVAILABLE_ERROR, errorMsg); + default: + throw new FetchError(ErrorCode.FETCH_ERROR, errorMsg); + } + } + return response; + } + + const logger$a = getLogger('pyscript/pyodide'); + /* + RemoteInterpreter class is responsible to process requests from the + `InterpreterClient` class -- these can be requests for installation of + a package, executing code, etc. + + Currently, the only interpreter available is Pyodide as indicated by the + `InterpreterInterface` type above. This serves as a Union of types of + different interpreters which will be added in near future. + + Methods available handle loading of the interpreter, initialization, + running code, loading and installation of packages, loading from files etc. + + The class will be turned `abstract` in future, to support more runtimes + such as MicroPython. + */ + class RemoteInterpreter extends Object { + constructor(src = 'https://cdn.jsdelivr.net/pyodide/v0.22.1/full/pyodide.js') { + super(); + this.src = src; + } + /** + * loads the interface for the interpreter and saves an instance of it + * in the `this.interface` property along with calling of other + * additional convenience functions. + * */ + /** + * Although `loadPyodide` is used below, + * notice that it is not imported i.e. + * import { loadPyodide } from 'pyodide'; + * is not used at the top of this file. + * + * This is because, if it's used, loadPyodide + * behaves mischievously i.e. it tries to load + * `pyodide.asm.js` and `pyodide_py.tar` but + * with paths that are wrong such as: + * + * http://127.0.0.1:8080/build/pyodide_py.tar + * which results in a 404 since `build` doesn't + * contain these files and is clearly the wrong + * path. + */ + async loadInterpreter(config, stdio) { + this.interface = await loadPyodide({ + stdout: (msg) => { + stdio.stdout_writeline(msg); + }, + stderr: (msg) => { + stdio.stderr_writeline(msg); + }, + fullStdLib: false, + }); + // TODO: Remove this once `runtimes` is removed! + this.interpreter = this.interface; + this.globals = this.interface.globals; + if (config.packages) { + logger$a.info('Found packages in configuration to install. Loading micropip...'); + await this.loadPackage('micropip'); + } + logger$a.info('pyodide loaded and initialized'); + await this.run('print("Python initialization complete")'); + } + /* eslint-disable */ + async run(code) { + /** + * eslint wants `await` keyword to be used i.e. + * { result: await this.interface.runPython(code) } + * However, `await` is not a no-op (no-operation) i.e. + * `await 42` is NOT the same as `42` i.e. if the awaited + * thing is not a promise, it is wrapped inside a promise and + * that promise is awaited. Thus, it changes the execution order. + * See https://stackoverflow.com/questions/55262996/does-awaiting-a-non-promise-have-any-detectable-effect + * Thus, `eslint` is disabled for this block / snippet. + */ + /** + * The output of `runPython` is wrapped inside an object + * since an object is not thennable and avoids return of + * a coroutine directly. This is so we do not `await` the results + * of the underlying python execution, even if it's an + * awaitable object (Future, Task, etc.) + */ + return { result: this.interface.runPython(code) }; + } + /* eslint-enable */ + /** + * delegates the registration of JS modules to + * the underlying interface. + * */ + registerJsModule(name, module) { + this.interface.registerJsModule(name, module); + } + /** + * delegates the loading of packages to + * the underlying interface. + * */ + async loadPackage(names) { + logger$a.info(`pyodide.loadPackage: ${names.toString()}`); + // the new way in v0.22.1 is to pass it as a dict of options i.e. + // { messageCallback: logger.info.bind(logger), errorCallback: logger.info.bind(logger) } + // but one of our tests tries to use a locally downloaded older version of pyodide + // for which the signature of `loadPackage` accepts the above params as args i.e. + // the call uses `logger.info.bind(logger), logger.info.bind(logger)`. + const pyodide_version = (await this.run("import sys; sys.modules['pyodide'].__version__")).result.toString(); + if (pyodide_version.startsWith('0.22')) { + await this.interface.loadPackage(names, { + messageCallback: logger$a.info.bind(logger$a), + errorCallback: logger$a.info.bind(logger$a), + }); + } + else { + await this.interface.loadPackage(names, logger$a.info.bind(logger$a), logger$a.info.bind(logger$a)); + } + } + /** + * delegates the installation of packages + * (using a package manager, which can be specific to + * the interface) to the underlying interface. + * + * For Pyodide, we use `micropip` + * */ + async installPackage(package_name) { + if (package_name.length > 0) { + logger$a.info(`micropip install ${package_name.toString()}`); + const micropip = this.interface.pyimport('micropip'); + try { + await micropip.install(package_name); + micropip.destroy(); + } + catch (e) { + let exceptionMessage = `Unable to install package(s) '` + package_name + `'.`; + // If we can't fetch `package_name` micropip.install throws a huge + // Python traceback in `e.message` this logic is to handle the + // error and throw a more sensible error message instead of the + // huge traceback. + if (e.message.includes("Can't find a pure Python 3 wheel")) { + exceptionMessage += + ` Reason: Can't find a pure Python 3 Wheel for package(s) '` + + package_name + + `'. See: https://pyodide.org/en/stable/usage/faq.html#micropip-can-t-find-a-pure-python-wheel ` + + `for more information.`; + } + else if (e.message.includes("Can't fetch metadata")) { + exceptionMessage += + ' Unable to find package in PyPI. ' + + 'Please make sure you have entered a correct package name.'; + } + else { + exceptionMessage += + ` Reason: ${e.message}. Please open an issue at ` + + `https://github.com/pyscript/pyscript/issues/new if you require help or ` + + `you think it's a bug.`; + } + logger$a.error(e); + throw new InstallError(ErrorCode.MICROPIP_INSTALL_ERROR, exceptionMessage); + } + } + } + /** + * + * @param path : the path in the filesystem + * @param fetch_path : the path to be fetched + * + * Given a file available at `fetch_path` URL (eg: + * `http://dummy.com/hi.py`), the function downloads the file and saves it + * to the `path` (eg: `a/b/c/foo.py`) on the FS. + * + * Example usage: await loadFromFile(`a/b/c/foo.py`, + * `http://dummy.com/hi.py`) + * + * Write content of `http://dummy.com/hi.py` to `a/b/c/foo.py` + * + * NOTE: The `path` parameter expects to have the `filename` in it i.e. + * `a/b/c/foo.py` is valid while `a/b/c` (i.e. only the folders) are + * incorrect. + * + * The path will be resolved relative to the current working directory, + * which is initially `/home/pyodide`. So by default `a/b.py` will be placed + * in `/home/pyodide/a/b.py`, `../a/b.py` will be placed into `/home/a/b.py` + * and `/a/b.py` will be placed into `/a/b.py`. + */ + async loadFromFile(path, fetch_path) { + // eslint-disable-next-line @typescript-eslint/ban-ts-comment + // @ts-ignore + path = this.interface._module.PATH_FS.resolve(path); + // eslint-disable-next-line @typescript-eslint/ban-ts-comment + // @ts-ignore + const dir = this.interface._module.PATH.dirname(path); + this.interface.FS.mkdirTree(dir); + // `robustFetch` checks for failures in getting a response + const response = await robustFetch(fetch_path); + const buffer = await response.arrayBuffer(); + const data = new Uint8Array(buffer); + this.interface.FS.writeFile(path, data, { canOwn: true }); + } + /** + * delegates clearing importlib's module path + * caches to the underlying interface + */ + invalidate_module_path_cache() { + const importlib = this.interface.pyimport('importlib'); + importlib.invalidate_caches(); + } + } + + const logger$9 = getLogger('pyscript/interpreter'); + /* + InterpreterClient class is responsible to request code execution + (among other things) from a `RemoteInterpreter` + */ + class InterpreterClient extends Object { + constructor(config, stdio) { + super(); + this.config = config; + this._remote = new RemoteInterpreter(this.config.interpreters[0].src); + this.stdio = stdio; + } + /** + * initializes the remote interpreter, which further loads the underlying + * interface. + * */ + async initializeRemote() { + await this._remote.loadInterpreter(this.config, this.stdio); + this.globals = this._remote.globals; + } + /** + * delegates the code to be run to the underlying interface of + * the remote interpreter. + * Python exceptions are turned into JS exceptions. + * */ + async run(code) { + return await this._remote.run(code); + } + /** + * Same as run, but Python exceptions are not propagated: instead, they + * are logged to the console. + * + * This is a bad API and should be killed/refactored/changed eventually, + * but for now we have code which relies on it. + * */ + async runButDontRaise(code) { + let result; + try { + result = (await this.run(code)).result; + } + catch (error) { + logger$9.error('Error:', error); + } + return result; + } + } + + const logger$8 = getLogger('plugin'); + class Plugin { + /** Validate the configuration of the plugin and handle default values. + * + * Individual plugins are expected to check that the config keys/sections + * which are relevant to them contains valid values, and to raise an error + * if they contains unknown keys. + * + * This is also a good place where set default values for those keys which + * are not specified by the user. + * + * This hook should **NOT** contain expensive operations, else it delays + * the download of the python interpreter which is initiated later. + */ + configure(config) { } + /** The preliminary initialization phase is complete and we are about to + * download and launch the Python interpreter. + * + * We can assume that the page is already shown to the user and that the + * DOM content has been loaded. This is a good place where to add tags to + * the DOM, if needed. + * + * This hook should **NOT** contain expensive operations, else it delays + * the download of the python interpreter which is initiated later. + */ + beforeLaunch(config) { } + /** The Python interpreter has been launched, the virtualenv has been + * installed and we are ready to execute user code. + * + * The tags will be executed after this hook. + */ + afterSetup(interpreter) { } + /** The source of a > tag has been fetched, and we're about + * to evaluate that source using the provided interpreter. + * + * @param options.interpreter The Interpreter object that will be used to evaluated the Python source code + * @param options.src {string} The Python source code to be evaluated + * @param options.pyScriptTag The HTML tag that originated the evaluation + */ + beforePyScriptExec(options) { } + /** The Python in a has just been evaluated, but control + * has not been ceded back to the JavaScript event loop yet + * + * @param options.interpreter The Interpreter object that will be used to evaluated the Python source code + * @param options.src {string} The Python source code to be evaluated + * @param options.pyScriptTag The HTML tag that originated the evaluation + * @param options.result The returned result of evaluating the Python (if any) + */ + afterPyScriptExec(options) { } + /** Startup complete. The interpreter is initialized and ready, user + * scripts have been executed: the main initialization logic ends here and + * the page is ready to accept user interactions. + */ + afterStartup(interpreter) { } + /** Called when an UserError is raised + */ + onUserError(error) { } + } + class PluginManager { + constructor() { + this._plugins = []; + this._pythonPlugins = []; + } + add(...plugins) { + for (const p of plugins) + this._plugins.push(p); + } + addPythonPlugin(plugin) { + this._pythonPlugins.push(plugin); + } + configure(config) { + for (const p of this._plugins) + p.configure?.(config); + for (const p of this._pythonPlugins) + p.configure?.(config); + } + beforeLaunch(config) { + for (const p of this._plugins) { + try { + p?.beforeLaunch?.(config); + } + catch (e) { + logger$8.error(`Error while calling beforeLaunch hook of plugin ${p.constructor.name}`, e); + } + } + } + afterSetup(interpreter) { + for (const p of this._plugins) { + try { + p.afterSetup?.(interpreter); + } + catch (e) { + logger$8.error(`Error while calling afterSetup hook of plugin ${p.constructor.name}`, e); + } + } + for (const p of this._pythonPlugins) + p.afterSetup?.(interpreter); + } + afterStartup(interpreter) { + for (const p of this._plugins) + p.afterStartup?.(interpreter); + for (const p of this._pythonPlugins) + p.afterStartup?.(interpreter); + } + beforePyScriptExec(options) { + for (const p of this._plugins) + p.beforePyScriptExec?.(options); + for (const p of this._pythonPlugins) + p.beforePyScriptExec?.callKwargs(options); + } + afterPyScriptExec(options) { + for (const p of this._plugins) + p.afterPyScriptExec?.(options); + for (const p of this._pythonPlugins) + p.afterPyScriptExec?.callKwargs(options); + } + onUserError(error) { + for (const p of this._plugins) + p.onUserError?.(error); + for (const p of this._pythonPlugins) + p.onUserError?.(error); + } + } + /** + * Defines a new CustomElement (via customElement.defines) with `tag`, + * where the new CustomElement is a proxy that delegates the logic to + * pyPluginClass. + * + * @param tag - tag that will be used to define the new CustomElement (i.e: "py-script") + * @param pyPluginClass - class that will be used to create instance to be + * used as CustomElement logic handler. Any DOM event + * received by the newly created CustomElement will be + * delegated to that instance. + */ + function define_custom_element(tag, pyPluginClass) { + logger$8.info(`creating plugin: ${tag}`); + class ProxyCustomElement extends HTMLElement { + constructor() { + logger$8.debug(`creating ${tag} plugin instance`); + super(); + this.shadow = this.attachShadow({ mode: 'open' }); + this.wrapper = document.createElement('slot'); + this.shadow.appendChild(this.wrapper); + this.originalInnerHTML = this.innerHTML; + this.pyPluginInstance = pyPluginClass(this); + } + connectedCallback() { + const innerHTML = this.pyPluginInstance.connect(); + if (typeof innerHTML === 'string') + this.innerHTML = innerHTML; + } + } + customElements.define(tag, ProxyCustomElement); + } + + const logger$7 = getLogger('pyexec'); + async function pyExec(interpreter, pysrc, outElem) { + //This is pyscript.py + const pyscript_py = interpreter._remote.interface.pyimport('pyscript'); + ensureUniqueId(outElem); + pyscript_py.set_current_display_target(outElem.id); + try { + try { + if (pyscript_py.uses_top_level_await(pysrc)) { + throw new UserError(ErrorCode.TOP_LEVEL_AWAIT, 'The use of top-level "await", "async for", and ' + + '"async with" has been removed.' + + '\nPlease write a coroutine containing ' + + 'your code and schedule it using asyncio.ensure_future() or similar.' + + '\nSee https://docs.pyscript.net/latest/guides/asyncio.html for more information.'); + } + return await interpreter.run(pysrc); + } + catch (err) { + // XXX: currently we display exceptions in the same position as + // the output. But we probably need a better way to do that, + // e.g. allowing plugins to intercept exceptions and display them + // in a configurable way. + displayPyException(err, outElem); + return { result: undefined }; + } + } + finally { + pyscript_py.set_current_display_target(undefined); + pyscript_py.destroy(); + } + } + /** + * Javascript API to call the python display() function + * + * Expected usage: + * pyDisplay(interpreter, obj); + * pyDisplay(interpreter, obj, { target: targetID }); + */ + function pyDisplay(interpreter, obj, kwargs) { + const display = interpreter.globals.get('display'); + if (kwargs === undefined) + display(obj); + else { + display.callKwargs(obj, kwargs); + } + } + function displayPyException(err, errElem) { + //addClasses(errElem, ['py-error']) + const pre = document.createElement('pre'); + pre.className = 'py-error'; + if (err.name === 'PythonError') { + // err.message contains the python-level traceback (i.e. a string + // starting with: "Traceback (most recent call last) ..." + logger$7.error('Python exception:\n' + err.message); + pre.innerText = err.message; + } + else { + // this is very likely a normal JS exception. The best we can do is to + // display it as is. + logger$7.error('Non-python exception:\n' + err); + pre.innerText = err; + } + errElem.appendChild(pre); + } + + const logger$6 = getLogger('py-script'); + function make_PyScript(interpreter, app) { + class PyScript extends HTMLElement { + async connectedCallback() { + /** + * Since connectedCallback is async, multiple py-script tags can be executed in + * an order which is not particularly sequential. The locking mechanism here ensures + * a sequential execution of multiple py-script tags present in one page. + * + * Concurrent access to the multiple py-script tags is thus avoided. + */ + let releaseLock; + try { + releaseLock = await app.tagExecutionLock(); + ensureUniqueId(this); + // Save innerHTML information in srcCode so we can access it later + // once we clean innerHTML (which is required since we don't want + // source code to be rendered on the screen) + this.srcCode = this.innerHTML; + const pySrc = await this.getPySrc(); + this.innerHTML = ''; + app.plugins.beforePyScriptExec({ interpreter: interpreter, src: pySrc, pyScriptTag: this }); + const result = (await pyExec(interpreter, pySrc, this)).result; + app.plugins.afterPyScriptExec({ + interpreter: interpreter, + src: pySrc, + pyScriptTag: this, + result: result, + }); + } + finally { + releaseLock(); + } + } + async getPySrc() { + if (this.hasAttribute('src')) { + const url = this.getAttribute('src'); + try { + const response = await robustFetch(url); + return await response.text(); + } + catch (e) { + _createAlertBanner(e.message); + this.innerHTML = ''; + throw e; + } + } + else { + return htmlDecode(this.srcCode); + } + } + } + return PyScript; + } + /** Defines all possible py-on* and their corresponding event types */ + const pyAttributeToEvent = new Map([ + // Leaving pys-onClick and pys-onKeyDown for backward compatibility + ['pys-onClick', 'click'], + ['pys-onKeyDown', 'keydown'], + ['py-onClick', 'click'], + ['py-onKeyDown', 'keydown'], + // Window Events + ['py-afterprint', 'afterprint'], + ['py-beforeprint', 'beforeprint'], + ['py-beforeunload', 'beforeunload'], + ['py-error', 'error'], + ['py-hashchange', 'hashchange'], + ['py-load', 'load'], + ['py-message', 'message'], + ['py-offline', 'offline'], + ['py-online', 'online'], + ['py-pagehide', 'pagehide'], + ['py-pageshow', 'pageshow'], + ['py-popstate', 'popstate'], + ['py-resize', 'resize'], + ['py-storage', 'storage'], + ['py-unload', 'unload'], + // Form Events + ['py-blur', 'blur'], + ['py-change', 'change'], + ['py-contextmenu', 'contextmenu'], + ['py-focus', 'focus'], + ['py-input', 'input'], + ['py-invalid', 'invalid'], + ['py-reset', 'reset'], + ['py-search', 'search'], + ['py-select', 'select'], + ['py-submit', 'submit'], + // Keyboard Events + ['py-keydown', 'keydown'], + ['py-keypress', 'keypress'], + ['py-keyup', 'keyup'], + // Mouse Events + ['py-click', 'click'], + ['py-dblclick', 'dblclick'], + ['py-mousedown', 'mousedown'], + ['py-mousemove', 'mousemove'], + ['py-mouseout', 'mouseout'], + ['py-mouseover', 'mouseover'], + ['py-mouseup', 'mouseup'], + ['py-mousewheel', 'mousewheel'], + ['py-wheel', 'wheel'], + // Drag Events + ['py-drag', 'drag'], + ['py-dragend', 'dragend'], + ['py-dragenter', 'dragenter'], + ['py-dragleave', 'dragleave'], + ['py-dragover', 'dragover'], + ['py-dragstart', 'dragstart'], + ['py-drop', 'drop'], + ['py-scroll', 'scroll'], + // Clipboard Events + ['py-copy', 'copy'], + ['py-cut', 'cut'], + ['py-paste', 'paste'], + // Media Events + ['py-abort', 'abort'], + ['py-canplay', 'canplay'], + ['py-canplaythrough', 'canplaythrough'], + ['py-cuechange', 'cuechange'], + ['py-durationchange', 'durationchange'], + ['py-emptied', 'emptied'], + ['py-ended', 'ended'], + ['py-loadeddata', 'loadeddata'], + ['py-loadedmetadata', 'loadedmetadata'], + ['py-loadstart', 'loadstart'], + ['py-pause', 'pause'], + ['py-play', 'play'], + ['py-playing', 'playing'], + ['py-progress', 'progress'], + ['py-ratechange', 'ratechange'], + ['py-seeked', 'seeked'], + ['py-seeking', 'seeking'], + ['py-stalled', 'stalled'], + ['py-suspend', 'suspend'], + ['py-timeupdate', 'timeupdate'], + ['py-volumechange', 'volumechange'], + ['py-waiting', 'waiting'], + // Misc Events + ['py-toggle', 'toggle'], + ]); + /** Initialize all elements with py-* handlers attributes */ + function initHandlers(interpreter) { + logger$6.debug('Initializing py-* event handlers...'); + for (const pyAttribute of pyAttributeToEvent.keys()) { + createElementsWithEventListeners(interpreter, pyAttribute); + } + } + /** Initializes an element with the given py-on* attribute and its handler */ + function createElementsWithEventListeners(interpreter, pyAttribute) { + const matches = document.querySelectorAll(`[${pyAttribute}]`); + for (const el of matches) { + // If the element doesn't have an id, let's add one automatically! + if (el.id.length === 0) { + ensureUniqueId(el); + } + const handlerCode = el.getAttribute(pyAttribute); + const event = pyAttributeToEvent.get(pyAttribute); + if (pyAttribute === 'pys-onClick' || pyAttribute === 'pys-onKeyDown') { + const msg = `The attribute 'pys-onClick' and 'pys-onKeyDown' are deprecated. Please 'py-click="myFunction()"' ` + + ` or 'py-keydown="myFunction()"' instead.`; + createDeprecationWarning(msg, msg); + const source = ` + from pyodide.ffi import create_proxy + Element("${el.id}").element.addEventListener("${event}", create_proxy(${handlerCode})) + `; + // We meed to run the source code in a try/catch block, because + // the source code may contain a syntax error, which will cause + // the splashscreen to not be removed. + try { + interpreter.run(source); + } + catch (e) { + logger$6.error(e.message); + } + } + else { + el.addEventListener(event, () => { + void (async () => { + try { + await interpreter.run(handlerCode); + } + catch (err) { + displayPyException(err, el.parentElement); + } + })(); + }); + } + // TODO: Should we actually map handlers in JS instead of Python? + // el.onclick = (evt: any) => { + // console.log("click"); + // new Promise((resolve, reject) => { + // setTimeout(() => { + // console.log('Inside') + // }, 300); + // }).then(() => { + // console.log("resolved") + // }); + // // let handlerCode = el.getAttribute('py-onClick'); + // // pyodide.runPython(handlerCode); + // } + } + } + /** Mount all elements with attribute py-mount into the Python namespace */ + async function mountElements(interpreter) { + const matches = document.querySelectorAll('[py-mount]'); + logger$6.info(`py-mount: found ${matches.length} elements`); + let source = ''; + for (const el of matches) { + const mountName = el.getAttribute('py-mount') || el.id.split('-').join('_'); + source += `\n${mountName} = Element("${el.id}")`; + } + await interpreter.run(source); + } + + function calculatePaths(fetch_cfg) { + const fetchPaths = []; + const paths = []; + fetch_cfg.forEach(function (each_fetch_cfg) { + const from = each_fetch_cfg.from || ''; + const to_folder = each_fetch_cfg.to_folder || '.'; + const to_file = each_fetch_cfg.to_file; + const files = each_fetch_cfg.files; + if (files !== undefined) { + if (to_file !== undefined) { + throw new UserError(ErrorCode.BAD_CONFIG, `Cannot use 'to_file' and 'files' parameters together!`); + } + for (const each_f of files) { + const each_fetch_path = joinPaths([from, each_f]); + fetchPaths.push(each_fetch_path); + const each_path = joinPaths([to_folder, each_f]); + paths.push(each_path); + } + } + else { + fetchPaths.push(from); + const filename = to_file || from.split('/').pop(); + if (filename === '') { + throw new UserError(ErrorCode.BAD_CONFIG, `Couldn't determine the filename from the path ${from}, please supply 'to_file' parameter.`); + } + else { + paths.push(joinPaths([to_folder, filename])); + } + } + }); + return [paths, fetchPaths]; + } + + /** + The data structure for documents. @nonabstract + */ + class Text { + /** + @internal + */ + constructor() { } + /** + Get the line description around the given position. + */ + lineAt(pos) { + if (pos < 0 || pos > this.length) + throw new RangeError(`Invalid position ${pos} in document of length ${this.length}`); + return this.lineInner(pos, false, 1, 0); + } + /** + Get the description for the given (1-based) line number. + */ + line(n) { + if (n < 1 || n > this.lines) + throw new RangeError(`Invalid line number ${n} in ${this.lines}-line document`); + return this.lineInner(n, true, 1, 0); + } + /** + Replace a range of the text with the given content. + */ + replace(from, to, text) { + let parts = []; + this.decompose(0, from, parts, 2 /* Open.To */); + if (text.length) + text.decompose(0, text.length, parts, 1 /* Open.From */ | 2 /* Open.To */); + this.decompose(to, this.length, parts, 1 /* Open.From */); + return TextNode.from(parts, this.length - (to - from) + text.length); + } + /** + Append another document to this one. + */ + append(other) { + return this.replace(this.length, this.length, other); + } + /** + Retrieve the text between the given points. + */ + slice(from, to = this.length) { + let parts = []; + this.decompose(from, to, parts, 0); + return TextNode.from(parts, to - from); + } + /** + Test whether this text is equal to another instance. + */ + eq(other) { + if (other == this) + return true; + if (other.length != this.length || other.lines != this.lines) + return false; + let start = this.scanIdentical(other, 1), end = this.length - this.scanIdentical(other, -1); + let a = new RawTextCursor(this), b = new RawTextCursor(other); + for (let skip = start, pos = start;;) { + a.next(skip); + b.next(skip); + skip = 0; + if (a.lineBreak != b.lineBreak || a.done != b.done || a.value != b.value) + return false; + pos += a.value.length; + if (a.done || pos >= end) + return true; + } + } + /** + Iterate over the text. When `dir` is `-1`, iteration happens + from end to start. This will return lines and the breaks between + them as separate strings. + */ + iter(dir = 1) { return new RawTextCursor(this, dir); } + /** + Iterate over a range of the text. When `from` > `to`, the + iterator will run in reverse. + */ + iterRange(from, to = this.length) { return new PartialTextCursor(this, from, to); } + /** + Return a cursor that iterates over the given range of lines, + _without_ returning the line breaks between, and yielding empty + strings for empty lines. + + When `from` and `to` are given, they should be 1-based line numbers. + */ + iterLines(from, to) { + let inner; + if (from == null) { + inner = this.iter(); + } + else { + if (to == null) + to = this.lines + 1; + let start = this.line(from).from; + inner = this.iterRange(start, Math.max(start, to == this.lines + 1 ? this.length : to <= 1 ? 0 : this.line(to - 1).to)); + } + return new LineCursor(inner); + } + /** + @internal + */ + toString() { return this.sliceString(0); } + /** + Convert the document to an array of lines (which can be + deserialized again via [`Text.of`](https://codemirror.net/6/docs/ref/#state.Text^of)). + */ + toJSON() { + let lines = []; + this.flatten(lines); + return lines; + } + /** + Create a `Text` instance for the given array of lines. + */ + static of(text) { + if (text.length == 0) + throw new RangeError("A document must have at least one line"); + if (text.length == 1 && !text[0]) + return Text.empty; + return text.length <= 32 /* Tree.Branch */ ? new TextLeaf(text) : TextNode.from(TextLeaf.split(text, [])); + } + } + // Leaves store an array of line strings. There are always line breaks + // between these strings. Leaves are limited in size and have to be + // contained in TextNode instances for bigger documents. + class TextLeaf extends Text { + constructor(text, length = textLength(text)) { + super(); + this.text = text; + this.length = length; + } + get lines() { return this.text.length; } + get children() { return null; } + lineInner(target, isLine, line, offset) { + for (let i = 0;; i++) { + let string = this.text[i], end = offset + string.length; + if ((isLine ? line : end) >= target) + return new Line(offset, end, line, string); + offset = end + 1; + line++; + } + } + decompose(from, to, target, open) { + let text = from <= 0 && to >= this.length ? this + : new TextLeaf(sliceText(this.text, from, to), Math.min(to, this.length) - Math.max(0, from)); + if (open & 1 /* Open.From */) { + let prev = target.pop(); + let joined = appendText(text.text, prev.text.slice(), 0, text.length); + if (joined.length <= 32 /* Tree.Branch */) { + target.push(new TextLeaf(joined, prev.length + text.length)); + } + else { + let mid = joined.length >> 1; + target.push(new TextLeaf(joined.slice(0, mid)), new TextLeaf(joined.slice(mid))); + } + } + else { + target.push(text); + } + } + replace(from, to, text) { + if (!(text instanceof TextLeaf)) + return super.replace(from, to, text); + let lines = appendText(this.text, appendText(text.text, sliceText(this.text, 0, from)), to); + let newLen = this.length + text.length - (to - from); + if (lines.length <= 32 /* Tree.Branch */) + return new TextLeaf(lines, newLen); + return TextNode.from(TextLeaf.split(lines, []), newLen); + } + sliceString(from, to = this.length, lineSep = "\n") { + let result = ""; + for (let pos = 0, i = 0; pos <= to && i < this.text.length; i++) { + let line = this.text[i], end = pos + line.length; + if (pos > from && i) + result += lineSep; + if (from < end && to > pos) + result += line.slice(Math.max(0, from - pos), to - pos); + pos = end + 1; + } + return result; + } + flatten(target) { + for (let line of this.text) + target.push(line); + } + scanIdentical() { return 0; } + static split(text, target) { + let part = [], len = -1; + for (let line of text) { + part.push(line); + len += line.length + 1; + if (part.length == 32 /* Tree.Branch */) { + target.push(new TextLeaf(part, len)); + part = []; + len = -1; + } + } + if (len > -1) + target.push(new TextLeaf(part, len)); + return target; + } + } + // Nodes provide the tree structure of the `Text` type. They store a + // number of other nodes or leaves, taking care to balance themselves + // on changes. There are implied line breaks _between_ the children of + // a node (but not before the first or after the last child). + class TextNode extends Text { + constructor(children, length) { + super(); + this.children = children; + this.length = length; + this.lines = 0; + for (let child of children) + this.lines += child.lines; + } + lineInner(target, isLine, line, offset) { + for (let i = 0;; i++) { + let child = this.children[i], end = offset + child.length, endLine = line + child.lines - 1; + if ((isLine ? endLine : end) >= target) + return child.lineInner(target, isLine, line, offset); + offset = end + 1; + line = endLine + 1; + } + } + decompose(from, to, target, open) { + for (let i = 0, pos = 0; pos <= to && i < this.children.length; i++) { + let child = this.children[i], end = pos + child.length; + if (from <= end && to >= pos) { + let childOpen = open & ((pos <= from ? 1 /* Open.From */ : 0) | (end >= to ? 2 /* Open.To */ : 0)); + if (pos >= from && end <= to && !childOpen) + target.push(child); + else + child.decompose(from - pos, to - pos, target, childOpen); + } + pos = end + 1; + } + } + replace(from, to, text) { + if (text.lines < this.lines) + for (let i = 0, pos = 0; i < this.children.length; i++) { + let child = this.children[i], end = pos + child.length; + // Fast path: if the change only affects one child and the + // child's size remains in the acceptable range, only update + // that child + if (from >= pos && to <= end) { + let updated = child.replace(from - pos, to - pos, text); + let totalLines = this.lines - child.lines + updated.lines; + if (updated.lines < (totalLines >> (5 /* Tree.BranchShift */ - 1)) && + updated.lines > (totalLines >> (5 /* Tree.BranchShift */ + 1))) { + let copy = this.children.slice(); + copy[i] = updated; + return new TextNode(copy, this.length - (to - from) + text.length); + } + return super.replace(pos, end, updated); + } + pos = end + 1; + } + return super.replace(from, to, text); + } + sliceString(from, to = this.length, lineSep = "\n") { + let result = ""; + for (let i = 0, pos = 0; i < this.children.length && pos <= to; i++) { + let child = this.children[i], end = pos + child.length; + if (pos > from && i) + result += lineSep; + if (from < end && to > pos) + result += child.sliceString(from - pos, to - pos, lineSep); + pos = end + 1; + } + return result; + } + flatten(target) { + for (let child of this.children) + child.flatten(target); + } + scanIdentical(other, dir) { + if (!(other instanceof TextNode)) + return 0; + let length = 0; + let [iA, iB, eA, eB] = dir > 0 ? [0, 0, this.children.length, other.children.length] + : [this.children.length - 1, other.children.length - 1, -1, -1]; + for (;; iA += dir, iB += dir) { + if (iA == eA || iB == eB) + return length; + let chA = this.children[iA], chB = other.children[iB]; + if (chA != chB) + return length + chA.scanIdentical(chB, dir); + length += chA.length + 1; + } + } + static from(children, length = children.reduce((l, ch) => l + ch.length + 1, -1)) { + let lines = 0; + for (let ch of children) + lines += ch.lines; + if (lines < 32 /* Tree.Branch */) { + let flat = []; + for (let ch of children) + ch.flatten(flat); + return new TextLeaf(flat, length); + } + let chunk = Math.max(32 /* Tree.Branch */, lines >> 5 /* Tree.BranchShift */), maxChunk = chunk << 1, minChunk = chunk >> 1; + let chunked = [], currentLines = 0, currentLen = -1, currentChunk = []; + function add(child) { + let last; + if (child.lines > maxChunk && child instanceof TextNode) { + for (let node of child.children) + add(node); + } + else if (child.lines > minChunk && (currentLines > minChunk || !currentLines)) { + flush(); + chunked.push(child); + } + else if (child instanceof TextLeaf && currentLines && + (last = currentChunk[currentChunk.length - 1]) instanceof TextLeaf && + child.lines + last.lines <= 32 /* Tree.Branch */) { + currentLines += child.lines; + currentLen += child.length + 1; + currentChunk[currentChunk.length - 1] = new TextLeaf(last.text.concat(child.text), last.length + 1 + child.length); + } + else { + if (currentLines + child.lines > chunk) + flush(); + currentLines += child.lines; + currentLen += child.length + 1; + currentChunk.push(child); + } + } + function flush() { + if (currentLines == 0) + return; + chunked.push(currentChunk.length == 1 ? currentChunk[0] : TextNode.from(currentChunk, currentLen)); + currentLen = -1; + currentLines = currentChunk.length = 0; + } + for (let child of children) + add(child); + flush(); + return chunked.length == 1 ? chunked[0] : new TextNode(chunked, length); + } + } + Text.empty = /*@__PURE__*/new TextLeaf([""], 0); + function textLength(text) { + let length = -1; + for (let line of text) + length += line.length + 1; + return length; + } + function appendText(text, target, from = 0, to = 1e9) { + for (let pos = 0, i = 0, first = true; i < text.length && pos <= to; i++) { + let line = text[i], end = pos + line.length; + if (end >= from) { + if (end > to) + line = line.slice(0, to - pos); + if (pos < from) + line = line.slice(from - pos); + if (first) { + target[target.length - 1] += line; + first = false; + } + else + target.push(line); + } + pos = end + 1; + } + return target; + } + function sliceText(text, from, to) { + return appendText(text, [""], from, to); + } + class RawTextCursor { + constructor(text, dir = 1) { + this.dir = dir; + this.done = false; + this.lineBreak = false; + this.value = ""; + this.nodes = [text]; + this.offsets = [dir > 0 ? 1 : (text instanceof TextLeaf ? text.text.length : text.children.length) << 1]; + } + nextInner(skip, dir) { + this.done = this.lineBreak = false; + for (;;) { + let last = this.nodes.length - 1; + let top = this.nodes[last], offsetValue = this.offsets[last], offset = offsetValue >> 1; + let size = top instanceof TextLeaf ? top.text.length : top.children.length; + if (offset == (dir > 0 ? size : 0)) { + if (last == 0) { + this.done = true; + this.value = ""; + return this; + } + if (dir > 0) + this.offsets[last - 1]++; + this.nodes.pop(); + this.offsets.pop(); + } + else if ((offsetValue & 1) == (dir > 0 ? 0 : 1)) { + this.offsets[last] += dir; + if (skip == 0) { + this.lineBreak = true; + this.value = "\n"; + return this; + } + skip--; + } + else if (top instanceof TextLeaf) { + // Move to the next string + let next = top.text[offset + (dir < 0 ? -1 : 0)]; + this.offsets[last] += dir; + if (next.length > Math.max(0, skip)) { + this.value = skip == 0 ? next : dir > 0 ? next.slice(skip) : next.slice(0, next.length - skip); + return this; + } + skip -= next.length; + } + else { + let next = top.children[offset + (dir < 0 ? -1 : 0)]; + if (skip > next.length) { + skip -= next.length; + this.offsets[last] += dir; + } + else { + if (dir < 0) + this.offsets[last]--; + this.nodes.push(next); + this.offsets.push(dir > 0 ? 1 : (next instanceof TextLeaf ? next.text.length : next.children.length) << 1); + } + } + } + } + next(skip = 0) { + if (skip < 0) { + this.nextInner(-skip, (-this.dir)); + skip = this.value.length; + } + return this.nextInner(skip, this.dir); + } + } + class PartialTextCursor { + constructor(text, start, end) { + this.value = ""; + this.done = false; + this.cursor = new RawTextCursor(text, start > end ? -1 : 1); + this.pos = start > end ? text.length : 0; + this.from = Math.min(start, end); + this.to = Math.max(start, end); + } + nextInner(skip, dir) { + if (dir < 0 ? this.pos <= this.from : this.pos >= this.to) { + this.value = ""; + this.done = true; + return this; + } + skip += Math.max(0, dir < 0 ? this.pos - this.to : this.from - this.pos); + let limit = dir < 0 ? this.pos - this.from : this.to - this.pos; + if (skip > limit) + skip = limit; + limit -= skip; + let { value } = this.cursor.next(skip); + this.pos += (value.length + skip) * dir; + this.value = value.length <= limit ? value : dir < 0 ? value.slice(value.length - limit) : value.slice(0, limit); + this.done = !this.value; + return this; + } + next(skip = 0) { + if (skip < 0) + skip = Math.max(skip, this.from - this.pos); + else if (skip > 0) + skip = Math.min(skip, this.to - this.pos); + return this.nextInner(skip, this.cursor.dir); + } + get lineBreak() { return this.cursor.lineBreak && this.value != ""; } + } + class LineCursor { + constructor(inner) { + this.inner = inner; + this.afterBreak = true; + this.value = ""; + this.done = false; + } + next(skip = 0) { + let { done, lineBreak, value } = this.inner.next(skip); + if (done) { + this.done = true; + this.value = ""; + } + else if (lineBreak) { + if (this.afterBreak) { + this.value = ""; + } + else { + this.afterBreak = true; + this.next(); + } + } + else { + this.value = value; + this.afterBreak = false; + } + return this; + } + get lineBreak() { return false; } + } + if (typeof Symbol != "undefined") { + Text.prototype[Symbol.iterator] = function () { return this.iter(); }; + RawTextCursor.prototype[Symbol.iterator] = PartialTextCursor.prototype[Symbol.iterator] = + LineCursor.prototype[Symbol.iterator] = function () { return this; }; + } + /** + This type describes a line in the document. It is created + on-demand when lines are [queried](https://codemirror.net/6/docs/ref/#state.Text.lineAt). + */ + class Line { + /** + @internal + */ + constructor( + /** + The position of the start of the line. + */ + from, + /** + The position at the end of the line (_before_ the line break, + or at the end of document for the last line). + */ + to, + /** + This line's line number (1-based). + */ + number, + /** + The line's content. + */ + text) { + this.from = from; + this.to = to; + this.number = number; + this.text = text; + } + /** + The length of the line (not including any line break after it). + */ + get length() { return this.to - this.from; } + } + + // Compressed representation of the Grapheme_Cluster_Break=Extend + // information from + // http://www.unicode.org/Public/13.0.0/ucd/auxiliary/GraphemeBreakProperty.txt. + // Each pair of elements represents a range, as an offet from the + // previous range and a length. Numbers are in base-36, with the empty + // string being a shorthand for 1. + let extend = /*@__PURE__*/"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(s => s ? parseInt(s, 36) : 1); + // Convert offsets into absolute values + for (let i = 1; i < extend.length; i++) + extend[i] += extend[i - 1]; + function isExtendingChar(code) { + for (let i = 1; i < extend.length; i += 2) + if (extend[i] > code) + return extend[i - 1] <= code; + return false; + } + function isRegionalIndicator(code) { + return code >= 0x1F1E6 && code <= 0x1F1FF; + } + const ZWJ = 0x200d; + /** + Returns a next grapheme cluster break _after_ (not equal to) + `pos`, if `forward` is true, or before otherwise. Returns `pos` + itself if no further cluster break is available in the string. + Moves across surrogate pairs, extending characters (when + `includeExtending` is true), characters joined with zero-width + joiners, and flag emoji. + */ + function findClusterBreak(str, pos, forward = true, includeExtending = true) { + return (forward ? nextClusterBreak : prevClusterBreak)(str, pos, includeExtending); + } + function nextClusterBreak(str, pos, includeExtending) { + if (pos == str.length) + return pos; + // If pos is in the middle of a surrogate pair, move to its start + if (pos && surrogateLow(str.charCodeAt(pos)) && surrogateHigh(str.charCodeAt(pos - 1))) + pos--; + let prev = codePointAt(str, pos); + pos += codePointSize(prev); + while (pos < str.length) { + let next = codePointAt(str, pos); + if (prev == ZWJ || next == ZWJ || includeExtending && isExtendingChar(next)) { + pos += codePointSize(next); + prev = next; + } + else if (isRegionalIndicator(next)) { + let countBefore = 0, i = pos - 2; + while (i >= 0 && isRegionalIndicator(codePointAt(str, i))) { + countBefore++; + i -= 2; + } + if (countBefore % 2 == 0) + break; + else + pos += 2; + } + else { + break; + } + } + return pos; + } + function prevClusterBreak(str, pos, includeExtending) { + while (pos > 0) { + let found = nextClusterBreak(str, pos - 2, includeExtending); + if (found < pos) + return found; + pos--; + } + return 0; + } + function surrogateLow(ch) { return ch >= 0xDC00 && ch < 0xE000; } + function surrogateHigh(ch) { return ch >= 0xD800 && ch < 0xDC00; } + /** + Find the code point at the given position in a string (like the + [`codePointAt`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/codePointAt) + string method). + */ + function codePointAt(str, pos) { + let code0 = str.charCodeAt(pos); + if (!surrogateHigh(code0) || pos + 1 == str.length) + return code0; + let code1 = str.charCodeAt(pos + 1); + if (!surrogateLow(code1)) + return code0; + return ((code0 - 0xd800) << 10) + (code1 - 0xdc00) + 0x10000; + } + /** + Given a Unicode codepoint, return the JavaScript string that + respresents it (like + [`String.fromCodePoint`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/fromCodePoint)). + */ + function fromCodePoint(code) { + if (code <= 0xffff) + return String.fromCharCode(code); + code -= 0x10000; + return String.fromCharCode((code >> 10) + 0xd800, (code & 1023) + 0xdc00); + } + /** + The amount of positions a character takes up a JavaScript string. + */ + function codePointSize(code) { return code < 0x10000 ? 1 : 2; } + + const DefaultSplit = /\r\n?|\n/; + /** + Distinguishes different ways in which positions can be mapped. + */ + var MapMode = /*@__PURE__*/(function (MapMode) { + /** + Map a position to a valid new position, even when its context + was deleted. + */ + MapMode[MapMode["Simple"] = 0] = "Simple"; + /** + Return null if deletion happens across the position. + */ + MapMode[MapMode["TrackDel"] = 1] = "TrackDel"; + /** + Return null if the character _before_ the position is deleted. + */ + MapMode[MapMode["TrackBefore"] = 2] = "TrackBefore"; + /** + Return null if the character _after_ the position is deleted. + */ + MapMode[MapMode["TrackAfter"] = 3] = "TrackAfter"; + return MapMode})(MapMode || (MapMode = {})); + /** + A change description is a variant of [change set](https://codemirror.net/6/docs/ref/#state.ChangeSet) + that doesn't store the inserted text. As such, it can't be + applied, but is cheaper to store and manipulate. + */ + class ChangeDesc { + // Sections are encoded as pairs of integers. The first is the + // length in the current document, and the second is -1 for + // unaffected sections, and the length of the replacement content + // otherwise. So an insertion would be (0, n>0), a deletion (n>0, + // 0), and a replacement two positive numbers. + /** + @internal + */ + constructor( + /** + @internal + */ + sections) { + this.sections = sections; + } + /** + The length of the document before the change. + */ + get length() { + let result = 0; + for (let i = 0; i < this.sections.length; i += 2) + result += this.sections[i]; + return result; + } + /** + The length of the document after the change. + */ + get newLength() { + let result = 0; + for (let i = 0; i < this.sections.length; i += 2) { + let ins = this.sections[i + 1]; + result += ins < 0 ? this.sections[i] : ins; + } + return result; + } + /** + False when there are actual changes in this set. + */ + get empty() { return this.sections.length == 0 || this.sections.length == 2 && this.sections[1] < 0; } + /** + Iterate over the unchanged parts left by these changes. `posA` + provides the position of the range in the old document, `posB` + the new position in the changed document. + */ + iterGaps(f) { + for (let i = 0, posA = 0, posB = 0; i < this.sections.length;) { + let len = this.sections[i++], ins = this.sections[i++]; + if (ins < 0) { + f(posA, posB, len); + posB += len; + } + else { + posB += ins; + } + posA += len; + } + } + /** + Iterate over the ranges changed by these changes. (See + [`ChangeSet.iterChanges`](https://codemirror.net/6/docs/ref/#state.ChangeSet.iterChanges) for a + variant that also provides you with the inserted text.) + `fromA`/`toA` provides the extent of the change in the starting + document, `fromB`/`toB` the extent of the replacement in the + changed document. + + When `individual` is true, adjacent changes (which are kept + separate for [position mapping](https://codemirror.net/6/docs/ref/#state.ChangeDesc.mapPos)) are + reported separately. + */ + iterChangedRanges(f, individual = false) { + iterChanges(this, f, individual); + } + /** + Get a description of the inverted form of these changes. + */ + get invertedDesc() { + let sections = []; + for (let i = 0; i < this.sections.length;) { + let len = this.sections[i++], ins = this.sections[i++]; + if (ins < 0) + sections.push(len, ins); + else + sections.push(ins, len); + } + return new ChangeDesc(sections); + } + /** + Compute the combined effect of applying another set of changes + after this one. The length of the document after this set should + match the length before `other`. + */ + composeDesc(other) { return this.empty ? other : other.empty ? this : composeSets(this, other); } + /** + Map this description, which should start with the same document + as `other`, over another set of changes, so that it can be + applied after it. When `before` is true, map as if the changes + in `other` happened before the ones in `this`. + */ + mapDesc(other, before = false) { return other.empty ? this : mapSet(this, other, before); } + mapPos(pos, assoc = -1, mode = MapMode.Simple) { + let posA = 0, posB = 0; + for (let i = 0; i < this.sections.length;) { + let len = this.sections[i++], ins = this.sections[i++], endA = posA + len; + if (ins < 0) { + if (endA > pos) + return posB + (pos - posA); + posB += len; + } + else { + if (mode != MapMode.Simple && endA >= pos && + (mode == MapMode.TrackDel && posA < pos && endA > pos || + mode == MapMode.TrackBefore && posA < pos || + mode == MapMode.TrackAfter && endA > pos)) + return null; + if (endA > pos || endA == pos && assoc < 0 && !len) + return pos == posA || assoc < 0 ? posB : posB + ins; + posB += ins; + } + posA = endA; + } + if (pos > posA) + throw new RangeError(`Position ${pos} is out of range for changeset of length ${posA}`); + return posB; + } + /** + Check whether these changes touch a given range. When one of the + changes entirely covers the range, the string `"cover"` is + returned. + */ + touchesRange(from, to = from) { + for (let i = 0, pos = 0; i < this.sections.length && pos <= to;) { + let len = this.sections[i++], ins = this.sections[i++], end = pos + len; + if (ins >= 0 && pos <= to && end >= from) + return pos < from && end > to ? "cover" : true; + pos = end; + } + return false; + } + /** + @internal + */ + toString() { + let result = ""; + for (let i = 0; i < this.sections.length;) { + let len = this.sections[i++], ins = this.sections[i++]; + result += (result ? " " : "") + len + (ins >= 0 ? ":" + ins : ""); + } + return result; + } + /** + Serialize this change desc to a JSON-representable value. + */ + toJSON() { return this.sections; } + /** + Create a change desc from its JSON representation (as produced + by [`toJSON`](https://codemirror.net/6/docs/ref/#state.ChangeDesc.toJSON). + */ + static fromJSON(json) { + if (!Array.isArray(json) || json.length % 2 || json.some(a => typeof a != "number")) + throw new RangeError("Invalid JSON representation of ChangeDesc"); + return new ChangeDesc(json); + } + /** + @internal + */ + static create(sections) { return new ChangeDesc(sections); } + } + /** + A change set represents a group of modifications to a document. It + stores the document length, and can only be applied to documents + with exactly that length. + */ + class ChangeSet extends ChangeDesc { + constructor(sections, + /** + @internal + */ + inserted) { + super(sections); + this.inserted = inserted; + } + /** + Apply the changes to a document, returning the modified + document. + */ + apply(doc) { + if (this.length != doc.length) + throw new RangeError("Applying change set to a document with the wrong length"); + iterChanges(this, (fromA, toA, fromB, _toB, text) => doc = doc.replace(fromB, fromB + (toA - fromA), text), false); + return doc; + } + mapDesc(other, before = false) { return mapSet(this, other, before, true); } + /** + Given the document as it existed _before_ the changes, return a + change set that represents the inverse of this set, which could + be used to go from the document created by the changes back to + the document as it existed before the changes. + */ + invert(doc) { + let sections = this.sections.slice(), inserted = []; + for (let i = 0, pos = 0; i < sections.length; i += 2) { + let len = sections[i], ins = sections[i + 1]; + if (ins >= 0) { + sections[i] = ins; + sections[i + 1] = len; + let index = i >> 1; + while (inserted.length < index) + inserted.push(Text.empty); + inserted.push(len ? doc.slice(pos, pos + len) : Text.empty); + } + pos += len; + } + return new ChangeSet(sections, inserted); + } + /** + Combine two subsequent change sets into a single set. `other` + must start in the document produced by `this`. If `this` goes + `docA` → `docB` and `other` represents `docB` → `docC`, the + returned value will represent the change `docA` → `docC`. + */ + compose(other) { return this.empty ? other : other.empty ? this : composeSets(this, other, true); } + /** + Given another change set starting in the same document, maps this + change set over the other, producing a new change set that can be + applied to the document produced by applying `other`. When + `before` is `true`, order changes as if `this` comes before + `other`, otherwise (the default) treat `other` as coming first. + + Given two changes `A` and `B`, `A.compose(B.map(A))` and + `B.compose(A.map(B, true))` will produce the same document. This + provides a basic form of [operational + transformation](https://en.wikipedia.org/wiki/Operational_transformation), + and can be used for collaborative editing. + */ + map(other, before = false) { return other.empty ? this : mapSet(this, other, before, true); } + /** + Iterate over the changed ranges in the document, calling `f` for + each, with the range in the original document (`fromA`-`toA`) + and the range that replaces it in the new document + (`fromB`-`toB`). + + When `individual` is true, adjacent changes are reported + separately. + */ + iterChanges(f, individual = false) { + iterChanges(this, f, individual); + } + /** + Get a [change description](https://codemirror.net/6/docs/ref/#state.ChangeDesc) for this change + set. + */ + get desc() { return ChangeDesc.create(this.sections); } + /** + @internal + */ + filter(ranges) { + let resultSections = [], resultInserted = [], filteredSections = []; + let iter = new SectionIter(this); + done: for (let i = 0, pos = 0;;) { + let next = i == ranges.length ? 1e9 : ranges[i++]; + while (pos < next || pos == next && iter.len == 0) { + if (iter.done) + break done; + let len = Math.min(iter.len, next - pos); + addSection(filteredSections, len, -1); + let ins = iter.ins == -1 ? -1 : iter.off == 0 ? iter.ins : 0; + addSection(resultSections, len, ins); + if (ins > 0) + addInsert(resultInserted, resultSections, iter.text); + iter.forward(len); + pos += len; + } + let end = ranges[i++]; + while (pos < end) { + if (iter.done) + break done; + let len = Math.min(iter.len, end - pos); + addSection(resultSections, len, -1); + addSection(filteredSections, len, iter.ins == -1 ? -1 : iter.off == 0 ? iter.ins : 0); + iter.forward(len); + pos += len; + } + } + return { changes: new ChangeSet(resultSections, resultInserted), + filtered: ChangeDesc.create(filteredSections) }; + } + /** + Serialize this change set to a JSON-representable value. + */ + toJSON() { + let parts = []; + for (let i = 0; i < this.sections.length; i += 2) { + let len = this.sections[i], ins = this.sections[i + 1]; + if (ins < 0) + parts.push(len); + else if (ins == 0) + parts.push([len]); + else + parts.push([len].concat(this.inserted[i >> 1].toJSON())); + } + return parts; + } + /** + Create a change set for the given changes, for a document of the + given length, using `lineSep` as line separator. + */ + static of(changes, length, lineSep) { + let sections = [], inserted = [], pos = 0; + let total = null; + function flush(force = false) { + if (!force && !sections.length) + return; + if (pos < length) + addSection(sections, length - pos, -1); + let set = new ChangeSet(sections, inserted); + total = total ? total.compose(set.map(total)) : set; + sections = []; + inserted = []; + pos = 0; + } + function process(spec) { + if (Array.isArray(spec)) { + for (let sub of spec) + process(sub); + } + else if (spec instanceof ChangeSet) { + if (spec.length != length) + throw new RangeError(`Mismatched change set length (got ${spec.length}, expected ${length})`); + flush(); + total = total ? total.compose(spec.map(total)) : spec; + } + else { + let { from, to = from, insert } = spec; + if (from > to || from < 0 || to > length) + throw new RangeError(`Invalid change range ${from} to ${to} (in doc of length ${length})`); + let insText = !insert ? Text.empty : typeof insert == "string" ? Text.of(insert.split(lineSep || DefaultSplit)) : insert; + let insLen = insText.length; + if (from == to && insLen == 0) + return; + if (from < pos) + flush(); + if (from > pos) + addSection(sections, from - pos, -1); + addSection(sections, to - from, insLen); + addInsert(inserted, sections, insText); + pos = to; + } + } + process(changes); + flush(!total); + return total; + } + /** + Create an empty changeset of the given length. + */ + static empty(length) { + return new ChangeSet(length ? [length, -1] : [], []); + } + /** + Create a changeset from its JSON representation (as produced by + [`toJSON`](https://codemirror.net/6/docs/ref/#state.ChangeSet.toJSON). + */ + static fromJSON(json) { + if (!Array.isArray(json)) + throw new RangeError("Invalid JSON representation of ChangeSet"); + let sections = [], inserted = []; + for (let i = 0; i < json.length; i++) { + let part = json[i]; + if (typeof part == "number") { + sections.push(part, -1); + } + else if (!Array.isArray(part) || typeof part[0] != "number" || part.some((e, i) => i && typeof e != "string")) { + throw new RangeError("Invalid JSON representation of ChangeSet"); + } + else if (part.length == 1) { + sections.push(part[0], 0); + } + else { + while (inserted.length < i) + inserted.push(Text.empty); + inserted[i] = Text.of(part.slice(1)); + sections.push(part[0], inserted[i].length); + } + } + return new ChangeSet(sections, inserted); + } + /** + @internal + */ + static createSet(sections, inserted) { + return new ChangeSet(sections, inserted); + } + } + function addSection(sections, len, ins, forceJoin = false) { + if (len == 0 && ins <= 0) + return; + let last = sections.length - 2; + if (last >= 0 && ins <= 0 && ins == sections[last + 1]) + sections[last] += len; + else if (len == 0 && sections[last] == 0) + sections[last + 1] += ins; + else if (forceJoin) { + sections[last] += len; + sections[last + 1] += ins; + } + else + sections.push(len, ins); + } + function addInsert(values, sections, value) { + if (value.length == 0) + return; + let index = (sections.length - 2) >> 1; + if (index < values.length) { + values[values.length - 1] = values[values.length - 1].append(value); + } + else { + while (values.length < index) + values.push(Text.empty); + values.push(value); + } + } + function iterChanges(desc, f, individual) { + let inserted = desc.inserted; + for (let posA = 0, posB = 0, i = 0; i < desc.sections.length;) { + let len = desc.sections[i++], ins = desc.sections[i++]; + if (ins < 0) { + posA += len; + posB += len; + } + else { + let endA = posA, endB = posB, text = Text.empty; + for (;;) { + endA += len; + endB += ins; + if (ins && inserted) + text = text.append(inserted[(i - 2) >> 1]); + if (individual || i == desc.sections.length || desc.sections[i + 1] < 0) + break; + len = desc.sections[i++]; + ins = desc.sections[i++]; + } + f(posA, endA, posB, endB, text); + posA = endA; + posB = endB; + } + } + } + function mapSet(setA, setB, before, mkSet = false) { + // Produce a copy of setA that applies to the document after setB + // has been applied (assuming both start at the same document). + let sections = [], insert = mkSet ? [] : null; + let a = new SectionIter(setA), b = new SectionIter(setB); + // Iterate over both sets in parallel. inserted tracks, for changes + // in A that have to be processed piece-by-piece, whether their + // content has been inserted already, and refers to the section + // index. + for (let inserted = -1;;) { + if (a.ins == -1 && b.ins == -1) { + // Move across ranges skipped by both sets. + let len = Math.min(a.len, b.len); + addSection(sections, len, -1); + a.forward(len); + b.forward(len); + } + else if (b.ins >= 0 && (a.ins < 0 || inserted == a.i || a.off == 0 && (b.len < a.len || b.len == a.len && !before))) { + // If there's a change in B that comes before the next change in + // A (ordered by start pos, then len, then before flag), skip + // that (and process any changes in A it covers). + let len = b.len; + addSection(sections, b.ins, -1); + while (len) { + let piece = Math.min(a.len, len); + if (a.ins >= 0 && inserted < a.i && a.len <= piece) { + addSection(sections, 0, a.ins); + if (insert) + addInsert(insert, sections, a.text); + inserted = a.i; + } + a.forward(piece); + len -= piece; + } + b.next(); + } + else if (a.ins >= 0) { + // Process the part of a change in A up to the start of the next + // non-deletion change in B (if overlapping). + let len = 0, left = a.len; + while (left) { + if (b.ins == -1) { + let piece = Math.min(left, b.len); + len += piece; + left -= piece; + b.forward(piece); + } + else if (b.ins == 0 && b.len < left) { + left -= b.len; + b.next(); + } + else { + break; + } + } + addSection(sections, len, inserted < a.i ? a.ins : 0); + if (insert && inserted < a.i) + addInsert(insert, sections, a.text); + inserted = a.i; + a.forward(a.len - left); + } + else if (a.done && b.done) { + return insert ? ChangeSet.createSet(sections, insert) : ChangeDesc.create(sections); + } + else { + throw new Error("Mismatched change set lengths"); + } + } + } + function composeSets(setA, setB, mkSet = false) { + let sections = []; + let insert = mkSet ? [] : null; + let a = new SectionIter(setA), b = new SectionIter(setB); + for (let open = false;;) { + if (a.done && b.done) { + return insert ? ChangeSet.createSet(sections, insert) : ChangeDesc.create(sections); + } + else if (a.ins == 0) { // Deletion in A + addSection(sections, a.len, 0, open); + a.next(); + } + else if (b.len == 0 && !b.done) { // Insertion in B + addSection(sections, 0, b.ins, open); + if (insert) + addInsert(insert, sections, b.text); + b.next(); + } + else if (a.done || b.done) { + throw new Error("Mismatched change set lengths"); + } + else { + let len = Math.min(a.len2, b.len), sectionLen = sections.length; + if (a.ins == -1) { + let insB = b.ins == -1 ? -1 : b.off ? 0 : b.ins; + addSection(sections, len, insB, open); + if (insert && insB) + addInsert(insert, sections, b.text); + } + else if (b.ins == -1) { + addSection(sections, a.off ? 0 : a.len, len, open); + if (insert) + addInsert(insert, sections, a.textBit(len)); + } + else { + addSection(sections, a.off ? 0 : a.len, b.off ? 0 : b.ins, open); + if (insert && !b.off) + addInsert(insert, sections, b.text); + } + open = (a.ins > len || b.ins >= 0 && b.len > len) && (open || sections.length > sectionLen); + a.forward2(len); + b.forward(len); + } + } + } + class SectionIter { + constructor(set) { + this.set = set; + this.i = 0; + this.next(); + } + next() { + let { sections } = this.set; + if (this.i < sections.length) { + this.len = sections[this.i++]; + this.ins = sections[this.i++]; + } + else { + this.len = 0; + this.ins = -2; + } + this.off = 0; + } + get done() { return this.ins == -2; } + get len2() { return this.ins < 0 ? this.len : this.ins; } + get text() { + let { inserted } = this.set, index = (this.i - 2) >> 1; + return index >= inserted.length ? Text.empty : inserted[index]; + } + textBit(len) { + let { inserted } = this.set, index = (this.i - 2) >> 1; + return index >= inserted.length && !len ? Text.empty + : inserted[index].slice(this.off, len == null ? undefined : this.off + len); + } + forward(len) { + if (len == this.len) + this.next(); + else { + this.len -= len; + this.off += len; + } + } + forward2(len) { + if (this.ins == -1) + this.forward(len); + else if (len == this.ins) + this.next(); + else { + this.ins -= len; + this.off += len; + } + } + } + + /** + A single selection range. When + [`allowMultipleSelections`](https://codemirror.net/6/docs/ref/#state.EditorState^allowMultipleSelections) + is enabled, a [selection](https://codemirror.net/6/docs/ref/#state.EditorSelection) may hold + multiple ranges. By default, selections hold exactly one range. + */ + class SelectionRange { + constructor( + /** + The lower boundary of the range. + */ + from, + /** + The upper boundary of the range. + */ + to, flags) { + this.from = from; + this.to = to; + this.flags = flags; + } + /** + The anchor of the range—the side that doesn't move when you + extend it. + */ + get anchor() { return this.flags & 16 /* RangeFlag.Inverted */ ? this.to : this.from; } + /** + The head of the range, which is moved when the range is + [extended](https://codemirror.net/6/docs/ref/#state.SelectionRange.extend). + */ + get head() { return this.flags & 16 /* RangeFlag.Inverted */ ? this.from : this.to; } + /** + True when `anchor` and `head` are at the same position. + */ + get empty() { return this.from == this.to; } + /** + If this is a cursor that is explicitly associated with the + character on one of its sides, this returns the side. -1 means + the character before its position, 1 the character after, and 0 + means no association. + */ + get assoc() { return this.flags & 4 /* RangeFlag.AssocBefore */ ? -1 : this.flags & 8 /* RangeFlag.AssocAfter */ ? 1 : 0; } + /** + The bidirectional text level associated with this cursor, if + any. + */ + get bidiLevel() { + let level = this.flags & 3 /* RangeFlag.BidiLevelMask */; + return level == 3 ? null : level; + } + /** + The goal column (stored vertical offset) associated with a + cursor. This is used to preserve the vertical position when + [moving](https://codemirror.net/6/docs/ref/#view.EditorView.moveVertically) across + lines of different length. + */ + get goalColumn() { + let value = this.flags >> 5 /* RangeFlag.GoalColumnOffset */; + return value == 33554431 /* RangeFlag.NoGoalColumn */ ? undefined : value; + } + /** + Map this range through a change, producing a valid range in the + updated document. + */ + map(change, assoc = -1) { + let from, to; + if (this.empty) { + from = to = change.mapPos(this.from, assoc); + } + else { + from = change.mapPos(this.from, 1); + to = change.mapPos(this.to, -1); + } + return from == this.from && to == this.to ? this : new SelectionRange(from, to, this.flags); + } + /** + Extend this range to cover at least `from` to `to`. + */ + extend(from, to = from) { + if (from <= this.anchor && to >= this.anchor) + return EditorSelection.range(from, to); + let head = Math.abs(from - this.anchor) > Math.abs(to - this.anchor) ? from : to; + return EditorSelection.range(this.anchor, head); + } + /** + Compare this range to another range. + */ + eq(other) { + return this.anchor == other.anchor && this.head == other.head; + } + /** + Return a JSON-serializable object representing the range. + */ + toJSON() { return { anchor: this.anchor, head: this.head }; } + /** + Convert a JSON representation of a range to a `SelectionRange` + instance. + */ + static fromJSON(json) { + if (!json || typeof json.anchor != "number" || typeof json.head != "number") + throw new RangeError("Invalid JSON representation for SelectionRange"); + return EditorSelection.range(json.anchor, json.head); + } + /** + @internal + */ + static create(from, to, flags) { + return new SelectionRange(from, to, flags); + } + } + /** + An editor selection holds one or more selection ranges. + */ + class EditorSelection { + constructor( + /** + The ranges in the selection, sorted by position. Ranges cannot + overlap (but they may touch, if they aren't empty). + */ + ranges, + /** + The index of the _main_ range in the selection (which is + usually the range that was added last). + */ + mainIndex) { + this.ranges = ranges; + this.mainIndex = mainIndex; + } + /** + Map a selection through a change. Used to adjust the selection + position for changes. + */ + map(change, assoc = -1) { + if (change.empty) + return this; + return EditorSelection.create(this.ranges.map(r => r.map(change, assoc)), this.mainIndex); + } + /** + Compare this selection to another selection. + */ + eq(other) { + if (this.ranges.length != other.ranges.length || + this.mainIndex != other.mainIndex) + return false; + for (let i = 0; i < this.ranges.length; i++) + if (!this.ranges[i].eq(other.ranges[i])) + return false; + return true; + } + /** + Get the primary selection range. Usually, you should make sure + your code applies to _all_ ranges, by using methods like + [`changeByRange`](https://codemirror.net/6/docs/ref/#state.EditorState.changeByRange). + */ + get main() { return this.ranges[this.mainIndex]; } + /** + Make sure the selection only has one range. Returns a selection + holding only the main range from this selection. + */ + asSingle() { + return this.ranges.length == 1 ? this : new EditorSelection([this.main], 0); + } + /** + Extend this selection with an extra range. + */ + addRange(range, main = true) { + return EditorSelection.create([range].concat(this.ranges), main ? 0 : this.mainIndex + 1); + } + /** + Replace a given range with another range, and then normalize the + selection to merge and sort ranges if necessary. + */ + replaceRange(range, which = this.mainIndex) { + let ranges = this.ranges.slice(); + ranges[which] = range; + return EditorSelection.create(ranges, this.mainIndex); + } + /** + Convert this selection to an object that can be serialized to + JSON. + */ + toJSON() { + return { ranges: this.ranges.map(r => r.toJSON()), main: this.mainIndex }; + } + /** + Create a selection from a JSON representation. + */ + static fromJSON(json) { + if (!json || !Array.isArray(json.ranges) || typeof json.main != "number" || json.main >= json.ranges.length) + throw new RangeError("Invalid JSON representation for EditorSelection"); + return new EditorSelection(json.ranges.map((r) => SelectionRange.fromJSON(r)), json.main); + } + /** + Create a selection holding a single range. + */ + static single(anchor, head = anchor) { + return new EditorSelection([EditorSelection.range(anchor, head)], 0); + } + /** + Sort and merge the given set of ranges, creating a valid + selection. + */ + static create(ranges, mainIndex = 0) { + if (ranges.length == 0) + throw new RangeError("A selection needs at least one range"); + for (let pos = 0, i = 0; i < ranges.length; i++) { + let range = ranges[i]; + if (range.empty ? range.from <= pos : range.from < pos) + return EditorSelection.normalized(ranges.slice(), mainIndex); + pos = range.to; + } + return new EditorSelection(ranges, mainIndex); + } + /** + Create a cursor selection range at the given position. You can + safely ignore the optional arguments in most situations. + */ + static cursor(pos, assoc = 0, bidiLevel, goalColumn) { + return SelectionRange.create(pos, pos, (assoc == 0 ? 0 : assoc < 0 ? 4 /* RangeFlag.AssocBefore */ : 8 /* RangeFlag.AssocAfter */) | + (bidiLevel == null ? 3 : Math.min(2, bidiLevel)) | + ((goalColumn !== null && goalColumn !== void 0 ? goalColumn : 33554431 /* RangeFlag.NoGoalColumn */) << 5 /* RangeFlag.GoalColumnOffset */)); + } + /** + Create a selection range. + */ + static range(anchor, head, goalColumn) { + let goal = (goalColumn !== null && goalColumn !== void 0 ? goalColumn : 33554431 /* RangeFlag.NoGoalColumn */) << 5 /* RangeFlag.GoalColumnOffset */; + return head < anchor ? SelectionRange.create(head, anchor, 16 /* RangeFlag.Inverted */ | goal | 8 /* RangeFlag.AssocAfter */) + : SelectionRange.create(anchor, head, goal | (head > anchor ? 4 /* RangeFlag.AssocBefore */ : 0)); + } + /** + @internal + */ + static normalized(ranges, mainIndex = 0) { + let main = ranges[mainIndex]; + ranges.sort((a, b) => a.from - b.from); + mainIndex = ranges.indexOf(main); + for (let i = 1; i < ranges.length; i++) { + let range = ranges[i], prev = ranges[i - 1]; + if (range.empty ? range.from <= prev.to : range.from < prev.to) { + let from = prev.from, to = Math.max(range.to, prev.to); + if (i <= mainIndex) + mainIndex--; + ranges.splice(--i, 2, range.anchor > range.head ? EditorSelection.range(to, from) : EditorSelection.range(from, to)); + } + } + return new EditorSelection(ranges, mainIndex); + } + } + function checkSelection(selection, docLength) { + for (let range of selection.ranges) + if (range.to > docLength) + throw new RangeError("Selection points outside of document"); + } + + let nextID = 0; + /** + A facet is a labeled value that is associated with an editor + state. It takes inputs from any number of extensions, and combines + those into a single output value. + + Examples of uses of facets are the [tab + size](https://codemirror.net/6/docs/ref/#state.EditorState^tabSize), [editor + attributes](https://codemirror.net/6/docs/ref/#view.EditorView^editorAttributes), and [update + listeners](https://codemirror.net/6/docs/ref/#view.EditorView^updateListener). + */ + class Facet { + constructor( + /** + @internal + */ + combine, + /** + @internal + */ + compareInput, + /** + @internal + */ + compare, isStatic, enables) { + this.combine = combine; + this.compareInput = compareInput; + this.compare = compare; + this.isStatic = isStatic; + /** + @internal + */ + this.id = nextID++; + this.default = combine([]); + this.extensions = typeof enables == "function" ? enables(this) : enables; + } + /** + Define a new facet. + */ + static define(config = {}) { + return new Facet(config.combine || ((a) => a), config.compareInput || ((a, b) => a === b), config.compare || (!config.combine ? sameArray$1 : (a, b) => a === b), !!config.static, config.enables); + } + /** + Returns an extension that adds the given value to this facet. + */ + of(value) { + return new FacetProvider([], this, 0 /* Provider.Static */, value); + } + /** + Create an extension that computes a value for the facet from a + state. You must take care to declare the parts of the state that + this value depends on, since your function is only called again + for a new state when one of those parts changed. + + In cases where your value depends only on a single field, you'll + want to use the [`from`](https://codemirror.net/6/docs/ref/#state.Facet.from) method instead. + */ + compute(deps, get) { + if (this.isStatic) + throw new Error("Can't compute a static facet"); + return new FacetProvider(deps, this, 1 /* Provider.Single */, get); + } + /** + Create an extension that computes zero or more values for this + facet from a state. + */ + computeN(deps, get) { + if (this.isStatic) + throw new Error("Can't compute a static facet"); + return new FacetProvider(deps, this, 2 /* Provider.Multi */, get); + } + from(field, get) { + if (!get) + get = x => x; + return this.compute([field], state => get(state.field(field))); + } + } + function sameArray$1(a, b) { + return a == b || a.length == b.length && a.every((e, i) => e === b[i]); + } + class FacetProvider { + constructor(dependencies, facet, type, value) { + this.dependencies = dependencies; + this.facet = facet; + this.type = type; + this.value = value; + this.id = nextID++; + } + dynamicSlot(addresses) { + var _a; + let getter = this.value; + let compare = this.facet.compareInput; + let id = this.id, idx = addresses[id] >> 1, multi = this.type == 2 /* Provider.Multi */; + let depDoc = false, depSel = false, depAddrs = []; + for (let dep of this.dependencies) { + if (dep == "doc") + depDoc = true; + else if (dep == "selection") + depSel = true; + else if ((((_a = addresses[dep.id]) !== null && _a !== void 0 ? _a : 1) & 1) == 0) + depAddrs.push(addresses[dep.id]); + } + return { + create(state) { + state.values[idx] = getter(state); + return 1 /* SlotStatus.Changed */; + }, + update(state, tr) { + if ((depDoc && tr.docChanged) || (depSel && (tr.docChanged || tr.selection)) || ensureAll(state, depAddrs)) { + let newVal = getter(state); + if (multi ? !compareArray(newVal, state.values[idx], compare) : !compare(newVal, state.values[idx])) { + state.values[idx] = newVal; + return 1 /* SlotStatus.Changed */; + } + } + return 0; + }, + reconfigure: (state, oldState) => { + let newVal = getter(state); + let oldAddr = oldState.config.address[id]; + if (oldAddr != null) { + let oldVal = getAddr(oldState, oldAddr); + if (this.dependencies.every(dep => { + return dep instanceof Facet ? oldState.facet(dep) === state.facet(dep) : + dep instanceof StateField ? oldState.field(dep, false) == state.field(dep, false) : true; + }) || (multi ? compareArray(newVal, oldVal, compare) : compare(newVal, oldVal))) { + state.values[idx] = oldVal; + return 0; + } + } + state.values[idx] = newVal; + return 1 /* SlotStatus.Changed */; + } + }; + } + } + function compareArray(a, b, compare) { + if (a.length != b.length) + return false; + for (let i = 0; i < a.length; i++) + if (!compare(a[i], b[i])) + return false; + return true; + } + function ensureAll(state, addrs) { + let changed = false; + for (let addr of addrs) + if (ensureAddr(state, addr) & 1 /* SlotStatus.Changed */) + changed = true; + return changed; + } + function dynamicFacetSlot(addresses, facet, providers) { + let providerAddrs = providers.map(p => addresses[p.id]); + let providerTypes = providers.map(p => p.type); + let dynamic = providerAddrs.filter(p => !(p & 1)); + let idx = addresses[facet.id] >> 1; + function get(state) { + let values = []; + for (let i = 0; i < providerAddrs.length; i++) { + let value = getAddr(state, providerAddrs[i]); + if (providerTypes[i] == 2 /* Provider.Multi */) + for (let val of value) + values.push(val); + else + values.push(value); + } + return facet.combine(values); + } + return { + create(state) { + for (let addr of providerAddrs) + ensureAddr(state, addr); + state.values[idx] = get(state); + return 1 /* SlotStatus.Changed */; + }, + update(state, tr) { + if (!ensureAll(state, dynamic)) + return 0; + let value = get(state); + if (facet.compare(value, state.values[idx])) + return 0; + state.values[idx] = value; + return 1 /* SlotStatus.Changed */; + }, + reconfigure(state, oldState) { + let depChanged = ensureAll(state, providerAddrs); + let oldProviders = oldState.config.facets[facet.id], oldValue = oldState.facet(facet); + if (oldProviders && !depChanged && sameArray$1(providers, oldProviders)) { + state.values[idx] = oldValue; + return 0; + } + let value = get(state); + if (facet.compare(value, oldValue)) { + state.values[idx] = oldValue; + return 0; + } + state.values[idx] = value; + return 1 /* SlotStatus.Changed */; + } + }; + } + const initField = /*@__PURE__*/Facet.define({ static: true }); + /** + Fields can store additional information in an editor state, and + keep it in sync with the rest of the state. + */ + class StateField { + constructor( + /** + @internal + */ + id, createF, updateF, compareF, + /** + @internal + */ + spec) { + this.id = id; + this.createF = createF; + this.updateF = updateF; + this.compareF = compareF; + this.spec = spec; + /** + @internal + */ + this.provides = undefined; + } + /** + Define a state field. + */ + static define(config) { + let field = new StateField(nextID++, config.create, config.update, config.compare || ((a, b) => a === b), config); + if (config.provide) + field.provides = config.provide(field); + return field; + } + create(state) { + let init = state.facet(initField).find(i => i.field == this); + return ((init === null || init === void 0 ? void 0 : init.create) || this.createF)(state); + } + /** + @internal + */ + slot(addresses) { + let idx = addresses[this.id] >> 1; + return { + create: (state) => { + state.values[idx] = this.create(state); + return 1 /* SlotStatus.Changed */; + }, + update: (state, tr) => { + let oldVal = state.values[idx]; + let value = this.updateF(oldVal, tr); + if (this.compareF(oldVal, value)) + return 0; + state.values[idx] = value; + return 1 /* SlotStatus.Changed */; + }, + reconfigure: (state, oldState) => { + if (oldState.config.address[this.id] != null) { + state.values[idx] = oldState.field(this); + return 0; + } + state.values[idx] = this.create(state); + return 1 /* SlotStatus.Changed */; + } + }; + } + /** + Returns an extension that enables this field and overrides the + way it is initialized. Can be useful when you need to provide a + non-default starting value for the field. + */ + init(create) { + return [this, initField.of({ field: this, create })]; + } + /** + State field instances can be used as + [`Extension`](https://codemirror.net/6/docs/ref/#state.Extension) values to enable the field in a + given state. + */ + get extension() { return this; } + } + const Prec_ = { lowest: 4, low: 3, default: 2, high: 1, highest: 0 }; + function prec(value) { + return (ext) => new PrecExtension(ext, value); + } + /** + By default extensions are registered in the order they are found + in the flattened form of nested array that was provided. + Individual extension values can be assigned a precedence to + override this. Extensions that do not have a precedence set get + the precedence of the nearest parent with a precedence, or + [`default`](https://codemirror.net/6/docs/ref/#state.Prec.default) if there is no such parent. The + final ordering of extensions is determined by first sorting by + precedence and then by order within each precedence. + */ + const Prec = { + /** + The highest precedence level, for extensions that should end up + near the start of the precedence ordering. + */ + highest: /*@__PURE__*/prec(Prec_.highest), + /** + A higher-than-default precedence, for extensions that should + come before those with default precedence. + */ + high: /*@__PURE__*/prec(Prec_.high), + /** + The default precedence, which is also used for extensions + without an explicit precedence. + */ + default: /*@__PURE__*/prec(Prec_.default), + /** + A lower-than-default precedence. + */ + low: /*@__PURE__*/prec(Prec_.low), + /** + The lowest precedence level. Meant for things that should end up + near the end of the extension order. + */ + lowest: /*@__PURE__*/prec(Prec_.lowest) + }; + class PrecExtension { + constructor(inner, prec) { + this.inner = inner; + this.prec = prec; + } + } + /** + Extension compartments can be used to make a configuration + dynamic. By [wrapping](https://codemirror.net/6/docs/ref/#state.Compartment.of) part of your + configuration in a compartment, you can later + [replace](https://codemirror.net/6/docs/ref/#state.Compartment.reconfigure) that part through a + transaction. + */ + class Compartment { + /** + Create an instance of this compartment to add to your [state + configuration](https://codemirror.net/6/docs/ref/#state.EditorStateConfig.extensions). + */ + of(ext) { return new CompartmentInstance(this, ext); } + /** + Create an [effect](https://codemirror.net/6/docs/ref/#state.TransactionSpec.effects) that + reconfigures this compartment. + */ + reconfigure(content) { + return Compartment.reconfigure.of({ compartment: this, extension: content }); + } + /** + Get the current content of the compartment in the state, or + `undefined` if it isn't present. + */ + get(state) { + return state.config.compartments.get(this); + } + } + class CompartmentInstance { + constructor(compartment, inner) { + this.compartment = compartment; + this.inner = inner; + } + } + class Configuration { + constructor(base, compartments, dynamicSlots, address, staticValues, facets) { + this.base = base; + this.compartments = compartments; + this.dynamicSlots = dynamicSlots; + this.address = address; + this.staticValues = staticValues; + this.facets = facets; + this.statusTemplate = []; + while (this.statusTemplate.length < dynamicSlots.length) + this.statusTemplate.push(0 /* SlotStatus.Unresolved */); + } + staticFacet(facet) { + let addr = this.address[facet.id]; + return addr == null ? facet.default : this.staticValues[addr >> 1]; + } + static resolve(base, compartments, oldState) { + let fields = []; + let facets = Object.create(null); + let newCompartments = new Map(); + for (let ext of flatten(base, compartments, newCompartments)) { + if (ext instanceof StateField) + fields.push(ext); + else + (facets[ext.facet.id] || (facets[ext.facet.id] = [])).push(ext); + } + let address = Object.create(null); + let staticValues = []; + let dynamicSlots = []; + for (let field of fields) { + address[field.id] = dynamicSlots.length << 1; + dynamicSlots.push(a => field.slot(a)); + } + let oldFacets = oldState === null || oldState === void 0 ? void 0 : oldState.config.facets; + for (let id in facets) { + let providers = facets[id], facet = providers[0].facet; + let oldProviders = oldFacets && oldFacets[id] || []; + if (providers.every(p => p.type == 0 /* Provider.Static */)) { + address[facet.id] = (staticValues.length << 1) | 1; + if (sameArray$1(oldProviders, providers)) { + staticValues.push(oldState.facet(facet)); + } + else { + let value = facet.combine(providers.map(p => p.value)); + staticValues.push(oldState && facet.compare(value, oldState.facet(facet)) ? oldState.facet(facet) : value); + } + } + else { + for (let p of providers) { + if (p.type == 0 /* Provider.Static */) { + address[p.id] = (staticValues.length << 1) | 1; + staticValues.push(p.value); + } + else { + address[p.id] = dynamicSlots.length << 1; + dynamicSlots.push(a => p.dynamicSlot(a)); + } + } + address[facet.id] = dynamicSlots.length << 1; + dynamicSlots.push(a => dynamicFacetSlot(a, facet, providers)); + } + } + let dynamic = dynamicSlots.map(f => f(address)); + return new Configuration(base, newCompartments, dynamic, address, staticValues, facets); + } + } + function flatten(extension, compartments, newCompartments) { + let result = [[], [], [], [], []]; + let seen = new Map(); + function inner(ext, prec) { + let known = seen.get(ext); + if (known != null) { + if (known <= prec) + return; + let found = result[known].indexOf(ext); + if (found > -1) + result[known].splice(found, 1); + if (ext instanceof CompartmentInstance) + newCompartments.delete(ext.compartment); + } + seen.set(ext, prec); + if (Array.isArray(ext)) { + for (let e of ext) + inner(e, prec); + } + else if (ext instanceof CompartmentInstance) { + if (newCompartments.has(ext.compartment)) + throw new RangeError(`Duplicate use of compartment in extensions`); + let content = compartments.get(ext.compartment) || ext.inner; + newCompartments.set(ext.compartment, content); + inner(content, prec); + } + else if (ext instanceof PrecExtension) { + inner(ext.inner, ext.prec); + } + else if (ext instanceof StateField) { + result[prec].push(ext); + if (ext.provides) + inner(ext.provides, prec); + } + else if (ext instanceof FacetProvider) { + result[prec].push(ext); + if (ext.facet.extensions) + inner(ext.facet.extensions, Prec_.default); + } + else { + let content = ext.extension; + if (!content) + throw new Error(`Unrecognized extension value in extension set (${ext}). This sometimes happens because multiple instances of @codemirror/state are loaded, breaking instanceof checks.`); + inner(content, prec); + } + } + inner(extension, Prec_.default); + return result.reduce((a, b) => a.concat(b)); + } + function ensureAddr(state, addr) { + if (addr & 1) + return 2 /* SlotStatus.Computed */; + let idx = addr >> 1; + let status = state.status[idx]; + if (status == 4 /* SlotStatus.Computing */) + throw new Error("Cyclic dependency between fields and/or facets"); + if (status & 2 /* SlotStatus.Computed */) + return status; + state.status[idx] = 4 /* SlotStatus.Computing */; + let changed = state.computeSlot(state, state.config.dynamicSlots[idx]); + return state.status[idx] = 2 /* SlotStatus.Computed */ | changed; + } + function getAddr(state, addr) { + return addr & 1 ? state.config.staticValues[addr >> 1] : state.values[addr >> 1]; + } + + const languageData = /*@__PURE__*/Facet.define(); + const allowMultipleSelections = /*@__PURE__*/Facet.define({ + combine: values => values.some(v => v), + static: true + }); + const lineSeparator = /*@__PURE__*/Facet.define({ + combine: values => values.length ? values[0] : undefined, + static: true + }); + const changeFilter = /*@__PURE__*/Facet.define(); + const transactionFilter = /*@__PURE__*/Facet.define(); + const transactionExtender = /*@__PURE__*/Facet.define(); + const readOnly = /*@__PURE__*/Facet.define({ + combine: values => values.length ? values[0] : false + }); + + /** + Annotations are tagged values that are used to add metadata to + transactions in an extensible way. They should be used to model + things that effect the entire transaction (such as its [time + stamp](https://codemirror.net/6/docs/ref/#state.Transaction^time) or information about its + [origin](https://codemirror.net/6/docs/ref/#state.Transaction^userEvent)). For effects that happen + _alongside_ the other changes made by the transaction, [state + effects](https://codemirror.net/6/docs/ref/#state.StateEffect) are more appropriate. + */ + class Annotation { + /** + @internal + */ + constructor( + /** + The annotation type. + */ + type, + /** + The value of this annotation. + */ + value) { + this.type = type; + this.value = value; + } + /** + Define a new type of annotation. + */ + static define() { return new AnnotationType(); } + } + /** + Marker that identifies a type of [annotation](https://codemirror.net/6/docs/ref/#state.Annotation). + */ + class AnnotationType { + /** + Create an instance of this annotation. + */ + of(value) { return new Annotation(this, value); } + } + /** + Representation of a type of state effect. Defined with + [`StateEffect.define`](https://codemirror.net/6/docs/ref/#state.StateEffect^define). + */ + class StateEffectType { + /** + @internal + */ + constructor( + // The `any` types in these function types are there to work + // around TypeScript issue #37631, where the type guard on + // `StateEffect.is` mysteriously stops working when these properly + // have type `Value`. + /** + @internal + */ + map) { + this.map = map; + } + /** + Create a [state effect](https://codemirror.net/6/docs/ref/#state.StateEffect) instance of this + type. + */ + of(value) { return new StateEffect(this, value); } + } + /** + State effects can be used to represent additional effects + associated with a [transaction](https://codemirror.net/6/docs/ref/#state.Transaction.effects). They + are often useful to model changes to custom [state + fields](https://codemirror.net/6/docs/ref/#state.StateField), when those changes aren't implicit in + document or selection changes. + */ + class StateEffect { + /** + @internal + */ + constructor( + /** + @internal + */ + type, + /** + The value of this effect. + */ + value) { + this.type = type; + this.value = value; + } + /** + Map this effect through a position mapping. Will return + `undefined` when that ends up deleting the effect. + */ + map(mapping) { + let mapped = this.type.map(this.value, mapping); + return mapped === undefined ? undefined : mapped == this.value ? this : new StateEffect(this.type, mapped); + } + /** + Tells you whether this effect object is of a given + [type](https://codemirror.net/6/docs/ref/#state.StateEffectType). + */ + is(type) { return this.type == type; } + /** + Define a new effect type. The type parameter indicates the type + of values that his effect holds. + */ + static define(spec = {}) { + return new StateEffectType(spec.map || (v => v)); + } + /** + Map an array of effects through a change set. + */ + static mapEffects(effects, mapping) { + if (!effects.length) + return effects; + let result = []; + for (let effect of effects) { + let mapped = effect.map(mapping); + if (mapped) + result.push(mapped); + } + return result; + } + } + /** + This effect can be used to reconfigure the root extensions of + the editor. Doing this will discard any extensions + [appended](https://codemirror.net/6/docs/ref/#state.StateEffect^appendConfig), but does not reset + the content of [reconfigured](https://codemirror.net/6/docs/ref/#state.Compartment.reconfigure) + compartments. + */ + StateEffect.reconfigure = /*@__PURE__*/StateEffect.define(); + /** + Append extensions to the top-level configuration of the editor. + */ + StateEffect.appendConfig = /*@__PURE__*/StateEffect.define(); + /** + Changes to the editor state are grouped into transactions. + Typically, a user action creates a single transaction, which may + contain any number of document changes, may change the selection, + or have other effects. Create a transaction by calling + [`EditorState.update`](https://codemirror.net/6/docs/ref/#state.EditorState.update), or immediately + dispatch one by calling + [`EditorView.dispatch`](https://codemirror.net/6/docs/ref/#view.EditorView.dispatch). + */ + class Transaction { + constructor( + /** + The state from which the transaction starts. + */ + startState, + /** + The document changes made by this transaction. + */ + changes, + /** + The selection set by this transaction, or undefined if it + doesn't explicitly set a selection. + */ + selection, + /** + The effects added to the transaction. + */ + effects, + /** + @internal + */ + annotations, + /** + Whether the selection should be scrolled into view after this + transaction is dispatched. + */ + scrollIntoView) { + this.startState = startState; + this.changes = changes; + this.selection = selection; + this.effects = effects; + this.annotations = annotations; + this.scrollIntoView = scrollIntoView; + /** + @internal + */ + this._doc = null; + /** + @internal + */ + this._state = null; + if (selection) + checkSelection(selection, changes.newLength); + if (!annotations.some((a) => a.type == Transaction.time)) + this.annotations = annotations.concat(Transaction.time.of(Date.now())); + } + /** + @internal + */ + static create(startState, changes, selection, effects, annotations, scrollIntoView) { + return new Transaction(startState, changes, selection, effects, annotations, scrollIntoView); + } + /** + The new document produced by the transaction. Contrary to + [`.state`](https://codemirror.net/6/docs/ref/#state.Transaction.state)`.doc`, accessing this won't + force the entire new state to be computed right away, so it is + recommended that [transaction + filters](https://codemirror.net/6/docs/ref/#state.EditorState^transactionFilter) use this getter + when they need to look at the new document. + */ + get newDoc() { + return this._doc || (this._doc = this.changes.apply(this.startState.doc)); + } + /** + The new selection produced by the transaction. If + [`this.selection`](https://codemirror.net/6/docs/ref/#state.Transaction.selection) is undefined, + this will [map](https://codemirror.net/6/docs/ref/#state.EditorSelection.map) the start state's + current selection through the changes made by the transaction. + */ + get newSelection() { + return this.selection || this.startState.selection.map(this.changes); + } + /** + The new state created by the transaction. Computed on demand + (but retained for subsequent access), so it is recommended not to + access it in [transaction + filters](https://codemirror.net/6/docs/ref/#state.EditorState^transactionFilter) when possible. + */ + get state() { + if (!this._state) + this.startState.applyTransaction(this); + return this._state; + } + /** + Get the value of the given annotation type, if any. + */ + annotation(type) { + for (let ann of this.annotations) + if (ann.type == type) + return ann.value; + return undefined; + } + /** + Indicates whether the transaction changed the document. + */ + get docChanged() { return !this.changes.empty; } + /** + Indicates whether this transaction reconfigures the state + (through a [configuration compartment](https://codemirror.net/6/docs/ref/#state.Compartment) or + with a top-level configuration + [effect](https://codemirror.net/6/docs/ref/#state.StateEffect^reconfigure). + */ + get reconfigured() { return this.startState.config != this.state.config; } + /** + Returns true if the transaction has a [user + event](https://codemirror.net/6/docs/ref/#state.Transaction^userEvent) annotation that is equal to + or more specific than `event`. For example, if the transaction + has `"select.pointer"` as user event, `"select"` and + `"select.pointer"` will match it. + */ + isUserEvent(event) { + let e = this.annotation(Transaction.userEvent); + return !!(e && (e == event || e.length > event.length && e.slice(0, event.length) == event && e[event.length] == ".")); + } + } + /** + Annotation used to store transaction timestamps. Automatically + added to every transaction, holding `Date.now()`. + */ + Transaction.time = /*@__PURE__*/Annotation.define(); + /** + Annotation used to associate a transaction with a user interface + event. Holds a string identifying the event, using a + dot-separated format to support attaching more specific + information. The events used by the core libraries are: + + - `"input"` when content is entered + - `"input.type"` for typed input + - `"input.type.compose"` for composition + - `"input.paste"` for pasted input + - `"input.drop"` when adding content with drag-and-drop + - `"input.complete"` when autocompleting + - `"delete"` when the user deletes content + - `"delete.selection"` when deleting the selection + - `"delete.forward"` when deleting forward from the selection + - `"delete.backward"` when deleting backward from the selection + - `"delete.cut"` when cutting to the clipboard + - `"move"` when content is moved + - `"move.drop"` when content is moved within the editor through drag-and-drop + - `"select"` when explicitly changing the selection + - `"select.pointer"` when selecting with a mouse or other pointing device + - `"undo"` and `"redo"` for history actions + + Use [`isUserEvent`](https://codemirror.net/6/docs/ref/#state.Transaction.isUserEvent) to check + whether the annotation matches a given event. + */ + Transaction.userEvent = /*@__PURE__*/Annotation.define(); + /** + Annotation indicating whether a transaction should be added to + the undo history or not. + */ + Transaction.addToHistory = /*@__PURE__*/Annotation.define(); + /** + Annotation indicating (when present and true) that a transaction + represents a change made by some other actor, not the user. This + is used, for example, to tag other people's changes in + collaborative editing. + */ + Transaction.remote = /*@__PURE__*/Annotation.define(); + function joinRanges(a, b) { + let result = []; + for (let iA = 0, iB = 0;;) { + let from, to; + if (iA < a.length && (iB == b.length || b[iB] >= a[iA])) { + from = a[iA++]; + to = a[iA++]; + } + else if (iB < b.length) { + from = b[iB++]; + to = b[iB++]; + } + else + return result; + if (!result.length || result[result.length - 1] < from) + result.push(from, to); + else if (result[result.length - 1] < to) + result[result.length - 1] = to; + } + } + function mergeTransaction(a, b, sequential) { + var _a; + let mapForA, mapForB, changes; + if (sequential) { + mapForA = b.changes; + mapForB = ChangeSet.empty(b.changes.length); + changes = a.changes.compose(b.changes); + } + else { + mapForA = b.changes.map(a.changes); + mapForB = a.changes.mapDesc(b.changes, true); + changes = a.changes.compose(mapForA); + } + return { + changes, + selection: b.selection ? b.selection.map(mapForB) : (_a = a.selection) === null || _a === void 0 ? void 0 : _a.map(mapForA), + effects: StateEffect.mapEffects(a.effects, mapForA).concat(StateEffect.mapEffects(b.effects, mapForB)), + annotations: a.annotations.length ? a.annotations.concat(b.annotations) : b.annotations, + scrollIntoView: a.scrollIntoView || b.scrollIntoView + }; + } + function resolveTransactionInner(state, spec, docSize) { + let sel = spec.selection, annotations = asArray$1(spec.annotations); + if (spec.userEvent) + annotations = annotations.concat(Transaction.userEvent.of(spec.userEvent)); + return { + changes: spec.changes instanceof ChangeSet ? spec.changes + : ChangeSet.of(spec.changes || [], docSize, state.facet(lineSeparator)), + selection: sel && (sel instanceof EditorSelection ? sel : EditorSelection.single(sel.anchor, sel.head)), + effects: asArray$1(spec.effects), + annotations, + scrollIntoView: !!spec.scrollIntoView + }; + } + function resolveTransaction(state, specs, filter) { + let s = resolveTransactionInner(state, specs.length ? specs[0] : {}, state.doc.length); + if (specs.length && specs[0].filter === false) + filter = false; + for (let i = 1; i < specs.length; i++) { + if (specs[i].filter === false) + filter = false; + let seq = !!specs[i].sequential; + s = mergeTransaction(s, resolveTransactionInner(state, specs[i], seq ? s.changes.newLength : state.doc.length), seq); + } + let tr = Transaction.create(state, s.changes, s.selection, s.effects, s.annotations, s.scrollIntoView); + return extendTransaction(filter ? filterTransaction(tr) : tr); + } + // Finish a transaction by applying filters if necessary. + function filterTransaction(tr) { + let state = tr.startState; + // Change filters + let result = true; + for (let filter of state.facet(changeFilter)) { + let value = filter(tr); + if (value === false) { + result = false; + break; + } + if (Array.isArray(value)) + result = result === true ? value : joinRanges(result, value); + } + if (result !== true) { + let changes, back; + if (result === false) { + back = tr.changes.invertedDesc; + changes = ChangeSet.empty(state.doc.length); + } + else { + let filtered = tr.changes.filter(result); + changes = filtered.changes; + back = filtered.filtered.mapDesc(filtered.changes).invertedDesc; + } + tr = Transaction.create(state, changes, tr.selection && tr.selection.map(back), StateEffect.mapEffects(tr.effects, back), tr.annotations, tr.scrollIntoView); + } + // Transaction filters + let filters = state.facet(transactionFilter); + for (let i = filters.length - 1; i >= 0; i--) { + let filtered = filters[i](tr); + if (filtered instanceof Transaction) + tr = filtered; + else if (Array.isArray(filtered) && filtered.length == 1 && filtered[0] instanceof Transaction) + tr = filtered[0]; + else + tr = resolveTransaction(state, asArray$1(filtered), false); + } + return tr; + } + function extendTransaction(tr) { + let state = tr.startState, extenders = state.facet(transactionExtender), spec = tr; + for (let i = extenders.length - 1; i >= 0; i--) { + let extension = extenders[i](tr); + if (extension && Object.keys(extension).length) + spec = mergeTransaction(spec, resolveTransactionInner(state, extension, tr.changes.newLength), true); + } + return spec == tr ? tr : Transaction.create(state, tr.changes, tr.selection, spec.effects, spec.annotations, spec.scrollIntoView); + } + const none$2 = []; + function asArray$1(value) { + return value == null ? none$2 : Array.isArray(value) ? value : [value]; + } + + /** + The categories produced by a [character + categorizer](https://codemirror.net/6/docs/ref/#state.EditorState.charCategorizer). These are used + do things like selecting by word. + */ + var CharCategory = /*@__PURE__*/(function (CharCategory) { + /** + Word characters. + */ + CharCategory[CharCategory["Word"] = 0] = "Word"; + /** + Whitespace. + */ + CharCategory[CharCategory["Space"] = 1] = "Space"; + /** + Anything else. + */ + CharCategory[CharCategory["Other"] = 2] = "Other"; + return CharCategory})(CharCategory || (CharCategory = {})); + const nonASCIISingleCaseWordChar = /[\u00df\u0587\u0590-\u05f4\u0600-\u06ff\u3040-\u309f\u30a0-\u30ff\u3400-\u4db5\u4e00-\u9fcc\uac00-\ud7af]/; + let wordChar; + try { + wordChar = /*@__PURE__*/new RegExp("[\\p{Alphabetic}\\p{Number}_]", "u"); + } + catch (_) { } + function hasWordChar(str) { + if (wordChar) + return wordChar.test(str); + for (let i = 0; i < str.length; i++) { + let ch = str[i]; + if (/\w/.test(ch) || ch > "\x80" && (ch.toUpperCase() != ch.toLowerCase() || nonASCIISingleCaseWordChar.test(ch))) + return true; + } + return false; + } + function makeCategorizer(wordChars) { + return (char) => { + if (!/\S/.test(char)) + return CharCategory.Space; + if (hasWordChar(char)) + return CharCategory.Word; + for (let i = 0; i < wordChars.length; i++) + if (char.indexOf(wordChars[i]) > -1) + return CharCategory.Word; + return CharCategory.Other; + }; + } + + /** + The editor state class is a persistent (immutable) data structure. + To update a state, you [create](https://codemirror.net/6/docs/ref/#state.EditorState.update) a + [transaction](https://codemirror.net/6/docs/ref/#state.Transaction), which produces a _new_ state + instance, without modifying the original object. + + As such, _never_ mutate properties of a state directly. That'll + just break things. + */ + class EditorState { + constructor( + /** + @internal + */ + config, + /** + The current document. + */ + doc, + /** + The current selection. + */ + selection, + /** + @internal + */ + values, computeSlot, tr) { + this.config = config; + this.doc = doc; + this.selection = selection; + this.values = values; + this.status = config.statusTemplate.slice(); + this.computeSlot = computeSlot; + // Fill in the computed state immediately, so that further queries + // for it made during the update return this state + if (tr) + tr._state = this; + for (let i = 0; i < this.config.dynamicSlots.length; i++) + ensureAddr(this, i << 1); + this.computeSlot = null; + } + field(field, require = true) { + let addr = this.config.address[field.id]; + if (addr == null) { + if (require) + throw new RangeError("Field is not present in this state"); + return undefined; + } + ensureAddr(this, addr); + return getAddr(this, addr); + } + /** + Create a [transaction](https://codemirror.net/6/docs/ref/#state.Transaction) that updates this + state. Any number of [transaction specs](https://codemirror.net/6/docs/ref/#state.TransactionSpec) + can be passed. Unless + [`sequential`](https://codemirror.net/6/docs/ref/#state.TransactionSpec.sequential) is set, the + [changes](https://codemirror.net/6/docs/ref/#state.TransactionSpec.changes) (if any) of each spec + are assumed to start in the _current_ document (not the document + produced by previous specs), and its + [selection](https://codemirror.net/6/docs/ref/#state.TransactionSpec.selection) and + [effects](https://codemirror.net/6/docs/ref/#state.TransactionSpec.effects) are assumed to refer + to the document created by its _own_ changes. The resulting + transaction contains the combined effect of all the different + specs. For [selection](https://codemirror.net/6/docs/ref/#state.TransactionSpec.selection), later + specs take precedence over earlier ones. + */ + update(...specs) { + return resolveTransaction(this, specs, true); + } + /** + @internal + */ + applyTransaction(tr) { + let conf = this.config, { base, compartments } = conf; + for (let effect of tr.effects) { + if (effect.is(Compartment.reconfigure)) { + if (conf) { + compartments = new Map; + conf.compartments.forEach((val, key) => compartments.set(key, val)); + conf = null; + } + compartments.set(effect.value.compartment, effect.value.extension); + } + else if (effect.is(StateEffect.reconfigure)) { + conf = null; + base = effect.value; + } + else if (effect.is(StateEffect.appendConfig)) { + conf = null; + base = asArray$1(base).concat(effect.value); + } + } + let startValues; + if (!conf) { + conf = Configuration.resolve(base, compartments, this); + let intermediateState = new EditorState(conf, this.doc, this.selection, conf.dynamicSlots.map(() => null), (state, slot) => slot.reconfigure(state, this), null); + startValues = intermediateState.values; + } + else { + startValues = tr.startState.values.slice(); + } + new EditorState(conf, tr.newDoc, tr.newSelection, startValues, (state, slot) => slot.update(state, tr), tr); + } + /** + Create a [transaction spec](https://codemirror.net/6/docs/ref/#state.TransactionSpec) that + replaces every selection range with the given content. + */ + replaceSelection(text) { + if (typeof text == "string") + text = this.toText(text); + return this.changeByRange(range => ({ changes: { from: range.from, to: range.to, insert: text }, + range: EditorSelection.cursor(range.from + text.length) })); + } + /** + Create a set of changes and a new selection by running the given + function for each range in the active selection. The function + can return an optional set of changes (in the coordinate space + of the start document), plus an updated range (in the coordinate + space of the document produced by the call's own changes). This + method will merge all the changes and ranges into a single + changeset and selection, and return it as a [transaction + spec](https://codemirror.net/6/docs/ref/#state.TransactionSpec), which can be passed to + [`update`](https://codemirror.net/6/docs/ref/#state.EditorState.update). + */ + changeByRange(f) { + let sel = this.selection; + let result1 = f(sel.ranges[0]); + let changes = this.changes(result1.changes), ranges = [result1.range]; + let effects = asArray$1(result1.effects); + for (let i = 1; i < sel.ranges.length; i++) { + let result = f(sel.ranges[i]); + let newChanges = this.changes(result.changes), newMapped = newChanges.map(changes); + for (let j = 0; j < i; j++) + ranges[j] = ranges[j].map(newMapped); + let mapBy = changes.mapDesc(newChanges, true); + ranges.push(result.range.map(mapBy)); + changes = changes.compose(newMapped); + effects = StateEffect.mapEffects(effects, newMapped).concat(StateEffect.mapEffects(asArray$1(result.effects), mapBy)); + } + return { + changes, + selection: EditorSelection.create(ranges, sel.mainIndex), + effects + }; + } + /** + Create a [change set](https://codemirror.net/6/docs/ref/#state.ChangeSet) from the given change + description, taking the state's document length and line + separator into account. + */ + changes(spec = []) { + if (spec instanceof ChangeSet) + return spec; + return ChangeSet.of(spec, this.doc.length, this.facet(EditorState.lineSeparator)); + } + /** + Using the state's [line + separator](https://codemirror.net/6/docs/ref/#state.EditorState^lineSeparator), create a + [`Text`](https://codemirror.net/6/docs/ref/#state.Text) instance from the given string. + */ + toText(string) { + return Text.of(string.split(this.facet(EditorState.lineSeparator) || DefaultSplit)); + } + /** + Return the given range of the document as a string. + */ + sliceDoc(from = 0, to = this.doc.length) { + return this.doc.sliceString(from, to, this.lineBreak); + } + /** + Get the value of a state [facet](https://codemirror.net/6/docs/ref/#state.Facet). + */ + facet(facet) { + let addr = this.config.address[facet.id]; + if (addr == null) + return facet.default; + ensureAddr(this, addr); + return getAddr(this, addr); + } + /** + Convert this state to a JSON-serializable object. When custom + fields should be serialized, you can pass them in as an object + mapping property names (in the resulting object, which should + not use `doc` or `selection`) to fields. + */ + toJSON(fields) { + let result = { + doc: this.sliceDoc(), + selection: this.selection.toJSON() + }; + if (fields) + for (let prop in fields) { + let value = fields[prop]; + if (value instanceof StateField && this.config.address[value.id] != null) + result[prop] = value.spec.toJSON(this.field(fields[prop]), this); + } + return result; + } + /** + Deserialize a state from its JSON representation. When custom + fields should be deserialized, pass the same object you passed + to [`toJSON`](https://codemirror.net/6/docs/ref/#state.EditorState.toJSON) when serializing as + third argument. + */ + static fromJSON(json, config = {}, fields) { + if (!json || typeof json.doc != "string") + throw new RangeError("Invalid JSON representation for EditorState"); + let fieldInit = []; + if (fields) + for (let prop in fields) { + if (Object.prototype.hasOwnProperty.call(json, prop)) { + let field = fields[prop], value = json[prop]; + fieldInit.push(field.init(state => field.spec.fromJSON(value, state))); + } + } + return EditorState.create({ + doc: json.doc, + selection: EditorSelection.fromJSON(json.selection), + extensions: config.extensions ? fieldInit.concat([config.extensions]) : fieldInit + }); + } + /** + Create a new state. You'll usually only need this when + initializing an editor—updated states are created by applying + transactions. + */ + static create(config = {}) { + let configuration = Configuration.resolve(config.extensions || [], new Map); + let doc = config.doc instanceof Text ? config.doc + : Text.of((config.doc || "").split(configuration.staticFacet(EditorState.lineSeparator) || DefaultSplit)); + let selection = !config.selection ? EditorSelection.single(0) + : config.selection instanceof EditorSelection ? config.selection + : EditorSelection.single(config.selection.anchor, config.selection.head); + checkSelection(selection, doc.length); + if (!configuration.staticFacet(allowMultipleSelections)) + selection = selection.asSingle(); + return new EditorState(configuration, doc, selection, configuration.dynamicSlots.map(() => null), (state, slot) => slot.create(state), null); + } + /** + The size (in columns) of a tab in the document, determined by + the [`tabSize`](https://codemirror.net/6/docs/ref/#state.EditorState^tabSize) facet. + */ + get tabSize() { return this.facet(EditorState.tabSize); } + /** + Get the proper [line-break](https://codemirror.net/6/docs/ref/#state.EditorState^lineSeparator) + string for this state. + */ + get lineBreak() { return this.facet(EditorState.lineSeparator) || "\n"; } + /** + Returns true when the editor is + [configured](https://codemirror.net/6/docs/ref/#state.EditorState^readOnly) to be read-only. + */ + get readOnly() { return this.facet(readOnly); } + /** + Look up a translation for the given phrase (via the + [`phrases`](https://codemirror.net/6/docs/ref/#state.EditorState^phrases) facet), or return the + original string if no translation is found. + + If additional arguments are passed, they will be inserted in + place of markers like `$1` (for the first value) and `$2`, etc. + A single `$` is equivalent to `$1`, and `$$` will produce a + literal dollar sign. + */ + phrase(phrase, ...insert) { + for (let map of this.facet(EditorState.phrases)) + if (Object.prototype.hasOwnProperty.call(map, phrase)) { + phrase = map[phrase]; + break; + } + if (insert.length) + phrase = phrase.replace(/\$(\$|\d*)/g, (m, i) => { + if (i == "$") + return "$"; + let n = +(i || 1); + return !n || n > insert.length ? m : insert[n - 1]; + }); + return phrase; + } + /** + Find the values for a given language data field, provided by the + the [`languageData`](https://codemirror.net/6/docs/ref/#state.EditorState^languageData) facet. + */ + languageDataAt(name, pos, side = -1) { + let values = []; + for (let provider of this.facet(languageData)) { + for (let result of provider(this, pos, side)) { + if (Object.prototype.hasOwnProperty.call(result, name)) + values.push(result[name]); + } + } + return values; + } + /** + Return a function that can categorize strings (expected to + represent a single [grapheme cluster](https://codemirror.net/6/docs/ref/#state.findClusterBreak)) + into one of: + + - Word (contains an alphanumeric character or a character + explicitly listed in the local language's `"wordChars"` + language data, which should be a string) + - Space (contains only whitespace) + - Other (anything else) + */ + charCategorizer(at) { + return makeCategorizer(this.languageDataAt("wordChars", at).join("")); + } + /** + Find the word at the given position, meaning the range + containing all [word](https://codemirror.net/6/docs/ref/#state.CharCategory.Word) characters + around it. If no word characters are adjacent to the position, + this returns null. + */ + wordAt(pos) { + let { text, from, length } = this.doc.lineAt(pos); + let cat = this.charCategorizer(pos); + let start = pos - from, end = pos - from; + while (start > 0) { + let prev = findClusterBreak(text, start, false); + if (cat(text.slice(prev, start)) != CharCategory.Word) + break; + start = prev; + } + while (end < length) { + let next = findClusterBreak(text, end); + if (cat(text.slice(end, next)) != CharCategory.Word) + break; + end = next; + } + return start == end ? null : EditorSelection.range(start + from, end + from); + } + } + /** + A facet that, when enabled, causes the editor to allow multiple + ranges to be selected. Be careful though, because by default the + editor relies on the native DOM selection, which cannot handle + multiple selections. An extension like + [`drawSelection`](https://codemirror.net/6/docs/ref/#view.drawSelection) can be used to make + secondary selections visible to the user. + */ + EditorState.allowMultipleSelections = allowMultipleSelections; + /** + Configures the tab size to use in this state. The first + (highest-precedence) value of the facet is used. If no value is + given, this defaults to 4. + */ + EditorState.tabSize = /*@__PURE__*/Facet.define({ + combine: values => values.length ? values[0] : 4 + }); + /** + The line separator to use. By default, any of `"\n"`, `"\r\n"` + and `"\r"` is treated as a separator when splitting lines, and + lines are joined with `"\n"`. + + When you configure a value here, only that precise separator + will be used, allowing you to round-trip documents through the + editor without normalizing line separators. + */ + EditorState.lineSeparator = lineSeparator; + /** + This facet controls the value of the + [`readOnly`](https://codemirror.net/6/docs/ref/#state.EditorState.readOnly) getter, which is + consulted by commands and extensions that implement editing + functionality to determine whether they should apply. It + defaults to false, but when its highest-precedence value is + `true`, such functionality disables itself. + + Not to be confused with + [`EditorView.editable`](https://codemirror.net/6/docs/ref/#view.EditorView^editable), which + controls whether the editor's DOM is set to be editable (and + thus focusable). + */ + EditorState.readOnly = readOnly; + /** + Registers translation phrases. The + [`phrase`](https://codemirror.net/6/docs/ref/#state.EditorState.phrase) method will look through + all objects registered with this facet to find translations for + its argument. + */ + EditorState.phrases = /*@__PURE__*/Facet.define({ + compare(a, b) { + let kA = Object.keys(a), kB = Object.keys(b); + return kA.length == kB.length && kA.every(k => a[k] == b[k]); + } + }); + /** + A facet used to register [language + data](https://codemirror.net/6/docs/ref/#state.EditorState.languageDataAt) providers. + */ + EditorState.languageData = languageData; + /** + Facet used to register change filters, which are called for each + transaction (unless explicitly + [disabled](https://codemirror.net/6/docs/ref/#state.TransactionSpec.filter)), and can suppress + part of the transaction's changes. + + Such a function can return `true` to indicate that it doesn't + want to do anything, `false` to completely stop the changes in + the transaction, or a set of ranges in which changes should be + suppressed. Such ranges are represented as an array of numbers, + with each pair of two numbers indicating the start and end of a + range. So for example `[10, 20, 100, 110]` suppresses changes + between 10 and 20, and between 100 and 110. + */ + EditorState.changeFilter = changeFilter; + /** + Facet used to register a hook that gets a chance to update or + replace transaction specs before they are applied. This will + only be applied for transactions that don't have + [`filter`](https://codemirror.net/6/docs/ref/#state.TransactionSpec.filter) set to `false`. You + can either return a single transaction spec (possibly the input + transaction), or an array of specs (which will be combined in + the same way as the arguments to + [`EditorState.update`](https://codemirror.net/6/docs/ref/#state.EditorState.update)). + + When possible, it is recommended to avoid accessing + [`Transaction.state`](https://codemirror.net/6/docs/ref/#state.Transaction.state) in a filter, + since it will force creation of a state that will then be + discarded again, if the transaction is actually filtered. + + (This functionality should be used with care. Indiscriminately + modifying transaction is likely to break something or degrade + the user experience.) + */ + EditorState.transactionFilter = transactionFilter; + /** + This is a more limited form of + [`transactionFilter`](https://codemirror.net/6/docs/ref/#state.EditorState^transactionFilter), + which can only add + [annotations](https://codemirror.net/6/docs/ref/#state.TransactionSpec.annotations) and + [effects](https://codemirror.net/6/docs/ref/#state.TransactionSpec.effects). _But_, this type + of filter runs even if the transaction has disabled regular + [filtering](https://codemirror.net/6/docs/ref/#state.TransactionSpec.filter), making it suitable + for effects that don't need to touch the changes or selection, + but do want to process every transaction. + + Extenders run _after_ filters, when both are present. + */ + EditorState.transactionExtender = transactionExtender; + Compartment.reconfigure = /*@__PURE__*/StateEffect.define(); + + /** + Utility function for combining behaviors to fill in a config + object from an array of provided configs. `defaults` should hold + default values for all optional fields in `Config`. + + The function will, by default, error + when a field gets two values that aren't `===`-equal, but you can + provide combine functions per field to do something else. + */ + function combineConfig(configs, defaults, // Should hold only the optional properties of Config, but I haven't managed to express that + combine = {}) { + let result = {}; + for (let config of configs) + for (let key of Object.keys(config)) { + let value = config[key], current = result[key]; + if (current === undefined) + result[key] = value; + else if (current === value || value === undefined) ; // No conflict + else if (Object.hasOwnProperty.call(combine, key)) + result[key] = combine[key](current, value); + else + throw new Error("Config merge conflict for field " + key); + } + for (let key in defaults) + if (result[key] === undefined) + result[key] = defaults[key]; + return result; + } + + /** + Each range is associated with a value, which must inherit from + this class. + */ + class RangeValue { + /** + Compare this value with another value. Used when comparing + rangesets. The default implementation compares by identity. + Unless you are only creating a fixed number of unique instances + of your value type, it is a good idea to implement this + properly. + */ + eq(other) { return this == other; } + /** + Create a [range](https://codemirror.net/6/docs/ref/#state.Range) with this value. + */ + range(from, to = from) { return Range$1.create(from, to, this); } + } + RangeValue.prototype.startSide = RangeValue.prototype.endSide = 0; + RangeValue.prototype.point = false; + RangeValue.prototype.mapMode = MapMode.TrackDel; + /** + A range associates a value with a range of positions. + */ + class Range$1 { + constructor( + /** + The range's start position. + */ + from, + /** + Its end position. + */ + to, + /** + The value associated with this range. + */ + value) { + this.from = from; + this.to = to; + this.value = value; + } + /** + @internal + */ + static create(from, to, value) { + return new Range$1(from, to, value); + } + } + function cmpRange(a, b) { + return a.from - b.from || a.value.startSide - b.value.startSide; + } + class Chunk { + constructor(from, to, value, + // Chunks are marked with the largest point that occurs + // in them (or -1 for no points), so that scans that are + // only interested in points (such as the + // heightmap-related logic) can skip range-only chunks. + maxPoint) { + this.from = from; + this.to = to; + this.value = value; + this.maxPoint = maxPoint; + } + get length() { return this.to[this.to.length - 1]; } + // Find the index of the given position and side. Use the ranges' + // `from` pos when `end == false`, `to` when `end == true`. + findIndex(pos, side, end, startAt = 0) { + let arr = end ? this.to : this.from; + for (let lo = startAt, hi = arr.length;;) { + if (lo == hi) + return lo; + let mid = (lo + hi) >> 1; + let diff = arr[mid] - pos || (end ? this.value[mid].endSide : this.value[mid].startSide) - side; + if (mid == lo) + return diff >= 0 ? lo : hi; + if (diff >= 0) + hi = mid; + else + lo = mid + 1; + } + } + between(offset, from, to, f) { + for (let i = this.findIndex(from, -1000000000 /* C.Far */, true), e = this.findIndex(to, 1000000000 /* C.Far */, false, i); i < e; i++) + if (f(this.from[i] + offset, this.to[i] + offset, this.value[i]) === false) + return false; + } + map(offset, changes) { + let value = [], from = [], to = [], newPos = -1, maxPoint = -1; + for (let i = 0; i < this.value.length; i++) { + let val = this.value[i], curFrom = this.from[i] + offset, curTo = this.to[i] + offset, newFrom, newTo; + if (curFrom == curTo) { + let mapped = changes.mapPos(curFrom, val.startSide, val.mapMode); + if (mapped == null) + continue; + newFrom = newTo = mapped; + if (val.startSide != val.endSide) { + newTo = changes.mapPos(curFrom, val.endSide); + if (newTo < newFrom) + continue; + } + } + else { + newFrom = changes.mapPos(curFrom, val.startSide); + newTo = changes.mapPos(curTo, val.endSide); + if (newFrom > newTo || newFrom == newTo && val.startSide > 0 && val.endSide <= 0) + continue; + } + if ((newTo - newFrom || val.endSide - val.startSide) < 0) + continue; + if (newPos < 0) + newPos = newFrom; + if (val.point) + maxPoint = Math.max(maxPoint, newTo - newFrom); + value.push(val); + from.push(newFrom - newPos); + to.push(newTo - newPos); + } + return { mapped: value.length ? new Chunk(from, to, value, maxPoint) : null, pos: newPos }; + } + } + /** + A range set stores a collection of [ranges](https://codemirror.net/6/docs/ref/#state.Range) in a + way that makes them efficient to [map](https://codemirror.net/6/docs/ref/#state.RangeSet.map) and + [update](https://codemirror.net/6/docs/ref/#state.RangeSet.update). This is an immutable data + structure. + */ + class RangeSet { + constructor( + /** + @internal + */ + chunkPos, + /** + @internal + */ + chunk, + /** + @internal + */ + nextLayer, + /** + @internal + */ + maxPoint) { + this.chunkPos = chunkPos; + this.chunk = chunk; + this.nextLayer = nextLayer; + this.maxPoint = maxPoint; + } + /** + @internal + */ + static create(chunkPos, chunk, nextLayer, maxPoint) { + return new RangeSet(chunkPos, chunk, nextLayer, maxPoint); + } + /** + @internal + */ + get length() { + let last = this.chunk.length - 1; + return last < 0 ? 0 : Math.max(this.chunkEnd(last), this.nextLayer.length); + } + /** + The number of ranges in the set. + */ + get size() { + if (this.isEmpty) + return 0; + let size = this.nextLayer.size; + for (let chunk of this.chunk) + size += chunk.value.length; + return size; + } + /** + @internal + */ + chunkEnd(index) { + return this.chunkPos[index] + this.chunk[index].length; + } + /** + Update the range set, optionally adding new ranges or filtering + out existing ones. + + (Note: The type parameter is just there as a kludge to work + around TypeScript variance issues that prevented `RangeSet` + from being a subtype of `RangeSet` when `X` is a subtype of + `Y`.) + */ + update(updateSpec) { + let { add = [], sort = false, filterFrom = 0, filterTo = this.length } = updateSpec; + let filter = updateSpec.filter; + if (add.length == 0 && !filter) + return this; + if (sort) + add = add.slice().sort(cmpRange); + if (this.isEmpty) + return add.length ? RangeSet.of(add) : this; + let cur = new LayerCursor(this, null, -1).goto(0), i = 0, spill = []; + let builder = new RangeSetBuilder(); + while (cur.value || i < add.length) { + if (i < add.length && (cur.from - add[i].from || cur.startSide - add[i].value.startSide) >= 0) { + let range = add[i++]; + if (!builder.addInner(range.from, range.to, range.value)) + spill.push(range); + } + else if (cur.rangeIndex == 1 && cur.chunkIndex < this.chunk.length && + (i == add.length || this.chunkEnd(cur.chunkIndex) < add[i].from) && + (!filter || filterFrom > this.chunkEnd(cur.chunkIndex) || filterTo < this.chunkPos[cur.chunkIndex]) && + builder.addChunk(this.chunkPos[cur.chunkIndex], this.chunk[cur.chunkIndex])) { + cur.nextChunk(); + } + else { + if (!filter || filterFrom > cur.to || filterTo < cur.from || filter(cur.from, cur.to, cur.value)) { + if (!builder.addInner(cur.from, cur.to, cur.value)) + spill.push(Range$1.create(cur.from, cur.to, cur.value)); + } + cur.next(); + } + } + return builder.finishInner(this.nextLayer.isEmpty && !spill.length ? RangeSet.empty + : this.nextLayer.update({ add: spill, filter, filterFrom, filterTo })); + } + /** + Map this range set through a set of changes, return the new set. + */ + map(changes) { + if (changes.empty || this.isEmpty) + return this; + let chunks = [], chunkPos = [], maxPoint = -1; + for (let i = 0; i < this.chunk.length; i++) { + let start = this.chunkPos[i], chunk = this.chunk[i]; + let touch = changes.touchesRange(start, start + chunk.length); + if (touch === false) { + maxPoint = Math.max(maxPoint, chunk.maxPoint); + chunks.push(chunk); + chunkPos.push(changes.mapPos(start)); + } + else if (touch === true) { + let { mapped, pos } = chunk.map(start, changes); + if (mapped) { + maxPoint = Math.max(maxPoint, mapped.maxPoint); + chunks.push(mapped); + chunkPos.push(pos); + } + } + } + let next = this.nextLayer.map(changes); + return chunks.length == 0 ? next : new RangeSet(chunkPos, chunks, next || RangeSet.empty, maxPoint); + } + /** + Iterate over the ranges that touch the region `from` to `to`, + calling `f` for each. There is no guarantee that the ranges will + be reported in any specific order. When the callback returns + `false`, iteration stops. + */ + between(from, to, f) { + if (this.isEmpty) + return; + for (let i = 0; i < this.chunk.length; i++) { + let start = this.chunkPos[i], chunk = this.chunk[i]; + if (to >= start && from <= start + chunk.length && + chunk.between(start, from - start, to - start, f) === false) + return; + } + this.nextLayer.between(from, to, f); + } + /** + Iterate over the ranges in this set, in order, including all + ranges that end at or after `from`. + */ + iter(from = 0) { + return HeapCursor.from([this]).goto(from); + } + /** + @internal + */ + get isEmpty() { return this.nextLayer == this; } + /** + Iterate over the ranges in a collection of sets, in order, + starting from `from`. + */ + static iter(sets, from = 0) { + return HeapCursor.from(sets).goto(from); + } + /** + Iterate over two groups of sets, calling methods on `comparator` + to notify it of possible differences. + */ + static compare(oldSets, newSets, + /** + This indicates how the underlying data changed between these + ranges, and is needed to synchronize the iteration. `from` and + `to` are coordinates in the _new_ space, after these changes. + */ + textDiff, comparator, + /** + Can be used to ignore all non-point ranges, and points below + the given size. When -1, all ranges are compared. + */ + minPointSize = -1) { + let a = oldSets.filter(set => set.maxPoint > 0 || !set.isEmpty && set.maxPoint >= minPointSize); + let b = newSets.filter(set => set.maxPoint > 0 || !set.isEmpty && set.maxPoint >= minPointSize); + let sharedChunks = findSharedChunks(a, b, textDiff); + let sideA = new SpanCursor(a, sharedChunks, minPointSize); + let sideB = new SpanCursor(b, sharedChunks, minPointSize); + textDiff.iterGaps((fromA, fromB, length) => compare(sideA, fromA, sideB, fromB, length, comparator)); + if (textDiff.empty && textDiff.length == 0) + compare(sideA, 0, sideB, 0, 0, comparator); + } + /** + Compare the contents of two groups of range sets, returning true + if they are equivalent in the given range. + */ + static eq(oldSets, newSets, from = 0, to) { + if (to == null) + to = 1000000000 /* C.Far */; + let a = oldSets.filter(set => !set.isEmpty && newSets.indexOf(set) < 0); + let b = newSets.filter(set => !set.isEmpty && oldSets.indexOf(set) < 0); + if (a.length != b.length) + return false; + if (!a.length) + return true; + let sharedChunks = findSharedChunks(a, b); + let sideA = new SpanCursor(a, sharedChunks, 0).goto(from), sideB = new SpanCursor(b, sharedChunks, 0).goto(from); + for (;;) { + if (sideA.to != sideB.to || + !sameValues(sideA.active, sideB.active) || + sideA.point && (!sideB.point || !sideA.point.eq(sideB.point))) + return false; + if (sideA.to > to) + return true; + sideA.next(); + sideB.next(); + } + } + /** + Iterate over a group of range sets at the same time, notifying + the iterator about the ranges covering every given piece of + content. Returns the open count (see + [`SpanIterator.span`](https://codemirror.net/6/docs/ref/#state.SpanIterator.span)) at the end + of the iteration. + */ + static spans(sets, from, to, iterator, + /** + When given and greater than -1, only points of at least this + size are taken into account. + */ + minPointSize = -1) { + let cursor = new SpanCursor(sets, null, minPointSize).goto(from), pos = from; + let open = cursor.openStart; + for (;;) { + let curTo = Math.min(cursor.to, to); + if (cursor.point) { + iterator.point(pos, curTo, cursor.point, cursor.activeForPoint(cursor.to), open, cursor.pointRank); + open = cursor.openEnd(curTo) + (cursor.to > curTo ? 1 : 0); + } + else if (curTo > pos) { + iterator.span(pos, curTo, cursor.active, open); + open = cursor.openEnd(curTo); + } + if (cursor.to > to) + break; + pos = cursor.to; + cursor.next(); + } + return open; + } + /** + Create a range set for the given range or array of ranges. By + default, this expects the ranges to be _sorted_ (by start + position and, if two start at the same position, + `value.startSide`). You can pass `true` as second argument to + cause the method to sort them. + */ + static of(ranges, sort = false) { + let build = new RangeSetBuilder(); + for (let range of ranges instanceof Range$1 ? [ranges] : sort ? lazySort(ranges) : ranges) + build.add(range.from, range.to, range.value); + return build.finish(); + } + } + /** + The empty set of ranges. + */ + RangeSet.empty = /*@__PURE__*/new RangeSet([], [], null, -1); + function lazySort(ranges) { + if (ranges.length > 1) + for (let prev = ranges[0], i = 1; i < ranges.length; i++) { + let cur = ranges[i]; + if (cmpRange(prev, cur) > 0) + return ranges.slice().sort(cmpRange); + prev = cur; + } + return ranges; + } + RangeSet.empty.nextLayer = RangeSet.empty; + /** + A range set builder is a data structure that helps build up a + [range set](https://codemirror.net/6/docs/ref/#state.RangeSet) directly, without first allocating + an array of [`Range`](https://codemirror.net/6/docs/ref/#state.Range) objects. + */ + class RangeSetBuilder { + /** + Create an empty builder. + */ + constructor() { + this.chunks = []; + this.chunkPos = []; + this.chunkStart = -1; + this.last = null; + this.lastFrom = -1000000000 /* C.Far */; + this.lastTo = -1000000000 /* C.Far */; + this.from = []; + this.to = []; + this.value = []; + this.maxPoint = -1; + this.setMaxPoint = -1; + this.nextLayer = null; + } + finishChunk(newArrays) { + this.chunks.push(new Chunk(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; + if (newArrays) { + this.from = []; + this.to = []; + this.value = []; + } + } + /** + Add a range. Ranges should be added in sorted (by `from` and + `value.startSide`) order. + */ + add(from, to, value) { + if (!this.addInner(from, to, value)) + (this.nextLayer || (this.nextLayer = new RangeSetBuilder)).add(from, to, value); + } + /** + @internal + */ + addInner(from, to, value) { + let diff = from - this.lastTo || value.startSide - this.last.endSide; + if (diff <= 0 && (from - this.lastFrom || value.startSide - this.last.startSide) < 0) + throw new Error("Ranges must be added sorted by `from` position and `startSide`"); + if (diff < 0) + return false; + if (this.from.length == 250 /* C.ChunkSize */) + this.finishChunk(true); + if (this.chunkStart < 0) + this.chunkStart = from; + this.from.push(from - this.chunkStart); + this.to.push(to - this.chunkStart); + this.last = value; + this.lastFrom = from; + this.lastTo = to; + this.value.push(value); + if (value.point) + this.maxPoint = Math.max(this.maxPoint, to - from); + return true; + } + /** + @internal + */ + addChunk(from, chunk) { + if ((from - this.lastTo || chunk.value[0].startSide - this.last.endSide) < 0) + return false; + if (this.from.length) + this.finishChunk(true); + this.setMaxPoint = Math.max(this.setMaxPoint, chunk.maxPoint); + this.chunks.push(chunk); + this.chunkPos.push(from); + let last = chunk.value.length - 1; + this.last = chunk.value[last]; + this.lastFrom = chunk.from[last] + from; + this.lastTo = chunk.to[last] + from; + return true; + } + /** + Finish the range set. Returns the new set. The builder can't be + used anymore after this has been called. + */ + finish() { return this.finishInner(RangeSet.empty); } + /** + @internal + */ + finishInner(next) { + if (this.from.length) + this.finishChunk(false); + if (this.chunks.length == 0) + return next; + let result = RangeSet.create(this.chunkPos, this.chunks, this.nextLayer ? this.nextLayer.finishInner(next) : next, this.setMaxPoint); + this.from = null; // Make sure further `add` calls produce errors + return result; + } + } + function findSharedChunks(a, b, textDiff) { + let inA = new Map(); + for (let set of a) + for (let i = 0; i < set.chunk.length; i++) + if (set.chunk[i].maxPoint <= 0) + inA.set(set.chunk[i], set.chunkPos[i]); + let shared = new Set(); + for (let set of b) + for (let i = 0; i < set.chunk.length; i++) { + let known = inA.get(set.chunk[i]); + if (known != null && (textDiff ? textDiff.mapPos(known) : known) == set.chunkPos[i] && + !(textDiff === null || textDiff === void 0 ? void 0 : textDiff.touchesRange(known, known + set.chunk[i].length))) + shared.add(set.chunk[i]); + } + return shared; + } + class LayerCursor { + constructor(layer, skip, minPoint, rank = 0) { + this.layer = layer; + this.skip = skip; + this.minPoint = minPoint; + this.rank = rank; + } + get startSide() { return this.value ? this.value.startSide : 0; } + get endSide() { return this.value ? this.value.endSide : 0; } + goto(pos, side = -1000000000 /* C.Far */) { + this.chunkIndex = this.rangeIndex = 0; + this.gotoInner(pos, side, false); + return this; + } + gotoInner(pos, side, forward) { + while (this.chunkIndex < this.layer.chunk.length) { + let next = this.layer.chunk[this.chunkIndex]; + if (!(this.skip && this.skip.has(next) || + this.layer.chunkEnd(this.chunkIndex) < pos || + next.maxPoint < this.minPoint)) + break; + this.chunkIndex++; + forward = false; + } + if (this.chunkIndex < this.layer.chunk.length) { + let rangeIndex = this.layer.chunk[this.chunkIndex].findIndex(pos - this.layer.chunkPos[this.chunkIndex], side, true); + if (!forward || this.rangeIndex < rangeIndex) + this.setRangeIndex(rangeIndex); + } + this.next(); + } + forward(pos, side) { + if ((this.to - pos || this.endSide - side) < 0) + this.gotoInner(pos, side, true); + } + next() { + for (;;) { + if (this.chunkIndex == this.layer.chunk.length) { + this.from = this.to = 1000000000 /* C.Far */; + this.value = null; + break; + } + else { + let chunkPos = this.layer.chunkPos[this.chunkIndex], chunk = this.layer.chunk[this.chunkIndex]; + let from = chunkPos + chunk.from[this.rangeIndex]; + this.from = from; + this.to = chunkPos + chunk.to[this.rangeIndex]; + this.value = chunk.value[this.rangeIndex]; + this.setRangeIndex(this.rangeIndex + 1); + if (this.minPoint < 0 || this.value.point && this.to - this.from >= this.minPoint) + break; + } + } + } + setRangeIndex(index) { + if (index == this.layer.chunk[this.chunkIndex].value.length) { + this.chunkIndex++; + if (this.skip) { + while (this.chunkIndex < this.layer.chunk.length && this.skip.has(this.layer.chunk[this.chunkIndex])) + this.chunkIndex++; + } + this.rangeIndex = 0; + } + else { + this.rangeIndex = index; + } + } + nextChunk() { + this.chunkIndex++; + this.rangeIndex = 0; + this.next(); + } + compare(other) { + return this.from - other.from || this.startSide - other.startSide || this.rank - other.rank || + this.to - other.to || this.endSide - other.endSide; + } + } + class HeapCursor { + constructor(heap) { + this.heap = heap; + } + static from(sets, skip = null, minPoint = -1) { + let heap = []; + for (let i = 0; i < sets.length; i++) { + for (let cur = sets[i]; !cur.isEmpty; cur = cur.nextLayer) { + if (cur.maxPoint >= minPoint) + heap.push(new LayerCursor(cur, skip, minPoint, i)); + } + } + return heap.length == 1 ? heap[0] : new HeapCursor(heap); + } + get startSide() { return this.value ? this.value.startSide : 0; } + goto(pos, side = -1000000000 /* C.Far */) { + for (let cur of this.heap) + cur.goto(pos, side); + for (let i = this.heap.length >> 1; i >= 0; i--) + heapBubble(this.heap, i); + this.next(); + return this; + } + forward(pos, side) { + for (let cur of this.heap) + cur.forward(pos, side); + for (let i = this.heap.length >> 1; i >= 0; i--) + heapBubble(this.heap, i); + if ((this.to - pos || this.value.endSide - side) < 0) + this.next(); + } + next() { + if (this.heap.length == 0) { + this.from = this.to = 1000000000 /* C.Far */; + this.value = null; + this.rank = -1; + } + else { + let top = this.heap[0]; + this.from = top.from; + this.to = top.to; + this.value = top.value; + this.rank = top.rank; + if (top.value) + top.next(); + heapBubble(this.heap, 0); + } + } + } + function heapBubble(heap, index) { + for (let cur = heap[index];;) { + let childIndex = (index << 1) + 1; + if (childIndex >= heap.length) + break; + let child = heap[childIndex]; + if (childIndex + 1 < heap.length && child.compare(heap[childIndex + 1]) >= 0) { + child = heap[childIndex + 1]; + childIndex++; + } + if (cur.compare(child) < 0) + break; + heap[childIndex] = cur; + heap[index] = child; + index = childIndex; + } + } + class SpanCursor { + constructor(sets, skip, minPoint) { + this.minPoint = minPoint; + this.active = []; + this.activeTo = []; + this.activeRank = []; + this.minActive = -1; + // A currently active point range, if any + this.point = null; + this.pointFrom = 0; + this.pointRank = 0; + this.to = -1000000000 /* C.Far */; + this.endSide = 0; + this.openStart = -1; + this.cursor = HeapCursor.from(sets, skip, minPoint); + } + goto(pos, side = -1000000000 /* C.Far */) { + this.cursor.goto(pos, side); + this.active.length = this.activeTo.length = this.activeRank.length = 0; + this.minActive = -1; + this.to = pos; + this.endSide = side; + this.openStart = -1; + this.next(); + return this; + } + forward(pos, side) { + while (this.minActive > -1 && (this.activeTo[this.minActive] - pos || this.active[this.minActive].endSide - side) < 0) + this.removeActive(this.minActive); + this.cursor.forward(pos, side); + } + removeActive(index) { + remove(this.active, index); + remove(this.activeTo, index); + remove(this.activeRank, index); + this.minActive = findMinIndex(this.active, this.activeTo); + } + addActive(trackOpen) { + let i = 0, { value, to, rank } = this.cursor; + while (i < this.activeRank.length && this.activeRank[i] <= rank) + i++; + insert(this.active, i, value); + insert(this.activeTo, i, to); + insert(this.activeRank, i, rank); + if (trackOpen) + insert(trackOpen, i, this.cursor.from); + this.minActive = findMinIndex(this.active, this.activeTo); + } + // After calling this, if `this.point` != null, the next range is a + // point. Otherwise, it's a regular range, covered by `this.active`. + next() { + let from = this.to, wasPoint = this.point; + this.point = null; + let trackOpen = this.openStart < 0 ? [] : null, trackExtra = 0; + for (;;) { + let a = this.minActive; + if (a > -1 && (this.activeTo[a] - this.cursor.from || this.active[a].endSide - this.cursor.startSide) < 0) { + if (this.activeTo[a] > from) { + this.to = this.activeTo[a]; + this.endSide = this.active[a].endSide; + break; + } + this.removeActive(a); + if (trackOpen) + remove(trackOpen, a); + } + else if (!this.cursor.value) { + this.to = this.endSide = 1000000000 /* C.Far */; + break; + } + else if (this.cursor.from > from) { + this.to = this.cursor.from; + this.endSide = this.cursor.startSide; + break; + } + else { + let nextVal = this.cursor.value; + if (!nextVal.point) { // Opening a range + this.addActive(trackOpen); + if (this.cursor.from < from && this.cursor.to > from) + trackExtra++; + this.cursor.next(); + } + else if (wasPoint && this.cursor.to == this.to && this.cursor.from < this.cursor.to) { + // Ignore any non-empty points that end precisely at the end of the prev point + this.cursor.next(); + } + else { // New point + this.point = nextVal; + this.pointFrom = this.cursor.from; + this.pointRank = this.cursor.rank; + this.to = this.cursor.to; + this.endSide = nextVal.endSide; + if (this.cursor.from < from) + trackExtra = 1; + this.cursor.next(); + this.forward(this.to, this.endSide); + break; + } + } + } + if (trackOpen) { + let openStart = 0; + while (openStart < trackOpen.length && trackOpen[openStart] < from) + openStart++; + this.openStart = openStart + trackExtra; + } + } + activeForPoint(to) { + if (!this.active.length) + return this.active; + let active = []; + for (let i = this.active.length - 1; i >= 0; i--) { + if (this.activeRank[i] < this.pointRank) + break; + if (this.activeTo[i] > to || this.activeTo[i] == to && this.active[i].endSide >= this.point.endSide) + active.push(this.active[i]); + } + return active.reverse(); + } + openEnd(to) { + let open = 0; + for (let i = this.activeTo.length - 1; i >= 0 && this.activeTo[i] > to; i--) + open++; + return open; + } + } + function compare(a, startA, b, startB, length, comparator) { + a.goto(startA); + b.goto(startB); + let endB = startB + length; + let pos = startB, dPos = startB - startA; + for (;;) { + let diff = (a.to + dPos) - b.to || a.endSide - b.endSide; + let end = diff < 0 ? a.to + dPos : b.to, clipEnd = Math.min(end, endB); + if (a.point || b.point) { + if (!(a.point && b.point && (a.point == b.point || a.point.eq(b.point)) && + sameValues(a.activeForPoint(a.to + dPos), b.activeForPoint(b.to)))) + comparator.comparePoint(pos, clipEnd, a.point, b.point); + } + else { + if (clipEnd > pos && !sameValues(a.active, b.active)) + comparator.compareRange(pos, clipEnd, a.active, b.active); + } + if (end > endB) + break; + pos = end; + if (diff <= 0) + a.next(); + if (diff >= 0) + b.next(); + } + } + function sameValues(a, b) { + if (a.length != b.length) + return false; + for (let i = 0; i < a.length; i++) + if (a[i] != b[i] && !a[i].eq(b[i])) + return false; + return true; + } + function remove(array, index) { + for (let i = index, e = array.length - 1; i < e; i++) + array[i] = array[i + 1]; + array.pop(); + } + function insert(array, index, value) { + for (let i = array.length - 1; i >= index; i--) + array[i + 1] = array[i]; + array[index] = value; + } + function findMinIndex(value, array) { + let found = -1, foundPos = 1000000000 /* C.Far */; + for (let i = 0; i < array.length; i++) + if ((array[i] - foundPos || value[i].endSide - value[found].endSide) < 0) { + found = i; + foundPos = array[i]; + } + return found; + } + + /** + Count the column position at the given offset into the string, + taking extending characters and tab size into account. + */ + function countColumn(string, tabSize, to = string.length) { + let n = 0; + for (let i = 0; i < to;) { + if (string.charCodeAt(i) == 9) { + n += tabSize - (n % tabSize); + i++; + } + else { + n++; + i = findClusterBreak(string, i); + } + } + return n; + } + /** + Find the offset that corresponds to the given column position in a + string, taking extending characters and tab size into account. By + default, the string length is returned when it is too short to + reach the column. Pass `strict` true to make it return -1 in that + situation. + */ + function findColumn(string, col, tabSize, strict) { + for (let i = 0, n = 0;;) { + if (n >= col) + return i; + if (i == string.length) + break; + n += string.charCodeAt(i) == 9 ? tabSize - (n % tabSize) : 1; + i = findClusterBreak(string, i); + } + return strict === true ? -1 : string.length; + } + + const C = "\u037c"; + const COUNT = typeof Symbol == "undefined" ? "__" + C : Symbol.for(C); + const SET = typeof Symbol == "undefined" ? "__styleSet" + Math.floor(Math.random() * 1e8) : Symbol("styleSet"); + const top = typeof globalThis != "undefined" ? globalThis : typeof window != "undefined" ? window : {}; + + // :: - Style modules encapsulate a set of CSS rules defined from + // JavaScript. Their definitions are only available in a given DOM + // root after it has been _mounted_ there with `StyleModule.mount`. + // + // Style modules should be created once and stored somewhere, as + // opposed to re-creating them every time you need them. The amount of + // CSS rules generated for a given DOM root is bounded by the amount + // of style modules that were used. So to avoid leaking rules, don't + // create these dynamically, but treat them as one-time allocations. + class StyleModule { + // :: (Object